Merge "LayoutLib: misc fix." into honeycomb
diff --git a/api/11.xml b/api/11.xml
index 43bb440..e2f8025 100644
--- a/api/11.xml
+++ b/api/11.xml
@@ -61129,17 +61129,6 @@
visibility="public"
>
</method>
-<method name="getGL"
- return="javax.microedition.khronos.opengles.GL"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
<method name="getHeight"
return="int"
abstract="false"
diff --git a/api/current.xml b/api/current.xml
index 112c147..8b0c555 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -1255,17 +1255,6 @@
visibility="public"
>
</field>
-<field name="WRITE_MEDIA_STORAGE"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value=""android.permission.WRITE_MEDIA_STORAGE""
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
<field name="WRITE_SECURE_SETTINGS"
type="java.lang.String"
transient="false"
@@ -1486,7 +1475,7 @@
type="int"
transient="false"
volatile="false"
- value="17432591"
+ value="17432589"
static="true"
final="true"
deprecated="not deprecated"
@@ -1519,29 +1508,7 @@
type="int"
transient="false"
volatile="false"
- value="17432593"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="animator_fade_in"
- type="int"
- transient="false"
- volatile="false"
- value="17432589"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
-<field name="animator_fade_out"
- type="int"
- transient="false"
- volatile="false"
- value="17432590"
+ value="17432591"
static="true"
final="true"
deprecated="not deprecated"
@@ -1596,7 +1563,7 @@
type="int"
transient="false"
volatile="false"
- value="17432592"
+ value="17432590"
static="true"
final="true"
deprecated="not deprecated"
@@ -1618,7 +1585,7 @@
type="int"
transient="false"
volatile="false"
- value="17432594"
+ value="17432592"
static="true"
final="true"
deprecated="not deprecated"
@@ -2116,6 +2083,17 @@
visibility="public"
>
</field>
+<field name="alertDialogIcon"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16843607"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
<field name="alertDialogStyle"
type="int"
transient="false"
@@ -5900,6 +5878,17 @@
visibility="public"
>
</field>
+<field name="layerType"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="16843606"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
<field name="layout"
type="int"
transient="false"
@@ -19974,6 +19963,42 @@
</parameter>
</method>
</class>
+<class name="ArgbEvaluator"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<implements name="android.animation.TypeEvaluator">
+</implements>
+<constructor name="ArgbEvaluator"
+ type="android.animation.ArgbEvaluator"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<method name="evaluate"
+ return="java.lang.Object"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="fraction" type="float">
+</parameter>
+<parameter name="startValue" type="java.lang.Object">
+</parameter>
+<parameter name="endValue" type="java.lang.Object">
+</parameter>
+</method>
+</class>
<class name="DoubleEvaluator"
extends="java.lang.Object"
abstract="false"
@@ -20940,42 +20965,6 @@
</parameter>
</method>
</class>
-<class name="RGBEvaluator"
- extends="java.lang.Object"
- abstract="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<implements name="android.animation.TypeEvaluator">
-</implements>
-<constructor name="RGBEvaluator"
- type="android.animation.RGBEvaluator"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</constructor>
-<method name="evaluate"
- return="java.lang.Object"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="fraction" type="float">
-</parameter>
-<parameter name="startValue" type="java.lang.Object">
-</parameter>
-<parameter name="endValue" type="java.lang.Object">
-</parameter>
-</method>
-</class>
<interface name="TimeInterpolator"
abstract="true"
static="false"
@@ -22795,32 +22784,6 @@
<parameter name="args" type="java.lang.String[]">
</parameter>
</method>
-<method name="findFragmentById"
- return="android.app.Fragment"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="deprecated"
- visibility="public"
->
-<parameter name="id" type="int">
-</parameter>
-</method>
-<method name="findFragmentByTag"
- return="android.app.Fragment"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="deprecated"
- visibility="public"
->
-<parameter name="tag" type="java.lang.String">
-</parameter>
-</method>
<method name="findViewById"
return="android.view.View"
abstract="false"
@@ -24043,17 +24006,6 @@
<parameter name="view" type="android.view.View">
</parameter>
</method>
-<method name="openFragmentTransaction"
- return="android.app.FragmentTransaction"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="deprecated"
- visibility="public"
->
-</method>
<method name="openOptionsMenu"
return="void"
abstract="false"
@@ -24997,6 +24949,17 @@
<exception name="SecurityException" type="java.lang.SecurityException">
</exception>
</method>
+<method name="isRunningInTestHarness"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
<method name="isUserAMonkey"
return="boolean"
abstract="false"
@@ -26599,6 +26562,19 @@
<parameter name="icon" type="android.graphics.drawable.Drawable">
</parameter>
</method>
+<method name="setIconAttribute"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="attrId" type="int">
+</parameter>
+</method>
<method name="setInverseBackgroundForced"
return="void"
abstract="false"
@@ -26796,6 +26772,19 @@
<parameter name="icon" type="android.graphics.drawable.Drawable">
</parameter>
</method>
+<method name="setIconAttribute"
+ return="android.app.AlertDialog.Builder"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="attrId" type="int">
+</parameter>
+</method>
<method name="setInverseBackgroundForced"
return="android.app.AlertDialog.Builder"
abstract="false"
@@ -43575,6 +43564,41 @@
<parameter name="data" type="D">
</parameter>
</method>
+<method name="onLoadInBackground"
+ return="D"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="protected"
+>
+</method>
+<method name="setUpdateThrottle"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="delayMS" type="long">
+</parameter>
+</method>
+<method name="waitForLoader"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
</class>
<class name="BroadcastReceiver"
extends="java.lang.Object"
@@ -50153,21 +50177,6 @@
<parameter name="cursor" type="android.database.Cursor">
</parameter>
</method>
-<method name="registerContentObserver"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="cursor" type="android.database.Cursor">
-</parameter>
-<parameter name="observer" type="android.database.ContentObserver">
-</parameter>
-</method>
<method name="setProjection"
return="void"
abstract="false"
@@ -55394,7 +55403,7 @@
native="false"
synchronized="false"
static="false"
- final="true"
+ final="false"
deprecated="not deprecated"
visibility="public"
>
@@ -55519,7 +55528,7 @@
native="false"
synchronized="false"
static="false"
- final="true"
+ final="false"
deprecated="not deprecated"
visibility="public"
>
@@ -55541,7 +55550,7 @@
native="false"
synchronized="false"
static="false"
- final="true"
+ final="false"
deprecated="not deprecated"
visibility="public"
>
@@ -58367,6 +58376,17 @@
visibility="public"
>
</method>
+<method name="isEnabled"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
<field name="applicationInfo"
type="android.content.pm.ApplicationInfo"
transient="false"
@@ -67958,6 +67978,21 @@
<parameter name="selectionArgs" type="java.lang.String[]">
</parameter>
</method>
+<method name="concatenateWhere"
+ return="java.lang.String"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="a" type="java.lang.String">
+</parameter>
+<parameter name="b" type="java.lang.String">
+</parameter>
+</method>
<method name="createDbFromSqlStatements"
return="void"
abstract="false"
@@ -78198,17 +78233,6 @@
visibility="public"
>
</method>
-<method name="getGL"
- return="javax.microedition.khronos.opengles.GL"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="deprecated"
- visibility="protected"
->
-</method>
<method name="getHeight"
return="int"
abstract="false"
@@ -85932,6 +85956,97 @@
</parameter>
</constructor>
</class>
+<class name="SurfaceTexture"
+ extends="java.lang.Object"
+ abstract="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="SurfaceTexture"
+ type="android.graphics.SurfaceTexture"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="texName" type="int">
+</parameter>
+</constructor>
+<method name="setOnFrameAvailableListener"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="l" type="android.graphics.SurfaceTexture.OnFrameAvailableListener">
+</parameter>
+</method>
+<method name="updateTexImage"
+ return="void"
+ abstract="false"
+ native="true"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
+</class>
+<interface name="SurfaceTexture.OnFrameAvailableListener"
+ abstract="true"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<method name="onFrameAvailable"
+ return="void"
+ abstract="true"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="surfaceTexture" type="android.graphics.SurfaceTexture">
+</parameter>
+</method>
+</interface>
+<class name="SurfaceTexture.OutOfResourcesException"
+ extends="java.lang.Exception"
+ abstract="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="SurfaceTexture.OutOfResourcesException"
+ type="android.graphics.SurfaceTexture.OutOfResourcesException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</constructor>
+<constructor name="SurfaceTexture.OutOfResourcesException"
+ type="android.graphics.SurfaceTexture.OutOfResourcesException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="name" type="java.lang.String">
+</parameter>
+</constructor>
+</class>
<class name="SweepGradient"
extends="android.graphics.Shader"
abstract="false"
@@ -90422,6 +90537,19 @@
<exception name="IOException" type="java.io.IOException">
</exception>
</method>
+<method name="setPreviewTexture"
+ return="void"
+ abstract="false"
+ native="true"
+ synchronized="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="surfaceTexture" type="android.graphics.SurfaceTexture">
+</parameter>
+</method>
<method name="setZoomChangeListener"
return="void"
abstract="false"
@@ -136773,6 +136901,19 @@
deprecated="not deprecated"
visibility="protected"
>
+<parameter name="result" type="Result">
+</parameter>
+</method>
+<method name="onCancelled"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="protected"
+>
</method>
<method name="onPostExecute"
return="void"
@@ -140665,6 +140806,17 @@
visibility="public"
>
</method>
+<method name="isExternalStorageEmulated"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="true"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
<method name="isExternalStorageRemovable"
return="boolean"
abstract="false"
@@ -165864,6 +166016,175 @@
deprecated="not deprecated"
visibility="public"
>
+<method name="copy1DRangeFrom"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="off" type="int">
+</parameter>
+<parameter name="count" type="int">
+</parameter>
+<parameter name="d" type="int[]">
+</parameter>
+</method>
+<method name="copy1DRangeFrom"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="off" type="int">
+</parameter>
+<parameter name="count" type="int">
+</parameter>
+<parameter name="d" type="short[]">
+</parameter>
+</method>
+<method name="copy1DRangeFrom"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="off" type="int">
+</parameter>
+<parameter name="count" type="int">
+</parameter>
+<parameter name="d" type="byte[]">
+</parameter>
+</method>
+<method name="copy1DRangeFrom"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="off" type="int">
+</parameter>
+<parameter name="count" type="int">
+</parameter>
+<parameter name="d" type="float[]">
+</parameter>
+</method>
+<method name="copy2DRangeFrom"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="xoff" type="int">
+</parameter>
+<parameter name="yoff" type="int">
+</parameter>
+<parameter name="w" type="int">
+</parameter>
+<parameter name="h" type="int">
+</parameter>
+<parameter name="d" type="byte[]">
+</parameter>
+</method>
+<method name="copy2DRangeFrom"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="xoff" type="int">
+</parameter>
+<parameter name="yoff" type="int">
+</parameter>
+<parameter name="w" type="int">
+</parameter>
+<parameter name="h" type="int">
+</parameter>
+<parameter name="d" type="short[]">
+</parameter>
+</method>
+<method name="copy2DRangeFrom"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="xoff" type="int">
+</parameter>
+<parameter name="yoff" type="int">
+</parameter>
+<parameter name="w" type="int">
+</parameter>
+<parameter name="h" type="int">
+</parameter>
+<parameter name="d" type="int[]">
+</parameter>
+</method>
+<method name="copy2DRangeFrom"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="xoff" type="int">
+</parameter>
+<parameter name="yoff" type="int">
+</parameter>
+<parameter name="w" type="int">
+</parameter>
+<parameter name="h" type="int">
+</parameter>
+<parameter name="d" type="float[]">
+</parameter>
+</method>
+<method name="copy2DRangeFrom"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="xoff" type="int">
+</parameter>
+<parameter name="yoff" type="int">
+</parameter>
+<parameter name="b" type="android.graphics.Bitmap">
+</parameter>
+</method>
<method name="copyFrom"
return="void"
abstract="false"
@@ -165955,6 +166276,58 @@
<parameter name="b" type="android.graphics.Bitmap">
</parameter>
</method>
+<method name="copyTo"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="d" type="byte[]">
+</parameter>
+</method>
+<method name="copyTo"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="d" type="short[]">
+</parameter>
+</method>
+<method name="copyTo"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="d" type="int[]">
+</parameter>
+</method>
+<method name="copyTo"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="d" type="float[]">
+</parameter>
+</method>
<method name="createCubemapFromBitmap"
return="android.renderscript.Allocation"
abstract="false"
@@ -165971,8 +166344,6 @@
</parameter>
<parameter name="mips" type="android.renderscript.Allocation.MipmapControl">
</parameter>
-<parameter name="layout" type="android.renderscript.Allocation.CubemapLayout">
-</parameter>
<parameter name="usage" type="int">
</parameter>
</method>
@@ -165990,8 +166361,6 @@
</parameter>
<parameter name="b" type="android.graphics.Bitmap">
</parameter>
-<parameter name="layout" type="android.renderscript.Allocation.CubemapLayout">
-</parameter>
</method>
<method name="createFromBitmap"
return="android.renderscript.Allocation"
@@ -166180,32 +166549,6 @@
visibility="public"
>
</method>
-<method name="readData"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="d" type="int[]">
-</parameter>
-</method>
-<method name="readData"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="d" type="float[]">
-</parameter>
-</method>
<method name="resize"
return="void"
abstract="false"
@@ -166219,148 +166562,6 @@
<parameter name="dimX" type="int">
</parameter>
</method>
-<method name="subData"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="xoff" type="int">
-</parameter>
-<parameter name="fp" type="android.renderscript.FieldPacker">
-</parameter>
-</method>
-<method name="subData1D"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="off" type="int">
-</parameter>
-<parameter name="count" type="int">
-</parameter>
-<parameter name="d" type="int[]">
-</parameter>
-</method>
-<method name="subData1D"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="off" type="int">
-</parameter>
-<parameter name="count" type="int">
-</parameter>
-<parameter name="d" type="short[]">
-</parameter>
-</method>
-<method name="subData1D"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="off" type="int">
-</parameter>
-<parameter name="count" type="int">
-</parameter>
-<parameter name="d" type="byte[]">
-</parameter>
-</method>
-<method name="subData1D"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="off" type="int">
-</parameter>
-<parameter name="count" type="int">
-</parameter>
-<parameter name="d" type="float[]">
-</parameter>
-</method>
-<method name="subData2D"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="xoff" type="int">
-</parameter>
-<parameter name="yoff" type="int">
-</parameter>
-<parameter name="w" type="int">
-</parameter>
-<parameter name="h" type="int">
-</parameter>
-<parameter name="d" type="int[]">
-</parameter>
-</method>
-<method name="subData2D"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="xoff" type="int">
-</parameter>
-<parameter name="yoff" type="int">
-</parameter>
-<parameter name="w" type="int">
-</parameter>
-<parameter name="h" type="int">
-</parameter>
-<parameter name="d" type="float[]">
-</parameter>
-</method>
-<method name="subElementData"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="xoff" type="int">
-</parameter>
-<parameter name="component_number" type="int">
-</parameter>
-<parameter name="fp" type="android.renderscript.FieldPacker">
-</parameter>
-</method>
<method name="syncAll"
return="void"
abstract="false"
@@ -166419,39 +166620,6 @@
>
</field>
</class>
-<class name="Allocation.CubemapLayout"
- extends="java.lang.Enum"
- abstract="false"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-<method name="valueOf"
- return="android.renderscript.Allocation.CubemapLayout"
- abstract="false"
- native="false"
- synchronized="false"
- static="true"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="name" type="java.lang.String">
-</parameter>
-</method>
-<method name="values"
- return="android.renderscript.Allocation.CubemapLayout[]"
- abstract="false"
- native="false"
- synchronized="false"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-</class>
<class name="Allocation.MipmapControl"
extends="java.lang.Enum"
abstract="false"
@@ -170769,49 +170937,6 @@
deprecated="not deprecated"
visibility="public"
>
-<method name="bindAllocation"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="va" type="android.renderscript.Allocation">
-</parameter>
-<parameter name="slot" type="int">
-</parameter>
-</method>
-<method name="invoke"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="protected"
->
-<parameter name="slot" type="int">
-</parameter>
-</method>
-<method name="invoke"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="protected"
->
-<parameter name="slot" type="int">
-</parameter>
-<parameter name="v" type="android.renderscript.FieldPacker">
-</parameter>
-</method>
<method name="setTimeZone"
return="void"
abstract="false"
@@ -170825,122 +170950,6 @@
<parameter name="timeZone" type="java.lang.String">
</parameter>
</method>
-<method name="setVar"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="index" type="int">
-</parameter>
-<parameter name="v" type="float">
-</parameter>
-</method>
-<method name="setVar"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="index" type="int">
-</parameter>
-<parameter name="v" type="double">
-</parameter>
-</method>
-<method name="setVar"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="index" type="int">
-</parameter>
-<parameter name="v" type="int">
-</parameter>
-</method>
-<method name="setVar"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="index" type="int">
-</parameter>
-<parameter name="v" type="long">
-</parameter>
-</method>
-<method name="setVar"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="index" type="int">
-</parameter>
-<parameter name="v" type="boolean">
-</parameter>
-</method>
-<method name="setVar"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="index" type="int">
-</parameter>
-<parameter name="o" type="android.renderscript.BaseObj">
-</parameter>
-</method>
-<method name="setVar"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="index" type="int">
-</parameter>
-<parameter name="v" type="android.renderscript.FieldPacker">
-</parameter>
-</method>
-<field name="MAX_SLOT"
- type="int"
- transient="false"
- volatile="false"
- value="16"
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
</class>
<class name="Script.Builder"
extends="java.lang.Object"
@@ -171064,26 +171073,6 @@
>
</field>
</class>
-<class name="Script.Invokable"
- extends="java.lang.Object"
- abstract="false"
- static="true"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<method name="execute"
- return="void"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-</method>
-</class>
<class name="ScriptC"
extends="android.renderscript.Script"
abstract="false"
@@ -171092,32 +171081,6 @@
deprecated="not deprecated"
visibility="public"
>
-<constructor name="ScriptC"
- type="android.renderscript.ScriptC"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="protected"
->
-<parameter name="id" type="int">
-</parameter>
-<parameter name="rs" type="android.renderscript.RenderScript">
-</parameter>
-</constructor>
-<constructor name="ScriptC"
- type="android.renderscript.ScriptC"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="protected"
->
-<parameter name="rs" type="android.renderscript.RenderScript">
-</parameter>
-<parameter name="resources" type="android.content.res.Resources">
-</parameter>
-<parameter name="resourceID" type="int">
-</parameter>
-</constructor>
</class>
<class name="Short2"
extends="java.lang.Object"
@@ -198607,6 +198570,17 @@
<exception name="IOException" type="java.io.IOException">
</exception>
</method>
+<method name="isLenient"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
<method name="nextBoolean"
return="boolean"
abstract="false"
@@ -198737,21 +198711,6 @@
<exception name="IOException" type="java.io.IOException">
</exception>
</method>
-<method name="syntaxError"
- return="java.io.IOException"
- abstract="false"
- native="false"
- synchronized="false"
- static="false"
- final="false"
- deprecated="not deprecated"
- visibility="public"
->
-<parameter name="message" type="java.lang.String">
-</parameter>
-<exception name="IOException" type="java.io.IOException">
-</exception>
-</method>
</class>
<class name="JsonToken"
extends="java.lang.Enum"
@@ -198884,6 +198843,17 @@
<exception name="IOException" type="java.io.IOException">
</exception>
</method>
+<method name="isLenient"
+ return="boolean"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
<method name="name"
return="android.util.JsonWriter"
abstract="false"
@@ -198925,6 +198895,19 @@
<parameter name="indent" type="java.lang.String">
</parameter>
</method>
+<method name="setLenient"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="lenient" type="boolean">
+</parameter>
+</method>
<method name="value"
return="android.util.JsonWriter"
abstract="false"
@@ -198985,6 +198968,21 @@
<exception name="IOException" type="java.io.IOException">
</exception>
</method>
+<method name="value"
+ return="android.util.JsonWriter"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="value" type="java.lang.Number">
+</parameter>
+<exception name="IOException" type="java.io.IOException">
+</exception>
+</method>
</class>
<class name="Log"
extends="java.lang.Object"
@@ -199364,6 +199362,25 @@
</parameter>
</method>
</class>
+<class name="MalformedJsonException"
+ extends="java.io.IOException"
+ abstract="false"
+ static="false"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<constructor name="MalformedJsonException"
+ type="android.util.MalformedJsonException"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="message" type="java.lang.String">
+</parameter>
+</constructor>
+</class>
<class name="MonthDisplayHelper"
extends="java.lang.Object"
abstract="false"
@@ -213223,6 +213240,17 @@
visibility="public"
>
</method>
+<method name="getLayerType"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
<method name="getLayoutParams"
return="android.view.ViewGroup.LayoutParams"
abstract="false"
@@ -215725,6 +215753,21 @@
<parameter name="keepScreenOn" type="boolean">
</parameter>
</method>
+<method name="setLayerType"
+ return="void"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+<parameter name="layerType" type="int">
+</parameter>
+<parameter name="paint" type="android.graphics.Paint">
+</parameter>
+</method>
<method name="setLayoutParams"
return="void"
abstract="false"
@@ -216434,7 +216477,7 @@
>
<parameter name="data" type="android.content.ClipData">
</parameter>
-<parameter name="thumbBuilder" type="android.view.View.DragThumbnailBuilder">
+<parameter name="shadowBuilder" type="android.view.View.DragShadowBuilder">
</parameter>
<parameter name="myWindowOnly" type="boolean">
</parameter>
@@ -216812,6 +216855,39 @@
visibility="public"
>
</field>
+<field name="LAYER_TYPE_HARDWARE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="2"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="LAYER_TYPE_NONE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="0"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="LAYER_TYPE_SOFTWARE"
+ type="int"
+ transient="false"
+ volatile="false"
+ value="1"
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
<field name="MEASURED_HEIGHT_STATE_SHIFT"
type="int"
transient="false"
@@ -217248,7 +217324,7 @@
>
</field>
</class>
-<class name="View.DragThumbnailBuilder"
+<class name="View.DragShadowBuilder"
extends="java.lang.Object"
abstract="false"
static="true"
@@ -217256,8 +217332,8 @@
deprecated="not deprecated"
visibility="public"
>
-<constructor name="View.DragThumbnailBuilder"
- type="android.view.View.DragThumbnailBuilder"
+<constructor name="View.DragShadowBuilder"
+ type="android.view.View.DragShadowBuilder"
static="false"
final="false"
deprecated="not deprecated"
@@ -217277,7 +217353,7 @@
visibility="public"
>
</method>
-<method name="onDrawThumbnail"
+<method name="onDrawShadow"
return="void"
abstract="false"
native="false"
@@ -217290,7 +217366,7 @@
<parameter name="canvas" type="android.graphics.Canvas">
</parameter>
</method>
-<method name="onProvideThumbnailMetrics"
+<method name="onProvideShadowMetrics"
return="void"
abstract="false"
native="false"
@@ -217300,9 +217376,9 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="thumbnailSize" type="android.graphics.Point">
+<parameter name="shadowSize" type="android.graphics.Point">
</parameter>
-<parameter name="thumbnailTouchPoint" type="android.graphics.Point">
+<parameter name="shadowTouchPoint" type="android.graphics.Point">
</parameter>
</method>
</class>
@@ -257935,7 +258011,7 @@
deprecated="not deprecated"
visibility="public"
>
-<parameter name="arg0" type="T">
+<parameter name="t" type="T">
</parameter>
</method>
</interface>
diff --git a/cmds/pm/src/com/android/commands/pm/Pm.java b/cmds/pm/src/com/android/commands/pm/Pm.java
index a236a3c..cc6e739 100644
--- a/cmds/pm/src/com/android/commands/pm/Pm.java
+++ b/cmds/pm/src/com/android/commands/pm/Pm.java
@@ -18,9 +18,11 @@
import com.android.internal.content.PackageHelper;
+import android.app.ActivityManagerNative;
import android.content.ComponentName;
import android.content.pm.ApplicationInfo;
import android.content.pm.FeatureInfo;
+import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageDeleteObserver;
import android.content.pm.IPackageInstallObserver;
import android.content.pm.IPackageManager;
@@ -100,6 +102,11 @@
return;
}
+ if ("clear".equals(op)) {
+ runClear();
+ return;
+ }
+
if ("enable".equals(op)) {
runSetEnabledSetting(PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
return;
@@ -811,6 +818,55 @@
return obs.result;
}
+ class ClearDataObserver extends IPackageDataObserver.Stub {
+ boolean finished;
+ boolean result;
+
+ @Override
+ public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException {
+ synchronized (this) {
+ finished = true;
+ result = succeeded;
+ notifyAll();
+ }
+ }
+
+ }
+
+ private void runClear() {
+ String pkg = nextArg();
+ if (pkg == null) {
+ System.err.println("Error: no package specified");
+ showUsage();
+ return;
+ }
+
+ ClearDataObserver obs = new ClearDataObserver();
+ try {
+ if (!ActivityManagerNative.getDefault().clearApplicationUserData(pkg, obs)) {
+ System.err.println("Failed");
+ }
+
+ synchronized (obs) {
+ while (!obs.finished) {
+ try {
+ obs.wait();
+ } catch (InterruptedException e) {
+ }
+ }
+ }
+
+ if (obs.result) {
+ System.err.println("Success");
+ } else {
+ System.err.println("Failed");
+ }
+ } catch (RemoteException e) {
+ System.err.println(e.toString());
+ System.err.println(PM_NOT_RUNNING_ERR);
+ }
+ }
+
private static String enabledSettingToString(int state) {
switch (state) {
case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
@@ -946,6 +1002,7 @@
System.err.println(" pm path PACKAGE");
System.err.println(" pm install [-l] [-r] [-t] [-i INSTALLER_PACKAGE_NAME] [-s] [-f] PATH");
System.err.println(" pm uninstall [-k] PACKAGE");
+ System.err.println(" pm clear PACKAGE");
System.err.println(" pm enable PACKAGE_OR_COMPONENT");
System.err.println(" pm disable PACKAGE_OR_COMPONENT");
System.err.println(" pm setInstallLocation [0/auto] [1/internal] [2/external]");
@@ -991,6 +1048,8 @@
System.err.println(" -k: keep the data and cache directories around.");
System.err.println("after the package removal.");
System.err.println("");
+ System.err.println("The clear command deletes all data associated with a package.");
+ System.err.println("");
System.err.println("The enable and disable commands change the enabled state of");
System.err.println("a given package or component (written as \"package/class\").");
System.err.println("");
diff --git a/core/java/android/accounts/AccountManagerService.java b/core/java/android/accounts/AccountManagerService.java
index 72da2ce..6e04587 100644
--- a/core/java/android/accounts/AccountManagerService.java
+++ b/core/java/android/accounts/AccountManagerService.java
@@ -21,6 +21,7 @@
import com.android.internal.telephony.TelephonyIntents;
import android.Manifest;
+import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
@@ -162,8 +163,6 @@
private static AtomicReference<AccountManagerService> sThis =
new AtomicReference<AccountManagerService>();
- private static final boolean isDebuggableMonkeyBuild =
- SystemProperties.getBoolean("ro.monkey", false);
private static final Account[] EMPTY_ACCOUNT_ARRAY = new Account[]{};
static {
@@ -1992,12 +1991,12 @@
account.name, account.type};
final boolean permissionGranted =
DatabaseUtils.longForQuery(db, COUNT_OF_MATCHING_GRANTS, args) != 0;
- if (!permissionGranted && isDebuggableMonkeyBuild) {
+ if (!permissionGranted && ActivityManager.isRunningInTestHarness()) {
// TODO: Skip this check when running automated tests. Replace this
// with a more general solution.
Log.d(TAG, "no credentials permission for usage of " + account + ", "
+ authTokenType + " by uid " + Binder.getCallingUid()
- + " but ignoring since this is a monkey build");
+ + " but ignoring since device is in test harness.");
return true;
}
return permissionGranted;
diff --git a/core/java/android/animation/AnimatorInflater.java b/core/java/android/animation/AnimatorInflater.java
index 6e589e4..bcab66e 100644
--- a/core/java/android/animation/AnimatorInflater.java
+++ b/core/java/android/animation/AnimatorInflater.java
@@ -215,7 +215,7 @@
(toType <= TypedValue.TYPE_LAST_COLOR_INT))) {
// special case for colors: ignore valueType and get ints
getFloats = false;
- anim.setEvaluator(new RGBEvaluator());
+ anim.setEvaluator(new ArgbEvaluator());
}
if (getFloats) {
diff --git a/core/java/android/animation/RGBEvaluator.java b/core/java/android/animation/ArgbEvaluator.java
similarity index 97%
rename from core/java/android/animation/RGBEvaluator.java
rename to core/java/android/animation/ArgbEvaluator.java
index bae0af0..c3875be 100644
--- a/core/java/android/animation/RGBEvaluator.java
+++ b/core/java/android/animation/ArgbEvaluator.java
@@ -20,7 +20,7 @@
* This evaluator can be used to perform type interpolation between integer
* values that represent ARGB colors.
*/
-public class RGBEvaluator implements TypeEvaluator {
+public class ArgbEvaluator implements TypeEvaluator {
/**
* This function returns the calculated in-between value for a color
diff --git a/core/java/android/animation/LayoutTransition.java b/core/java/android/animation/LayoutTransition.java
index 8931450..d534163 100644
--- a/core/java/android/animation/LayoutTransition.java
+++ b/core/java/android/animation/LayoutTransition.java
@@ -600,6 +600,18 @@
// Remove the animation from the cache when it ends
anim.addListener(new AnimatorListenerAdapter() {
private boolean canceled = false;
+
+ @Override
+ public void onAnimationStart(Animator animator) {
+ if (mListeners != null) {
+ for (TransitionListener listener : mListeners) {
+ listener.startTransition(LayoutTransition.this, parent, child,
+ changeReason == APPEARING ?
+ CHANGE_APPEARING : CHANGE_DISAPPEARING);
+ }
+ }
+ }
+
@Override
public void onAnimationCancel(Animator animator) {
// we remove canceled animations immediately, not here
@@ -607,11 +619,19 @@
child.removeOnLayoutChangeListener(listener);
layoutChangeListenerMap.remove(child);
}
+
@Override
public void onAnimationEnd(Animator animator) {
if (!canceled) {
currentChangingAnimations.remove(child);
}
+ if (mListeners != null) {
+ for (TransitionListener listener : mListeners) {
+ listener.endTransition(LayoutTransition.this, parent, child,
+ changeReason == APPEARING ?
+ CHANGE_APPEARING : CHANGE_DISAPPEARING);
+ }
+ }
}
});
diff --git a/core/java/android/animation/ValueAnimator.java b/core/java/android/animation/ValueAnimator.java
index cfecec1..f884473 100755
--- a/core/java/android/animation/ValueAnimator.java
+++ b/core/java/android/animation/ValueAnimator.java
@@ -862,7 +862,7 @@
* of <code>startValue</code> and <code>endValue</code> in the constructor. But if these values
* are not one of these primitive types, or if different evaluation is desired (such as is
* necessary with int values that represent colors), a custom evaluator needs to be assigned.
- * For example, when running an animation on color values, the {@link RGBEvaluator}
+ * For example, when running an animation on color values, the {@link ArgbEvaluator}
* should be used to get correct RGB color interpolation.
*
* <p>If this ValueAnimator has only one set of values being animated between, this evaluator
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 938c47d..ec2f771 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -73,13 +73,11 @@
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.widget.AdapterView;
-import android.widget.FrameLayout;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.List;
/**
* An activity is a single, focused thing that the user can do. Almost all
@@ -1579,16 +1577,6 @@
return mFragments;
}
- /**
- * Start a series of edit operations on the Fragments associated with
- * this activity.
- * @deprecated use {@link #getFragmentManager}.
- */
- @Deprecated
- public FragmentTransaction openFragmentTransaction() {
- return mFragments.openTransaction();
- }
-
void invalidateFragmentIndex(int index) {
//Log.v(TAG, "invalidateFragmentIndex: index=" + index);
if (mAllLoaderManagers != null) {
@@ -1770,30 +1758,6 @@
}
/**
- * Finds a fragment that was identified by the given id either when inflated
- * from XML or as the container ID when added in a transaction. This only
- * returns fragments that are currently added to the activity's content.
- * @return The fragment if found or null otherwise.
- * @deprecated use {@link #getFragmentManager}.
- */
- @Deprecated
- public Fragment findFragmentById(int id) {
- return mFragments.findFragmentById(id);
- }
-
- /**
- * Finds a fragment that was identified by the given tag either when inflated
- * from XML or as supplied when added in a transaction. This only
- * returns fragments that are currently added to the activity's content.
- * @return The fragment if found or null otherwise.
- * @deprecated use {@link #getFragmentManager}.
- */
- @Deprecated
- public Fragment findFragmentByTag(String tag) {
- return mFragments.findFragmentByTag(tag);
- }
-
- /**
* Set the activity content from a layout resource. The resource will be
* inflated, adding all top-level views to the activity.
*
diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java
index 096a6eb..44db50f 100644
--- a/core/java/android/app/ActivityManager.java
+++ b/core/java/android/app/ActivityManager.java
@@ -1149,4 +1149,11 @@
}
return false;
}
+
+ /**
+ * Returns "true" if device is running in a test harness.
+ */
+ public static boolean isRunningInTestHarness() {
+ return SystemProperties.getBoolean("ro.test_harness", false);
+ }
}
diff --git a/core/java/android/app/AlertDialog.java b/core/java/android/app/AlertDialog.java
index 9850a12..70e3616 100644
--- a/core/java/android/app/AlertDialog.java
+++ b/core/java/android/app/AlertDialog.java
@@ -270,6 +270,17 @@
mAlert.setIcon(icon);
}
+ /**
+ * Set an icon as supplied by a theme attribute. e.g. android.R.attr.alertDialogIcon
+ *
+ * @param attrId ID of a theme attribute that points to a drawable resource.
+ */
+ public void setIconAttribute(int attrId) {
+ TypedValue out = new TypedValue();
+ mContext.getTheme().resolveAttribute(attrId, out, true);
+ mAlert.setIcon(out.resourceId);
+ }
+
public void setInverseBackgroundForced(boolean forceInverseBackground) {
mAlert.setInverseBackgroundForced(forceInverseBackground);
}
@@ -399,7 +410,19 @@
P.mIcon = icon;
return this;
}
-
+
+ /**
+ * Set an icon as supplied by a theme attribute. e.g. android.R.attr.alertDialogIcon
+ *
+ * @param attrId ID of a theme attribute that points to a drawable resource.
+ */
+ public Builder setIconAttribute(int attrId) {
+ TypedValue out = new TypedValue();
+ P.mContext.getTheme().resolveAttribute(attrId, out, true);
+ P.mIconId = out.resourceId;
+ return this;
+ }
+
/**
* Set a listener to be invoked when the positive button of the dialog is pressed.
* @param textId The resource id of the text to display in the positive button
diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java
index 72f7286..16d3a7f 100644
--- a/core/java/android/app/ContextImpl.java
+++ b/core/java/android/app/ContextImpl.java
@@ -485,6 +485,11 @@
}
@Override
+ public int getThemeResId() {
+ return mThemeResource;
+ }
+
+ @Override
public Resources.Theme getTheme() {
if (mTheme == null) {
if (mThemeResource == 0) {
diff --git a/core/java/android/app/DialogFragment.java b/core/java/android/app/DialogFragment.java
index bcd46d9..72a455e 100644
--- a/core/java/android/app/DialogFragment.java
+++ b/core/java/android/app/DialogFragment.java
@@ -211,7 +211,7 @@
*/
@Deprecated
public void show(Activity activity, String tag) {
- FragmentTransaction ft = activity.openFragmentTransaction();
+ FragmentTransaction ft = activity.getFragmentManager().openTransaction();
ft.add(this, tag);
ft.commit();
}
diff --git a/core/java/android/app/FragmentTransaction.java b/core/java/android/app/FragmentTransaction.java
index 5aec348..1b8debc 100644
--- a/core/java/android/app/FragmentTransaction.java
+++ b/core/java/android/app/FragmentTransaction.java
@@ -24,8 +24,8 @@
* @param fragment The fragment to be added. This fragment must not already
* be added to the activity.
* @param tag Optional tag name for the fragment, to later retrieve the
- * fragment with {@link Activity#findFragmentByTag(String)
- * Activity.findFragmentByTag(String)}.
+ * fragment with {@link FragmentManager#findFragmentByTag(String)
+ * FragmentManager.findFragmentByTag(String)}.
*
* @return Returns the same FragmentTransaction instance.
*/
@@ -47,8 +47,8 @@
* to be replaced.
* @param fragment The new fragment to place in the container.
* @param tag Optional tag name for the fragment, to later retrieve the
- * fragment with {@link Activity#findFragmentByTag(String)
- * Activity.findFragmentByTag(String)}.
+ * fragment with {@link FragmentManager#findFragmentByTag(String)
+ * FragmentManager.findFragmentByTag(String)}.
*
* @return Returns the same FragmentTransaction instance.
*/
diff --git a/core/java/android/bluetooth/BluetoothClass.java b/core/java/android/bluetooth/BluetoothClass.java
index e604e6b..54bf4af 100644
--- a/core/java/android/bluetooth/BluetoothClass.java
+++ b/core/java/android/bluetooth/BluetoothClass.java
@@ -226,6 +226,24 @@
public static final int HEALTH_PULSE_OXIMETER = 0x0914;
public static final int HEALTH_PULSE_RATE = 0x0918;
public static final int HEALTH_DATA_DISPLAY = 0x091C;
+
+ // Devices in PERIPHERAL major class
+ /**
+ * @hide
+ */
+ public static final int PERIPHERAL_NON_KEYBOARD_NON_POINTING = 0x0500;
+ /**
+ * @hide
+ */
+ public static final int PERIPHERAL_KEYBOARD = 0x0540;
+ /**
+ * @hide
+ */
+ public static final int PERIPHERAL_POINTING = 0x0580;
+ /**
+ * @hide
+ */
+ public static final int PERIPHERAL_KEYBOARD_POINTING = 0x05C0;
}
/**
diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java
index e15d003..24217d7 100644
--- a/core/java/android/bluetooth/BluetoothDevice.java
+++ b/core/java/android/bluetooth/BluetoothDevice.java
@@ -239,7 +239,7 @@
public static final String EXTRA_PAIRING_VARIANT =
"android.bluetooth.device.extra.PAIRING_VARIANT";
/** @hide */
- public static final String EXTRA_PASSKEY = "android.bluetooth.device.extra.PASSKEY";
+ public static final String EXTRA_PAIRING_KEY = "android.bluetooth.device.extra.PAIRING_KEY";
/**
* Broadcast Action: This intent is used to broadcast the {@link UUID}
@@ -276,58 +276,113 @@
public static final String ACTION_PAIRING_CANCEL =
"android.bluetooth.device.action.PAIRING_CANCEL";
- /** A bond attempt succeeded
- * @hide */
+ /**
+ * A bond attempt succeeded
+ * @hide
+ */
public static final int BOND_SUCCESS = 0;
- /** A bond attempt failed because pins did not match, or remote device did
+
+ /**
+ * A bond attempt failed because pins did not match, or remote device did
* not respond to pin request in time
- * @hide */
+ * @hide
+ */
public static final int UNBOND_REASON_AUTH_FAILED = 1;
- /** A bond attempt failed because the other side explicitly rejected
+
+ /**
+ * A bond attempt failed because the other side explicitly rejected
* bonding
- * @hide */
+ * @hide
+ */
public static final int UNBOND_REASON_AUTH_REJECTED = 2;
- /** A bond attempt failed because we canceled the bonding process
- * @hide */
+
+ /**
+ * A bond attempt failed because we canceled the bonding process
+ * @hide
+ */
public static final int UNBOND_REASON_AUTH_CANCELED = 3;
- /** A bond attempt failed because we could not contact the remote device
- * @hide */
+
+ /**
+ * A bond attempt failed because we could not contact the remote device
+ * @hide
+ */
public static final int UNBOND_REASON_REMOTE_DEVICE_DOWN = 4;
- /** A bond attempt failed because a discovery is in progress
- * @hide */
+
+ /**
+ * A bond attempt failed because a discovery is in progress
+ * @hide
+ */
public static final int UNBOND_REASON_DISCOVERY_IN_PROGRESS = 5;
- /** A bond attempt failed because of authentication timeout
- * @hide */
+
+ /**
+ * A bond attempt failed because of authentication timeout
+ * @hide
+ */
public static final int UNBOND_REASON_AUTH_TIMEOUT = 6;
- /** A bond attempt failed because of repeated attempts
- * @hide */
+
+ /**
+ * A bond attempt failed because of repeated attempts
+ * @hide
+ */
public static final int UNBOND_REASON_REPEATED_ATTEMPTS = 7;
- /** A bond attempt failed because we received an Authentication Cancel
- * by remote end
- * @hide */
+
+ /**
+ * A bond attempt failed because we received an Authentication Cancel
+ * by remote end
+ * @hide
+ */
public static final int UNBOND_REASON_REMOTE_AUTH_CANCELED = 8;
- /** An existing bond was explicitly revoked
- * @hide */
+
+ /**
+ * An existing bond was explicitly revoked
+ * @hide
+ */
public static final int UNBOND_REASON_REMOVED = 9;
- /** The user will be prompted to enter a pin
- * @hide */
+ /**
+ * The user will be prompted to enter a pin
+ * @hide
+ */
public static final int PAIRING_VARIANT_PIN = 0;
- /** The user will be prompted to enter a passkey
- * @hide */
+
+ /**
+ * The user will be prompted to enter a passkey
+ * @hide
+ */
public static final int PAIRING_VARIANT_PASSKEY = 1;
- /** The user will be prompted to confirm the passkey displayed on the screen
- * @hide */
+
+ /**
+ * The user will be prompted to confirm the passkey displayed on the screen
+ * @hide
+ */
public static final int PAIRING_VARIANT_PASSKEY_CONFIRMATION = 2;
- /** The user will be prompted to accept or deny the incoming pairing request
- * @hide */
+
+ /**
+ * The user will be prompted to accept or deny the incoming pairing request
+ * @hide
+ */
public static final int PAIRING_VARIANT_CONSENT = 3;
- /** The user will be prompted to enter the passkey displayed on remote device
- * @hide */
+
+ /**
+ * The user will be prompted to enter the passkey displayed on remote device
+ * This is used for Bluetooth 2.1 pairing.
+ * @hide
+ */
public static final int PAIRING_VARIANT_DISPLAY_PASSKEY = 4;
- /** The user will be prompted to accept or deny the OOB pairing request
- * @hide */
- public static final int PAIRING_VARIANT_OOB_CONSENT = 5;
+
+ /**
+ * The user will be prompted to enter the PIN displayed on remote device.
+ * This is used for Bluetooth 2.0 pairing.
+ * @hide
+ */
+ public static final int PAIRING_VARIANT_DISPLAY_PIN = 5;
+
+ /**
+ * The user will be prompted to accept or deny the OOB pairing request
+ * @hide
+ */
+ public static final int PAIRING_VARIANT_OOB_CONSENT = 6;
+
/**
* Used as an extra field in {@link #ACTION_UUID} intents,
* Contains the {@link android.os.ParcelUuid}s of the remote device which
diff --git a/core/java/android/bluetooth/BluetoothDeviceProfileState.java b/core/java/android/bluetooth/BluetoothDeviceProfileState.java
index 80a80bd..21144f2 100644
--- a/core/java/android/bluetooth/BluetoothDeviceProfileState.java
+++ b/core/java/android/bluetooth/BluetoothDeviceProfileState.java
@@ -149,10 +149,6 @@
newState == BluetoothInputDevice.STATE_DISCONNECTED) {
sendMessage(TRANSITION_TO_STABLE);
}
- } else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
- Message msg = new Message();
- msg.what = AUTO_CONNECT_PROFILES;
- sendMessage(msg);
} else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
// This is technically not needed, but we can get stuck sometimes.
// For example, if incoming A2DP fails, we are not informed by Bluez
diff --git a/core/java/android/content/AsyncTaskLoader.java b/core/java/android/content/AsyncTaskLoader.java
index d6bc959..98710558 100644
--- a/core/java/android/content/AsyncTaskLoader.java
+++ b/core/java/android/content/AsyncTaskLoader.java
@@ -17,6 +17,13 @@
package android.content;
import android.os.AsyncTask;
+import android.os.Handler;
+import android.os.SystemClock;
+import android.util.TimeUtils;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.util.concurrent.CountDownLatch;
/**
* Abstract Loader that provides an {@link AsyncTask} to do the work.
@@ -24,57 +31,125 @@
* @param <D> the data type to be loaded.
*/
public abstract class AsyncTaskLoader<D> extends Loader<D> {
- final class LoadTask extends AsyncTask<Void, Void, D> {
- private D result;
+
+ private static final String TAG = "AsyncTaskLoader";
+
+ final class LoadTask extends AsyncTask<Void, Void, D> implements Runnable {
+
+ D result;
+ boolean waiting;
+
+ private CountDownLatch done = new CountDownLatch(1);
/* Runs on a worker thread */
@Override
protected D doInBackground(Void... params) {
- result = AsyncTaskLoader.this.loadInBackground();
+ result = AsyncTaskLoader.this.onLoadInBackground();
return result;
}
/* Runs on the UI thread */
@Override
protected void onPostExecute(D data) {
- AsyncTaskLoader.this.dispatchOnLoadComplete(this, data);
+ try {
+ AsyncTaskLoader.this.dispatchOnLoadComplete(this, data);
+ } finally {
+ done.countDown();
+ }
}
@Override
protected void onCancelled() {
- AsyncTaskLoader.this.onCancelled(result);
+ try {
+ AsyncTaskLoader.this.dispatchOnCancelled(this, result);
+ } finally {
+ done.countDown();
+ }
+ }
+
+ @Override
+ public void run() {
+ waiting = false;
+ AsyncTaskLoader.this.executePendingTask();
}
}
- LoadTask mTask;
+ volatile LoadTask mTask;
+ volatile LoadTask mCancellingTask;
+
+ long mUpdateThrottle;
+ long mLastLoadCompleteTime = -10000;
+ Handler mHandler;
public AsyncTaskLoader(Context context) {
super(context);
}
+ /**
+ * Set amount to throttle updates by. This is the minimum time from
+ * when the last {@link #onLoadInBackground()} call has completed until
+ * a new load is scheduled.
+ *
+ * @param delayMS Amount of delay, in milliseconds.
+ */
+ public void setUpdateThrottle(long delayMS) {
+ mUpdateThrottle = delayMS;
+ if (delayMS != 0) {
+ mHandler = new Handler();
+ }
+ }
+
@Override
protected void onForceLoad() {
super.onForceLoad();
cancelLoad();
mTask = new LoadTask();
- mTask.execute((Void[]) null);
+ executePendingTask();
}
/**
* Attempt to cancel the current load task. See {@link AsyncTask#cancel(boolean)}
- * for more info.
+ * for more info. Must be called on the main thread of the process.
*
- * @return <tt>false</tt> if the task could not be canceled,
+ * <p>Cancelling is not an immediate operation, since the load is performed
+ * in a background thread. If there is currently a load in progress, this
+ * method requests that the load be cancelled, and notes this is the case;
+ * once the background thread has completed its work its remaining state
+ * will be cleared. If another load request comes in during this time,
+ * it will be held until the cancelled load is complete.
+ *
+ * @return Returns <tt>false</tt> if the task could not be cancelled,
* typically because it has already completed normally, or
- * because {@link #startLoading()} hasn't been called, and
- * <tt>true</tt> otherwise
+ * because {@link #startLoading()} hasn't been called; returns
+ * <tt>true</tt> otherwise.
*/
public boolean cancelLoad() {
if (mTask != null) {
- boolean cancelled = mTask.cancel(false);
- mTask = null;
- return cancelled;
+ if (mCancellingTask != null) {
+ // There was a pending task already waiting for a previous
+ // one being canceled; just drop it.
+ if (mTask.waiting) {
+ mTask.waiting = false;
+ mHandler.removeCallbacks(mTask);
+ }
+ mTask = null;
+ return false;
+ } else if (mTask.waiting) {
+ // There is a task, but it is waiting for the time it should
+ // execute. We can just toss it.
+ mTask.waiting = false;
+ mHandler.removeCallbacks(mTask);
+ mTask = null;
+ return false;
+ } else {
+ boolean cancelled = mTask.cancel(false);
+ if (cancelled) {
+ mCancellingTask = mTask;
+ }
+ mTask = null;
+ return cancelled;
+ }
}
return false;
}
@@ -86,23 +161,98 @@
public void onCancelled(D data) {
}
+ void executePendingTask() {
+ if (mCancellingTask == null && mTask != null) {
+ if (mTask.waiting) {
+ mTask.waiting = false;
+ mHandler.removeCallbacks(mTask);
+ }
+ if (mUpdateThrottle > 0) {
+ long now = SystemClock.uptimeMillis();
+ if (now < (mLastLoadCompleteTime+mUpdateThrottle)) {
+ // Not yet time to do another load.
+ mTask.waiting = true;
+ mHandler.postAtTime(mTask, mLastLoadCompleteTime+mUpdateThrottle);
+ return;
+ }
+ }
+ mTask.execute((Void[]) null);
+ }
+ }
+
+ void dispatchOnCancelled(LoadTask task, D data) {
+ onCancelled(data);
+ if (mCancellingTask == task) {
+ mLastLoadCompleteTime = SystemClock.uptimeMillis();
+ mCancellingTask = null;
+ executePendingTask();
+ }
+ }
+
void dispatchOnLoadComplete(LoadTask task, D data) {
if (mTask != task) {
- onCancelled(data);
+ dispatchOnCancelled(task, data);
} else {
+ mLastLoadCompleteTime = SystemClock.uptimeMillis();
mTask = null;
deliverResult(data);
}
}
/**
- * Called on a worker thread to perform the actual load. Implementations should not deliver the
- * results directly, but should return them from this method, which will eventually end up
- * calling deliverResult on the UI thread. If implementations need to process
- * the results on the UI thread they may override deliverResult and do so
- * there.
- *
- * @return the result of the load
*/
public abstract D loadInBackground();
+
+ /**
+ * Called on a worker thread to perform the actual load. Implementations should not deliver the
+ * result directly, but should return them from this method, which will eventually end up
+ * calling {@link #deliverResult} on the UI thread. If implementations need to process
+ * the results on the UI thread they may override {@link #deliverResult} and do so
+ * there.
+ *
+ * @return Implementations must return the result of their load operation.
+ */
+ protected D onLoadInBackground() {
+ return loadInBackground();
+ }
+
+ /**
+ * Locks the current thread until the loader completes the current load
+ * operation. Returns immediately if there is no load operation running.
+ * Should not be called from the UI thread: calling it from the UI
+ * thread would cause a deadlock.
+ * <p>
+ * Use for testing only. <b>Never</b> call this from a UI thread.
+ */
+ public void waitForLoader() {
+ LoadTask task = mTask;
+ if (task != null) {
+ try {
+ task.done.await();
+ } catch (InterruptedException e) {
+ // Ignore
+ }
+ }
+ }
+
+ @Override
+ public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
+ super.dump(prefix, fd, writer, args);
+ if (mTask != null) {
+ writer.print(prefix); writer.print("mTask="); writer.print(mTask);
+ writer.print(" waiting="); writer.println(mTask.waiting);
+ }
+ if (mCancellingTask != null) {
+ writer.print(prefix); writer.print("mCancellingTask="); writer.print(mCancellingTask);
+ writer.print(" waiting="); writer.println(mCancellingTask.waiting);
+ }
+ if (mUpdateThrottle != 0) {
+ writer.print(prefix); writer.print("mUpdateThrottle=");
+ TimeUtils.formatDuration(mUpdateThrottle, writer);
+ writer.print(" mLastLoadCompleteTime=");
+ TimeUtils.formatDuration(mLastLoadCompleteTime,
+ SystemClock.uptimeMillis(), writer);
+ writer.println();
+ }
+ }
}
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index b128d31..227df21 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -227,6 +227,12 @@
*/
public abstract void setTheme(int resid);
+ /** @hide Needed for some internal implementation... not public because
+ * you can't assume this actually means anything. */
+ public int getThemeResId() {
+ return 0;
+ }
+
/**
* Return the Theme object associated with this Context.
*/
diff --git a/core/java/android/content/ContextWrapper.java b/core/java/android/content/ContextWrapper.java
index f8928e4..545144e 100644
--- a/core/java/android/content/ContextWrapper.java
+++ b/core/java/android/content/ContextWrapper.java
@@ -106,6 +106,12 @@
mBase.setTheme(resid);
}
+ /** @hide */
+ @Override
+ public int getThemeResId() {
+ return mBase.getThemeResId();
+ }
+
@Override
public Resources.Theme getTheme() {
return mBase.getTheme();
diff --git a/core/java/android/content/CursorLoader.java b/core/java/android/content/CursorLoader.java
index 8ab0973..38ebaf2 100644
--- a/core/java/android/content/CursorLoader.java
+++ b/core/java/android/content/CursorLoader.java
@@ -55,7 +55,7 @@
* Registers an observer to get notifications from the content provider
* when the cursor needs to be refreshed.
*/
- public void registerContentObserver(Cursor cursor, ContentObserver observer) {
+ void registerContentObserver(Cursor cursor, ContentObserver observer) {
cursor.registerContentObserver(mObserver);
}
diff --git a/core/java/android/content/Loader.java b/core/java/android/content/Loader.java
index ef81fe4..d63fe69 100644
--- a/core/java/android/content/Loader.java
+++ b/core/java/android/content/Loader.java
@@ -28,6 +28,13 @@
* they should monitor the source of their data and deliver new results when the contents
* change.
*
+ * <p><b>Note on threading:</b> Clients of loaders should as a rule perform
+ * any calls on to a Loader from the main thread of their process (that is,
+ * the thread the Activity callbacks and other things occur on). Subclasses
+ * of Loader (such as {@link AsyncTaskLoader}) will often perform their work
+ * in a separate thread, but when delivering their results this too should
+ * be done on the main thread.</p>
+ *
* <p>Subclasses generally must implement at least {@link #onStartLoading()},
* {@link #onStopLoading()}, {@link #onForceLoad()}, and {@link #onReset()}.
*
@@ -80,7 +87,7 @@
/**
* Sends the result of the load to the registered listener. Should only be called by subclasses.
*
- * Must be called from the UI thread.
+ * Must be called from the process's main thread.
*
* @param data the result of the load
*/
@@ -105,10 +112,11 @@
}
/**
- * Registers a class that will receive callbacks when a load is complete. The callbacks will
- * be called on the UI thread so it's safe to pass the results to widgets.
+ * Registers a class that will receive callbacks when a load is complete.
+ * The callback will be called on the process's main thread so it's safe to
+ * pass the results to widgets.
*
- * Must be called from the UI thread
+ * <p>Must be called from the process's main thread.
*/
public void registerListener(int id, OnLoadCompleteListener<D> listener) {
if (mListener != null) {
@@ -119,7 +127,9 @@
}
/**
- * Must be called from the UI thread
+ * Remove a listener that was previously added with {@link #registerListener}.
+ *
+ * Must be called from the process's main thread.
*/
public void unregisterListener(OnLoadCompleteListener<D> listener) {
if (mListener == null) {
@@ -150,17 +160,19 @@
}
/**
- * Starts an asynchronous load of the contacts list data. When the result is ready the callbacks
- * will be called on the UI thread. If a previous load has been completed and is still valid
- * the result may be passed to the callbacks immediately. The loader will monitor the source of
- * the data set and may deliver future callbacks if the source changes. Calling
- * {@link #stopLoading} will stop the delivery of callbacks.
+ * Starts an asynchronous load of the Loader's data. When the result
+ * is ready the callbacks will be called on the process's main thread.
+ * If a previous load has been completed and is still valid
+ * the result may be passed to the callbacks immediately.
+ * The loader will monitor the source of
+ * the data set and may deliver future callbacks if the source changes.
+ * Calling {@link #stopLoading} will stop the delivery of callbacks.
*
* <p>This updates the Loader's internal state so that
* {@link #isStarted()} and {@link #isReset()} will return the correct
* values, and then calls the implementation's {@link #onStartLoading()}.
*
- * <p>Must be called from the UI thread.
+ * <p>Must be called from the process's main thread.
*/
public final void startLoading() {
mStarted = true;
@@ -182,14 +194,15 @@
* implementation's {@link #onForceLoad()}. You generally should only call this
* when the loader is started -- that is, {@link #isStarted()} returns true.
*
- * <p>Must be called from the UI thread.
+ * <p>Must be called from the process's main thread.
*/
- public final void forceLoad() {
+ public void forceLoad() {
onForceLoad();
}
/**
* Subclasses must implement this to take care of requests to {@link #forceLoad()}.
+ * This will always be called from the process's main thread.
*/
protected void onForceLoad() {
}
@@ -206,9 +219,9 @@
* {@link #isStarted()} will return the correct
* value, and then calls the implementation's {@link #onStopLoading()}.
*
- * <p>Must be called from the UI thread.
+ * <p>Must be called from the process's main thread.
*/
- public final void stopLoading() {
+ public void stopLoading() {
mStarted = false;
onStopLoading();
}
@@ -217,6 +230,7 @@
* Subclasses must implement this to take care of stopping their loader,
* as per {@link #stopLoading()}. This is not called by clients directly,
* but as a result of a call to {@link #stopLoading()}.
+ * This will always be called from the process's main thread.
*/
protected void onStopLoading() {
}
@@ -231,9 +245,9 @@
* {@link #isStarted()} and {@link #isReset()} will return the correct
* values, and then calls the implementation's {@link #onReset()}.
*
- * <p>Must be called from the UI thread.
+ * <p>Must be called from the process's main thread.
*/
- public final void reset() {
+ public void reset() {
onReset();
mReset = true;
mStarted = false;
@@ -244,6 +258,7 @@
* Subclasses must implement this to take care of resetting their loader,
* as per {@link #reset()}. This is not called by clients directly,
* but as a result of a call to {@link #reset()}.
+ * This will always be called from the process's main thread.
*/
protected void onReset() {
}
@@ -265,7 +280,7 @@
* if so, it simply calls {@link #forceLoad()}; otherwise, it sets a flag
* so that {@link #takeContentChanged()} returns true.
*
- * <p>Must be called from the UI thread.
+ * <p>Must be called from the process's main thread.
*/
public void onContentChanged() {
if (mStarted) {
diff --git a/core/java/android/content/SyncManager.java b/core/java/android/content/SyncManager.java
index 8b292c9..2fa2834 100644
--- a/core/java/android/content/SyncManager.java
+++ b/core/java/android/content/SyncManager.java
@@ -237,43 +237,7 @@
private BroadcastReceiver mConnectivityIntentReceiver =
new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
- NetworkInfo networkInfo =
- intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
- NetworkInfo.State state = (networkInfo == null ? NetworkInfo.State.UNKNOWN :
- networkInfo.getState());
- if (Log.isLoggable(TAG, Log.VERBOSE)) {
- Log.v(TAG, "received connectivity action. network info: " + networkInfo);
- }
-
- final boolean wasConnected = mDataConnectionIsConnected;
- // only pay attention to the CONNECTED and DISCONNECTED states.
- // if connected, we are connected.
- // if disconnected, we may not be connected. in some cases, we may be connected on
- // a different network.
- // e.g., if switching from GPRS to WiFi, we may receive the CONNECTED to WiFi and
- // DISCONNECTED for GPRS in any order. if we receive the CONNECTED first, and then
- // a DISCONNECTED, we want to make sure we set mDataConnectionIsConnected to true
- // since we still have a WiFi connection.
- switch (state) {
- case CONNECTED:
- mDataConnectionIsConnected = true;
- break;
- case DISCONNECTED:
- mDataConnectionIsConnected = !intent.getBooleanExtra(
- ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
- break;
- default:
- // ignore the rest of the states -- leave our boolean alone.
- }
- if (mDataConnectionIsConnected) {
- if (!wasConnected) {
- if (Log.isLoggable(TAG, Log.VERBOSE)) {
- Log.v(TAG, "Reconnection detected: clearing all backoffs");
- }
- mSyncStorageEngine.clearAllBackoffs();
- }
- sendCheckAlarmsMessage();
- }
+ sendCheckAlarmsMessage();
}
};
@@ -1409,8 +1373,12 @@
public void handleMessage(Message msg) {
long earliestFuturePollTime = Long.MAX_VALUE;
long nextPendingSyncTime = Long.MAX_VALUE;
+ // Setting the value here instead of a method because we want the dumpsys logs
+ // to have the most recent value used.
try {
waitUntilReadyToRun();
+ NetworkInfo networkInfo = getConnectivityManager().getActiveNetworkInfo();
+ mDataConnectionIsConnected = (networkInfo != null) && networkInfo.isConnected();
mSyncManagerWakeLock.acquire();
// Always do this first so that we be sure that any periodic syncs that
// are ready to run have been converted into pending syncs. This allows the
diff --git a/core/java/android/content/pm/ComponentInfo.java b/core/java/android/content/pm/ComponentInfo.java
index f16c4ef..2812477 100644
--- a/core/java/android/content/pm/ComponentInfo.java
+++ b/core/java/android/content/pm/ComponentInfo.java
@@ -98,6 +98,13 @@
}
return name;
}
+
+ /**
+ * Return whether this component and its enclosing application are enabled.
+ */
+ public boolean isEnabled() {
+ return enabled && applicationInfo.enabled;
+ }
/**
* Return the icon resource identifier to use for this component. If
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index ad74707..c8ca080 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -3086,7 +3086,11 @@
if (!sCompatibilityModeEnabled) {
ai.disableCompatibilityMode();
}
- ai.enabled = p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
+ if (p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
+ ai.enabled = true;
+ } else if (p.mSetEnabled == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
+ ai.enabled = false;
+ }
return ai;
}
diff --git a/core/java/android/database/BulkCursorToCursorAdaptor.java b/core/java/android/database/BulkCursorToCursorAdaptor.java
index 2cb2aec..16becf5 100644
--- a/core/java/android/database/BulkCursorToCursorAdaptor.java
+++ b/core/java/android/database/BulkCursorToCursorAdaptor.java
@@ -154,7 +154,10 @@
false /* the window will be accessed across processes */));
if (mCount != -1) {
mPos = -1;
- mWindow = null;
+ if (mWindow != null) {
+ mWindow.close();
+ mWindow = null;
+ }
// super.requery() will call onChanged. Do it here instead of relying on the
// observer from the far side so that observers can see a correct value for mCount
diff --git a/core/java/android/database/CursorWindow.java b/core/java/android/database/CursorWindow.java
index d15fb88..bd78063 100644
--- a/core/java/android/database/CursorWindow.java
+++ b/core/java/android/database/CursorWindow.java
@@ -17,12 +17,14 @@
package android.database;
import android.content.res.Resources;
+import android.database.sqlite.DatabaseObjectNotClosedException;
import android.database.sqlite.SQLiteClosable;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Process;
+import android.os.StrictMode;
import android.util.Log;
import android.util.SparseIntArray;
@@ -45,6 +47,7 @@
private int nWindow;
private int mStartPos;
+ private final Throwable mStackTrace;
/**
* Creates a new empty window.
@@ -56,6 +59,7 @@
int rslt = native_init(sCursorWindowSize, localWindow);
printDebugMsgIfError(rslt);
recordNewWindow(Binder.getCallingPid(), nWindow);
+ mStackTrace = new DatabaseObjectNotClosedException().fillInStackTrace();
}
private void printDebugMsgIfError(int rslt) {
@@ -561,7 +565,16 @@
@Override
protected void finalize() {
- // Just in case someone forgot to call close...
+ if (nWindow == 0) {
+ return;
+ }
+ if (StrictMode.vmSqliteObjectLeaksEnabled()) {
+ StrictMode.onSqliteObjectLeaked(
+ "Releasing cursor in a finalizer. Please ensure " +
+ "that you explicitly call close() on your cursor: ",
+ mStackTrace);
+ }
+ recordClosingOfWindow(nWindow);
close_native();
}
@@ -593,6 +606,7 @@
IBinder nativeBinder = source.readStrongBinder();
mStartPos = source.readInt();
int rslt = native_init(nativeBinder);
+ mStackTrace = new DatabaseObjectNotClosedException().fillInStackTrace();
printDebugMsgIfError(rslt);
}
@@ -607,8 +621,7 @@
@Override
protected void onAllReferencesReleased() {
- int windowId = nWindow;
- recordClosingOfWindow(Binder.getCallingPid(), nWindow);
+ recordClosingOfWindow(nWindow);
close_native();
}
@@ -623,7 +636,7 @@
}
}
- private void recordClosingOfWindow(int pid, int window) {
+ private void recordClosingOfWindow(int window) {
synchronized (sWindowToPidMap) {
if (sWindowToPidMap.size() == 0) {
// this means we are not in the ContentProvider.
diff --git a/core/java/android/database/DatabaseUtils.java b/core/java/android/database/DatabaseUtils.java
index 70a7fb6..f428aad 100644
--- a/core/java/android/database/DatabaseUtils.java
+++ b/core/java/android/database/DatabaseUtils.java
@@ -311,7 +311,6 @@
/**
* Concatenates two SQL WHERE clauses, handling empty or null values.
- * @hide
*/
public static String concatenateWhere(String a, String b) {
if (TextUtils.isEmpty(a)) {
diff --git a/core/java/android/database/sqlite/SQLiteCursor.java b/core/java/android/database/sqlite/SQLiteCursor.java
index 5a6c667..4c2d123 100644
--- a/core/java/android/database/sqlite/SQLiteCursor.java
+++ b/core/java/android/database/sqlite/SQLiteCursor.java
@@ -407,15 +407,32 @@
mWindow.clear();
}
mPos = -1;
- SQLiteDatabase db = mQuery.mDatabase.getDatabaseHandle(mQuery.mSql);
+ SQLiteDatabase db = null;
+ try {
+ db = mQuery.mDatabase.getDatabaseHandle(mQuery.mSql);
+ } catch (IllegalStateException e) {
+ // for backwards compatibility, just return false
+ Log.w(TAG, "requery() failed " + e.getMessage(), e);
+ return false;
+ }
if (!db.equals(mQuery.mDatabase)) {
// since we need to use a different database connection handle,
// re-compile the query
- db.lock();
+ try {
+ db.lock();
+ } catch (IllegalStateException e) {
+ // for backwards compatibility, just return false
+ Log.w(TAG, "requery() failed " + e.getMessage(), e);
+ return false;
+ }
try {
// close the old mQuery object and open a new one
mQuery.close();
mQuery = new SQLiteQuery(db, mQuery);
+ } catch (IllegalStateException e) {
+ // for backwards compatibility, just return false
+ Log.w(TAG, "requery() failed " + e.getMessage(), e);
+ return false;
} finally {
db.unlock();
}
@@ -427,6 +444,10 @@
queryThreadLock();
try {
mQuery.requery();
+ } catch (IllegalStateException e) {
+ // for backwards compatibility, just return false
+ Log.w(TAG, "requery() failed " + e.getMessage(), e);
+ return false;
} finally {
queryThreadUnlock();
}
@@ -437,7 +458,13 @@
Log.v(TAG, "--- Requery()ed cursor " + this + ": " + mQuery);
}
- boolean result = super.requery();
+ boolean result = false;
+ try {
+ result = super.requery();
+ } catch (IllegalStateException e) {
+ // for backwards compatibility, just return false
+ Log.w(TAG, "requery() failed " + e.getMessage(), e);
+ }
if (Config.LOGV) {
long timeEnd = System.currentTimeMillis();
Log.v(TAG, "requery (" + (timeEnd - timeStart) + " ms): " + mDriver.toString());
diff --git a/core/java/android/database/sqlite/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java
index 57a18bc..b1c84a1 100644
--- a/core/java/android/database/sqlite/SQLiteDatabase.java
+++ b/core/java/android/database/sqlite/SQLiteDatabase.java
@@ -958,13 +958,7 @@
sBlockSize = new StatFs("/data").getBlockSize();
}
sqliteDatabase.setPageSize(sBlockSize);
- //STOPSHIP - uncomment the following line
- //sqliteDatabase.setJournalMode(path, "TRUNCATE");
- // STOPSHIP remove the following lines
- if (!path.equalsIgnoreCase(MEMORY_DB_PATH)) {
- sqliteDatabase.enableWriteAheadLogging();
- }
- // END STOPSHIP
+ sqliteDatabase.setJournalMode(path, "TRUNCATE");
// add this database to the list of databases opened in this process
synchronized(mActiveDatabases) {
diff --git a/core/java/android/database/sqlite/SQLiteStatement.java b/core/java/android/database/sqlite/SQLiteStatement.java
index 5e96928..c76cc6c 100644
--- a/core/java/android/database/sqlite/SQLiteStatement.java
+++ b/core/java/android/database/sqlite/SQLiteStatement.java
@@ -131,6 +131,10 @@
long retValue = native_1x1_long();
mDatabase.logTimeStat(mSql, timeStart);
return retValue;
+ } catch (SQLiteDoneException e) {
+ throw new SQLiteDoneException(
+ "expected 1 row from this query but query returned no data. check the query: " +
+ mSql);
} finally {
releaseAndUnlock();
}
@@ -150,6 +154,10 @@
String retValue = native_1x1_string();
mDatabase.logTimeStat(mSql, timeStart);
return retValue;
+ } catch (SQLiteDoneException e) {
+ throw new SQLiteDoneException(
+ "expected 1 row from this query but query returned no data. check the query: " +
+ mSql);
} finally {
releaseAndUnlock();
}
@@ -172,6 +180,10 @@
} catch (IOException ex) {
Log.e(TAG, "simpleQueryForBlobFileDescriptor() failed", ex);
return null;
+ } catch (SQLiteDoneException e) {
+ throw new SQLiteDoneException(
+ "expected 1 row from this query but query returned no data. check the query: " +
+ mSql);
} finally {
releaseAndUnlock();
}
diff --git a/core/java/android/hardware/Camera.java b/core/java/android/hardware/Camera.java
index d4bef75..207785c 100644
--- a/core/java/android/hardware/Camera.java
+++ b/core/java/android/hardware/Camera.java
@@ -27,6 +27,7 @@
import android.view.Surface;
import android.view.SurfaceHolder;
import android.graphics.ImageFormat;
+import android.graphics.SurfaceTexture;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
@@ -324,8 +325,10 @@
/**
* Sets the {@link Surface} to be used for live preview.
- * A surface is necessary for preview, and preview is necessary to take
- * pictures. The same surface can be re-set without harm.
+ * Either a surface or surface texture is necessary for preview, and
+ * preview is necessary to take pictures. The same surface can be re-set
+ * without harm. Setting a preview surface will un-set any preview surface
+ * texture that was set via {@link #setPreviewTexture}.
*
* <p>The {@link SurfaceHolder} must already contain a surface when this
* method is called. If you are using {@link android.view.SurfaceView},
@@ -357,6 +360,29 @@
private native final void setPreviewDisplay(Surface surface);
/**
+ * Sets the {@link SurfaceTexture} to be used for live preview.
+ * Either a surface or surface texture is necessary for preview, and
+ * preview is necessary to take pictures. The same surface texture can be
+ * re-set without harm. Setting a preview surface texture will un-set any
+ * preview surface that was set via {@link #setPreviewDisplay}.
+ *
+ * <p>This method must be called before {@link #startPreview()}. The
+ * one exception is that if the preview surface texture is not set (or set
+ * to null) before startPreview() is called, then this method may be called
+ * once with a non-null parameter to set the preview surface. (This allows
+ * camera setup and surface creation to happen in parallel, saving time.)
+ * The preview surface texture may not otherwise change while preview is
+ * running.
+ *
+ * @param surfaceTexture the {@link SurfaceTexture} to which the preview
+ * images are to be sent or null to remove the current preview surface
+ * texture
+ * @throws IOException if the method fails (for example, if the surface
+ * texture is unavailable or unsuitable).
+ */
+ public native final void setPreviewTexture(SurfaceTexture surfaceTexture);
+
+ /**
* Callback interface used to deliver copies of preview frames as
* they are displayed.
*
diff --git a/core/java/android/net/Downloads.java b/core/java/android/net/Downloads.java
index ddde5c1..ed6d103 100644
--- a/core/java/android/net/Downloads.java
+++ b/core/java/android/net/Downloads.java
@@ -196,7 +196,7 @@
* @return a boolean whether the download is successful.
*/
public boolean isSuccessful() {
- return android.provider.Downloads.Impl.isStatusCompleted(statusCode);
+ return android.provider.Downloads.Impl.isStatusSuccess(statusCode);
}
}
diff --git a/core/java/android/os/AsyncTask.java b/core/java/android/os/AsyncTask.java
index 9d5d742..9f7e31c 100644
--- a/core/java/android/os/AsyncTask.java
+++ b/core/java/android/os/AsyncTask.java
@@ -26,6 +26,7 @@
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
@@ -111,6 +112,15 @@
* computation finishes. The result of the background computation is passed to
* this step as a parameter.</li>
* </ol>
+ *
+ * <h2>Cancelling a task</h2>
+ * <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking
+ * this method will cause subsequent calls to {@link #isCancelled()} to return true.
+ * After invoking this method, {@link #onCancelled(Object)}, instead of
+ * {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])}
+ * returns. To ensure that a task is cancelled as quickly as possible, you should always
+ * check the return value of {@link #isCancelled()} periodically from
+ * {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p>
*
* <h2>Threading rules</h2>
* <p>There are a few threading rules that must be followed for this class to
@@ -157,7 +167,6 @@
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
- private static final int MESSAGE_POST_CANCEL = 0x3;
private static final InternalHandler sHandler = new InternalHandler();
@@ -165,6 +174,8 @@
private final FutureTask<Result> mFuture;
private volatile Status mStatus = Status.PENDING;
+
+ private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
/**
* Indicates the current status of the task. Each status will be set only once
@@ -196,52 +207,49 @@
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
+ mTaskInvoked.set(true);
+
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
- return doInBackground(mParams);
+ return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask<Result>(mWorker) {
-
- @Override
- protected void set(Result v) {
- super.set(v);
- if (isCancelled()) {
- Message message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
- new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
- message.sendToTarget();
- }
- }
-
@Override
protected void done() {
- Message message;
- Result result = null;
-
try {
- result = get();
+ final Result result = get();
+
+ postResultIfNotInvoked(result);
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
- message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
- new AsyncTaskResult<Result>(AsyncTask.this, (Result[]) null));
- message.sendToTarget();
- return;
+ postResultIfNotInvoked(null);
} catch (Throwable t) {
throw new RuntimeException("An error occured while executing "
+ "doInBackground()", t);
}
-
- message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
- new AsyncTaskResult<Result>(AsyncTask.this, result));
- message.sendToTarget();
}
};
}
+ private void postResultIfNotInvoked(Result result) {
+ final boolean wasTaskInvoked = mTaskInvoked.get();
+ if (!wasTaskInvoked) {
+ postResult(result);
+ }
+ }
+
+ private Result postResult(Result result) {
+ Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
+ new AsyncTaskResult<Result>(this, result));
+ message.sendToTarget();
+ return result;
+ }
+
/**
* Returns the current status of this task.
*
@@ -279,14 +287,16 @@
}
/**
- * Runs on the UI thread after {@link #doInBackground}. The
- * specified result is the value returned by {@link #doInBackground}
- * or null if the task was cancelled or an exception occurred.
+ * <p>Runs on the UI thread after {@link #doInBackground}. The
+ * specified result is the value returned by {@link #doInBackground}.</p>
+ *
+ * <p>This method won't be invoked if the task was cancelled.</p>
*
* @param result The result of the operation computed by {@link #doInBackground}.
*
* @see #onPreExecute
* @see #doInBackground
+ * @see #onCancelled(Object)
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
@@ -306,8 +316,33 @@
}
/**
- * Runs on the UI thread after {@link #cancel(boolean)} is invoked.
+ * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
+ * {@link #doInBackground(Object[])} has finished.</p>
+ *
+ * <p>The default implementation simply invokes {@link #onCancelled()} and
+ * ignores the result. If you write your own implementation, do not call
+ * <code>super.onCancelled(result)</code>.</p>
*
+ * @param result The result, if any, computed in
+ * {@link #doInBackground(Object[])}, can be null
+ *
+ * @see #cancel(boolean)
+ * @see #isCancelled()
+ */
+ @SuppressWarnings({"UnusedParameters"})
+ protected void onCancelled(Result result) {
+ onCancelled();
+ }
+
+ /**
+ * <p>Applications should preferably override {@link #onCancelled(Object)}.
+ * This method is invoked by the default implementation of
+ * {@link #onCancelled(Object)}.</p>
+ *
+ * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
+ * {@link #doInBackground(Object[])} has finished.</p>
+ *
+ * @see #onCancelled(Object)
* @see #cancel(boolean)
* @see #isCancelled()
*/
@@ -316,7 +351,9 @@
/**
* Returns <tt>true</tt> if this task was cancelled before it completed
- * normally.
+ * normally. If you are calling {@link #cancel(boolean)} on the task,
+ * the value returned by this method should be checked periodically from
+ * {@link #doInBackground(Object[])} to end the task as soon as possible.
*
* @return <tt>true</tt> if task was cancelled before it completed
*
@@ -327,14 +364,22 @@
}
/**
- * Attempts to cancel execution of this task. This attempt will
+ * <p>Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, already been cancelled,
* or could not be cancelled for some other reason. If successful,
* and this task has not started when <tt>cancel</tt> is called,
- * this task should never run. If the task has already started,
+ * this task should never run. If the task has already started,
* then the <tt>mayInterruptIfRunning</tt> parameter determines
* whether the thread executing this task should be interrupted in
- * an attempt to stop the task.
+ * an attempt to stop the task.</p>
+ *
+ * <p>Calling this method will result in {@link #onCancelled(Object)} being
+ * invoked on the UI thread after {@link #doInBackground(Object[])}
+ * returns. Calling this method guarantees that {@link #onPostExecute(Object)}
+ * is never invoked. After invoking this method, you should check the
+ * value returned by {@link #isCancelled()} periodically from
+ * {@link #doInBackground(Object[])} to finish the task as early as
+ * possible.</p>
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
@@ -345,7 +390,7 @@
* <tt>true</tt> otherwise
*
* @see #isCancelled()
- * @see #onCancelled()
+ * @see #onCancelled(Object)
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
return mFuture.cancel(mayInterruptIfRunning);
@@ -444,8 +489,11 @@
}
private void finish(Result result) {
- if (isCancelled()) result = null;
- onPostExecute(result);
+ if (isCancelled()) {
+ onCancelled(result);
+ } else {
+ onPostExecute(result);
+ }
mStatus = Status.FINISHED;
}
@@ -462,9 +510,6 @@
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
- case MESSAGE_POST_CANCEL:
- result.mTask.onCancelled();
- break;
}
}
}
diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java
index 4688847..4f188f8 100644
--- a/core/java/android/os/Environment.java
+++ b/core/java/android/os/Environment.java
@@ -414,8 +414,6 @@
* emulated. If true, the device does not have real external storage
* and certain system services such as the package manager use this
* to determine where to install an application.
- *
- * @hide
*/
public static boolean isExternalStorageEmulated() {
if (mIsExternalStorageEmulated == null) {
diff --git a/core/java/android/provider/ContactsContract.java b/core/java/android/provider/ContactsContract.java
index d1ca0c9..ee091f0 100644
--- a/core/java/android/provider/ContactsContract.java
+++ b/core/java/android/provider/ContactsContract.java
@@ -3430,12 +3430,6 @@
* <th colspan='4'>PhoneLookup</th>
* </tr>
* <tr>
- * <td>long</td>
- * <td>{@link #_ID}</td>
- * <td>read-only</td>
- * <td>Data row ID.</td>
- * </tr>
- * <tr>
* <td>String</td>
* <td>{@link #NUMBER}</td>
* <td>read-only</td>
@@ -3462,6 +3456,12 @@
* <th colspan='4'>Join with {@link Contacts}</th>
* </tr>
* <tr>
+ * <td>long</td>
+ * <td>{@link #_ID}</td>
+ * <td>read-only</td>
+ * <td>Contact ID.</td>
+ * </tr>
+ * <tr>
* <td>String</td>
* <td>{@link #LOOKUP_KEY}</td>
* <td>read-only</td>
diff --git a/core/java/android/provider/MediaStore.java b/core/java/android/provider/MediaStore.java
index fb4bed7..9f0ea32 100644
--- a/core/java/android/provider/MediaStore.java
+++ b/core/java/android/provider/MediaStore.java
@@ -1028,6 +1028,13 @@
public static final String ALBUM_ARTIST = "album_artist";
/**
+ * Whether the song is part of a compilation
+ * <P>Type: TEXT</P>
+ * @hide
+ */
+ public static final String COMPILATION = "compilation";
+
+ /**
* A non human readable key calculated from the ARTIST, used for
* searching, sorting and grouping
* <P>Type: TEXT</P>
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 873674d2..cec99e9 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -3244,8 +3244,8 @@
/**
* Minimum percentage of free storage on the device that is used to determine if
- * the device is running low on storage.
- * Say this value is set to 10, the device is considered running low on storage
+ * the device is running low on storage. The default is 10.
+ * <p>Say this value is set to 10, the device is considered running low on storage
* if 90% or more of the device storage is filled up.
* @hide
*/
@@ -3253,6 +3253,16 @@
"sys_storage_threshold_percentage";
/**
+ * Maximum byte size of the low storage threshold. This is to ensure
+ * that {@link #SYS_STORAGE_THRESHOLD_PERCENTAGE} does not result in
+ * an overly large threshold for large storage devices. Currently this
+ * must be less than 2GB. This default is 500MB.
+ * @hide
+ */
+ public static final String SYS_STORAGE_THRESHOLD_MAX_BYTES =
+ "sys_storage_threshold_max_bytes";
+
+ /**
* Minimum bytes of free storage on the device before the data
* partition is considered full. By default, 1 MB is reserved
* to avoid system-wide SQLite disk full exceptions.
diff --git a/core/java/android/server/BluetoothEventLoop.java b/core/java/android/server/BluetoothEventLoop.java
index c04bb52..ae729d2d 100644
--- a/core/java/android/server/BluetoothEventLoop.java
+++ b/core/java/android/server/BluetoothEventLoop.java
@@ -493,7 +493,7 @@
mWakeLock.acquire();
Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mAdapter.getRemoteDevice(address));
- intent.putExtra(BluetoothDevice.EXTRA_PASSKEY, passkey);
+ intent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, passkey);
intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION);
mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
@@ -523,6 +523,9 @@
String pendingOutgoingAddress =
mBluetoothService.getPendingOutgoingBonding();
+ BluetoothClass btClass = new BluetoothClass(mBluetoothService.getRemoteClass(address));
+ int btDeviceClass = btClass.getDeviceClass();
+
if (address.equals(pendingOutgoingAddress)) {
// we initiated the bonding
@@ -533,10 +536,8 @@
return;
}
- BluetoothClass btClass = new BluetoothClass(mBluetoothService.getRemoteClass(address));
-
// try 0000 once if the device looks dumb
- switch (btClass.getDeviceClass()) {
+ switch (btDeviceClass) {
case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET:
case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
case BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES:
@@ -546,6 +547,27 @@
if (mBluetoothService.attemptAutoPair(address)) return;
}
}
+
+ // STOPSHIP: Hack for MOT keyboards
+ boolean motKeyboard = false;
+ String name = mBluetoothService.getRemoteName(address);
+ if (name == null && address.startsWith("00:0F:F6") ||
+ (name != null && name.startsWith("Motorola"))) {
+ motKeyboard = true;
+ }
+
+ if (!motKeyboard) {
+ if (btDeviceClass == BluetoothClass.Device.PERIPHERAL_KEYBOARD ||
+ btDeviceClass == BluetoothClass.Device.PERIPHERAL_KEYBOARD_POINTING) {
+ // Its a keyboard. Follow the HID spec recommendation of creating the
+ // passkey and displaying it to the user.
+ // Generate a variable PIN. This is not truly random but good enough.
+ int pin = (int) Math.floor(Math.random() * 10000);
+ sendDisplayPinIntent(address, pin);
+ return;
+ }
+ }
+
// Acquire wakelock during PIN code request to bring up LCD display
mWakeLock.acquire();
Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
@@ -565,7 +587,7 @@
mWakeLock.acquire();
Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mAdapter.getRemoteDevice(address));
- intent.putExtra(BluetoothDevice.EXTRA_PASSKEY, passkey);
+ intent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, passkey);
intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
BluetoothDevice.PAIRING_VARIANT_DISPLAY_PASSKEY);
mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
@@ -573,6 +595,19 @@
mWakeLock.release();
}
+ private void sendDisplayPinIntent(String address, int pin) {
+ // Acquire wakelock during PIN code request to bring up LCD display
+ mWakeLock.acquire();
+ Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST);
+ intent.putExtra(BluetoothDevice.EXTRA_DEVICE, mAdapter.getRemoteDevice(address));
+ intent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, pin);
+ intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT,
+ BluetoothDevice.PAIRING_VARIANT_DISPLAY_PIN);
+ mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM);
+ //Release wakelock to allow the LCD to go off after the PIN popup notifcation.
+ mWakeLock.release();
+ }
+
private void onRequestOobData(String objectPath , int nativeData) {
String address = checkPairingRequestAndGetAddress(objectPath, nativeData);
if (address == null) return;
diff --git a/core/java/android/util/CalendarUtils.java b/core/java/android/util/CalendarUtils.java
index 1b2a894..b2b4897 100644
--- a/core/java/android/util/CalendarUtils.java
+++ b/core/java/android/util/CalendarUtils.java
@@ -88,6 +88,12 @@
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
synchronized (mTZCallbacks) {
+ if (cursor == null) {
+ mTZQueryInProgress = false;
+ mFirstTZRequest = true;
+ return;
+ }
+
boolean writePrefs = false;
// Check the values in the db
int keyColumn = cursor.getColumnIndexOrThrow(CalendarCache.KEY);
diff --git a/core/java/android/util/JsonReader.java b/core/java/android/util/JsonReader.java
index 8025545..8f44895 100644
--- a/core/java/android/util/JsonReader.java
+++ b/core/java/android/util/JsonReader.java
@@ -16,6 +16,7 @@
package android.util;
+import java.io.EOFException;
import java.io.IOException;
import java.io.Reader;
import java.io.Closeable;
@@ -249,6 +250,13 @@
}
/**
+ * Returns true if this parser is liberal in what it accepts.
+ */
+ public boolean isLenient() {
+ return lenient;
+ }
+
+ /**
* Consumes the next token from the JSON stream and asserts that it is the
* beginning of a new array.
*/
@@ -311,7 +319,7 @@
case EMPTY_DOCUMENT:
replaceTop(JsonScope.NONEMPTY_DOCUMENT);
JsonToken firstToken = nextValue();
- if (token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
+ if (!lenient && token != JsonToken.BEGIN_ARRAY && token != JsonToken.BEGIN_OBJECT) {
throw new IOException(
"Expected JSON document to start with '[' or '{' but was " + token);
}
@@ -327,7 +335,15 @@
case NONEMPTY_OBJECT:
return nextInObject(false);
case NONEMPTY_DOCUMENT:
- return token = JsonToken.END_DOCUMENT;
+ try {
+ JsonToken token = nextValue();
+ if (lenient) {
+ return token;
+ }
+ throw syntaxError("Expected EOF");
+ } catch (EOFException e) {
+ return token = JsonToken.END_DOCUMENT; // TODO: avoid throwing here?
+ }
case CLOSED:
throw new IllegalStateException("JsonReader is closed");
default:
@@ -758,7 +774,7 @@
}
}
- throw syntaxError("End of input");
+ throw new EOFException("End of input");
}
private void checkLenient() throws IOException {
@@ -1030,8 +1046,6 @@
* form -12.34e+56. Fractional and exponential parts are optional. Leading
* zeroes are not allowed in the value or exponential part, but are allowed
* in the fraction.
- *
- * <p>This has a side effect of setting isInteger.
*/
private JsonToken decodeNumber(char[] chars, int offset, int length) {
int i = offset;
@@ -1085,8 +1099,8 @@
* Throws a new IO exception with the given message and a context snippet
* with this reader's content.
*/
- public IOException syntaxError(String message) throws IOException {
- throw new JsonSyntaxException(message + " near " + getSnippet());
+ private IOException syntaxError(String message) throws IOException {
+ throw new MalformedJsonException(message + " near " + getSnippet());
}
private CharSequence getSnippet() {
@@ -1097,10 +1111,4 @@
snippet.append(buffer, pos, afterPos);
return snippet;
}
-
- private static class JsonSyntaxException extends IOException {
- private JsonSyntaxException(String s) {
- super(s);
- }
- }
}
diff --git a/core/java/android/util/JsonWriter.java b/core/java/android/util/JsonWriter.java
index 89cad79..47e84c5 100644
--- a/core/java/android/util/JsonWriter.java
+++ b/core/java/android/util/JsonWriter.java
@@ -138,6 +138,8 @@
*/
private String separator = ":";
+ private boolean lenient;
+
/**
* Creates a new instance that writes a JSON-encoded stream to {@code out}.
* For best performance, ensure {@link Writer} is buffered; wrapping in
@@ -169,6 +171,29 @@
}
/**
+ * Configure this writer to relax its syntax rules. By default, this writer
+ * only emits well-formed JSON as specified by <a
+ * href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>. Setting the writer
+ * to lenient permits the following:
+ * <ul>
+ * <li>Top-level values of any type. With strict writing, the top-level
+ * value must be an object or an array.
+ * <li>Numbers may be {@link Double#isNaN() NaNs} or {@link
+ * Double#isInfinite() infinities}.
+ * </ul>
+ */
+ public void setLenient(boolean lenient) {
+ this.lenient = lenient;
+ }
+
+ /**
+ * Returns true if this writer has relaxed syntax rules.
+ */
+ public boolean isLenient() {
+ return lenient;
+ }
+
+ /**
* Begins encoding a new array. Each call to this method must be paired with
* a call to {@link #endArray}.
*
@@ -306,11 +331,11 @@
* Encodes {@code value}.
*
* @param value a finite value. May not be {@link Double#isNaN() NaNs} or
- * {@link Double#isInfinite() infinities}.
+ * {@link Double#isInfinite() infinities} unless this writer is lenient.
* @return this writer.
*/
public JsonWriter value(double value) throws IOException {
- if (Double.isNaN(value) || Double.isInfinite(value)) {
+ if (!lenient && (Double.isNaN(value) || Double.isInfinite(value))) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
beforeValue(false);
@@ -330,6 +355,28 @@
}
/**
+ * Encodes {@code value}.
+ *
+ * @param value a finite value. May not be {@link Double#isNaN() NaNs} or
+ * {@link Double#isInfinite() infinities} unless this writer is lenient.
+ * @return this writer.
+ */
+ public JsonWriter value(Number value) throws IOException {
+ if (value == null) {
+ return nullValue();
+ }
+
+ String string = value.toString();
+ if (!lenient &&
+ (string.equals("-Infinity") || string.equals("Infinity") || string.equals("NaN"))) {
+ throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
+ }
+ beforeValue(false);
+ out.append(string);
+ return this;
+ }
+
+ /**
* Ensures all buffered data is written to the underlying {@link Writer}
* and flushes that writer.
*/
@@ -364,7 +411,6 @@
switch (c) {
case '"':
case '\\':
- case '/':
out.write('\\');
out.write(c);
break;
@@ -439,7 +485,7 @@
private void beforeValue(boolean root) throws IOException {
switch (peek()) {
case EMPTY_DOCUMENT: // first in document
- if (!root) {
+ if (!lenient && !root) {
throw new IllegalStateException(
"JSON must start with an array or an object.");
}
diff --git a/core/java/android/util/MalformedJsonException.java b/core/java/android/util/MalformedJsonException.java
new file mode 100644
index 0000000..63c19ff
--- /dev/null
+++ b/core/java/android/util/MalformedJsonException.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2011 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.util;
+
+import java.io.IOException;
+
+/**
+ * Thrown when a reader encounters malformed JSON. Some syntax errors can be
+ * ignored by calling {@link JsonReader#setLenient(boolean)}.
+ */
+public final class MalformedJsonException extends IOException {
+ private static final long serialVersionUID = 1L;
+
+ public MalformedJsonException(String message) {
+ super(message);
+ }
+}
diff --git a/core/java/android/view/ContextThemeWrapper.java b/core/java/android/view/ContextThemeWrapper.java
index ae938e7..be4152b 100644
--- a/core/java/android/view/ContextThemeWrapper.java
+++ b/core/java/android/view/ContextThemeWrapper.java
@@ -51,6 +51,12 @@
initializeTheme();
}
+ /** @hide */
+ @Override
+ public int getThemeResId() {
+ return mThemeResource;
+ }
+
@Override public Resources.Theme getTheme() {
if (mTheme != null) {
return mTheme;
diff --git a/core/java/android/view/GLES20Canvas.java b/core/java/android/view/GLES20Canvas.java
index 67b22fa..04a521e 100644
--- a/core/java/android/view/GLES20Canvas.java
+++ b/core/java/android/view/GLES20Canvas.java
@@ -85,7 +85,7 @@
protected void setupRenderer(boolean record) {
if (record) {
- mRenderer = nCreateDisplayListRenderer();
+ mRenderer = nGetDisplayListRenderer(mRenderer);
} else {
mRenderer = nCreateRenderer();
}
@@ -93,28 +93,33 @@
if (mRenderer == 0) {
throw new IllegalStateException("Could not create GLES20Canvas renderer");
} else {
- if (mFinalizer == null) {
- mFinalizer = new CanvasFinalizer(mRenderer);
- } else {
- mFinalizer.replaceNativeObject(mRenderer);
- }
+ mFinalizer = CanvasFinalizer.getFinalizer(mFinalizer, mRenderer);
}
}
- private native int nCreateRenderer();
- private native int nCreateDisplayListRenderer();
-
+ private native int nCreateRenderer();
+ private static native int nGetDisplayListRenderer(int renderer);
private static native void nDestroyRenderer(int renderer);
private static class CanvasFinalizer {
int mRenderer;
- CanvasFinalizer(int renderer) {
+ // Factory method returns new instance if old one is null, or old instance
+ // otherwise, destroying native renderer along the way as necessary
+ static CanvasFinalizer getFinalizer(CanvasFinalizer oldFinalizer, int renderer) {
+ if (oldFinalizer == null) {
+ return new CanvasFinalizer(renderer);
+ }
+ oldFinalizer.replaceNativeObject(renderer);
+ return oldFinalizer;
+ }
+
+ private CanvasFinalizer(int renderer) {
mRenderer = renderer;
}
- void replaceNativeObject(int newRenderer) {
- if (mRenderer != 0) {
+ private void replaceNativeObject(int newRenderer) {
+ if (mRenderer != 0 && newRenderer != mRenderer) {
nDestroyRenderer(mRenderer);
}
mRenderer = newRenderer;
@@ -122,7 +127,11 @@
@Override
protected void finalize() throws Throwable {
- replaceNativeObject(0);
+ try {
+ replaceNativeObject(0);
+ } finally {
+ super.finalize();
+ }
}
}
@@ -199,10 +208,10 @@
///////////////////////////////////////////////////////////////////////////
int getDisplayList() {
- return nCreateDisplayList(mRenderer);
+ return nGetDisplayList(mRenderer);
}
- private native int nCreateDisplayList(int renderer);
+ private native int nGetDisplayList(int renderer);
static void destroyDisplayList(int displayList) {
nDestroyDisplayList(displayList);
@@ -390,8 +399,11 @@
@Override
public int saveLayer(float left, float top, float right, float bottom, Paint paint,
int saveFlags) {
- int nativePaint = paint == null ? 0 : paint.mNativePaint;
- return nSaveLayer(mRenderer, left, top, right, bottom, nativePaint, saveFlags);
+ boolean hasColorFilter = paint != null && setupColorFilter(paint);
+ final int nativePaint = paint == null ? 0 : paint.mNativePaint;
+ int count = nSaveLayer(mRenderer, left, top, right, bottom, nativePaint, saveFlags);
+ if (hasColorFilter) nResetModifiers(mRenderer);
+ return count;
}
private native int nSaveLayer(int renderer, float left, float top, float right, float bottom,
diff --git a/core/java/android/view/GLES20DisplayList.java b/core/java/android/view/GLES20DisplayList.java
index bd18fdd..c548659 100644
--- a/core/java/android/view/GLES20DisplayList.java
+++ b/core/java/android/view/GLES20DisplayList.java
@@ -70,11 +70,7 @@
mRecorded = true;
mNativeDisplayList = mCanvas.getDisplayList();
- if (mFinalizer == null) {
- mFinalizer = new DisplayListFinalizer(mNativeDisplayList);
- } else {
- mFinalizer.replaceNativeObject(mNativeDisplayList);
- }
+ mFinalizer = DisplayListFinalizer.getFinalizer(mFinalizer, mNativeDisplayList);
}
}
@@ -86,12 +82,23 @@
private static class DisplayListFinalizer {
int mNativeDisplayList;
- DisplayListFinalizer(int nativeDisplayList) {
+ // Factory method returns new instance if old one is null, or old instance
+ // otherwise, destroying native display list along the way as necessary
+ static DisplayListFinalizer getFinalizer(DisplayListFinalizer oldFinalizer,
+ int nativeDisplayList) {
+ if (oldFinalizer == null) {
+ return new DisplayListFinalizer(nativeDisplayList);
+ }
+ oldFinalizer.replaceNativeObject(nativeDisplayList);
+ return oldFinalizer;
+ }
+
+ private DisplayListFinalizer(int nativeDisplayList) {
mNativeDisplayList = nativeDisplayList;
}
- void replaceNativeObject(int newNativeDisplayList) {
- if (mNativeDisplayList != 0) {
+ private void replaceNativeObject(int newNativeDisplayList) {
+ if (mNativeDisplayList != 0 && mNativeDisplayList != newNativeDisplayList) {
GLES20Canvas.destroyDisplayList(mNativeDisplayList);
}
mNativeDisplayList = newNativeDisplayList;
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 4c62358..32f0b14 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -58,7 +58,6 @@
import android.util.Pools;
import android.util.SparseArray;
import android.view.ContextMenu.ContextMenuInfo;
-import android.view.View.MeasureSpec;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityEventSource;
import android.view.accessibility.AccessibilityManager;
@@ -546,6 +545,10 @@
* subtree rooted by that node. When an animation is started, the framework will
* take care of redrawing the appropriate views until the animation completes.
* </p>
+ * <p>
+ * Starting with Android 3.0, the preferred way of animating views is to use the
+ * {@link android.animation} package APIs.
+ * </p>
*
* <a name="Security"></a>
* <h3>Security</h3>
@@ -569,6 +572,7 @@
* See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}.
* </p>
*
+ * @attr ref android.R.styleable#View_alpha
* @attr ref android.R.styleable#View_background
* @attr ref android.R.styleable#View_clickable
* @attr ref android.R.styleable#View_contentDescription
@@ -584,6 +588,7 @@
* @attr ref android.R.styleable#View_focusableInTouchMode
* @attr ref android.R.styleable#View_hapticFeedbackEnabled
* @attr ref android.R.styleable#View_keepScreenOn
+ * @attr ref android.R.styleable#View_layerType
* @attr ref android.R.styleable#View_longClickable
* @attr ref android.R.styleable#View_minHeight
* @attr ref android.R.styleable#View_minWidth
@@ -2152,6 +2157,69 @@
public static final int SCROLLBAR_POSITION_RIGHT = 2;
/**
+ * Indicates that the view does not have a layer.
+ *
+ * @see #getLayerType()
+ * @see #setLayerType(int, android.graphics.Paint)
+ * @see #LAYER_TYPE_SOFTWARE
+ * @see #LAYER_TYPE_HARDWARE
+ */
+ public static final int LAYER_TYPE_NONE = 0;
+
+ /**
+ * <p>Indicates that the view has a software layer. A software layer is backed
+ * by a bitmap and causes the view to be rendered using Android's software
+ * rendering pipeline, even if hardware acceleration is enabled.</p>
+ *
+ * <p>Software layers have various usages:</p>
+ * <p>When the application is not using hardware acceleration, a software layer
+ * is useful to apply a specific color filter and/or blending mode and/or
+ * translucency to a view and all its children.</p>
+ * <p>When the application is using hardware acceleration, a software layer
+ * is useful to render drawing primitives not supported by the hardware
+ * accelerated pipeline. It can also be used to cache a complex view tree
+ * into a texture and reduce the complexity of drawing operations. For instance,
+ * when animating a complex view tree with a translation, a software layer can
+ * be used to render the view tree only once.</p>
+ * <p>Software layers should be avoided when the affected view tree updates
+ * often. Every update will require to re-render the software layer, which can
+ * potentially be slow (particularly when hardware acceleration is turned on
+ * since the layer will have to be uploaded into a hardware texture after every
+ * update.)</p>
+ *
+ * @see #getLayerType()
+ * @see #setLayerType(int, android.graphics.Paint)
+ * @see #LAYER_TYPE_NONE
+ * @see #LAYER_TYPE_HARDWARE
+ */
+ public static final int LAYER_TYPE_SOFTWARE = 1;
+
+ /**
+ * <p>Indicates that the view has a hardware layer. A hardware layer is backed
+ * by a hardware specific texture (generally Frame Buffer Objects or FBO on
+ * OpenGL hardware) and causes the view to be rendered using Android's hardware
+ * rendering pipeline, but only if hardware acceleration is turned on for the
+ * view hierarchy. When hardware acceleration is turned off, hardware layers
+ * behave exactly as {@link #LAYER_TYPE_SOFTWARE software layers}.</p>
+ *
+ * <p>A hardware layer is useful to apply a specific color filter and/or
+ * blending mode and/or translucency to a view and all its children.</p>
+ * <p>A hardware layer can also be used to increase the rendering quality when
+ * rotation transformations are applied on a view. It can also be used to
+ * prevent potential clipping issues when applying 3D transforms on a view.</p>
+ *
+ * @see #getLayerType()
+ * @see #setLayerType(int, android.graphics.Paint)
+ * @see #LAYER_TYPE_NONE
+ * @see #LAYER_TYPE_SOFTWARE
+ */
+ public static final int LAYER_TYPE_HARDWARE = 2;
+
+ @ViewDebug.ExportedProperty(category = "drawing")
+ int mLayerType = LAYER_TYPE_NONE;
+ Paint mLayerPaint;
+
+ /**
* Simple constructor to use when creating a view from code.
*
* @param context The Context the view is running in, through which it can
@@ -2489,6 +2557,9 @@
case R.styleable.View_verticalScrollbarPosition:
mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
break;
+ case R.styleable.View_layerType:
+ setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
+ break;
}
}
@@ -5763,11 +5834,18 @@
}
/**
- * Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
- * completely transparent and 1 means the view is completely opaque.
+ * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is
+ * completely transparent and 1 means the view is completely opaque.</p>
+ *
+ * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is
+ * responsible for applying the opacity itself. Otherwise, calling this method is
+ * equivalent to calling {@link #setLayerType(int, android.graphics.Paint)} and
+ * setting a hardware layer.</p>
*
* @param alpha The opacity of the view.
*
+ * @see #setLayerType(int, android.graphics.Paint)
+ *
* @attr ref android.R.styleable#View_alpha
*/
public void setAlpha(float alpha) {
@@ -7747,18 +7825,107 @@
}
/**
+ * <p>Specifies the type of layer backing this view. The layer can be
+ * {@link #LAYER_TYPE_NONE disabled}, {@link #LAYER_TYPE_SOFTWARE software} or
+ * {@link #LAYER_TYPE_HARDWARE hardware}.</p>
+ *
+ * <p>A layer is associated with an optional {@link android.graphics.Paint}
+ * instance that controls how the layer is composed on screen. The following
+ * properties of the paint are taken into account when composing the layer:</p>
+ * <ul>
+ * <li>{@link android.graphics.Paint#getAlpha() Translucency (alpha)}</li>
+ * <li>{@link android.graphics.Paint#getXfermode() Blending mode}</li>
+ * <li>{@link android.graphics.Paint#getColorFilter() Color filter}</li>
+ * </ul>
+ *
+ * <p>If this view has an alpha value set to < 1.0 by calling
+ * {@link #setAlpha(float)}, the alpha value of the layer's paint is replaced by
+ * this view's alpha value. Calling {@link #setAlpha(float)} is therefore
+ * equivalent to setting a hardware layer on this view and providing a paint with
+ * the desired alpha value.<p>
+ *
+ * <p>Refer to the documentation of {@link #LAYER_TYPE_NONE disabled},
+ * {@link #LAYER_TYPE_SOFTWARE software} and {@link #LAYER_TYPE_HARDWARE hardware}
+ * for more information on when and how to use layers.</p>
+ *
+ * @param layerType The ype of layer to use with this view, must be one of
+ * {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
+ * {@link #LAYER_TYPE_HARDWARE}
+ * @param paint The paint used to compose the layer. This argument is optional
+ * and can be null. It is ignored when the layer type is
+ * {@link #LAYER_TYPE_NONE}
+ *
+ * @see #getLayerType()
+ * @see #LAYER_TYPE_NONE
+ * @see #LAYER_TYPE_SOFTWARE
+ * @see #LAYER_TYPE_HARDWARE
+ * @see #setAlpha(float)
+ *
+ * @attr ref android.R.styleable#View_layerType
+ */
+ public void setLayerType(int layerType, Paint paint) {
+ if (layerType < LAYER_TYPE_NONE || layerType > LAYER_TYPE_HARDWARE) {
+ throw new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, "
+ + "LAYER_TYPE_SOFTWARE or LAYER_TYPE_HARDWARE");
+ }
+
+ // Destroy any previous software drawing cache if needed
+ if (mLayerType == LAYER_TYPE_SOFTWARE && layerType != LAYER_TYPE_SOFTWARE) {
+ if (mDrawingCache != null) {
+ mDrawingCache.recycle();
+ mDrawingCache = null;
+ }
+
+ if (mUnscaledDrawingCache != null) {
+ mUnscaledDrawingCache.recycle();
+ mUnscaledDrawingCache = null;
+ }
+ }
+
+ mLayerType = layerType;
+ mLayerPaint = mLayerType == LAYER_TYPE_NONE ? null : paint;
+
+ invalidate();
+ }
+
+ /**
+ * Indicates what type of layer is currently associated with this view. By default
+ * a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
+ * Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
+ * for more information on the different types of layers.
+ *
+ * @return {@link #LAYER_TYPE_NONE}, {@link #LAYER_TYPE_SOFTWARE} or
+ * {@link #LAYER_TYPE_HARDWARE}
+ *
+ * @see #setLayerType(int, android.graphics.Paint)
+ * @see #LAYER_TYPE_NONE
+ * @see #LAYER_TYPE_SOFTWARE
+ * @see #LAYER_TYPE_HARDWARE
+ */
+ public int getLayerType() {
+ return mLayerType;
+ }
+
+ /**
* <p>Enables or disables the drawing cache. When the drawing cache is enabled, the next call
* to {@link #getDrawingCache()} or {@link #buildDrawingCache()} will draw the view in a
* bitmap. Calling {@link #draw(android.graphics.Canvas)} will not draw from the cache when
* the cache is enabled. To benefit from the cache, you must request the drawing cache by
* calling {@link #getDrawingCache()} and draw it on screen if the returned bitmap is not
* null.</p>
+ *
+ * <p>Enabling the drawing cache is similar to
+ * {@link #setLayerType(int, android.graphics.Paint) setting a layer} when hardware
+ * acceleration is turned off. When hardware acceleration is turned on enabling the
+ * drawing cache has either no effect or the cache used at drawing time is not a bitmap.
+ * This API can however be used to manually generate a bitmap copy of this view.</p>
*
* @param enabled true to enable the drawing cache, false otherwise
*
* @see #isDrawingCacheEnabled()
* @see #getDrawingCache()
* @see #buildDrawingCache()
+ * @see #setLayerType(int, android.graphics.Paint)
*/
public void setDrawingCacheEnabled(boolean enabled) {
setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED);
@@ -8077,7 +8244,8 @@
canvas.translate(-mScrollX, -mScrollY);
mPrivateFlags |= DRAWN;
- if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated) {
+ if (mAttachInfo == null || !mAttachInfo.mHardwareAccelerated ||
+ mLayerType != LAYER_TYPE_NONE) {
mPrivateFlags |= DRAWING_CACHE_VALID;
}
@@ -10314,17 +10482,17 @@
/**
* !!! TODO: real docs
*
- * The base class implementation makes the thumbnail the same size and appearance
+ * The base class implementation makes the shadow the same size and appearance
* as the view itself, and positions it with its center at the touch point.
*/
- public static class DragThumbnailBuilder {
+ public static class DragShadowBuilder {
private final WeakReference<View> mView;
/**
- * Construct a thumbnail builder object for use with the given view.
+ * Construct a shadow builder object for use with the given view.
* @param view
*/
- public DragThumbnailBuilder(View view) {
+ public DragShadowBuilder(View view) {
mView = new WeakReference<View>(view);
}
@@ -10333,56 +10501,57 @@
}
/**
- * Provide the draggable-thumbnail metrics for the operation: the dimensions of
- * the thumbnail image itself, and the point within that thumbnail that should
+ * Provide the draggable-shadow metrics for the operation: the dimensions of
+ * the shadow image itself, and the point within that shadow that should
* be centered under the touch location while dragging.
* <p>
- * The default implementation sets the dimensions of the thumbnail to be the
- * same as the dimensions of the View itself and centers the thumbnail under
+ * The default implementation sets the dimensions of the shadow to be the
+ * same as the dimensions of the View itself and centers the shadow under
* the touch point.
*
- * @param thumbnailSize The application should set the {@code x} member of this
- * parameter to the desired thumbnail width, and the {@code y} member to
+ * @param shadowSize The application should set the {@code x} member of this
+ * parameter to the desired shadow width, and the {@code y} member to
* the desired height.
- * @param thumbnailTouchPoint The application should set this point to be the
- * location within the thumbnail that should track directly underneath
+ * @param shadowTouchPoint The application should set this point to be the
+ * location within the shadow that should track directly underneath
* the touch point on the screen during a drag.
*/
- public void onProvideThumbnailMetrics(Point thumbnailSize, Point thumbnailTouchPoint) {
+ public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
final View view = mView.get();
if (view != null) {
- thumbnailSize.set(view.getWidth(), view.getHeight());
- thumbnailTouchPoint.set(thumbnailSize.x / 2, thumbnailSize.y / 2);
+ shadowSize.set(view.getWidth(), view.getHeight());
+ shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
} else {
Log.e(View.VIEW_LOG_TAG, "Asked for drag thumb metrics but no view");
}
}
/**
- * Draw the thumbnail image for the upcoming drag. The thumbnail canvas was
- * created with the dimensions supplied by the onProvideThumbnailMetrics()
- * callback.
+ * Draw the shadow image for the upcoming drag. The shadow canvas was
+ * created with the dimensions supplied by the
+ * {@link #onProvideShadowMetrics(Point, Point)} callback.
*
* @param canvas
*/
- public void onDrawThumbnail(Canvas canvas) {
+ public void onDrawShadow(Canvas canvas) {
final View view = mView.get();
if (view != null) {
view.draw(canvas);
} else {
- Log.e(View.VIEW_LOG_TAG, "Asked to draw drag thumb but no view");
+ Log.e(View.VIEW_LOG_TAG, "Asked to draw drag shadow but no view");
}
}
}
/**
- * Drag and drop. App calls startDrag(), then callbacks to the thumbnail builder's
- * onProvideThumbnailMetrics() and onDrawThumbnail() methods happen, then the drag
+ * Drag and drop. App calls startDrag(), then callbacks to the shadow builder's
+ * {@link DragShadowBuilder#onProvideShadowMetrics(Point, Point)} and
+ * {@link DragShadowBuilder#onDrawShadow(Canvas)} methods happen, then the drag
* operation is handed over to the OS.
* !!! TODO: real docs
*
* @param data !!! TODO
- * @param thumbBuilder !!! TODO
+ * @param shadowBuilder !!! TODO
* @param myWindowOnly When {@code true}, indicates that the drag operation should be
* restricted to the calling application. In this case only the calling application
* will see any DragEvents related to this drag operation.
@@ -10395,37 +10564,37 @@
* @return {@code true} if the drag operation was initiated successfully; {@code false} if
* an error prevented the drag from taking place.
*/
- public final boolean startDrag(ClipData data, DragThumbnailBuilder thumbBuilder,
+ public final boolean startDrag(ClipData data, DragShadowBuilder shadowBuilder,
boolean myWindowOnly, Object myLocalState) {
if (ViewDebug.DEBUG_DRAG) {
Log.d(VIEW_LOG_TAG, "startDrag: data=" + data + " local=" + myWindowOnly);
}
boolean okay = false;
- Point thumbSize = new Point();
- Point thumbTouchPoint = new Point();
- thumbBuilder.onProvideThumbnailMetrics(thumbSize, thumbTouchPoint);
+ Point shadowSize = new Point();
+ Point shadowTouchPoint = new Point();
+ shadowBuilder.onProvideShadowMetrics(shadowSize, shadowTouchPoint);
- if ((thumbSize.x < 0) || (thumbSize.y < 0) ||
- (thumbTouchPoint.x < 0) || (thumbTouchPoint.y < 0)) {
- throw new IllegalStateException("Drag thumb dimensions must not be negative");
+ if ((shadowSize.x < 0) || (shadowSize.y < 0) ||
+ (shadowTouchPoint.x < 0) || (shadowTouchPoint.y < 0)) {
+ throw new IllegalStateException("Drag shadow dimensions must not be negative");
}
if (ViewDebug.DEBUG_DRAG) {
- Log.d(VIEW_LOG_TAG, "drag thumb: width=" + thumbSize.x + " height=" + thumbSize.y
- + " thumbX=" + thumbTouchPoint.x + " thumbY=" + thumbTouchPoint.y);
+ Log.d(VIEW_LOG_TAG, "drag shadow: width=" + shadowSize.x + " height=" + shadowSize.y
+ + " shadowX=" + shadowTouchPoint.x + " shadowY=" + shadowTouchPoint.y);
}
Surface surface = new Surface();
try {
IBinder token = mAttachInfo.mSession.prepareDrag(mAttachInfo.mWindow,
- myWindowOnly, thumbSize.x, thumbSize.y, surface);
+ myWindowOnly, shadowSize.x, shadowSize.y, surface);
if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "prepareDrag returned token=" + token
+ " surface=" + surface);
if (token != null) {
Canvas canvas = surface.lockCanvas(null);
try {
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
- thumbBuilder.onDrawThumbnail(canvas);
+ shadowBuilder.onDrawShadow(canvas);
} finally {
surface.unlockCanvasAndPost(canvas);
}
@@ -10435,12 +10604,12 @@
// Cache the local state object for delivery with DragEvents
root.setLocalDragState(myLocalState);
- // repurpose 'thumbSize' for the last touch point
- root.getLastTouchPoint(thumbSize);
+ // repurpose 'shadowSize' for the last touch point
+ root.getLastTouchPoint(shadowSize);
okay = mAttachInfo.mSession.performDrag(mAttachInfo.mWindow, token,
- thumbSize.x, thumbSize.y,
- thumbTouchPoint.x, thumbTouchPoint.y, data);
+ shadowSize.x, shadowSize.y,
+ shadowTouchPoint.x, shadowTouchPoint.y, data);
if (ViewDebug.DEBUG_DRAG) Log.d(VIEW_LOG_TAG, "performDrag returned " + okay);
}
} catch (Exception e) {
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 58fadb9..7af611e 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -129,6 +129,19 @@
private int[] mTmpPointerIds;
private MotionEvent.PointerCoords[] mTmpPointerCoords;
+ // For debugging only. You can see these in hierarchyviewer.
+ @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
+ @ViewDebug.ExportedProperty(category = "events")
+ private long mLastTouchDownTime;
+ @ViewDebug.ExportedProperty(category = "events")
+ private int mLastTouchDownIndex = -1;
+ @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
+ @ViewDebug.ExportedProperty(category = "events")
+ private float mLastTouchDownX;
+ @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
+ @ViewDebug.ExportedProperty(category = "events")
+ private float mLastTouchDownY;
+
/**
* Internal flags.
*
@@ -1157,6 +1170,10 @@
resetCancelNextUpFlag(child);
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
+ mLastTouchDownTime = ev.getDownTime();
+ mLastTouchDownIndex = i;
+ mLastTouchDownX = ev.getX();
+ mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
@@ -2161,11 +2178,15 @@
boolean concatMatrix = false;
boolean scalingRequired = false;
- boolean caching = false;
+ boolean caching;
+ final int layerType = child.getLayerType();
+
if ((flags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE ||
(flags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE) {
caching = true;
if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
+ } else {
+ caching = layerType != LAYER_TYPE_NONE;
}
if (a != null) {
@@ -2256,9 +2277,17 @@
Bitmap cache = null;
if (caching) {
if (!canvas.isHardwareAccelerated()) {
+ if (layerType != LAYER_TYPE_NONE) {
+ child.buildDrawingCache(true);
+ }
cache = child.getDrawingCache(true);
} else {
- displayList = child.getDisplayList();
+ if (layerType == LAYER_TYPE_SOFTWARE) {
+ child.buildDrawingCache(true);
+ cache = child.getDrawingCache(true);
+ } else {
+ displayList = child.getDisplayList();
+ }
}
}
@@ -2276,6 +2305,8 @@
canvas.scale(scale, scale);
}
}
+
+ boolean layerSaved = false;
if (transformToApply != null || alpha < 1.0f || !child.hasIdentityMatrix()) {
if (transformToApply != null || !childHasIdentityMatrix) {
@@ -2317,12 +2348,24 @@
final int multipliedAlpha = (int) (255 * alpha);
if (!child.onSetAlpha(multipliedAlpha)) {
int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
- if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
+ if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN ||
+ layerType != LAYER_TYPE_NONE) {
layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
}
- canvas.saveLayerAlpha(sx, sy, sx + cr - cl, sy + cb - ct, multipliedAlpha,
- layerFlags);
+ if (layerType != LAYER_TYPE_NONE && child.mLayerPaint != null) {
+ child.mLayerPaint.setAlpha(multipliedAlpha);
+ canvas.saveLayer(sx, sy, sx + cr - cl, sy + cb - ct,
+ child.mLayerPaint, layerFlags);
+ } else {
+ canvas.saveLayerAlpha(sx, sy, sx + cr - cl, sy + cb - ct,
+ multipliedAlpha, layerFlags);
+ }
+ layerSaved = true;
} else {
+ // Alpha is handled by the child directly, clobber the layer's alpha
+ if (layerType != LAYER_TYPE_NONE && child.mLayerPaint != null) {
+ child.mLayerPaint.setAlpha(255);
+ }
child.mPrivateFlags |= ALPHA_SET;
}
}
@@ -2345,6 +2388,10 @@
}
if (hasNoCache) {
+ if (!layerSaved && layerType == LAYER_TYPE_HARDWARE) {
+ canvas.saveLayer(sx, sy, sx + cr - cl, sy + cb - ct, child.mLayerPaint,
+ Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
+ }
if (!hasDisplayList) {
// Fast path for layouts with no backgrounds
if ((child.mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
@@ -2362,13 +2409,22 @@
}
} else if (cache != null) {
child.mPrivateFlags &= ~DIRTY_MASK;
- final Paint cachePaint = mCachePaint;
- if (alpha < 1.0f) {
- cachePaint.setAlpha((int) (alpha * 255));
- mGroupFlags |= FLAG_ALPHA_LOWER_THAN_ONE;
- } else if ((flags & FLAG_ALPHA_LOWER_THAN_ONE) == FLAG_ALPHA_LOWER_THAN_ONE) {
- cachePaint.setAlpha(255);
- mGroupFlags &= ~FLAG_ALPHA_LOWER_THAN_ONE;
+ Paint cachePaint;
+
+ if (layerType == LAYER_TYPE_NONE || child.mLayerPaint == null) {
+ cachePaint = mCachePaint;
+ if (alpha < 1.0f) {
+ cachePaint.setAlpha((int) (alpha * 255));
+ mGroupFlags |= FLAG_ALPHA_LOWER_THAN_ONE;
+ } else if ((flags & FLAG_ALPHA_LOWER_THAN_ONE) == FLAG_ALPHA_LOWER_THAN_ONE) {
+ cachePaint.setAlpha(255);
+ mGroupFlags &= ~FLAG_ALPHA_LOWER_THAN_ONE;
+ }
+ } else {
+ cachePaint = child.mLayerPaint;
+ if (alpha < 1.0f) {
+ cachePaint.setAlpha((int) (alpha * 255));
+ }
}
canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
}
@@ -2805,6 +2861,9 @@
}
children[index] = child;
mChildrenCount++;
+ if (mLastTouchDownIndex >= index) {
+ mLastTouchDownIndex++;
+ }
} else {
throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
}
@@ -2825,6 +2884,12 @@
} else {
throw new IndexOutOfBoundsException();
}
+ if (mLastTouchDownIndex == index) {
+ mLastTouchDownTime = 0;
+ mLastTouchDownIndex = -1;
+ } else if (mLastTouchDownIndex > index) {
+ mLastTouchDownIndex--;
+ }
}
// This method also sets the children's mParent to null
@@ -3330,7 +3395,7 @@
child.getAnimation() == null;
// Mark the child as dirty, using the appropriate flag
// Make sure we do not set both flags at the same time
- final int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY;
+ int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY;
final int[] location = attachInfo.mInvalidateChildLocation;
location[CHILD_LEFT_INDEX] = child.mLeft;
@@ -3361,8 +3426,14 @@
// If the parent is dirty opaque or not dirty, mark it dirty with the opaque
// flag coming from the child that initiated the invalidate
- if (view != null && (view.mPrivateFlags & DIRTY_MASK) != DIRTY) {
- view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag;
+ if (view != null) {
+ if ((view.mViewFlags & FADING_EDGE_MASK) != 0 &&
+ view.getSolidColor() == 0 && !view.isOpaque()) {
+ opaqueFlag = DIRTY;
+ }
+ if ((view.mPrivateFlags & DIRTY_MASK) != DIRTY) {
+ view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag;
+ }
}
parent = parent.invalidateChildInParent(location, dirty);
diff --git a/core/java/android/view/ViewRoot.java b/core/java/android/view/ViewRoot.java
index 366393c..7c55f7b 100644
--- a/core/java/android/view/ViewRoot.java
+++ b/core/java/android/view/ViewRoot.java
@@ -1073,11 +1073,6 @@
}
}
surfaceChanged = true;
-
- if (mAttachInfo.mHardwareRenderer != null) {
- // This will bail out early if already initialized
- mAttachInfo.mHardwareRenderer.initialize(mHolder);
- }
}
if (surfaceChanged) {
mSurfaceHolderCallback.surfaceChanged(mSurfaceHolder,
diff --git a/core/java/android/view/WindowManager.java b/core/java/android/view/WindowManager.java
index c435c43..c54a3cf 100644
--- a/core/java/android/view/WindowManager.java
+++ b/core/java/android/view/WindowManager.java
@@ -636,8 +636,33 @@
public static final int FLAG_SPLIT_TOUCH = 0x00800000;
/**
- * Indicates whether this window should be hardware accelerated.
- * Requesting hardware acceleration does not guarantee it will happen.
+ * <p>Indicates whether this window should be hardware accelerated.
+ * Requesting hardware acceleration does not guarantee it will happen.</p>
+ *
+ * <p>This flag can be controlled programmatically <em>only</em> to enable
+ * hardware acceleration. To enable hardware acceleration for a given
+ * window programmatically, do the following:</p>
+ *
+ * <pre>
+ * Window w = activity.getWindow(); // in Activity's onCreate() for instance
+ * w.setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
+ * WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
+ * </pre>
+ *
+ * <p>It is important to remember that this flag <strong>must</strong>
+ * be set before setting the content view of your activity or dialog.</p>
+ *
+ * <p>This flag cannot be used to disable hardware acceleration after it
+ * was enabled in your manifest using
+ * {@link android.R.attr#hardwareAccelerated}. If you need to selectively
+ * and programmatically disable hardware acceleration (for automated testing
+ * for instance), make sure it is turned off in your manifest and enable it
+ * on your activity or dialog when you need it instead, using the method
+ * described above.</p>
+ *
+ * <p>This flag is automatically set by the system if the
+ * {@link android.R.attr#hardwareAccelerated android:hardwareAccelerated}
+ * XML attribute is set to true on an activity or on the application.</p>
*/
public static final int FLAG_HARDWARE_ACCELERATED = 0x01000000;
diff --git a/core/java/android/view/WindowManagerPolicy.java b/core/java/android/view/WindowManagerPolicy.java
index 3479bf5..cb0a2a9 100644
--- a/core/java/android/view/WindowManagerPolicy.java
+++ b/core/java/android/view/WindowManagerPolicy.java
@@ -85,6 +85,17 @@
public final static boolean WATCH_POINTER = false;
+ /**
+ * Sticky broadcast of the current HDMI plugged state.
+ */
+ public final static String ACTION_HDMI_PLUGGED = "android.intent.action.HDMI_PLUGGED";
+
+ /**
+ * Extra in {@link #ACTION_HDMI_PLUGGED} indicating the state: true if
+ * plugged in to HDMI, false if not.
+ */
+ public final static String EXTRA_HDMI_PLUGGED_STATE = "state";
+
// flags for interceptKeyTq
/**
* Pass this event to the user / app. To be returned from {@link #interceptKeyTq}.
diff --git a/core/java/android/webkit/AccessibilityInjector.java b/core/java/android/webkit/AccessibilityInjector.java
index bb20fb6..5198a0e 100644
--- a/core/java/android/webkit/AccessibilityInjector.java
+++ b/core/java/android/webkit/AccessibilityInjector.java
@@ -71,6 +71,7 @@
private static final int ACTION_TRAVERSE_CURRENT_AXIS = 1;
private static final int ACTION_TRAVERSE_GIVEN_AXIS = 2;
private static final int ACTION_PERFORM_AXIS_TRANSITION = 3;
+ private static final int ACTION_TRAVERSE_DEFAULT_WEB_VIEW_BEHAVIOR_AXIS = 4;
// the default WebView behavior abstracted as a navigation axis
private static final int NAVIGATION_AXIS_DEFAULT_WEB_VIEW_BEHAVIOR = 7;
@@ -153,7 +154,6 @@
direction = binding.getFirstArgument(i);
// on second null selection string in same direction => WebView handle the event
if (direction == mLastDirection && mIsLastSelectionStringNull) {
- mLastDirection = direction;
mIsLastSelectionStringNull = false;
return false;
}
@@ -170,6 +170,22 @@
prefromAxisTransition(fromAxis, toAxis, sendEvent, contentDescription);
mLastDownEventHandled = true;
break;
+ case ACTION_TRAVERSE_DEFAULT_WEB_VIEW_BEHAVIOR_AXIS:
+ // This is a special case since we treat the default WebView navigation
+ // behavior as one of the possible navigation axis the user can use.
+ // If we are not on the default WebView navigation axis this is NOP.
+ if (mCurrentAxis == NAVIGATION_AXIS_DEFAULT_WEB_VIEW_BEHAVIOR) {
+ // While WebVew handles navigation we do not get null selection
+ // strings so do not check for that here as the cases above.
+ mLastDirection = binding.getFirstArgument(i);
+ sendEvent = (binding.getSecondArgument(i) == 1);
+ traverseGivenAxis(mLastDirection, NAVIGATION_AXIS_DEFAULT_WEB_VIEW_BEHAVIOR,
+ sendEvent, contentDescription);
+ mLastDownEventHandled = false;
+ } else {
+ mLastDownEventHandled = true;
+ }
+ break;
default:
Log.w(LOG_TAG, "Unknown action code: " + actionCode);
}
@@ -236,21 +252,26 @@
*/
private boolean traverseGivenAxis(int direction, int axis, boolean sendEvent,
String contentDescription) {
- // if the axis is the default let WebView handle the event
+ WebViewCore webViewCore = mWebView.getWebViewCore();
+ if (webViewCore == null) {
+ return false;
+ }
+
+ AccessibilityEvent event = null;
+ if (sendEvent) {
+ event = getPartialyPopulatedAccessibilityEvent();
+ // the text will be set upon receiving the selection string
+ event.setContentDescription(contentDescription);
+ }
+ mScheduledEventStack.push(event);
+
+ // if the axis is the default let WebView handle the event which will
+ // result in cursor ring movement and selection of its content
if (axis == NAVIGATION_AXIS_DEFAULT_WEB_VIEW_BEHAVIOR) {
return false;
}
- WebViewCore webViewCore = mWebView.getWebViewCore();
- if (webViewCore != null) {
- AccessibilityEvent event = null;
- if (sendEvent) {
- event = getPartialyPopulatedAccessibilityEvent();
- // the text will be set upon receiving the selection string
- event.setContentDescription(contentDescription);
- }
- mScheduledEventStack.push(event);
- webViewCore.sendMessage(EventHub.MODIFY_SELECTION, direction, axis);
- }
+
+ webViewCore.sendMessage(EventHub.MODIFY_SELECTION, direction, axis);
return true;
}
diff --git a/core/java/android/webkit/BrowserFrame.java b/core/java/android/webkit/BrowserFrame.java
index cdb6959..de1faa2 100644
--- a/core/java/android/webkit/BrowserFrame.java
+++ b/core/java/android/webkit/BrowserFrame.java
@@ -488,8 +488,10 @@
}
}
}
- WebViewWorker.getHandler().sendEmptyMessage(
- WebViewWorker.MSG_TRIM_CACHE);
+ if (!JniUtil.useChromiumHttpStack()) {
+ WebViewWorker.getHandler().sendEmptyMessage(
+ WebViewWorker.MSG_TRIM_CACHE);
+ }
break;
}
diff --git a/core/java/android/webkit/CacheLoader.java b/core/java/android/webkit/CacheLoader.java
index 05c02b0..0721045 100644
--- a/core/java/android/webkit/CacheLoader.java
+++ b/core/java/android/webkit/CacheLoader.java
@@ -18,6 +18,7 @@
import android.net.http.Headers;
import android.text.TextUtils;
+import android.webkit.JniUtil;
/**
* This class is a concrete implementation of StreamLoader that uses a
@@ -36,6 +37,9 @@
*/
CacheLoader(LoadListener loadListener, CacheManager.CacheResult result) {
super(loadListener);
+
+ assert !JniUtil.useChromiumHttpStack();
+
mCacheResult = result;
}
diff --git a/core/java/android/webkit/CacheManager.java b/core/java/android/webkit/CacheManager.java
index 9eecafa..e46daad 100644
--- a/core/java/android/webkit/CacheManager.java
+++ b/core/java/android/webkit/CacheManager.java
@@ -190,6 +190,11 @@
* @param context The application context.
*/
static void init(Context context) {
+ if (JniUtil.useChromiumHttpStack()) {
+ // TODO: Need to init mBaseDir.
+ return;
+ }
+
mDataBase = WebViewDatabase.getInstance(context.getApplicationContext());
mBaseDir = new File(context.getCacheDir(), "webviewCache");
if (createCacheDirectory() && mClearCacheOnInit) {
@@ -204,6 +209,8 @@
* @return true if the cache directory didn't exist and was created.
*/
static private boolean createCacheDirectory() {
+ assert !JniUtil.useChromiumHttpStack();
+
if (!mBaseDir.exists()) {
if(!mBaseDir.mkdirs()) {
Log.w(LOGTAG, "Unable to create webviewCache directory");
@@ -245,6 +252,8 @@
* @param disabled Whether the cache should be disabled
*/
static void setCacheDisabled(boolean disabled) {
+ assert !JniUtil.useChromiumHttpStack();
+
if (disabled == mDisabled) {
return;
}
@@ -269,6 +278,8 @@
// only called from WebViewWorkerThread
// make sure to call enableTransaction/disableTransaction in pair
static boolean enableTransaction() {
+ assert !JniUtil.useChromiumHttpStack();
+
if (++mRefCount == 1) {
mDataBase.startCacheTransaction();
return true;
@@ -279,6 +290,8 @@
// only called from WebViewWorkerThread
// make sure to call enableTransaction/disableTransaction in pair
static boolean disableTransaction() {
+ assert !JniUtil.useChromiumHttpStack();
+
if (--mRefCount == 0) {
mDataBase.endCacheTransaction();
return true;
@@ -289,12 +302,16 @@
// only called from WebViewWorkerThread
// make sure to call startTransaction/endTransaction in pair
static boolean startTransaction() {
+ assert !JniUtil.useChromiumHttpStack();
+
return mDataBase.startCacheTransaction();
}
// only called from WebViewWorkerThread
// make sure to call startTransaction/endTransaction in pair
static boolean endTransaction() {
+ assert !JniUtil.useChromiumHttpStack();
+
boolean ret = mDataBase.endCacheTransaction();
if (++mTrimCacheCount >= TRIM_CACHE_INTERVAL) {
mTrimCacheCount = 0;
@@ -347,8 +364,12 @@
return null;
}
- String databaseKey = getDatabaseKey(url, postIdentifier);
+ if (JniUtil.useChromiumHttpStack()) {
+ // TODO: Implement this.
+ return null;
+ }
+ String databaseKey = getDatabaseKey(url, postIdentifier);
CacheResult result = mDataBase.getCache(databaseKey);
if (result == null) {
return null;
@@ -415,6 +436,11 @@
@Deprecated
public static CacheResult createCacheFile(String url, int statusCode,
Headers headers, String mimeType, boolean forceCache) {
+ if (JniUtil.useChromiumHttpStack()) {
+ // TODO: Implement this.
+ return null;
+ }
+
return createCacheFile(url, statusCode, headers, mimeType, 0,
forceCache);
}
@@ -422,6 +448,8 @@
static CacheResult createCacheFile(String url, int statusCode,
Headers headers, String mimeType, long postIdentifier,
boolean forceCache) {
+ assert !JniUtil.useChromiumHttpStack();
+
if (!forceCache && mDisabled) {
return null;
}
@@ -493,6 +521,11 @@
return;
}
+ if (JniUtil.useChromiumHttpStack()) {
+ // TODO: Implement this.
+ return;
+ }
+
if (!cacheRet.outFile.exists()) {
// the file in the cache directory can be removed by the system
return;
@@ -520,6 +553,8 @@
}
static boolean cleanupCacheFile(CacheResult cacheRet) {
+ assert !JniUtil.useChromiumHttpStack();
+
try {
cacheRet.outStream.close();
} catch (IOException e) {
@@ -534,6 +569,8 @@
* @return Whether the removal succeeded.
*/
static boolean removeAllCacheFiles() {
+ assert !JniUtil.useChromiumHttpStack();
+
// Note, this is called before init() when the database is
// created or upgraded.
if (mBaseDir == null) {
@@ -570,6 +607,8 @@
}
static void trimCacheIfNeeded() {
+ assert !JniUtil.useChromiumHttpStack();
+
if (mDataBase.getCacheTotalSize() > CACHE_THRESHOLD) {
List<String> pathList = mDataBase.trimCache(CACHE_TRIM_AMOUNT);
int size = pathList.size();
@@ -603,6 +642,8 @@
}
static void clearCache() {
+ assert !JniUtil.useChromiumHttpStack();
+
// delete database
mDataBase.clearCache();
}
@@ -617,12 +658,16 @@
}
private static String getDatabaseKey(String url, long postIdentifier) {
+ assert !JniUtil.useChromiumHttpStack();
+
if (postIdentifier == 0) return url;
return postIdentifier + url;
}
@SuppressWarnings("deprecation")
private static void setupFiles(String url, CacheResult cacheRet) {
+ assert !JniUtil.useChromiumHttpStack();
+
if (true) {
// Note: SHA1 is much stronger hash. But the cost of setupFiles() is
// 3.2% cpu time for a fresh load of nytimes.com. While a simple
@@ -689,6 +734,8 @@
}
private static void appendAsHex(int i, StringBuffer ret) {
+ assert !JniUtil.useChromiumHttpStack();
+
String hex = Integer.toHexString(i);
switch (hex.length()) {
case 1:
@@ -718,6 +765,8 @@
private static CacheResult parseHeaders(int statusCode, Headers headers,
String mimeType) {
+ assert !JniUtil.useChromiumHttpStack();
+
// if the contentLength is already larger than CACHE_MAX_SIZE, skip it
if (headers.getContentLength() > CACHE_MAX_SIZE) return null;
@@ -734,8 +783,7 @@
CacheResult ret = new CacheResult();
ret.httpStatusCode = statusCode;
- String location = headers.getLocation();
- if (location != null) ret.location = location;
+ ret.location = headers.getLocation();
ret.expires = -1;
ret.expiresString = headers.getExpires();
@@ -754,15 +802,9 @@
}
}
- String contentDisposition = headers.getContentDisposition();
- if (contentDisposition != null) {
- ret.contentdisposition = contentDisposition;
- }
+ ret.contentdisposition = headers.getContentDisposition();
- String crossDomain = headers.getXPermittedCrossDomainPolicies();
- if (crossDomain != null) {
- ret.crossDomain = crossDomain;
- }
+ ret.crossDomain = headers.getXPermittedCrossDomainPolicies();
// lastModified and etag may be set back to http header. So they can't
// be empty string.
@@ -772,7 +814,9 @@
}
String etag = headers.getEtag();
- if (etag != null && etag.length() > 0) ret.etag = etag;
+ if (etag != null && etag.length() > 0) {
+ ret.etag = etag;
+ }
String cacheControl = headers.getCacheControl();
if (cacheControl != null) {
diff --git a/core/java/android/webkit/FindActionModeCallback.java b/core/java/android/webkit/FindActionModeCallback.java
index 842f6c8..a322fa3d 100644
--- a/core/java/android/webkit/FindActionModeCallback.java
+++ b/core/java/android/webkit/FindActionModeCallback.java
@@ -34,7 +34,7 @@
import android.view.inputmethod.InputMethodManager;
class FindActionModeCallback implements ActionMode.Callback, TextWatcher,
- View.OnLongClickListener {
+ View.OnLongClickListener, View.OnClickListener {
private View mCustomView;
private EditText mEditText;
private TextView mMatches;
@@ -53,6 +53,7 @@
// Override long click so that select ActionMode is not opened, which
// would exit find ActionMode.
mEditText.setOnLongClickListener(this);
+ mEditText.setOnClickListener(this);
setText("");
mMatches = (TextView) mCustomView.findViewById(
com.android.internal.R.id.matches);
@@ -105,7 +106,17 @@
throw new AssertionError(
"No WebView for FindActionModeCallback::findNext");
}
+ if (!mMatchesFound) {
+ findAll();
+ return;
+ }
+ if (0 == mNumberOfMatches) {
+ // There are no matches, so moving to the next match will not do
+ // anything.
+ return;
+ }
mWebView.findNext(next);
+ updateMatchesString();
}
/*
@@ -143,6 +154,7 @@
/*
* Update the string which tells the user how many matches were found, and
* which match is currently highlighted.
+ * Not to be called when mNumberOfMatches is 0.
*/
private void updateMatchesString() {
String template = mResources.getQuantityString(
@@ -157,6 +169,13 @@
@Override
public boolean onLongClick(View v) { return true; }
+ // OnClickListener implementation
+
+ @Override
+ public void onClick(View v) {
+ findNext(true);
+ }
+
// ActionMode.Callback implementation
@Override
@@ -192,10 +211,6 @@
"No WebView for FindActionModeCallback::onActionItemClicked");
}
mInput.hideSoftInputFromWindow(mWebView.getWindowToken(), 0);
- if (!mMatchesFound) {
- findAll();
- return true;
- }
switch(item.getItemId()) {
case com.android.internal.R.id.find_prev:
findNext(false);
@@ -206,7 +221,6 @@
default:
return false;
}
- updateMatchesString();
return true;
}
diff --git a/core/java/android/webkit/FrameLoader.java b/core/java/android/webkit/FrameLoader.java
index 951dab3..2b44775 100644
--- a/core/java/android/webkit/FrameLoader.java
+++ b/core/java/android/webkit/FrameLoader.java
@@ -22,6 +22,7 @@
import android.os.Build;
import android.util.Log;
import android.webkit.CacheManager.CacheResult;
+import android.webkit.JniUtil;
import java.util.HashMap;
import java.util.Map;
@@ -56,6 +57,8 @@
FrameLoader(LoadListener listener, WebSettings settings,
String method, WebResourceResponse interceptResponse) {
+ assert !JniUtil.useChromiumHttpStack();
+
mListener = listener;
mHeaders = null;
mMethod = method;
@@ -148,9 +151,10 @@
}
- /* package */
- static boolean handleLocalFile(String url, LoadListener loadListener,
+ private static boolean handleLocalFile(String url, LoadListener loadListener,
WebSettings settings) {
+ assert !JniUtil.useChromiumHttpStack();
+
// Attempt to decode the percent-encoded url before passing to the
// local loaders.
try {
diff --git a/core/java/android/webkit/LoadListener.java b/core/java/android/webkit/LoadListener.java
index a29299d..6d1d39a 100644
--- a/core/java/android/webkit/LoadListener.java
+++ b/core/java/android/webkit/LoadListener.java
@@ -35,6 +35,7 @@
import android.os.Message;
import android.util.Log;
import android.webkit.CacheManager.CacheResult;
+import android.webkit.JniUtil;
import com.android.internal.R;
@@ -156,6 +157,8 @@
int nativeLoader, boolean synchronous, boolean isMainPageLoader,
boolean isMainResource, boolean userGesture, long postIdentifier,
String username, String password) {
+ assert !JniUtil.useChromiumHttpStack();
+
if (DebugFlags.LOAD_LISTENER) {
Log.v(LOGTAG, "LoadListener constructor url=" + url);
}
@@ -991,6 +994,7 @@
* URL.
*/
static boolean willLoadFromCache(String url, long identifier) {
+ assert !JniUtil.useChromiumHttpStack();
boolean inCache =
CacheManager.getCacheFile(url, identifier, null) != null;
if (DebugFlags.LOAD_LISTENER) {
diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java
index aa80179..6750422 100644
--- a/core/java/android/webkit/WebSettings.java
+++ b/core/java/android/webkit/WebSettings.java
@@ -485,11 +485,12 @@
// default to "en"
buffer.append("en");
}
- buffer.append("; ");
+ buffer.append(";");
// add the model for the release build
if ("REL".equals(Build.VERSION.CODENAME)) {
final String model = Build.MODEL;
if (model.length() > 0) {
+ buffer.append(" ");
buffer.append(model);
}
}
@@ -657,10 +658,11 @@
}
/**
- * Return whether the WebView is saving form data.
+ * Return whether the WebView is saving form data and displaying prior
+ * entries/autofill++. Always false in private browsing mode.
*/
public boolean getSaveFormData() {
- return mSaveFormData;
+ return mSaveFormData && !mPrivateBrowsingEnabled;
}
/**
diff --git a/core/java/android/webkit/WebTextView.java b/core/java/android/webkit/WebTextView.java
index 4c2f0b4..1313fcc 100644
--- a/core/java/android/webkit/WebTextView.java
+++ b/core/java/android/webkit/WebTextView.java
@@ -204,11 +204,6 @@
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
- if (!mWebView.nativeCursorMatchesFocus()) {
- return down ? mWebView.onKeyDown(keyCode, event) : mWebView
- .onKeyUp(keyCode, event);
-
- }
isArrowKey = true;
break;
}
@@ -258,10 +253,6 @@
if (isPopupShowing()) {
return super.dispatchKeyEvent(event);
}
- if (!mWebView.nativeCursorMatchesFocus()) {
- return down ? mWebView.onKeyDown(keyCode, event) : mWebView
- .onKeyUp(keyCode, event);
- }
// Center key should be passed to a potential onClick
if (!down) {
mWebView.centerKeyPressOnTextField();
@@ -753,12 +744,7 @@
if (event.getAction() != MotionEvent.ACTION_MOVE) {
return false;
}
- // If the Cursor is not on the text input, webview should handle the
- // trackball
- if (!mWebView.nativeCursorMatchesFocus()) {
- return mWebView.onTrackballEvent(event);
- }
- Spannable text = (Spannable) getText();
+ Spannable text = getText();
MovementMethod move = getMovementMethod();
if (move != null && getLayout() != null &&
move.onTrackballEvent(this, text, event)) {
diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java
index bd268e1..4a9e441 100644
--- a/core/java/android/webkit/WebView.java
+++ b/core/java/android/webkit/WebView.java
@@ -56,6 +56,7 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
+import android.os.SystemClock;
import android.provider.Settings;
import android.speech.tts.TextToSpeech;
import android.text.Selection;
@@ -823,6 +824,11 @@
private static final long SELECT_SCROLL_INTERVAL = 1000 / 60; // 60 / second
private int mAutoScrollX = 0;
private int mAutoScrollY = 0;
+ private int mMinAutoScrollX = 0;
+ private int mMaxAutoScrollX = 0;
+ private int mMinAutoScrollY = 0;
+ private int mMaxAutoScrollY = 0;
+ private Rect mScrollingLayerBounds = new Rect();
private boolean mSentAutoScrollMessage = false;
// Used to notify listeners of a new picture.
@@ -2612,10 +2618,6 @@
private int computeRealHorizontalScrollRange() {
if (mDrawHistory) {
return mHistoryWidth;
- } else if (mHorizontalScrollBarMode == SCROLLBAR_ALWAYSOFF
- && !mZoomManager.canZoomOut()) {
- // only honor the scrollbar mode when it is at minimum zoom level
- return computeHorizontalScrollExtent();
} else {
// to avoid rounding error caused unnecessary scrollbar, use floor
return (int) Math.floor(mContentWidth * mZoomManager.getScale());
@@ -2646,10 +2648,6 @@
private int computeRealVerticalScrollRange() {
if (mDrawHistory) {
return mHistoryHeight;
- } else if (mVerticalScrollBarMode == SCROLLBAR_ALWAYSOFF
- && !mZoomManager.canZoomOut()) {
- // only honor the scrollbar mode when it is at minimum zoom level
- return computeVerticalScrollExtent();
} else {
// to avoid rounding error caused unnecessary scrollbar, use floor
return (int) Math.floor(mContentHeight * mZoomManager.getScale());
@@ -2956,12 +2954,12 @@
* @return boolean True if the find dialog is shown, false otherwise.
*/
public boolean showFindDialog(String text, boolean showIme) {
- mFindCallback = new FindActionModeCallback(mContext);
- if (startActionMode(mFindCallback) == null) {
+ FindActionModeCallback callback = new FindActionModeCallback(mContext);
+ if (startActionMode(callback) == null) {
// Could not start the action mode, so end Find on page
- mFindCallback = null;
return false;
}
+ mFindCallback = callback;
setFindIsUp(true);
mFindCallback.setWebView(this);
if (showIme) {
@@ -4540,36 +4538,52 @@
// Bubble up the key event if
// 1. it is a system key; or
// 2. the host application wants to handle it;
- // 3. the accessibility injector is present and wants to handle it;
if (event.isSystem()
- || mCallbackProxy.uiOverrideKeyEvent(event)
- || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) {
+ || mCallbackProxy.uiOverrideKeyEvent(event)) {
return false;
}
- // if an accessibility script is injected we delegate to it the key handling.
- // this script is a screen reader which is a fully fledged solution for blind
- // users to navigate in and interact with web pages.
+ // accessibility support
if (accessibilityScriptInjected()) {
+ // if an accessibility script is injected we delegate to it the key handling.
+ // this script is a screen reader which is a fully fledged solution for blind
+ // users to navigate in and interact with web pages.
mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
return true;
- }
-
- if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
- || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
- if (!nativePageShouldHandleShiftAndArrows() && !nativeCursorWantsKeyEvents()
- && !mSelectingText) {
- setUpSelect();
- }
+ } else if (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event)) {
+ // if an accessibility injector is present (no JavaScript enabled or the site opts
+ // out injecting our JavaScript screen reader) we let it decide whether to act on
+ // and consume the event.
+ return true;
}
if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
- pageUp(false);
- return true;
+ if (event.hasNoModifiers()) {
+ pageUp(false);
+ return true;
+ } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
+ pageUp(true);
+ return true;
+ }
}
if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
- pageDown(false);
+ if (event.hasNoModifiers()) {
+ pageDown(false);
+ return true;
+ } else if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
+ pageDown(true);
+ return true;
+ }
+ }
+
+ if (keyCode == KeyEvent.KEYCODE_MOVE_HOME && event.hasNoModifiers()) {
+ pageUp(true);
+ return true;
+ }
+
+ if (keyCode == KeyEvent.KEYCODE_MOVE_END && event.hasNoModifiers()) {
+ pageDown(true);
return true;
}
@@ -4580,6 +4594,22 @@
letPageHandleNavKey(keyCode, event.getEventTime(), true, event.getMetaState());
return true;
}
+ if (event.hasModifiers(KeyEvent.META_ALT_ON)) {
+ switch (keyCode) {
+ case KeyEvent.KEYCODE_DPAD_UP:
+ pageUp(true);
+ return true;
+ case KeyEvent.KEYCODE_DPAD_DOWN:
+ pageDown(true);
+ return true;
+ case KeyEvent.KEYCODE_DPAD_LEFT:
+ nativeClearCursor(); // start next trackball movement from page edge
+ return pinScrollTo(0, mScrollY, true, 0);
+ case KeyEvent.KEYCODE_DPAD_RIGHT:
+ nativeClearCursor(); // start next trackball movement from page edge
+ return pinScrollTo(mContentWidth, mScrollY, true, 0);
+ }
+ }
if (mSelectingText) {
int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
@@ -4599,6 +4629,8 @@
if (isEnterActionKey(keyCode)) {
switchOutDrawHistory();
+ boolean wantsKeyEvents = nativeCursorNodePointer() == 0
+ || nativeCursorWantsKeyEvents();
if (event.getRepeatCount() == 0) {
if (mSelectingText) {
return true; // discard press if copy in progress
@@ -4609,16 +4641,10 @@
// Already checked mNativeClass, so we do not need to check it
// again.
nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
- return true;
+ if (!wantsKeyEvents) return true;
}
// Bubble up the key event as WebView doesn't handle it
- return false;
- }
-
- if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
- && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
- // turn off copy select if a shift-key combo is pressed
- selectionDone();
+ if (!wantsKeyEvents) return false;
}
if (getSettings().getNavDump()) {
@@ -4700,27 +4726,23 @@
// Bubble up the key event if
// 1. it is a system key; or
// 2. the host application wants to handle it;
- // 3. the accessibility injector is present and wants to handle it;
if (event.isSystem()
- || mCallbackProxy.uiOverrideKeyEvent(event)
- || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) {
+ || mCallbackProxy.uiOverrideKeyEvent(event)) {
return false;
}
- // if an accessibility script is injected we delegate to it the key handling.
- // this script is a screen reader which is a fully fledged solution for blind
- // users to navigate in and interact with web pages.
+ // accessibility support
if (accessibilityScriptInjected()) {
+ // if an accessibility script is injected we delegate to it the key handling.
+ // this script is a screen reader which is a fully fledged solution for blind
+ // users to navigate in and interact with web pages.
mWebViewCore.sendMessage(EventHub.KEY_UP, event);
return true;
- }
-
- if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
- || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
- if (!nativePageShouldHandleShiftAndArrows() && copySelection()) {
- selectionDone();
- return true;
- }
+ } else if (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event)) {
+ // if an accessibility injector is present (no JavaScript enabled or the site opts
+ // out injecting our JavaScript screen reader) we let it decide whether to act on
+ // and consume the event.
+ return true;
}
if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
@@ -4771,11 +4793,14 @@
}
clearTextEntry();
nativeShowCursorTimed();
- if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
+ if (mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
+ return true;
+ }
+ if (nativeCursorNodePointer() != 0 && !nativeCursorWantsKeyEvents()) {
mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
nativeCursorNodePointer());
+ return true;
}
- return true;
}
// TODO: should we pass all the keys to DOM or check the meta tag
@@ -4824,6 +4849,31 @@
selectionDone();
return false;
}
+ mMinAutoScrollX = 0;
+ mMaxAutoScrollX = getViewWidth();
+ mMinAutoScrollY = 0;
+ mMaxAutoScrollY = getViewHeightWithTitle();
+ mScrollingLayer = nativeScrollableLayer(viewToContentX(mSelectX),
+ viewToContentY(mSelectY), mScrollingLayerRect,
+ mScrollingLayerBounds);
+ if (mScrollingLayer != 0) {
+ if (mScrollingLayerRect.left != mScrollingLayerRect.right) {
+ mMinAutoScrollX = Math.max(mMinAutoScrollX,
+ contentToViewX(mScrollingLayerBounds.left));
+ mMaxAutoScrollX = Math.min(mMaxAutoScrollX,
+ contentToViewX(mScrollingLayerBounds.right));
+ }
+ if (mScrollingLayerRect.top != mScrollingLayerRect.bottom) {
+ mMinAutoScrollY = Math.max(mMinAutoScrollY,
+ contentToViewY(mScrollingLayerBounds.top));
+ mMaxAutoScrollY = Math.min(mMaxAutoScrollY,
+ contentToViewY(mScrollingLayerBounds.bottom));
+ }
+ }
+ mMinAutoScrollX += SELECT_SCROLL;
+ mMaxAutoScrollX -= SELECT_SCROLL;
+ mMinAutoScrollY += SELECT_SCROLL;
+ mMaxAutoScrollY -= SELECT_SCROLL;
return true;
}
@@ -5155,7 +5205,8 @@
// Textfields, plugins, and contentEditable nodes need to receive the
// shift up key even if another key was released while the shift key
// was held down.
- if (!inEditingMode() && (mNativeClass == 0
+ boolean inEditingMode = inEditingMode();
+ if (!inEditingMode && (mNativeClass == 0
|| !nativePageShouldHandleShiftAndArrows())) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
mGotKeyDown = true;
@@ -5172,7 +5223,13 @@
}
if (dispatch) {
- return super.dispatchKeyEvent(event);
+ if (inEditingMode) {
+ // Ensure that the WebTextView gets the event, even if it does
+ // not currently have a bounds.
+ return mWebTextView.dispatchKeyEvent(event);
+ } else {
+ return super.dispatchKeyEvent(event);
+ }
} else {
// We didn't dispatch, so let something else handle the key
return false;
@@ -5239,7 +5296,7 @@
int contentX = viewToContentX((int) x + mScrollX);
int contentY = viewToContentY((int) y + mScrollY);
mScrollingLayer = nativeScrollableLayer(contentX, contentY,
- mScrollingLayerRect);
+ mScrollingLayerRect, mScrollingLayerBounds);
if (mScrollingLayer != 0) {
mTouchMode = TOUCH_DRAG_LAYER_MODE;
}
@@ -5265,17 +5322,10 @@
+ " numPointers=" + ev.getPointerCount());
}
- int action = ev.getAction();
- float x = ev.getX();
- float y = ev.getY();
- long eventTime = ev.getEventTime();
-
- // mDeferMultitouch is a hack for layout tests, where it is used to
- // force passing multi-touch events to webkit.
- // FIXME: always pass multi-touch events to webkit and remove everything
- // related to mDeferMultitouch.
- if (ev.getPointerCount() > 1 &&
- (mDeferMultitouch || mZoomManager.isZoomScaleFixed())) {
+ // Always pass multi-touch event to WebKit first.
+ // If WebKit doesn't consume it and set preventDefault to true,
+ // WebView's private handler will handle it.
+ if (ev.getPointerCount() > 1) {
if (DebugFlags.WEB_VIEW) {
Log.v(LOGTAG, "passing " + ev.getPointerCount() + " points to webkit");
}
@@ -5283,59 +5333,15 @@
return true;
}
- final ScaleGestureDetector detector =
- mZoomManager.getMultiTouchGestureDetector();
+ return handleTouchEventCommon(ev);
+ }
- if (mZoomManager.supportsMultiTouchZoom() && ev.getPointerCount() > 1) {
- if (!detector.isInProgress() &&
- ev.getActionMasked() != MotionEvent.ACTION_POINTER_DOWN) {
- // Insert a fake pointer down event in order to start
- // the zoom scale detector.
- MotionEvent temp = MotionEvent.obtain(ev);
- // Clear the original event and set it to
- // ACTION_POINTER_DOWN.
- try {
- temp.setAction(temp.getAction() &
- ~MotionEvent.ACTION_MASK |
- MotionEvent.ACTION_POINTER_DOWN);
- detector.onTouchEvent(temp);
- } finally {
- temp.recycle();
- }
- }
+ private boolean handleTouchEventCommon(MotionEvent ev) {
+ int action = ev.getAction();
+ float x = ev.getX();
+ float y = ev.getY();
+ long eventTime = ev.getEventTime();
- detector.onTouchEvent(ev);
-
- if (detector.isInProgress()) {
- mLastTouchTime = eventTime;
- cancelLongPress();
- mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
- if (!mZoomManager.supportsPanDuringZoom()) {
- return true;
- }
- mTouchMode = TOUCH_DRAG_MODE;
- if (mVelocityTracker == null) {
- mVelocityTracker = VelocityTracker.obtain();
- }
- }
-
- x = detector.getFocusX();
- y = detector.getFocusY();
- action = ev.getAction() & MotionEvent.ACTION_MASK;
- if (action == MotionEvent.ACTION_POINTER_DOWN) {
- cancelTouch();
- action = MotionEvent.ACTION_DOWN;
- } else if (action == MotionEvent.ACTION_POINTER_UP) {
- // set mLastTouchX/Y to the remaining point
- mLastTouchX = x;
- mLastTouchY = y;
- } else if (action == MotionEvent.ACTION_MOVE) {
- // negative x or y indicate it is on the edge, skip it.
- if (x < 0 || y < 0) {
- return true;
- }
- }
- }
// Due to the touch screen edge effect, a touch closer to the edge
// always snapped to the edge. As getViewWidth() can be different from
@@ -5516,21 +5522,15 @@
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
- int layer = nativeScrollableLayer(contentX, contentY, mScrollingLayerRect);
- if (layer == 0) {
- mAutoScrollX = x <= SELECT_SCROLL ? -SELECT_SCROLL
- : x >= getViewWidth() - SELECT_SCROLL
- ? SELECT_SCROLL : 0;
- mAutoScrollY = y <= SELECT_SCROLL ? -SELECT_SCROLL
- : y >= getViewHeightWithTitle() - SELECT_SCROLL
- ? SELECT_SCROLL : 0;
- if (!mSentAutoScrollMessage) {
- mSentAutoScrollMessage = true;
- mPrivateHandler.sendEmptyMessageDelayed(
- SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
- }
- } else {
- // TODO: allow scrollable overflow div to autoscroll
+ mAutoScrollX = x <= mMinAutoScrollX ? -SELECT_SCROLL
+ : x >= mMaxAutoScrollX ? SELECT_SCROLL : 0;
+ mAutoScrollY = y <= mMinAutoScrollY ? -SELECT_SCROLL
+ : y >= mMaxAutoScrollY ? SELECT_SCROLL : 0;
+ if ((mAutoScrollX != 0 || mAutoScrollY != 0)
+ && !mSentAutoScrollMessage) {
+ mSentAutoScrollMessage = true;
+ mPrivateHandler.sendEmptyMessageDelayed(
+ SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
}
if (deltaX != 0 || deltaY != 0) {
nativeExtendSelection(contentX, contentY);
@@ -5554,22 +5554,6 @@
break;
}
- // Only lock dragging to one axis if we don't have a scale in progress.
- // Scaling implies free-roaming movement. Note this is only ever a question
- // if mZoomManager.supportsPanDuringZoom() is true.
- if (detector != null && !detector.isInProgress()) {
- // if it starts nearly horizontal or vertical, enforce it
- int ax = Math.abs(deltaX);
- int ay = Math.abs(deltaY);
- if (ax > MAX_SLOPE_FOR_DIAG * ay) {
- mSnapScrollMode = SNAP_X;
- mSnapPositive = deltaX > 0;
- } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
- mSnapScrollMode = SNAP_Y;
- mSnapPositive = deltaY > 0;
- }
- }
-
mTouchMode = TOUCH_DRAG_MODE;
mLastTouchX = x;
mLastTouchY = y;
@@ -5678,6 +5662,9 @@
mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
}
mLastTouchUpTime = eventTime;
+ if (mSentAutoScrollMessage) {
+ mAutoScrollX = mAutoScrollY = 0;
+ }
switch (mTouchMode) {
case TOUCH_DOUBLE_TAP_MODE: // double tap
mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
@@ -5823,13 +5810,82 @@
ted.mPoints[c] = new Point(x, y);
}
ted.mMetaState = ev.getMetaState();
- ted.mReprocess = mDeferTouchProcess;
+ ted.mReprocess = true;
+ ted.mMotionEvent = MotionEvent.obtain(ev);
mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
cancelLongPress();
mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
mPreventDefault = PREVENT_DEFAULT_IGNORE;
}
+ private boolean handleMultiTouchInWebView(MotionEvent ev) {
+ if (DebugFlags.WEB_VIEW) {
+ Log.v(LOGTAG, "multi-touch: " + ev + " at " + ev.getEventTime()
+ + " mTouchMode=" + mTouchMode
+ + " numPointers=" + ev.getPointerCount()
+ + " scrolloffset=(" + mScrollX + "," + mScrollY + ")");
+ }
+
+ final ScaleGestureDetector detector =
+ mZoomManager.getMultiTouchGestureDetector();
+ int action = ev.getAction();
+ float x = ev.getX();
+ float y = ev.getY();
+ long eventTime = ev.getEventTime();
+
+ if (!detector.isInProgress() &&
+ ev.getActionMasked() != MotionEvent.ACTION_POINTER_DOWN) {
+ // Insert a fake pointer down event in order to start
+ // the zoom scale detector.
+ MotionEvent temp = MotionEvent.obtain(ev);
+ // Clear the original event and set it to
+ // ACTION_POINTER_DOWN.
+ try {
+ temp.setAction(temp.getAction() &
+ ~MotionEvent.ACTION_MASK |
+ MotionEvent.ACTION_POINTER_DOWN);
+ detector.onTouchEvent(temp);
+ } finally {
+ temp.recycle();
+ }
+ }
+
+ detector.onTouchEvent(ev);
+
+ if (detector.isInProgress()) {
+ if (DebugFlags.WEB_VIEW) {
+ Log.v(LOGTAG, "detector is in progress");
+ }
+ mLastTouchTime = eventTime;
+ cancelLongPress();
+ mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
+ if (!mZoomManager.supportsPanDuringZoom()) {
+ return false;
+ }
+ mTouchMode = TOUCH_DRAG_MODE;
+ if (mVelocityTracker == null) {
+ mVelocityTracker = VelocityTracker.obtain();
+ }
+ }
+
+ action = ev.getAction() & MotionEvent.ACTION_MASK;
+ if (action == MotionEvent.ACTION_POINTER_DOWN) {
+ cancelTouch();
+ action = MotionEvent.ACTION_DOWN;
+ } else if (action == MotionEvent.ACTION_POINTER_UP) {
+ // set mLastTouchX/Y to the remaining point
+ mLastTouchX = x;
+ mLastTouchY = y;
+ } else if (action == MotionEvent.ACTION_MOVE) {
+ // negative x or y indicate it is on the edge, skip it.
+ if (x < 0 || y < 0) {
+ return false;
+ }
+ }
+
+ return handleTouchEventCommon(ev);
+ }
+
private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
if (shouldForwardTouchEvent()) {
if (removeEvents) {
@@ -6925,7 +6981,16 @@
mSentAutoScrollMessage = false;
break;
}
- pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0);
+ if (mScrollingLayer == 0) {
+ pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0);
+ } else {
+ mScrollingLayerRect.left += mAutoScrollX;
+ mScrollingLayerRect.top += mAutoScrollY;
+ nativeScrollLayer(mScrollingLayer,
+ mScrollingLayerRect.left,
+ mScrollingLayerRect.top);
+ invalidate();
+ }
sendEmptyMessageDelayed(
SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
break;
@@ -7193,6 +7258,13 @@
// prevent default is not called in WebCore, so the
// message needs to be reprocessed in UI
TouchEventData ted = (TouchEventData) msg.obj;
+
+ if (ted.mPoints.length > 1) { // for multi-touch.
+ handleMultiTouchInWebView(ted.mMotionEvent);
+ break;
+ }
+
+ // Following is for single touch.
switch (ted.mAction) {
case MotionEvent.ACTION_DOWN:
mLastDeferTouchX = contentToViewX(ted.mPoints[0].x)
@@ -7786,6 +7858,24 @@
cursorData());
}
+ /*
+ * Called from JNI when the cursor has moved. This method
+ * sends a message to the WebCore requesting the given
+ * nodePtr in the given framePrt to be selected which will
+ * result in firing an accessibility event announing its
+ * content.
+ *
+ * Note: Accessibility support.
+ */
+ @SuppressWarnings("unused")
+ // called from JNI
+ private void sendMoveSelection(int framePtr, int nodePtr) {
+ if (AccessibilityManager.getInstance(mContext).isEnabled()
+ && mAccessibilityInjector != null) {
+ mWebViewCore.sendMessage(EventHub.MOVE_SELECTION, framePtr, nodePtr);
+ }
+ }
+
// called by JNI
private void sendMotionUp(int touchGeneration,
int frame, int node, int x, int y) {
@@ -7880,6 +7970,9 @@
Rect contentCursorRingBounds = nativeGetCursorRingBounds();
if (contentCursorRingBounds.isEmpty()) return keyHandled;
Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
+ // set last touch so that context menu related functions will work
+ mLastTouchX = (viewCursorRingBounds.left + viewCursorRingBounds.right) / 2;
+ mLastTouchY = (viewCursorRingBounds.top + viewCursorRingBounds.bottom) / 2;
Rect visRect = new Rect();
calcOurVisibleRect(visRect);
Rect outset = new Rect(visRect);
@@ -7997,7 +8090,6 @@
private native int nativeCursorFramePointer();
private native Rect nativeCursorNodeBounds();
private native int nativeCursorNodePointer();
- /* package */ native boolean nativeCursorMatchesFocus();
private native boolean nativeCursorIntersects(Rect visibleRect);
private native boolean nativeCursorIsAnchor();
private native boolean nativeCursorIsTextInput();
@@ -8115,6 +8207,7 @@
native int nativeGetBlockLeftEdge(int x, int y, float scale);
// Returns a pointer to the scrollable LayerAndroid at the given point.
- private native int nativeScrollableLayer(int x, int y, Rect scrollRect);
+ private native int nativeScrollableLayer(int x, int y, Rect scrollRect,
+ Rect scrollBounds);
private native boolean nativeScrollLayer(int layer, int dx, int dy);
}
diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java
index 43ec378..8d5e71a 100644
--- a/core/java/android/webkit/WebViewCore.java
+++ b/core/java/android/webkit/WebViewCore.java
@@ -33,11 +33,13 @@
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
+import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.webkit.DeviceMotionService;
import android.webkit.DeviceMotionAndOrientationManager;
import android.webkit.DeviceOrientationService;
+import android.webkit.JniUtil;
import java.util.ArrayList;
import java.util.Collection;
@@ -113,8 +115,8 @@
*/
private int mViewportDensityDpi = -1;
- private int mRestoredScale = 0;
- private int mRestoredTextWrapScale = 0;
+ private float mRestoredScale = 0;
+ private float mRestoredTextWrapScale = 0;
private int mRestoredX = 0;
private int mRestoredY = 0;
@@ -626,6 +628,8 @@
/**
* Modifies the current selection.
*
+ * Note: Accessibility support.
+ *
* @param direction The direction in which to alter the selection.
* @param granularity The granularity of the selection modification.
*
@@ -633,6 +637,18 @@
*/
private native String nativeModifySelection(int direction, int granularity);
+ /**
+ * Moves the selection to given node i.e. selects that node.
+ *
+ * Note: Accessibility support.
+ *
+ * @param framePtr Pointer to the frame containing the node to be selected.
+ * @param nodePtr Pointer to the node to be selected.
+ *
+ * @return The selection string.
+ */
+ private native String nativeMoveSelection(int framePtr, int nodePtr);
+
// EventHub for processing messages
private final EventHub mEventHub;
// WebCore thread handler
@@ -815,6 +831,7 @@
Point[] mPoints;
int mMetaState;
boolean mReprocess;
+ MotionEvent mMotionEvent;
}
static class GeolocationPermissionsData {
@@ -993,6 +1010,9 @@
static final int PROXY_CHANGED = 193;
+ // accessibility support
+ static final int MOVE_SELECTION = 194;
+
// private message ids
private static final int DESTROY = 200;
@@ -1201,15 +1221,19 @@
Process.setThreadPriority(mTid,
Process.THREAD_PRIORITY_BACKGROUND);
pauseTimers();
- WebViewWorker.getHandler().sendEmptyMessage(
- WebViewWorker.MSG_PAUSE_CACHE_TRANSACTION);
+ if (!JniUtil.useChromiumHttpStack()) {
+ WebViewWorker.getHandler().sendEmptyMessage(
+ WebViewWorker.MSG_PAUSE_CACHE_TRANSACTION);
+ }
break;
case RESUME_TIMERS:
Process.setThreadPriority(mTid, mSavedPriority);
resumeTimers();
- WebViewWorker.getHandler().sendEmptyMessage(
- WebViewWorker.MSG_RESUME_CACHE_TRANSACTION);
+ if (!JniUtil.useChromiumHttpStack()) {
+ WebViewWorker.getHandler().sendEmptyMessage(
+ WebViewWorker.MSG_RESUME_CACHE_TRANSACTION);
+ }
break;
case ON_PAUSE:
@@ -1396,9 +1420,16 @@
break;
case MODIFY_SELECTION:
- String selectionString = nativeModifySelection(msg.arg1, msg.arg2);
+ String modifiedSelectionString = nativeModifySelection(msg.arg1,
+ msg.arg2);
mWebView.mPrivateHandler.obtainMessage(WebView.SELECTION_STRING_CHANGED,
- selectionString).sendToTarget();
+ modifiedSelectionString).sendToTarget();
+ break;
+
+ case MOVE_SELECTION:
+ String movedSelectionString = nativeMoveSelection(msg.arg1, msg.arg2);
+ mWebView.mPrivateHandler.obtainMessage(WebView.SELECTION_STRING_CHANGED,
+ movedSelectionString).sendToTarget();
break;
case LISTBOX_CHOICES:
@@ -1733,7 +1764,7 @@
private void clearCache(boolean includeDiskFiles) {
mBrowserFrame.clearCache();
- if (includeDiskFiles) {
+ if (includeDiskFiles && !JniUtil.useChromiumHttpStack()) {
CacheManager.removeAllCacheFiles();
}
}
@@ -2150,12 +2181,14 @@
// called by JNI
private void sendNotifyProgressFinished() {
sendUpdateTextEntry();
- // as CacheManager can behave based on database transaction, we need to
- // call tick() to trigger endTransaction
- WebViewWorker.getHandler().removeMessages(
- WebViewWorker.MSG_CACHE_TRANSACTION_TICKER);
- WebViewWorker.getHandler().sendEmptyMessage(
- WebViewWorker.MSG_CACHE_TRANSACTION_TICKER);
+ if (!JniUtil.useChromiumHttpStack()) {
+ // as CacheManager can behave based on database transaction, we need to
+ // call tick() to trigger endTransaction
+ WebViewWorker.getHandler().removeMessages(
+ WebViewWorker.MSG_CACHE_TRANSACTION_TICKER);
+ WebViewWorker.getHandler().sendEmptyMessage(
+ WebViewWorker.MSG_CACHE_TRANSACTION_TICKER);
+ }
contentDraw();
}
@@ -2212,8 +2245,8 @@
}
// reset the scroll position, the restored offset and scales
- mWebkitScrollX = mWebkitScrollY = mRestoredX = mRestoredY
- = mRestoredScale = mRestoredTextWrapScale = 0;
+ mWebkitScrollX = mWebkitScrollY = mRestoredX = mRestoredY = 0;
+ mRestoredScale = mRestoredTextWrapScale = 0;
}
// called by JNI
@@ -2319,9 +2352,9 @@
mInitialViewState.mMobileSite = (0 == mViewportWidth);
if (mRestoredScale > 0) {
mInitialViewState.mIsRestored = true;
- mInitialViewState.mViewScale = mRestoredScale / 100.0f;
+ mInitialViewState.mViewScale = mRestoredScale;
if (mRestoredTextWrapScale > 0) {
- mInitialViewState.mTextWrapScale = mRestoredTextWrapScale / 100.0f;
+ mInitialViewState.mTextWrapScale = mRestoredTextWrapScale;
} else {
mInitialViewState.mTextWrapScale = mInitialViewState.mViewScale;
}
@@ -2378,7 +2411,7 @@
// know the exact scale. If mRestoredScale is non-zero, use it;
// otherwise just use mTextWrapScale as the initial scale.
data.mScale = mInitialViewState.mViewScale == 0
- ? (mRestoredScale > 0 ? mRestoredScale / 100.0f
+ ? (mRestoredScale > 0 ? mRestoredScale
: mInitialViewState.mTextWrapScale)
: mInitialViewState.mViewScale;
if (DebugFlags.WEB_VIEW_CORE) {
@@ -2411,7 +2444,7 @@
}
// called by JNI
- private void restoreScale(int scale, int textWrapScale) {
+ private void restoreScale(float scale, float textWrapScale) {
if (mBrowserFrame.firstLayoutDone() == false) {
mRestoredScale = scale;
if (mSettings.getUseWideViewPort()) {
diff --git a/core/java/android/webkit/WebViewDatabase.java b/core/java/android/webkit/WebViewDatabase.java
index 8f89678..e1392ae 100644
--- a/core/java/android/webkit/WebViewDatabase.java
+++ b/core/java/android/webkit/WebViewDatabase.java
@@ -33,6 +33,7 @@
import android.util.Log;
import android.webkit.CookieManager.Cookie;
import android.webkit.CacheManager.CacheResult;
+import android.webkit.JniUtil;
public class WebViewDatabase {
private static final String DATABASE_FILE = "webview.db";
@@ -202,6 +203,17 @@
return;
}
+ initDatabase(context);
+ if (!JniUtil.useChromiumHttpStack()) {
+ initCacheDatabase(context);
+ }
+
+ // Thread done, notify.
+ mInitialized = true;
+ notify();
+ }
+
+ private void initDatabase(Context context) {
try {
mDatabase = context.openOrCreateDatabase(DATABASE_FILE, 0, null);
} catch (SQLiteException e) {
@@ -211,6 +223,7 @@
null);
}
}
+ mDatabase.enableWriteAheadLogging();
// mDatabase should not be null,
// the only case is RequestAPI test has problem to create db
@@ -221,7 +234,7 @@
}
if (mDatabase.getVersion() != DATABASE_VERSION) {
- mDatabase.beginTransaction();
+ mDatabase.beginTransactionNonExclusive();
try {
upgradeDatabase();
mDatabase.setTransactionSuccessful();
@@ -234,6 +247,10 @@
// improves performance as database's ReentrantLock is
// expansive
mDatabase.setLockingEnabled(false);
+ }
+
+ private void initCacheDatabase(Context context) {
+ assert !JniUtil.useChromiumHttpStack();
try {
mCacheDatabase = context.openOrCreateDatabase(
@@ -245,6 +262,7 @@
CACHE_DATABASE_FILE, 0, null);
}
}
+ mCacheDatabase.enableWriteAheadLogging();
// mCacheDatabase should not be null,
// the only case is RequestAPI test has problem to create db
@@ -255,7 +273,7 @@
}
if (mCacheDatabase.getVersion() != CACHE_DATABASE_VERSION) {
- mCacheDatabase.beginTransaction();
+ mCacheDatabase.beginTransactionNonExclusive();
try {
upgradeCacheDatabase();
bootstrapCacheDatabase();
@@ -306,10 +324,6 @@
.getColumnIndex(CACHE_CONTENTDISPOSITION_COL);
mCacheCrossDomainColIndex = mCacheInserter
.getColumnIndex(CACHE_CROSSDOMAIN_COL);
-
- // Thread done, notify.
- mInitialized = true;
- notify();
}
private static void upgradeDatabase() {
@@ -636,7 +650,7 @@
+ "WebViewWorkerThread instead of from "
+ Thread.currentThread().getName());
}
- mCacheDatabase.beginTransaction();
+ mCacheDatabase.beginTransactionNonExclusive();
return true;
}
return false;
@@ -668,6 +682,8 @@
* @return CacheResult The CacheManager.CacheResult
*/
CacheResult getCache(String url) {
+ assert !JniUtil.useChromiumHttpStack();
+
if (url == null || !checkInitialized()) {
return null;
}
@@ -708,6 +724,8 @@
* @param url The url
*/
void removeCache(String url) {
+ assert !JniUtil.useChromiumHttpStack();
+
if (url == null || !checkInitialized()) {
return;
}
@@ -722,6 +740,8 @@
* @param c The CacheManager.CacheResult
*/
void addCache(String url, CacheResult c) {
+ assert !JniUtil.useChromiumHttpStack();
+
if (url == null || !checkInitialized()) {
return;
}
diff --git a/core/java/android/webkit/WebViewWorker.java b/core/java/android/webkit/WebViewWorker.java
index c488150..6a4ca29 100644
--- a/core/java/android/webkit/WebViewWorker.java
+++ b/core/java/android/webkit/WebViewWorker.java
@@ -125,6 +125,7 @@
break;
}
case MSG_CREATE_CACHE: {
+ assert !JniUtil.useChromiumHttpStack();
CacheCreateData data = (CacheCreateData) msg.obj;
CacheManager.CacheResult cache = CacheManager.createCacheFile(
data.mUrl, data.mStatusCode, data.mHeaders,
@@ -137,6 +138,7 @@
break;
}
case MSG_UPDATE_CACHE_ENCODING: {
+ assert !JniUtil.useChromiumHttpStack();
CacheEncoding data = (CacheEncoding) msg.obj;
CacheManager.CacheResult cache = mCacheResultMap
.get(data.mListener);
@@ -146,6 +148,7 @@
break;
}
case MSG_APPEND_CACHE: {
+ assert !JniUtil.useChromiumHttpStack();
CacheData data = (CacheData) msg.obj;
CacheManager.CacheResult cache = mCacheResultMap
.get(data.mListener);
@@ -168,6 +171,7 @@
break;
}
case MSG_SAVE_CACHE: {
+ assert !JniUtil.useChromiumHttpStack();
CacheSaveData data = (CacheSaveData) msg.obj;
CacheManager.CacheResult cache = mCacheResultMap
.get(data.mListener);
@@ -178,6 +182,7 @@
break;
}
case MSG_REMOVE_CACHE: {
+ assert !JniUtil.useChromiumHttpStack();
LoadListener listener = (LoadListener) msg.obj;
CacheManager.CacheResult cache = mCacheResultMap.get(listener);
if (cache != null) {
@@ -187,14 +192,17 @@
break;
}
case MSG_TRIM_CACHE: {
+ assert !JniUtil.useChromiumHttpStack();
CacheManager.trimCacheIfNeeded();
break;
}
case MSG_CLEAR_CACHE: {
+ assert !JniUtil.useChromiumHttpStack();
CacheManager.clearCache();
break;
}
case MSG_CACHE_TRANSACTION_TICKER: {
+ assert !JniUtil.useChromiumHttpStack();
if (!mCacheTickersBlocked) {
CacheManager.endTransaction();
CacheManager.startTransaction();
@@ -204,6 +212,7 @@
break;
}
case MSG_PAUSE_CACHE_TRANSACTION: {
+ assert !JniUtil.useChromiumHttpStack();
if (CacheManager.disableTransaction()) {
mCacheTickersBlocked = true;
removeMessages(MSG_CACHE_TRANSACTION_TICKER);
@@ -211,6 +220,7 @@
break;
}
case MSG_RESUME_CACHE_TRANSACTION: {
+ assert !JniUtil.useChromiumHttpStack();
if (CacheManager.enableTransaction()) {
mCacheTickersBlocked = false;
sendEmptyMessageDelayed(MSG_CACHE_TRANSACTION_TICKER,
diff --git a/core/java/android/webkit/ZoomManager.java b/core/java/android/webkit/ZoomManager.java
index 075ecbc..b4a33de 100644
--- a/core/java/android/webkit/ZoomManager.java
+++ b/core/java/android/webkit/ZoomManager.java
@@ -150,6 +150,12 @@
private static float MINIMUM_SCALE_INCREMENT = 0.01f;
/*
+ * The touch points could be changed even the fingers stop moving.
+ * We use the following to filter out the zooming jitters.
+ */
+ private static float MINIMUM_SCALE_WITHOUT_JITTER = 0.05f;
+
+ /*
* The following member variables are only to be used for animating zoom. If
* mZoomScale is non-zero then we are in the middle of a zoom animation. The
* other variables are used as a cache (e.g. inverse) or as a way to store
@@ -260,8 +266,9 @@
public final float getReadingLevelScale() {
// The reading scale is at least 0.5f apart from the overview scale.
final float MIN_SCALE_DIFF = 0.5f;
- return Math.max(getZoomOverviewScale() + MIN_SCALE_DIFF,
- DEFAULT_READING_LEVEL_SCALE);
+ return computeScaleWithLimits(
+ Math.max(getZoomOverviewScale() + MIN_SCALE_DIFF,
+ DEFAULT_READING_LEVEL_SCALE));
}
public final float getInvDefaultScale() {
@@ -683,6 +690,10 @@
} else {
scale = Math.max(scale, mActualScale * 0.8f);
}
+ // if the scale change is too small, regard it as jitter and skip it.
+ if (Math.abs(scale - mActualScale) < MINIMUM_SCALE_WITHOUT_JITTER) {
+ return false;
+ }
setZoomCenter(detector.getFocusX(), detector.getFocusY());
setZoomScale(scale, false);
mWebView.invalidate();
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index fa74b4c..bccde8d 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -738,16 +738,6 @@
boolean smoothScrollbar = a.getBoolean(R.styleable.AbsListView_smoothScrollbar, true);
setSmoothScrollbarEnabled(smoothScrollbar);
- final int adapterId = a.getResourceId(R.styleable.AbsListView_adapter, 0);
- if (adapterId != 0) {
- final Context c = context;
- post(new Runnable() {
- public void run() {
- setAdapter(Adapters.loadAdapter(c, adapterId));
- }
- });
- }
-
setChoiceMode(a.getInt(R.styleable.AbsListView_choiceMode, CHOICE_MODE_NONE));
setFastScrollAlwaysVisible(
a.getBoolean(R.styleable.AbsListView_fastScrollAlwaysVisible, false));
@@ -2434,7 +2424,6 @@
}
private class PerformClick extends WindowRunnnable implements Runnable {
- View mChild;
int mClickMotionPosition;
public void run() {
@@ -2447,7 +2436,8 @@
if (adapter != null && mItemCount > 0 &&
motionPosition != INVALID_POSITION &&
motionPosition < adapter.getCount() && sameWindow()) {
- performItemClick(mChild, motionPosition, adapter.getItemId(motionPosition));
+ performItemClick(getChildAt(motionPosition - mFirstPosition), motionPosition,
+ adapter.getItemId(motionPosition));
}
}
}
@@ -3020,7 +3010,6 @@
}
final AbsListView.PerformClick performClick = mPerformClick;
- performClick.mChild = child;
performClick.mClickMotionPosition = motionPosition;
performClick.rememberWindowAttachCount();
@@ -3056,7 +3045,7 @@
child.setPressed(false);
setPressed(false);
if (!mDataChanged) {
- post(performClick);
+ performClick.run();
}
}
};
@@ -3068,7 +3057,7 @@
}
return true;
} else if (!mDataChanged && mAdapter.isEnabled(motionPosition)) {
- post(performClick);
+ performClick.run();
}
}
mTouchMode = TOUCH_MODE_REST;
@@ -4821,7 +4810,10 @@
if (mFiltered && mPopup != null && mPopup.isShowing()) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getRepeatCount() == 0) {
- getKeyDispatcherState().startTracking(event, this);
+ KeyEvent.DispatcherState state = getKeyDispatcherState();
+ if (state != null) {
+ state.startTracking(event, this);
+ }
handled = true;
} else if (event.getAction() == KeyEvent.ACTION_UP
&& event.isTracking() && !event.isCanceled()) {
diff --git a/core/java/android/widget/Adapters.java b/core/java/android/widget/Adapters.java
deleted file mode 100644
index 3849aa4..0000000
--- a/core/java/android/widget/Adapters.java
+++ /dev/null
@@ -1,1235 +0,0 @@
-/*
- * Copyright (C) 2010 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.widget;
-
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import android.app.Activity;
-import android.content.Context;
-import android.content.res.Resources;
-import android.content.res.TypedArray;
-import android.content.res.XmlResourceParser;
-import android.database.Cursor;
-import android.graphics.BitmapFactory;
-import android.net.Uri;
-import android.os.AsyncTask;
-import android.util.AttributeSet;
-import android.util.Xml;
-import android.view.View;
-
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-/**
- * @hide -- not sure if we really want this in the framework.
- *
- * <p>This class can be used to load {@link android.widget.Adapter adapters} defined in
- * XML resources. XML-defined adapters can be used to easily create adapters in your
- * own application or to pass adapters to other processes.</p>
- *
- * <h2>Types of adapters</h2>
- * <p>Adapters defined using XML resources can only be one of the following supported
- * types. Arbitrary adapters are not supported to guarantee the safety of the loaded
- * code when adapters are loaded across packages.</p>
- * <ul>
- * <li><a href="#xml-cursor-adapter">Cursor adapter</a>: a cursor adapter can be used
- * to display the content of a cursor, most often coming from a content provider</li>
- * </ul>
- * <p>The complete XML format definition of each adapter type is available below.</p>
- *
- * <a name="xml-cursor-adapter"></a>
- * <h2>Cursor adapter</h2>
- * <p>A cursor adapter XML definition starts with the
- * <a href="#xml-cursor-adapter-tag"><code><cursor-adapter /></code></a>
- * tag and may contain one or more instances of the following tags:</p>
- * <ul>
- * <li><a href="#xml-cursor-adapter-select-tag"><code><select /></code></a></li>
- * <li><a href="#xml-cursor-adapter-bind-tag"><code><bind /></code></a></li>
- * </ul>
- *
- * <a name="xml-cursor-adapter-tag"></a>
- * <h3><cursor-adapter /></h3>
- * <p>The <code><cursor-adapter /></code> element defines the beginning of the
- * document and supports the following attributes:</p>
- * <ul>
- * <li><code>android:layout</code>: Reference to the XML layout to be inflated for
- * each item of the adapter. This attribute is mandatory.</li>
- * <li><code>android:selection</code>: Selection expression, used when the
- * <code>android:uri</code> attribute is defined or when the adapter is loaded with
- * {@link android.widget.Adapters#loadCursorAdapter(android.content.Context, int, String, Object[])}.
- * This attribute is optional.</li>
- * <li><code>android:sortOrder</code>: Sort expression, used when the
- * <code>android:uri</code> attribute is defined or when the adapter is loaded with
- * {@link android.widget.Adapters#loadCursorAdapter(android.content.Context, int, String, Object[])}.
- * This attribute is optional.</li>
- * <li><code>android:uri</code>: URI of the content provider to query to retrieve a cursor.
- * Specifying this attribute is equivalent to calling
- * {@link android.widget.Adapters#loadCursorAdapter(android.content.Context, int, String, Object[])}.
- * If you call this method, the value of the XML attribute is ignored. This attribute is
- * optional.</li>
- * </ul>
- * <p>In addition, you can specify one or more instances of
- * <a href="#xml-cursor-adapter-select-tag"><code><select /></code></a> and
- * <a href="#xml-cursor-adapter-bind-tag"><code><bind /></code></a> tags as children
- * of <code><cursor-adapter /></code>.</p>
- *
- * <a name="xml-cursor-adapter-select-tag"></a>
- * <h3><select /></h3>
- * <p>The <code><select /></code> tag is used to select columns from the cursor
- * when doing the query. This can be very useful when using transformations in the
- * <code><bind /></code> elements. It can also be very useful if you are providing
- * your own <a href="#xml-cursor-adapter-bind-data-types">binder</a> or
- * <a href="#xml-cursor-adapter-bind-data-types">transformation</a> classes.
- * <code><select /></code> elements are ignored if you supply the cursor yourself.</p>
- * <p>The <code><select /></code> supports the following attributes:</p>
- * <ul>
- * <li><code>android:column</code>: Name of the column to select in the cursor during the
- * query operation</li>
- * </ul>
- * <p><strong>Note:</strong> The column named <code>_id</code> is always implicitly
- * selected.</p>
- *
- * <a name="xml-cursor-adapter-bind-tag"></a>
- * <h3><bind /></h3>
- * <p>The <code><bind /></code> tag is used to bind a column from the cursor to
- * a {@link android.view.View}. A column bound using this tag is automatically selected
- * during the query and a matching
- * <a href="#xml-cursor-adapter-select-tag"><code><select /></code> tag is therefore
- * not required.</p>
- *
- * <p>Each binding is declared as a one to one matching but
- * custom binder classes or special
- * <a href="#xml-cursor-adapter-bind-data-transformation">data transformations</a> can
- * allow you to bind several columns to a single view. In this case you must use the
- * <a href="#xml-cursor-adapter-select-tag"><code><select /></code> tag to make
- * sure any required column is part of the query.</p>
- *
- * <p>The <code><bind /></code> tag supports the following attributes:</p>
- * <ul>
- * <li><code>android:from</code>: The name of the column to bind from.
- * This attribute is mandatory. Note that <code>@</code> which are not used to reference resources
- * should be backslash protected as in <code>\@</code>.</li>
- * <li><code>android:to</code>: The id of the view to bind to. This attribute is mandatory.</li>
- * <li><code>android:as</code>: The <a href="#xml-cursor-adapter-bind-data-types">data type</a>
- * of the binding. This attribute is mandatory.</li>
- * </ul>
- *
- * <p>In addition, a <code><bind /></code> can contain zero or more instances of
- * <a href="#xml-cursor-adapter-bind-data-transformation">data transformations</a> children
- * tags.</p>
- *
- * <a name="xml-cursor-adapter-bind-data-types"></a>
- * <h4>Binding data types</h4>
- * <p>For a binding to occur the data type of the bound column/view pair must be specified.
- * The following data types are currently supported:</p>
- * <ul>
- * <li><code>string</code>: The content of the column is interpreted as a string and must be
- * bound to a {@link android.widget.TextView}</li>
- * <li><code>image</code>: The content of the column is interpreted as a blob describing an
- * image and must be bound to an {@link android.widget.ImageView}</li>
- * <li><code>image-uri</code>: The content of the column is interpreted as a URI to an image
- * and must be bound to an {@link android.widget.ImageView}</li>
- * <li><code>drawable</code>: The content of the column is interpreted as a resource id to a
- * drawable and must be bound to an {@link android.widget.ImageView}</li>
- * <li><code>tag</code>: The content of the column is interpreted as a string and will be set as
- * the tag (using {@link View#setTag(Object)} of the associated View. This can be used to
- * associate meta-data to your view, that can be used for instance by a listener.</li>
- * <li>A fully qualified class name: The name of a class corresponding to an implementation of
- * {@link android.widget.Adapters.CursorBinder}. Cursor binders can be used to provide
- * bindings not supported by default. Custom binders cannot be used with
- * {@link android.content.Context#isRestricted() restricted contexts}, for instance in an
- * application widget</li>
- * </ul>
- *
- * <a name="xml-cursor-adapter-bind-transformation"></a>
- * <h4>Binding transformations</h4>
- * <p>When defining a data binding you can specify an optional transformation by using one
- * of the following tags as a child of a <code><bind /></code> elements:</p>
- * <ul>
- * <li><code><map /></code>: Maps a constant string to a string or a resource. Use
- * one instance of this tag per value you want to map</li>
- * <li><code><transform /></code>: Transforms a column's value using an expression
- * or an instance of {@link android.widget.Adapters.CursorTransformation}</li>
- * </ul>
- * <p>While several <code><map /></code> tags can be used at the same time, you cannot
- * mix <code><map /></code> and <code><transform /></code> tags. If several
- * <code><transform /></code> tags are specified, only the last one is retained.</p>
- *
- * <a name="xml-cursor-adapter-bind-transformation-map" />
- * <p><strong><map /></strong></p>
- * <p>A map element simply specifies a value to match from and a value to match to. When
- * a column's value equals the value to match from, it is replaced with the value to match
- * to. The following attributes are supported:</p>
- * <ul>
- * <li><code>android:fromValue</code>: The value to match from. This attribute is mandatory</li>
- * <li><code>android:toValue</code>: The value to match to. This value can be either a string
- * or a resource identifier. This value is interpreted as a resource identifier when the
- * data binding is of type <code>drawable</code>. This attribute is mandatory</li>
- * </ul>
- *
- * <a name="xml-cursor-adapter-bind-transformation-transform"></a>
- * <p><strong><transform /></strong></p>
- * <p>A simple transform that occurs either by calling a specified class or by performing
- * simple text substitution. The following attributes are supported:</p>
- * <ul>
- * <li><code>android:withExpression</code>: The transformation expression. The expression is
- * a string containing column names surrounded with curly braces { and }. During the
- * transformation each column name is replaced by its value. All columns must have been
- * selected in the query. An example of expression is <code>"First name: {first_name},
- * last name: {last_name}"</code>. This attribute is mandatory
- * if <code>android:withClass</code> is not specified and ignored if <code>android:withClass</code>
- * is specified</li>
- * <li><code>android:withClass</code>: A fully qualified class name corresponding to an
- * implementation of {@link android.widget.Adapters.CursorTransformation}. Custom
- * transformations cannot be used with
- * {@link android.content.Context#isRestricted() restricted contexts}, for instance in
- * an app widget This attribute is mandatory if <code>android:withExpression</code> is
- * not specified</li>
- * </ul>
- *
- * <h3>Example</h3>
- * <p>The following example defines a cursor adapter that queries all the contacts with
- * a phone number using the contacts content provider. Each contact is displayed with
- * its display name, its favorite status and its photo. To display photos, a custom data
- * binder is declared:</p>
- *
- * <pre class="prettyprint">
- * <cursor-adapter xmlns:android="http://schemas.android.com/apk/res/android"
- * android:uri="content://com.android.contacts/contacts"
- * android:selection="has_phone_number=1"
- * android:layout="@layout/contact_item">
- *
- * <bind android:from="display_name" android:to="@id/name" android:as="string" />
- * <bind android:from="starred" android:to="@id/star" android:as="drawable">
- * <map android:fromValue="0" android:toValue="@android:drawable/star_big_off" />
- * <map android:fromValue="1" android:toValue="@android:drawable/star_big_on" />
- * </bind>
- * <bind android:from="_id" android:to="@id/name"
- * android:as="com.google.android.test.adapters.ContactPhotoBinder" />
- *
- * </cursor-adapter>
- * </pre>
- *
- * <h3>Related APIs</h3>
- * <ul>
- * <li>{@link android.widget.Adapters#loadAdapter(android.content.Context, int, Object[])}</li>
- * <li>{@link android.widget.Adapters#loadCursorAdapter(android.content.Context, int, android.database.Cursor, Object[])}</li>
- * <li>{@link android.widget.Adapters#loadCursorAdapter(android.content.Context, int, String, Object[])}</li>
- * <li>{@link android.widget.Adapters.CursorBinder}</li>
- * <li>{@link android.widget.Adapters.CursorTransformation}</li>
- * <li>{@link android.widget.CursorAdapter}</li>
- * </ul>
- *
- * @see android.widget.Adapter
- * @see android.content.ContentProvider
- *
- * attr ref android.R.styleable#CursorAdapter_layout
- * attr ref android.R.styleable#CursorAdapter_selection
- * attr ref android.R.styleable#CursorAdapter_sortOrder
- * attr ref android.R.styleable#CursorAdapter_uri
- * attr ref android.R.styleable#CursorAdapter_BindItem_as
- * attr ref android.R.styleable#CursorAdapter_BindItem_from
- * attr ref android.R.styleable#CursorAdapter_BindItem_to
- * attr ref android.R.styleable#CursorAdapter_MapItem_fromValue
- * attr ref android.R.styleable#CursorAdapter_MapItem_toValue
- * attr ref android.R.styleable#CursorAdapter_SelectItem_column
- * attr ref android.R.styleable#CursorAdapter_TransformItem_withClass
- * attr ref android.R.styleable#CursorAdapter_TransformItem_withExpression
- */
-@SuppressWarnings({"JavadocReference"})
-public class Adapters {
- private static final String ADAPTER_CURSOR = "cursor-adapter";
-
- /**
- * <p>Interface used to bind a {@link android.database.Cursor} column to a View. This
- * interface can be used to provide bindings for data types not supported by the
- * standard implementation of {@link android.widget.Adapters}.</p>
- *
- * <p>A binder is provided with a cursor transformation which may or may not be used
- * to transform the value retrieved from the cursor. The transformation is guaranteed
- * to never be null so it's always safe to apply the transformation.</p>
- *
- * <p>The binder is associated with a Context but can be re-used with multiple cursors.
- * As such, the implementation should make no assumption about the Cursor in use.</p>
- *
- * @see android.view.View
- * @see android.database.Cursor
- * @see android.widget.Adapters.CursorTransformation
- */
- public static abstract class CursorBinder {
- /**
- * <p>The context associated with this binder.</p>
- */
- protected final Context mContext;
-
- /**
- * <p>The transformation associated with this binder. This transformation is never
- * null and may or may not be applied to the Cursor data during the
- * {@link #bind(android.view.View, android.database.Cursor, int)} operation.</p>
- *
- * @see #bind(android.view.View, android.database.Cursor, int)
- */
- protected final CursorTransformation mTransformation;
-
- /**
- * <p>Creates a new Cursor binder.</p>
- *
- * @param context The context associated with this binder.
- * @param transformation The transformation associated with this binder. This
- * transformation may or may not be applied by the binder and is guaranteed
- * to not be null.
- */
- public CursorBinder(Context context, CursorTransformation transformation) {
- mContext = context;
- mTransformation = transformation;
- }
-
- /**
- * <p>Binds the specified Cursor column to the supplied View. The binding operation
- * can query other Cursor columns as needed. During the binding operation, values
- * retrieved from the Cursor may or may not be transformed using this binder's
- * cursor transformation.</p>
- *
- * @param view The view to bind data to.
- * @param cursor The cursor to bind data from.
- * @param columnIndex The column index in the cursor where the data to bind resides.
- *
- * @see #mTransformation
- *
- * @return True if the column was successfully bound to the View, false otherwise.
- */
- public abstract boolean bind(View view, Cursor cursor, int columnIndex);
- }
-
- /**
- * <p>Interface used to transform data coming out of a {@link android.database.Cursor}
- * before it is bound to a {@link android.view.View}.</p>
- *
- * <p>Transformations are used to transform text-based data (in the form of a String),
- * or to transform data into a resource identifier. A default implementation is provided
- * to generate resource identifiers.</p>
- *
- * @see android.database.Cursor
- * @see android.widget.Adapters.CursorBinder
- */
- public static abstract class CursorTransformation {
- /**
- * <p>The context associated with this transformation.</p>
- */
- protected final Context mContext;
-
- /**
- * <p>Creates a new Cursor transformation.</p>
- *
- * @param context The context associated with this transformation.
- */
- public CursorTransformation(Context context) {
- mContext = context;
- }
-
- /**
- * <p>Transforms the specified Cursor column into a String. The transformation
- * can simply return the content of the column as a String (this is known
- * as the identity transformation) or manipulate the content. For instance,
- * a transformation can perform text substitutions or concatenate other
- * columns with the specified column.</p>
- *
- * @param cursor The cursor that contains the data to transform.
- * @param columnIndex The index of the column to transform.
- *
- * @return A String containing the transformed value of the column.
- */
- public abstract String transform(Cursor cursor, int columnIndex);
-
- /**
- * <p>Transforms the specified Cursor column into a resource identifier.
- * The default implementation simply interprets the content of the column
- * as an integer.</p>
- *
- * @param cursor The cursor that contains the data to transform.
- * @param columnIndex The index of the column to transform.
- *
- * @return A resource identifier.
- */
- public int transformToResource(Cursor cursor, int columnIndex) {
- return cursor.getInt(columnIndex);
- }
- }
-
- /**
- * <p>Loads the {@link android.widget.CursorAdapter} defined in the specified
- * XML resource. The content of the adapter is loaded from the content provider
- * identified by the supplied URI.</p>
- *
- * <p><strong>Note:</strong> If the supplied {@link android.content.Context} is
- * an {@link android.app.Activity}, the cursor returned by the content provider
- * will be automatically managed. Otherwise, you are responsible for managing the
- * cursor yourself.</p>
- *
- * <p>The format of the XML definition of the cursor adapter is documented at
- * the top of this page.</p>
- *
- * @param context The context to load the XML resource from.
- * @param id The identifier of the XML resource declaring the adapter.
- * @param uri The URI of the content provider.
- * @param parameters Optional parameters to pass to the CursorAdapter, used
- * to substitute values in the selection expression.
- *
- * @return A {@link android.widget.CursorAdapter}
- *
- * @throws IllegalArgumentException If the XML resource does not contain
- * a valid <cursor-adapter /> definition.
- *
- * @see android.content.ContentProvider
- * @see android.widget.CursorAdapter
- * @see #loadAdapter(android.content.Context, int, Object[])
- */
- public static CursorAdapter loadCursorAdapter(Context context, int id, String uri,
- Object... parameters) {
-
- XmlCursorAdapter adapter = (XmlCursorAdapter) loadAdapter(context, id, ADAPTER_CURSOR,
- parameters);
-
- if (uri != null) {
- adapter.setUri(uri);
- }
- adapter.load();
-
- return adapter;
- }
-
- /**
- * <p>Loads the {@link android.widget.CursorAdapter} defined in the specified
- * XML resource. The content of the adapter is loaded from the specified cursor.
- * You are responsible for managing the supplied cursor.</p>
- *
- * <p>The format of the XML definition of the cursor adapter is documented at
- * the top of this page.</p>
- *
- * @param context The context to load the XML resource from.
- * @param id The identifier of the XML resource declaring the adapter.
- * @param cursor The cursor containing the data for the adapter.
- * @param parameters Optional parameters to pass to the CursorAdapter, used
- * to substitute values in the selection expression.
- *
- * @return A {@link android.widget.CursorAdapter}
- *
- * @throws IllegalArgumentException If the XML resource does not contain
- * a valid <cursor-adapter /> definition.
- *
- * @see android.content.ContentProvider
- * @see android.widget.CursorAdapter
- * @see android.database.Cursor
- * @see #loadAdapter(android.content.Context, int, Object[])
- */
- public static CursorAdapter loadCursorAdapter(Context context, int id, Cursor cursor,
- Object... parameters) {
-
- XmlCursorAdapter adapter = (XmlCursorAdapter) loadAdapter(context, id, ADAPTER_CURSOR,
- parameters);
-
- if (cursor != null) {
- adapter.changeCursor(cursor);
- }
-
- return adapter;
- }
-
- /**
- * <p>Loads the adapter defined in the specified XML resource. The XML definition of
- * the adapter must follow the format definition of one of the supported adapter
- * types described at the top of this page.</p>
- *
- * <p><strong>Note:</strong> If the loaded adapter is a {@link android.widget.CursorAdapter}
- * and the supplied {@link android.content.Context} is an {@link android.app.Activity},
- * the cursor returned by the content provider will be automatically managed. Otherwise,
- * you are responsible for managing the cursor yourself.</p>
- *
- * @param context The context to load the XML resource from.
- * @param id The identifier of the XML resource declaring the adapter.
- * @param parameters Optional parameters to pass to the adapter.
- *
- * @return An adapter instance.
- *
- * @see #loadCursorAdapter(android.content.Context, int, android.database.Cursor, Object[])
- * @see #loadCursorAdapter(android.content.Context, int, String, Object[])
- */
- public static BaseAdapter loadAdapter(Context context, int id, Object... parameters) {
- final BaseAdapter adapter = loadAdapter(context, id, null, parameters);
- if (adapter instanceof ManagedAdapter) {
- ((ManagedAdapter) adapter).load();
- }
- return adapter;
- }
-
- /**
- * Loads an adapter from the specified XML resource. The optional assertName can
- * be used to exit early if the adapter defined in the XML resource is not of the
- * expected type.
- *
- * @param context The context to associate with the adapter.
- * @param id The resource id of the XML document defining the adapter.
- * @param assertName The mandatory name of the adapter in the XML document.
- * Ignored if null.
- * @param parameters Optional parameters passed to the adapter.
- *
- * @return An instance of {@link android.widget.BaseAdapter}.
- */
- private static BaseAdapter loadAdapter(Context context, int id, String assertName,
- Object... parameters) {
-
- XmlResourceParser parser = null;
- try {
- parser = context.getResources().getXml(id);
- return createAdapterFromXml(context, parser, Xml.asAttributeSet(parser),
- id, parameters, assertName);
- } catch (XmlPullParserException ex) {
- Resources.NotFoundException rnf = new Resources.NotFoundException(
- "Can't load adapter resource ID " +
- context.getResources().getResourceEntryName(id));
- rnf.initCause(ex);
- throw rnf;
- } catch (IOException ex) {
- Resources.NotFoundException rnf = new Resources.NotFoundException(
- "Can't load adapter resource ID " +
- context.getResources().getResourceEntryName(id));
- rnf.initCause(ex);
- throw rnf;
- } finally {
- if (parser != null) parser.close();
- }
- }
-
- /**
- * Generates an adapter using the specified XML parser. This method is responsible
- * for choosing the type of the adapter to create based on the content of the
- * XML parser.
- *
- * This method will generate an {@link IllegalArgumentException} if
- * <code>assertName</code> is not null and does not match the root tag of the XML
- * document.
- */
- private static BaseAdapter createAdapterFromXml(Context c,
- XmlPullParser parser, AttributeSet attrs, int id, Object[] parameters,
- String assertName) throws XmlPullParserException, IOException {
-
- BaseAdapter adapter = null;
-
- // Make sure we are on a start tag.
- int type;
- int depth = parser.getDepth();
-
- while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) &&
- type != XmlPullParser.END_DOCUMENT) {
-
- if (type != XmlPullParser.START_TAG) {
- continue;
- }
-
- String name = parser.getName();
- if (assertName != null && !assertName.equals(name)) {
- throw new IllegalArgumentException("The adapter defined in " +
- c.getResources().getResourceEntryName(id) + " must be a <" +
- assertName + " />");
- }
-
- if (ADAPTER_CURSOR.equals(name)) {
- adapter = createCursorAdapter(c, parser, attrs, id, parameters);
- } else {
- throw new IllegalArgumentException("Unknown adapter name " + parser.getName() +
- " in " + c.getResources().getResourceEntryName(id));
- }
- }
-
- return adapter;
-
- }
-
- /**
- * Creates an XmlCursorAdapter using an XmlCursorAdapterParser.
- */
- private static XmlCursorAdapter createCursorAdapter(Context c, XmlPullParser parser,
- AttributeSet attrs, int id, Object[] parameters)
- throws IOException, XmlPullParserException {
-
- return new XmlCursorAdapterParser(c, parser, attrs, id).parse(parameters);
- }
-
- /**
- * Parser that can generate XmlCursorAdapter instances. This parser is responsible for
- * handling all the attributes and child nodes for a <cursor-adapter />.
- */
- private static class XmlCursorAdapterParser {
- private static final String ADAPTER_CURSOR_BIND = "bind";
- private static final String ADAPTER_CURSOR_SELECT = "select";
- private static final String ADAPTER_CURSOR_AS_STRING = "string";
- private static final String ADAPTER_CURSOR_AS_IMAGE = "image";
- private static final String ADAPTER_CURSOR_AS_TAG = "tag";
- private static final String ADAPTER_CURSOR_AS_IMAGE_URI = "image-uri";
- private static final String ADAPTER_CURSOR_AS_DRAWABLE = "drawable";
- private static final String ADAPTER_CURSOR_MAP = "map";
- private static final String ADAPTER_CURSOR_TRANSFORM = "transform";
-
- private final Context mContext;
- private final XmlPullParser mParser;
- private final AttributeSet mAttrs;
- private final int mId;
-
- private final HashMap<String, CursorBinder> mBinders;
- private final ArrayList<String> mFrom;
- private final ArrayList<Integer> mTo;
- private final CursorTransformation mIdentity;
- private final Resources mResources;
-
- public XmlCursorAdapterParser(Context c, XmlPullParser parser, AttributeSet attrs, int id) {
- mContext = c;
- mParser = parser;
- mAttrs = attrs;
- mId = id;
-
- mResources = mContext.getResources();
- mBinders = new HashMap<String, CursorBinder>();
- mFrom = new ArrayList<String>();
- mTo = new ArrayList<Integer>();
- mIdentity = new IdentityTransformation(mContext);
- }
-
- public XmlCursorAdapter parse(Object[] parameters)
- throws IOException, XmlPullParserException {
-
- Resources resources = mResources;
- TypedArray a = resources.obtainAttributes(mAttrs, com.android.internal.R.styleable.CursorAdapter);
-
- String uri = a.getString(com.android.internal.R.styleable.CursorAdapter_uri);
- String selection = a.getString(com.android.internal.R.styleable.CursorAdapter_selection);
- String sortOrder = a.getString(com.android.internal.R.styleable.CursorAdapter_sortOrder);
- int layout = a.getResourceId(com.android.internal.R.styleable.CursorAdapter_layout, 0);
- if (layout == 0) {
- throw new IllegalArgumentException("The layout specified in " +
- resources.getResourceEntryName(mId) + " does not exist");
- }
-
- a.recycle();
-
- XmlPullParser parser = mParser;
- int type;
- int depth = parser.getDepth();
-
- while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) &&
- type != XmlPullParser.END_DOCUMENT) {
-
- if (type != XmlPullParser.START_TAG) {
- continue;
- }
-
- String name = parser.getName();
-
- if (ADAPTER_CURSOR_BIND.equals(name)) {
- parseBindTag();
- } else if (ADAPTER_CURSOR_SELECT.equals(name)) {
- parseSelectTag();
- } else {
- throw new RuntimeException("Unknown tag name " + parser.getName() + " in " +
- resources.getResourceEntryName(mId));
- }
- }
-
- String[] fromArray = mFrom.toArray(new String[mFrom.size()]);
- int[] toArray = new int[mTo.size()];
- for (int i = 0; i < toArray.length; i++) {
- toArray[i] = mTo.get(i);
- }
-
- String[] selectionArgs = null;
- if (parameters != null) {
- selectionArgs = new String[parameters.length];
- for (int i = 0; i < selectionArgs.length; i++) {
- selectionArgs[i] = (String) parameters[i];
- }
- }
-
- return new XmlCursorAdapter(mContext, layout, uri, fromArray, toArray, selection,
- selectionArgs, sortOrder, mBinders);
- }
-
- private void parseSelectTag() {
- TypedArray a = mResources.obtainAttributes(mAttrs,
- com.android.internal.R.styleable.CursorAdapter_SelectItem);
-
- String fromName = a.getString(com.android.internal.R.styleable.CursorAdapter_SelectItem_column);
- if (fromName == null) {
- throw new IllegalArgumentException("A select item in " +
- mResources.getResourceEntryName(mId) +
- " does not have a 'column' attribute");
- }
-
- a.recycle();
-
- mFrom.add(fromName);
- mTo.add(View.NO_ID);
- }
-
- private void parseBindTag() throws IOException, XmlPullParserException {
- Resources resources = mResources;
- TypedArray a = resources.obtainAttributes(mAttrs,
- com.android.internal.R.styleable.CursorAdapter_BindItem);
-
- String fromName = a.getString(com.android.internal.R.styleable.CursorAdapter_BindItem_from);
- if (fromName == null) {
- throw new IllegalArgumentException("A bind item in " +
- resources.getResourceEntryName(mId) + " does not have a 'from' attribute");
- }
-
- int toName = a.getResourceId(com.android.internal.R.styleable.CursorAdapter_BindItem_to, 0);
- if (toName == 0) {
- throw new IllegalArgumentException("A bind item in " +
- resources.getResourceEntryName(mId) + " does not have a 'to' attribute");
- }
-
- String asType = a.getString(com.android.internal.R.styleable.CursorAdapter_BindItem_as);
- if (asType == null) {
- throw new IllegalArgumentException("A bind item in " +
- resources.getResourceEntryName(mId) + " does not have an 'as' attribute");
- }
-
- mFrom.add(fromName);
- mTo.add(toName);
- mBinders.put(fromName, findBinder(asType));
-
- a.recycle();
- }
-
- private CursorBinder findBinder(String type) throws IOException, XmlPullParserException {
- final XmlPullParser parser = mParser;
- final Context context = mContext;
- CursorTransformation transformation = mIdentity;
-
- int tagType;
- int depth = parser.getDepth();
-
- final boolean isDrawable = ADAPTER_CURSOR_AS_DRAWABLE.equals(type);
-
- while (((tagType = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth)
- && tagType != XmlPullParser.END_DOCUMENT) {
-
- if (tagType != XmlPullParser.START_TAG) {
- continue;
- }
-
- String name = parser.getName();
-
- if (ADAPTER_CURSOR_TRANSFORM.equals(name)) {
- transformation = findTransformation();
- } else if (ADAPTER_CURSOR_MAP.equals(name)) {
- if (!(transformation instanceof MapTransformation)) {
- transformation = new MapTransformation(context);
- }
- findMap(((MapTransformation) transformation), isDrawable);
- } else {
- throw new RuntimeException("Unknown tag name " + parser.getName() + " in " +
- context.getResources().getResourceEntryName(mId));
- }
- }
-
- if (ADAPTER_CURSOR_AS_STRING.equals(type)) {
- return new StringBinder(context, transformation);
- } else if (ADAPTER_CURSOR_AS_TAG.equals(type)) {
- return new TagBinder(context, transformation);
- } else if (ADAPTER_CURSOR_AS_IMAGE.equals(type)) {
- return new ImageBinder(context, transformation);
- } else if (ADAPTER_CURSOR_AS_IMAGE_URI.equals(type)) {
- return new ImageUriBinder(context, transformation);
- } else if (isDrawable) {
- return new DrawableBinder(context, transformation);
- } else {
- return createBinder(type, transformation);
- }
- }
-
- private CursorBinder createBinder(String type, CursorTransformation transformation) {
- if (mContext.isRestricted()) return null;
-
- try {
- final Class<?> klass = Class.forName(type, true, mContext.getClassLoader());
- if (CursorBinder.class.isAssignableFrom(klass)) {
- final Constructor<?> c = klass.getDeclaredConstructor(
- Context.class, CursorTransformation.class);
- return (CursorBinder) c.newInstance(mContext, transformation);
- }
- } catch (ClassNotFoundException e) {
- throw new IllegalArgumentException("Cannot instanciate binder type in " +
- mContext.getResources().getResourceEntryName(mId) + ": " + type, e);
- } catch (NoSuchMethodException e) {
- throw new IllegalArgumentException("Cannot instanciate binder type in " +
- mContext.getResources().getResourceEntryName(mId) + ": " + type, e);
- } catch (InvocationTargetException e) {
- throw new IllegalArgumentException("Cannot instanciate binder type in " +
- mContext.getResources().getResourceEntryName(mId) + ": " + type, e);
- } catch (InstantiationException e) {
- throw new IllegalArgumentException("Cannot instanciate binder type in " +
- mContext.getResources().getResourceEntryName(mId) + ": " + type, e);
- } catch (IllegalAccessException e) {
- throw new IllegalArgumentException("Cannot instanciate binder type in " +
- mContext.getResources().getResourceEntryName(mId) + ": " + type, e);
- }
-
- return null;
- }
-
- private void findMap(MapTransformation transformation, boolean drawable) {
- Resources resources = mResources;
-
- TypedArray a = resources.obtainAttributes(mAttrs,
- com.android.internal.R.styleable.CursorAdapter_MapItem);
-
- String from = a.getString(com.android.internal.R.styleable.CursorAdapter_MapItem_fromValue);
- if (from == null) {
- throw new IllegalArgumentException("A map item in " +
- resources.getResourceEntryName(mId) +
- " does not have a 'fromValue' attribute");
- }
-
- if (!drawable) {
- String to = a.getString(com.android.internal.R.styleable.CursorAdapter_MapItem_toValue);
- if (to == null) {
- throw new IllegalArgumentException("A map item in " +
- resources.getResourceEntryName(mId) +
- " does not have a 'toValue' attribute");
- }
- transformation.addStringMapping(from, to);
- } else {
- int to = a.getResourceId(com.android.internal.R.styleable.CursorAdapter_MapItem_toValue, 0);
- if (to == 0) {
- throw new IllegalArgumentException("A map item in " +
- resources.getResourceEntryName(mId) +
- " does not have a 'toValue' attribute");
- }
- transformation.addResourceMapping(from, to);
- }
-
- a.recycle();
- }
-
- private CursorTransformation findTransformation() {
- Resources resources = mResources;
- CursorTransformation transformation = null;
- TypedArray a = resources.obtainAttributes(mAttrs,
- com.android.internal.R.styleable.CursorAdapter_TransformItem);
-
- String className = a.getString(com.android.internal.R.styleable.CursorAdapter_TransformItem_withClass);
- if (className == null) {
- String expression = a.getString(
- com.android.internal.R.styleable.CursorAdapter_TransformItem_withExpression);
- transformation = createExpressionTransformation(expression);
- } else if (!mContext.isRestricted()) {
- try {
- final Class<?> klas = Class.forName(className, true, mContext.getClassLoader());
- if (CursorTransformation.class.isAssignableFrom(klas)) {
- final Constructor<?> c = klas.getDeclaredConstructor(Context.class);
- transformation = (CursorTransformation) c.newInstance(mContext);
- }
- } catch (ClassNotFoundException e) {
- throw new IllegalArgumentException("Cannot instanciate transform type in " +
- mContext.getResources().getResourceEntryName(mId) + ": " + className, e);
- } catch (NoSuchMethodException e) {
- throw new IllegalArgumentException("Cannot instanciate transform type in " +
- mContext.getResources().getResourceEntryName(mId) + ": " + className, e);
- } catch (InvocationTargetException e) {
- throw new IllegalArgumentException("Cannot instanciate transform type in " +
- mContext.getResources().getResourceEntryName(mId) + ": " + className, e);
- } catch (InstantiationException e) {
- throw new IllegalArgumentException("Cannot instanciate transform type in " +
- mContext.getResources().getResourceEntryName(mId) + ": " + className, e);
- } catch (IllegalAccessException e) {
- throw new IllegalArgumentException("Cannot instanciate transform type in " +
- mContext.getResources().getResourceEntryName(mId) + ": " + className, e);
- }
- }
-
- a.recycle();
-
- if (transformation == null) {
- throw new IllegalArgumentException("A transform item in " +
- resources.getResourceEntryName(mId) + " must have a 'withClass' or " +
- "'withExpression' attribute");
- }
-
- return transformation;
- }
-
- private CursorTransformation createExpressionTransformation(String expression) {
- return new ExpressionTransformation(mContext, expression);
- }
- }
-
- /**
- * Interface used by adapters that require to be loaded after creation.
- */
- private static interface ManagedAdapter {
- /**
- * Loads the content of the adapter, asynchronously.
- */
- void load();
- }
-
- /**
- * Implementation of a Cursor adapter defined in XML. This class is a thin wrapper
- * of a SimpleCursorAdapter. The main difference is the ability to handle CursorBinders.
- */
- private static class XmlCursorAdapter extends SimpleCursorAdapter implements ManagedAdapter {
- private String mUri;
- private final String mSelection;
- private final String[] mSelectionArgs;
- private final String mSortOrder;
- private final String[] mColumns;
- private final CursorBinder[] mBinders;
- private AsyncTask<Void,Void,Cursor> mLoadTask;
-
- XmlCursorAdapter(Context context, int layout, String uri, String[] from, int[] to,
- String selection, String[] selectionArgs, String sortOrder,
- HashMap<String, CursorBinder> binders) {
-
- super(context, layout, null, from, to);
- mContext = context;
- mUri = uri;
- mSelection = selection;
- mSelectionArgs = selectionArgs;
- mSortOrder = sortOrder;
- mColumns = new String[from.length + 1];
- // This is mandatory in CursorAdapter
- mColumns[0] = "_id";
- System.arraycopy(from, 0, mColumns, 1, from.length);
-
- CursorBinder basic = new StringBinder(context, new IdentityTransformation(context));
- final int count = from.length;
- mBinders = new CursorBinder[count];
-
- for (int i = 0; i < count; i++) {
- CursorBinder binder = binders.get(from[i]);
- if (binder == null) binder = basic;
- mBinders[i] = binder;
- }
- }
-
- @Override
- public void bindView(View view, Context context, Cursor cursor) {
- final int count = mTo.length;
- final int[] from = mFrom;
- final int[] to = mTo;
- final CursorBinder[] binders = mBinders;
-
- for (int i = 0; i < count; i++) {
- final View v = view.findViewById(to[i]);
- if (v != null) {
- binders[i].bind(v, cursor, from[i]);
- }
- }
- }
-
- public void load() {
- if (mUri != null) {
- mLoadTask = new QueryTask().execute();
- }
- }
-
- void setUri(String uri) {
- mUri = uri;
- }
-
- @Override
- public void changeCursor(Cursor c) {
- if (mLoadTask != null && mLoadTask.getStatus() != QueryTask.Status.FINISHED) {
- mLoadTask.cancel(true);
- mLoadTask = null;
- }
- super.changeCursor(c);
- }
-
- class QueryTask extends AsyncTask<Void, Void, Cursor> {
- @Override
- protected Cursor doInBackground(Void... params) {
- if (mContext instanceof Activity) {
- return ((Activity) mContext).managedQuery(
- Uri.parse(mUri), mColumns, mSelection, mSelectionArgs, mSortOrder);
- } else {
- return mContext.getContentResolver().query(
- Uri.parse(mUri), mColumns, mSelection, mSelectionArgs, mSortOrder);
- }
- }
-
- @Override
- protected void onPostExecute(Cursor cursor) {
- if (!isCancelled()) {
- XmlCursorAdapter.super.changeCursor(cursor);
- }
- }
- }
- }
-
- /**
- * Identity transformation, returns the content of the specified column as a String,
- * without performing any manipulation. This is used when no transformation is specified.
- */
- private static class IdentityTransformation extends CursorTransformation {
- public IdentityTransformation(Context context) {
- super(context);
- }
-
- @Override
- public String transform(Cursor cursor, int columnIndex) {
- return cursor.getString(columnIndex);
- }
- }
-
- /**
- * An expression transformation is a simple template based replacement utility.
- * In an expression, each segment of the form <code>{([^}]+)}</code> is replaced
- * with the value of the column of name $1.
- */
- private static class ExpressionTransformation extends CursorTransformation {
- private final ExpressionNode mFirstNode = new ConstantExpressionNode("");
- private final StringBuilder mBuilder = new StringBuilder();
-
- public ExpressionTransformation(Context context, String expression) {
- super(context);
-
- parse(expression);
- }
-
- private void parse(String expression) {
- ExpressionNode node = mFirstNode;
- int segmentStart;
- int count = expression.length();
-
- for (int i = 0; i < count; i++) {
- char c = expression.charAt(i);
- // Start a column name segment
- segmentStart = i;
- if (c == '{') {
- while (i < count && (c = expression.charAt(i)) != '}') {
- i++;
- }
- // We've reached the end, but the expression didn't close
- if (c != '}') {
- throw new IllegalStateException("The transform expression contains a " +
- "non-closed column name: " +
- expression.substring(segmentStart + 1, i));
- }
- node.next = new ColumnExpressionNode(expression.substring(segmentStart + 1, i));
- } else {
- while (i < count && (c = expression.charAt(i)) != '{') {
- i++;
- }
- node.next = new ConstantExpressionNode(expression.substring(segmentStart, i));
- // Rewind if we've reached a column expression
- if (c == '{') i--;
- }
- node = node.next;
- }
- }
-
- @Override
- public String transform(Cursor cursor, int columnIndex) {
- final StringBuilder builder = mBuilder;
- builder.delete(0, builder.length());
-
- ExpressionNode node = mFirstNode;
- // Skip the first node
- while ((node = node.next) != null) {
- builder.append(node.asString(cursor));
- }
-
- return builder.toString();
- }
-
- static abstract class ExpressionNode {
- public ExpressionNode next;
-
- public abstract String asString(Cursor cursor);
- }
-
- static class ConstantExpressionNode extends ExpressionNode {
- private final String mConstant;
-
- ConstantExpressionNode(String constant) {
- mConstant = constant;
- }
-
- @Override
- public String asString(Cursor cursor) {
- return mConstant;
- }
- }
-
- static class ColumnExpressionNode extends ExpressionNode {
- private final String mColumnName;
- private Cursor mSignature;
- private int mColumnIndex = -1;
-
- ColumnExpressionNode(String columnName) {
- mColumnName = columnName;
- }
-
- @Override
- public String asString(Cursor cursor) {
- if (cursor != mSignature || mColumnIndex == -1) {
- mColumnIndex = cursor.getColumnIndex(mColumnName);
- mSignature = cursor;
- }
-
- return cursor.getString(mColumnIndex);
- }
- }
- }
-
- /**
- * A map transformation offers a simple mapping between specified String values
- * to Strings or integers.
- */
- private static class MapTransformation extends CursorTransformation {
- private final HashMap<String, String> mStringMappings;
- private final HashMap<String, Integer> mResourceMappings;
-
- public MapTransformation(Context context) {
- super(context);
- mStringMappings = new HashMap<String, String>();
- mResourceMappings = new HashMap<String, Integer>();
- }
-
- void addStringMapping(String from, String to) {
- mStringMappings.put(from, to);
- }
-
- void addResourceMapping(String from, int to) {
- mResourceMappings.put(from, to);
- }
-
- @Override
- public String transform(Cursor cursor, int columnIndex) {
- final String value = cursor.getString(columnIndex);
- final String transformed = mStringMappings.get(value);
- return transformed == null ? value : transformed;
- }
-
- @Override
- public int transformToResource(Cursor cursor, int columnIndex) {
- final String value = cursor.getString(columnIndex);
- final Integer transformed = mResourceMappings.get(value);
- try {
- return transformed == null ? Integer.parseInt(value) : transformed;
- } catch (NumberFormatException e) {
- return 0;
- }
- }
- }
-
- /**
- * Binds a String to a TextView.
- */
- private static class StringBinder extends CursorBinder {
- public StringBinder(Context context, CursorTransformation transformation) {
- super(context, transformation);
- }
-
- @Override
- public boolean bind(View view, Cursor cursor, int columnIndex) {
- if (view instanceof TextView) {
- final String text = mTransformation.transform(cursor, columnIndex);
- ((TextView) view).setText(text);
- return true;
- }
- return false;
- }
- }
-
- /**
- * Binds an image blob to an ImageView.
- */
- private static class ImageBinder extends CursorBinder {
- public ImageBinder(Context context, CursorTransformation transformation) {
- super(context, transformation);
- }
-
- @Override
- public boolean bind(View view, Cursor cursor, int columnIndex) {
- if (view instanceof ImageView) {
- final byte[] data = cursor.getBlob(columnIndex);
- ((ImageView) view).setImageBitmap(BitmapFactory.decodeByteArray(data, 0,
- data.length));
- return true;
- }
- return false;
- }
- }
-
- private static class TagBinder extends CursorBinder {
- public TagBinder(Context context, CursorTransformation transformation) {
- super(context, transformation);
- }
-
- @Override
- public boolean bind(View view, Cursor cursor, int columnIndex) {
- final String text = mTransformation.transform(cursor, columnIndex);
- view.setTag(text);
- return true;
- }
- }
-
- /**
- * Binds an image URI to an ImageView.
- */
- private static class ImageUriBinder extends CursorBinder {
- public ImageUriBinder(Context context, CursorTransformation transformation) {
- super(context, transformation);
- }
-
- @Override
- public boolean bind(View view, Cursor cursor, int columnIndex) {
- if (view instanceof ImageView) {
- ((ImageView) view).setImageURI(Uri.parse(
- mTransformation.transform(cursor, columnIndex)));
- return true;
- }
- return false;
- }
- }
-
- /**
- * Binds a drawable resource identifier to an ImageView.
- */
- private static class DrawableBinder extends CursorBinder {
- public DrawableBinder(Context context, CursorTransformation transformation) {
- super(context, transformation);
- }
-
- @Override
- public boolean bind(View view, Cursor cursor, int columnIndex) {
- if (view instanceof ImageView) {
- final int resource = mTransformation.transformToResource(cursor, columnIndex);
- if (resource == 0) return false;
-
- ((ImageView) view).setImageResource(resource);
- return true;
- }
- return false;
- }
- }
-}
diff --git a/core/java/android/widget/AutoCompleteTextView.java b/core/java/android/widget/AutoCompleteTextView.java
index ee037cd..4d8d21f 100644
--- a/core/java/android/widget/AutoCompleteTextView.java
+++ b/core/java/android/widget/AutoCompleteTextView.java
@@ -607,10 +607,16 @@
// special case for the back key, we do not even try to send it
// to the drop down list but instead, consume it immediately
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
- getKeyDispatcherState().startTracking(event, this);
+ KeyEvent.DispatcherState state = getKeyDispatcherState();
+ if (state != null) {
+ state.startTracking(event, this);
+ }
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
- getKeyDispatcherState().handleUpEvent(event);
+ KeyEvent.DispatcherState state = getKeyDispatcherState();
+ if (state != null) {
+ state.handleUpEvent(event);
+ }
if (event.isTracking() && !event.isCanceled()) {
dismissDropDown();
return true;
diff --git a/core/java/android/widget/FastScroller.java b/core/java/android/widget/FastScroller.java
index 6ff671a..c06fe64 100644
--- a/core/java/android/widget/FastScroller.java
+++ b/core/java/android/widget/FastScroller.java
@@ -18,7 +18,6 @@
import android.content.Context;
import android.content.res.ColorStateList;
-import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
@@ -407,7 +406,10 @@
// Are there enough pages to require fast scroll? Recompute only if total count changes
if (mItemCount != totalItemCount && visibleItemCount > 0) {
mItemCount = totalItemCount;
- mLongList = mAlwaysShow || mItemCount / visibleItemCount >= MIN_PAGES;
+ mLongList = mItemCount / visibleItemCount >= MIN_PAGES;
+ }
+ if (mAlwaysShow) {
+ mLongList = true;
}
if (!mLongList) {
if (mState != STATE_NONE) {
@@ -416,8 +418,8 @@
return;
}
if (totalItemCount - visibleItemCount > 0 && mState != STATE_DRAGGING ) {
- mThumbY = ((mList.getHeight() - mThumbH) * firstVisibleItem)
- / (totalItemCount - visibleItemCount);
+ mThumbY = getThumbPositionForListPosition(firstVisibleItem, visibleItemCount,
+ totalItemCount);
if (mChangedBounds) {
resetThumbPos();
mChangedBounds = false;
@@ -579,6 +581,49 @@
}
}
+ private int getThumbPositionForListPosition(int firstVisibleItem, int visibleItemCount,
+ int totalItemCount) {
+ if (mSectionIndexer == null) {
+ getSectionsFromIndexer();
+ }
+ if (mSectionIndexer == null) {
+ return ((mList.getHeight() - mThumbH) * firstVisibleItem)
+ / (totalItemCount - visibleItemCount);
+ }
+
+ firstVisibleItem -= mListOffset;
+ if (firstVisibleItem < 0) {
+ return 0;
+ }
+ totalItemCount -= mListOffset;
+
+ final int trackHeight = mList.getHeight() - mThumbH;
+
+ final int section = mSectionIndexer.getSectionForPosition(firstVisibleItem);
+ final int sectionPos = mSectionIndexer.getPositionForSection(section);
+ final int nextSectionPos = mSectionIndexer.getPositionForSection(section + 1);
+ final int sectionCount = mSectionIndexer.getSections().length;
+ final int positionsInSection = nextSectionPos - sectionPos;
+
+ final View child = mList.getChildAt(0);
+ final float incrementalPos = firstVisibleItem +
+ (float) (mList.getPaddingTop() - child.getTop()) / child.getHeight();
+ final float posWithinSection = (incrementalPos - sectionPos) / positionsInSection;
+ int result = (int) ((section + posWithinSection) / sectionCount * trackHeight);
+
+ // Fake out the scrollbar for the last item. Since the section indexer won't
+ // ever actually move the list in this end space, make scrolling across the last item
+ // account for whatever space is remaining.
+ if (firstVisibleItem > 0 && firstVisibleItem + visibleItemCount == totalItemCount) {
+ final View lastChild = mList.getChildAt(visibleItemCount - 1);
+ final float lastItemVisible = (float) (mList.getHeight() - mList.getPaddingBottom()
+ - lastChild.getTop()) / lastChild.getHeight();
+ result += (trackHeight - result) * lastItemVisible;
+ }
+
+ return result;
+ }
+
private void cancelFling() {
// Cancel the list fling
MotionEvent cancelFling = MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0);
diff --git a/core/java/android/widget/FrameLayout.java b/core/java/android/widget/FrameLayout.java
index 7bae360..f659ead 100644
--- a/core/java/android/widget/FrameLayout.java
+++ b/core/java/android/widget/FrameLayout.java
@@ -265,11 +265,13 @@
final View child = getChildAt(i);
if (mMeasureAllChildren || child.getVisibility() != GONE) {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
- maxWidth = Math.max(maxWidth, child.getMeasuredWidth());
- maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
+ final LayoutParams lp = (LayoutParams) child.getLayoutParams();
+ maxWidth = Math.max(maxWidth,
+ child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
+ maxHeight = Math.max(maxHeight,
+ child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
if (measureMatchParentChildren) {
- final ViewGroup.LayoutParams lp = child.getLayoutParams();
if (lp.width == LayoutParams.MATCH_PARENT ||
lp.height == LayoutParams.MATCH_PARENT) {
mMatchParentChildren.add(child);
@@ -297,15 +299,15 @@
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
- if (mMatchParentChildren.size() > 0) {
- count = mMatchParentChildren.size();
+ count = mMatchParentChildren.size();
+ if (count > 1) {
for (int i = 0; i < count; i++) {
final View child = mMatchParentChildren.get(i);
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidthMeasureSpec;
int childHeightMeasureSpec;
-
+
if (lp.width == LayoutParams.MATCH_PARENT) {
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() -
mPaddingLeft - mPaddingRight - lp.leftMargin - lp.rightMargin,
@@ -321,7 +323,7 @@
mPaddingTop - mPaddingBottom - lp.topMargin - lp.bottomMargin,
MeasureSpec.EXACTLY);
} else {
- childHeightMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
+ childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin,
lp.height);
}
diff --git a/core/java/android/widget/HorizontalScrollView.java b/core/java/android/widget/HorizontalScrollView.java
index 50867b9..f6b1dbc 100644
--- a/core/java/android/widget/HorizontalScrollView.java
+++ b/core/java/android/widget/HorizontalScrollView.java
@@ -16,6 +16,7 @@
package android.widget;
+import android.view.ViewDebug;
import com.android.internal.R;
import android.util.AttributeSet;
@@ -115,6 +116,7 @@
* When set to true, the scroll view measure its child to make it fill the currently
* visible area.
*/
+ @ViewDebug.ExportedProperty(category = "layout")
private boolean mFillViewport;
/**
diff --git a/core/java/android/widget/ListPopupWindow.java b/core/java/android/widget/ListPopupWindow.java
index 3bba816..444a163d 100644
--- a/core/java/android/widget/ListPopupWindow.java
+++ b/core/java/android/widget/ListPopupWindow.java
@@ -915,10 +915,16 @@
// to the drop down list but instead, consume it immediately
final View anchorView = mDropDownAnchorView;
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
- anchorView.getKeyDispatcherState().startTracking(event, this);
+ KeyEvent.DispatcherState state = anchorView.getKeyDispatcherState();
+ if (state != null) {
+ state.startTracking(event, this);
+ }
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
- anchorView.getKeyDispatcherState().handleUpEvent(event);
+ KeyEvent.DispatcherState state = anchorView.getKeyDispatcherState();
+ if (state != null) {
+ state.handleUpEvent(event);
+ }
if (event.isTracking() && !event.isCanceled()) {
dismiss();
return true;
diff --git a/core/java/android/widget/PopupWindow.java b/core/java/android/widget/PopupWindow.java
index 5a5b6f4..79d6a81 100644
--- a/core/java/android/widget/PopupWindow.java
+++ b/core/java/android/widget/PopupWindow.java
@@ -1468,12 +1468,17 @@
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getRepeatCount() == 0) {
- getKeyDispatcherState().startTracking(event, this);
+ KeyEvent.DispatcherState state = getKeyDispatcherState();
+ if (state != null) {
+ state.startTracking(event, this);
+ }
return true;
- } else if (event.getAction() == KeyEvent.ACTION_UP
- && getKeyDispatcherState().isTracking(event) && !event.isCanceled()) {
- dismiss();
- return true;
+ } else if (event.getAction() == KeyEvent.ACTION_UP) {
+ KeyEvent.DispatcherState state = getKeyDispatcherState();
+ if (state != null && state.isTracking(event) && !event.isCanceled()) {
+ dismiss();
+ return true;
+ }
}
return super.dispatchKeyEvent(event);
} else {
diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java
index 02f5a8b..8558c70 100644
--- a/core/java/android/widget/ScrollView.java
+++ b/core/java/android/widget/ScrollView.java
@@ -16,6 +16,7 @@
package android.widget;
+import android.view.ViewDebug;
import com.android.internal.R;
import android.content.Context;
@@ -110,6 +111,7 @@
* When set to true, the scroll view measure its child to make it fill the currently
* visible area.
*/
+ @ViewDebug.ExportedProperty(category = "layout")
private boolean mFillViewport;
/**
diff --git a/core/java/android/widget/Spinner.java b/core/java/android/widget/Spinner.java
index 5a08442..0102628 100644
--- a/core/java/android/widget/Spinner.java
+++ b/core/java/android/widget/Spinner.java
@@ -25,7 +25,6 @@
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
-import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
@@ -262,7 +261,6 @@
setMeasuredDimension(Math.min(Math.max(measuredWidth, mPopup.measureContentWidth()),
MeasureSpec.getSize(widthMeasureSpec)),
getMeasuredHeight());
- Log.d(TAG, "onMeasure - old measured width " + measuredWidth + " new " + getMeasuredWidth());
}
}
@@ -672,6 +670,10 @@
@Override
public int measureContentWidth() {
final SpinnerAdapter adapter = getAdapter();
+ if (adapter == null) {
+ return 0;
+ }
+
int width = 0;
View itemView = null;
int itemType = 0;
diff --git a/core/java/android/widget/StackView.java b/core/java/android/widget/StackView.java
index ed06ded..0476d28 100644
--- a/core/java/android/widget/StackView.java
+++ b/core/java/android/widget/StackView.java
@@ -784,6 +784,18 @@
int stackDirection = (mStackMode == ITEMS_SLIDE_UP) ? 1 : -1;
+ // We need to prevent any clipping issues which may arise by setting a layer type.
+ // This doesn't come for free however, so we only want to enable it when required.
+ if (Float.compare(0f, mYProgress) != 0 && Float.compare(1.0f, mYProgress) != 0) {
+ if (mView.getLayerType() == LAYER_TYPE_NONE) {
+ mView.setLayerType(LAYER_TYPE_HARDWARE, null);
+ }
+ } else {
+ if (mView.getLayerType() != LAYER_TYPE_NONE) {
+ mView.setLayerType(LAYER_TYPE_NONE, null);
+ }
+ }
+
switch (mMode) {
case NORMAL_MODE:
viewLp.setVerticalOffset(Math.round(-r * stackDirection * mSlideAmount));
diff --git a/core/java/android/widget/Switch.java b/core/java/android/widget/Switch.java
index 8fb6fa3..cd4b732 100644
--- a/core/java/android/widget/Switch.java
+++ b/core/java/android/widget/Switch.java
@@ -479,9 +479,9 @@
}
private void animateThumbToCheckedState(boolean newCheckedState) {
- float targetPos = newCheckedState ? 0 : getThumbScrollRange();
// TODO animate!
- mThumbPosition = targetPos;
+ //float targetPos = newCheckedState ? 0 : getThumbScrollRange();
+ //mThumbPosition = targetPos;
setChecked(newCheckedState);
}
@@ -493,12 +493,15 @@
public void setChecked(boolean checked) {
super.setChecked(checked);
mThumbPosition = checked ? 0 : getThumbScrollRange();
+ invalidate();
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
+ mThumbPosition = isChecked() ? 0 : getThumbScrollRange();
+
int switchRight = getWidth() - getPaddingRight();
int switchLeft = switchRight - mSwitchWidth;
int switchTop = 0;
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index f0512f6..a1c286f 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -4672,6 +4672,9 @@
// don't let it be inserted into the text.
if ((event.getFlags() & KeyEvent.FLAG_EDITOR_ACTION) != 0
|| shouldAdvanceFocusOnEnter()) {
+ if (mOnClickListener != null) {
+ return 0;
+ }
return -1;
}
}
@@ -4780,7 +4783,6 @@
}
hideControllers();
- stopSelectionActionMode();
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
@@ -5119,6 +5121,7 @@
if (mInputMethodState != null) {
mInputMethodState.mExtracting = req;
}
+ // This stops a possible text selection mode. Maybe not intended.
hideControllers();
}
@@ -6781,7 +6784,7 @@
sendOnTextChanged(buffer, start, before, after);
onTextChanged(buffer, start, before, after);
- // Hide the controller if the amount of content changed
+ // Hide the controllers if the amount of content changed
if (before != after) {
hideControllers();
}
@@ -7645,9 +7648,7 @@
hasPrimaryClip());
}
- private boolean isWordCharacter(int position) {
- final char c = mTransformed.charAt(position);
- final int type = Character.getType(c);
+ private boolean isWordCharacter(int c, int type) {
return (c == '\'' || c == '"' ||
type == Character.UPPERCASE_LETTER ||
type == Character.LOWERCASE_LETTER ||
@@ -7696,35 +7697,32 @@
int start = end;
for (; start > 0; start--) {
- if (start == end) {
+ final char c = mTransformed.charAt(start - 1);
+ final int type = Character.getType(c);
+ if (start == end && type == Character.OTHER_PUNCTUATION) {
// Cases where the text ends with a '.' and we select from the end of the line
// (right after the dot), or when we select from the space character in "aaa, bbb".
- final char c = mTransformed.charAt(start - 1);
- final int type = Character.getType(c);
- if (type == Character.OTHER_PUNCTUATION) continue;
+ continue;
+ }
+ if (type == Character.SURROGATE) { // Two Character codepoint
+ end = start - 1; // Recheck as a pair when scanning forward
+ continue;
}
- if (!isWordCharacter(start - 1)) break;
+ if (!isWordCharacter(c, type)) break;
if ((end - start) > MAX_LENGTH) return -1;
}
for (; end < len; end++) {
- if (!isWordCharacter(end)) break;
+ final int c = Character.codePointAt(mTransformed, end);
+ final int type = Character.getType(c);
+ if (!isWordCharacter(c, type)) break;
if ((end - start) > MAX_LENGTH) return -1;
- }
-
- if (start == end) {
- return -1;
- }
-
- boolean hasLetter = false;
- for (int i = start; i < end; i++) {
- if (Character.isLetter(mTransformed.charAt(i))) {
- hasLetter = true;
- break;
+ if (c > 0xFFFF) { // Two Character codepoint
+ end++;
}
}
- if (!hasLetter) {
+ if (start == end) {
return -1;
}
@@ -7859,7 +7857,7 @@
MenuHandler handler = new MenuHandler();
- if (mText instanceof Spanned) {
+ if (mText instanceof Spanned && hasSelectionController()) {
long lastTouchOffset = getLastTouchOffsets();
final int selStart = extractRangeStartFromLong(lastTouchOffset);
final int selEnd = extractRangeEndFromLong(lastTouchOffset);
@@ -8041,32 +8039,32 @@
return packRangeInLong(min, max);
}
- private DragThumbnailBuilder getTextThumbnailBuilder(CharSequence text) {
- TextView thumbnail = (TextView) inflate(mContext,
+ private DragShadowBuilder getTextThumbnailBuilder(CharSequence text) {
+ TextView shadowView = (TextView) inflate(mContext,
com.android.internal.R.layout.text_drag_thumbnail, null);
- if (thumbnail == null) {
+ if (shadowView == null) {
throw new IllegalArgumentException("Unable to inflate text drag thumbnail");
}
- if (text.length() > DRAG_THUMBNAIL_MAX_TEXT_LENGTH) {
- text = text.subSequence(0, DRAG_THUMBNAIL_MAX_TEXT_LENGTH);
+ if (text.length() > DRAG_SHADOW_MAX_TEXT_LENGTH) {
+ text = text.subSequence(0, DRAG_SHADOW_MAX_TEXT_LENGTH);
}
- thumbnail.setText(text);
- thumbnail.setTextColor(getTextColors());
+ shadowView.setText(text);
+ shadowView.setTextColor(getTextColors());
- thumbnail.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge);
- thumbnail.setGravity(Gravity.CENTER);
+ shadowView.setTextAppearance(mContext, R.styleable.Theme_textAppearanceLarge);
+ shadowView.setGravity(Gravity.CENTER);
- thumbnail.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
+ shadowView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
- thumbnail.measure(size, size);
+ shadowView.measure(size, size);
- thumbnail.layout(0, 0, thumbnail.getMeasuredWidth(), thumbnail.getMeasuredHeight());
- thumbnail.invalidate();
- return new DragThumbnailBuilder(thumbnail);
+ shadowView.layout(0, 0, shadowView.getMeasuredWidth(), shadowView.getMeasuredHeight());
+ shadowView.invalidate();
+ return new DragShadowBuilder(shadowView);
}
private static class DragLocalState {
@@ -8212,9 +8210,12 @@
selectCurrentWord();
}
- final InputMethodManager imm = (InputMethodManager)
- getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
- imm.showSoftInput(this, 0, null);
+ if (!mTextIsSelectable) {
+ // Show the IME, except when selection non editable text.
+ final InputMethodManager imm = (InputMethodManager)
+ getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
+ imm.showSoftInput(this, 0, null);
+ }
ActionMode.Callback actionModeCallback = new SelectionActionModeCallback();
mSelectionActionMode = startActionMode(actionModeCallback);
@@ -8238,6 +8239,7 @@
private void stopSelectionActionMode() {
if (mSelectionActionMode != null) {
+ // This will hide the mSelectionModifierCursorController
mSelectionActionMode.finish();
}
}
@@ -8361,8 +8363,12 @@
if (mCustomSelectionActionModeCallback != null) {
mCustomSelectionActionModeCallback.onDestroyActionMode(mode);
}
- Selection.setSelection((Spannable) mText, getSelectionStart());
- hideSelectionModifierCursorController();
+ Selection.setSelection((Spannable) mText, getSelectionEnd());
+
+ if (mSelectionModifierCursorController != null) {
+ mSelectionModifierCursorController.hide();
+ }
+
mSelectionActionMode = null;
}
}
@@ -9178,16 +9184,12 @@
}
}
- private void hideSelectionModifierCursorController() {
- // No need to create the controller to hide it.
- if (mSelectionModifierCursorController != null) {
- mSelectionModifierCursorController.hide();
- }
- }
-
+ /**
+ * Hides the insertion controller and stops text selection mode, hiding the selection controller
+ */
private void hideControllers() {
hideInsertionPointCursorController();
- hideSelectionModifierCursorController();
+ stopSelectionActionMode();
}
/**
@@ -9508,7 +9510,7 @@
private static final InputFilter[] NO_FILTERS = new InputFilter[0];
private InputFilter[] mFilters = NO_FILTERS;
private static final Spanned EMPTY_SPANNED = new SpannedString("");
- private static int DRAG_THUMBNAIL_MAX_TEXT_LENGTH = 20;
+ private static int DRAG_SHADOW_MAX_TEXT_LENGTH = 20;
// System wide time for last cut or copy action.
private static long sLastCutOrCopyTime;
// Used to highlight a word when it is corrected by the IME
diff --git a/core/java/com/android/internal/app/HeavyWeightSwitcherActivity.java b/core/java/com/android/internal/app/HeavyWeightSwitcherActivity.java
index 1984167..ef7e651 100644
--- a/core/java/com/android/internal/app/HeavyWeightSwitcherActivity.java
+++ b/core/java/com/android/internal/app/HeavyWeightSwitcherActivity.java
@@ -28,6 +28,7 @@
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
+import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
@@ -84,8 +85,10 @@
button = findViewById((R.id.cancel));
button.setOnClickListener(mCancelListener);
+ TypedValue out = new TypedValue();
+ getTheme().resolveAttribute(android.R.attr.alertDialogIcon, out, true);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
- android.R.drawable.ic_dialog_alert);
+ out.resourceId);
}
void setText(int id, CharSequence text) {
diff --git a/core/java/com/android/internal/app/ShutdownThread.java b/core/java/com/android/internal/app/ShutdownThread.java
index cbdb947..d1c3e64 100644
--- a/core/java/com/android/internal/app/ShutdownThread.java
+++ b/core/java/com/android/internal/app/ShutdownThread.java
@@ -109,7 +109,7 @@
if (confirm) {
final CloseDialogReceiver closer = new CloseDialogReceiver(context);
final AlertDialog dialog = new AlertDialog.Builder(context)
- .setIcon(android.R.drawable.ic_dialog_alert)
+ .setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle(com.android.internal.R.string.power_off)
.setMessage(resourceId)
.setPositiveButton(com.android.internal.R.string.yes, new DialogInterface.OnClickListener() {
diff --git a/core/java/com/android/internal/view/menu/ActionMenuView.java b/core/java/com/android/internal/view/menu/ActionMenuView.java
index 96c1ed3..463902f 100644
--- a/core/java/com/android/internal/view/menu/ActionMenuView.java
+++ b/core/java/com/android/internal/view/menu/ActionMenuView.java
@@ -47,9 +47,7 @@
private boolean mReserveOverflow;
private OverflowMenuButton mOverflowButton;
private MenuPopupHelper mOverflowPopup;
-
- private float mButtonPaddingLeft;
- private float mButtonPaddingRight;
+
private float mDividerPadding;
private Drawable mDivider;
@@ -68,9 +66,10 @@
}
public void run() {
- mOverflowPopup = mPopup;
- mPopup.show();
- mPostedOpenRunnable = null;
+ if (mPopup.tryShow()) {
+ mOverflowPopup = mPopup;
+ mPostedOpenRunnable = null;
+ }
}
}
@@ -94,16 +93,9 @@
Configuration.SCREENLAYOUT_SIZE_XLARGE;
TypedArray a = context.obtainStyledAttributes(com.android.internal.R.styleable.Theme);
- final int buttonStyle = a.getResourceId(
- com.android.internal.R.styleable.Theme_actionButtonStyle, 0);
mDivider = a.getDrawable(com.android.internal.R.styleable.Theme_dividerVertical);
a.recycle();
- a = context.obtainStyledAttributes(buttonStyle, com.android.internal.R.styleable.View);
- mButtonPaddingLeft = a.getDimension(com.android.internal.R.styleable.View_paddingLeft, 0);
- mButtonPaddingRight = a.getDimension(com.android.internal.R.styleable.View_paddingRight, 0);
- a.recycle();
-
mDividerPadding = DIVIDER_PADDING * res.getDisplayMetrics().density;
setBaselineAligned(false);
@@ -147,6 +139,10 @@
mReserveOverflow = reserveOverflow;
}
+ public View getOverflowButton() {
+ return mOverflowButton;
+ }
+
@Override
protected LayoutParams generateDefaultLayoutParams() {
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
@@ -196,17 +192,6 @@
final MenuItemImpl itemData = itemsToShow.get(i);
View actionView = itemData.getActionView();
- if (actionView == null) {
- // Check for a layout ID instead
- final int layoutId = itemData.getActionViewId();
- if (layoutId != 0) {
- LayoutInflater inflater = LayoutInflater.from(getContext());
- actionView = inflater.inflate(layoutId, this, false);
- itemData.setActionView(0);
- itemData.setActionView(actionView);
- }
- }
-
if (actionView != null) {
final ViewParent parent = actionView.getParent();
if (parent instanceof ViewGroup) {
@@ -295,10 +280,7 @@
}
private LayoutParams makeActionViewLayoutParams(View view) {
- LayoutParams params = generateLayoutParams(view.getLayoutParams());
- params.leftMargin = (int) mButtonPaddingLeft;
- params.rightMargin = (int) mButtonPaddingRight;
- return params;
+ return generateLayoutParams(view.getLayoutParams());
}
private class OverflowMenuButton extends ImageButton {
diff --git a/core/java/com/android/internal/view/menu/MenuItemImpl.java b/core/java/com/android/internal/view/menu/MenuItemImpl.java
index 9faffe5..e1aa385 100644
--- a/core/java/com/android/internal/view/menu/MenuItemImpl.java
+++ b/core/java/com/android/internal/view/menu/MenuItemImpl.java
@@ -83,7 +83,6 @@
private int mShowAsAction = SHOW_AS_ACTION_NEVER;
private View mActionView;
- private int mActionViewId;
/** Used for the icon resource ID if this item does not have an icon */
static final int NO_ICON = 0;
@@ -696,15 +695,13 @@
}
public MenuItem setActionView(int resId) {
- mActionViewId = resId;
+ LayoutInflater inflater = LayoutInflater.from(mMenu.getContext());
+ ViewGroup parent = (ViewGroup) mMenu.getMenuView(MenuBuilder.TYPE_ACTION_BUTTON, null);
+ setActionView(inflater.inflate(resId, parent, false));
return this;
}
public View getActionView() {
return mActionView;
}
-
- public int getActionViewId() {
- return mActionViewId;
- }
}
diff --git a/core/java/com/android/internal/view/menu/MenuPopupHelper.java b/core/java/com/android/internal/view/menu/MenuPopupHelper.java
index a070835..b93fac4 100644
--- a/core/java/com/android/internal/view/menu/MenuPopupHelper.java
+++ b/core/java/com/android/internal/view/menu/MenuPopupHelper.java
@@ -68,7 +68,17 @@
}
}
+ public void setAnchorView(View anchor) {
+ mAnchorView = new WeakReference<View>(anchor);
+ }
+
public void show() {
+ if (!tryShow()) {
+ throw new IllegalStateException("MenuPopupHelper cannot be used without an anchor");
+ }
+ }
+
+ public boolean tryShow() {
mPopup = new ListPopupWindow(mContext, null, com.android.internal.R.attr.popupMenuStyle);
mPopup.setOnItemClickListener(this);
mPopup.setOnDismissListener(this);
@@ -92,13 +102,14 @@
mTreeObserver.addOnGlobalLayoutListener(this);
mPopup.setAnchorView(anchor);
} else {
- throw new IllegalStateException("MenuPopupHelper cannot be used without an anchor");
+ return false;
}
mPopup.setContentWidth(Math.min(measureContentWidth(adapter), mPopupMaxWidth));
mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
mPopup.show();
mPopup.getListView().setOnKeyListener(this);
+ return true;
}
public void dismiss() {
diff --git a/core/java/com/android/internal/widget/ActionBarContextView.java b/core/java/com/android/internal/widget/ActionBarContextView.java
index 5ae3616..23f89f1 100644
--- a/core/java/com/android/internal/widget/ActionBarContextView.java
+++ b/core/java/com/android/internal/widget/ActionBarContextView.java
@@ -159,7 +159,7 @@
}
public void initForMode(final ActionMode mode) {
- if (mAnimationMode == ANIMATE_OUT) {
+ if (mAnimationMode != ANIMATE_IDLE || mAnimateInOnLayout) {
killMode();
}
@@ -216,6 +216,7 @@
removeAllViews();
mCustomView = null;
mMenuView = null;
+ mAnimateInOnLayout = false;
}
public boolean showOverflowMenu() {
diff --git a/core/java/com/android/internal/widget/DigitalClock.java b/core/java/com/android/internal/widget/DigitalClock.java
index ebfe9a9..bc749d8 100644
--- a/core/java/com/android/internal/widget/DigitalClock.java
+++ b/core/java/com/android/internal/widget/DigitalClock.java
@@ -129,7 +129,7 @@
mTimeDisplayBackground.setTypeface(Typeface.createFromFile(SYSTEM_FONT_TIME_BACKGROUND));
mTimeDisplayForeground = (TextView) findViewById(R.id.timeDisplayForeground);
mTimeDisplayForeground.setTypeface(Typeface.createFromFile(SYSTEM_FONT_TIME_FOREGROUND));
- mAmPm = new AmPm(this, Typeface.createFromFile(SYSTEM_FONT_TIME_BACKGROUND));
+ mAmPm = new AmPm(this, null);
mCalendar = Calendar.getInstance();
setDateFormat();
diff --git a/core/jni/Android.mk b/core/jni/Android.mk
index 241bc3e..c635b39 100644
--- a/core/jni/Android.mk
+++ b/core/jni/Android.mk
@@ -111,6 +111,7 @@
android/graphics/Rasterizer.cpp \
android/graphics/Region.cpp \
android/graphics/Shader.cpp \
+ android/graphics/SurfaceTexture.cpp \
android/graphics/TextLayout.cpp \
android/graphics/Typeface.cpp \
android/graphics/Utils.cpp \
diff --git a/core/jni/AndroidRuntime.cpp b/core/jni/AndroidRuntime.cpp
index b6e4119..d28bdc9 100644
--- a/core/jni/AndroidRuntime.cpp
+++ b/core/jni/AndroidRuntime.cpp
@@ -111,6 +111,7 @@
extern int register_android_graphics_Picture(JNIEnv*);
extern int register_android_graphics_PorterDuff(JNIEnv* env);
extern int register_android_graphics_Rasterizer(JNIEnv* env);
+extern int register_android_graphics_SurfaceTexture(JNIEnv* env);
extern int register_android_graphics_Xfermode(JNIEnv* env);
extern int register_android_graphics_PixelFormat(JNIEnv* env);
extern int register_com_android_internal_graphics_NativeUtils(JNIEnv *env);
@@ -1235,6 +1236,7 @@
REG_JNI(register_android_graphics_Rasterizer),
REG_JNI(register_android_graphics_Region),
REG_JNI(register_android_graphics_Shader),
+ REG_JNI(register_android_graphics_SurfaceTexture),
REG_JNI(register_android_graphics_Typeface),
REG_JNI(register_android_graphics_Xfermode),
REG_JNI(register_android_graphics_YuvImage),
diff --git a/core/jni/android/graphics/SurfaceTexture.cpp b/core/jni/android/graphics/SurfaceTexture.cpp
new file mode 100644
index 0000000..2645045
--- /dev/null
+++ b/core/jni/android/graphics/SurfaceTexture.cpp
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2010 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 "SurfaceTexture"
+
+#include <stdio.h>
+
+#include <gui/SurfaceTexture.h>
+
+#include <android_runtime/AndroidRuntime.h>
+
+#include <utils/Log.h>
+#include <utils/misc.h>
+
+#include "android/graphics/GraphicsJNI.h"
+#include "jni.h"
+
+// ----------------------------------------------------------------------------
+
+namespace android {
+
+static const char* const OutOfResourcesException =
+ "android/graphics/SurfaceTexture$OutOfResourcesException";
+
+struct st_t {
+ jfieldID surfaceTexture;
+};
+static st_t st;
+
+// ----------------------------------------------------------------------------
+
+static void setSurfaceTexture(JNIEnv* env, jobject clazz,
+ const sp<SurfaceTexture>& surfaceTexture)
+{
+ SurfaceTexture* const p =
+ (SurfaceTexture*)env->GetIntField(clazz, st.surfaceTexture);
+ if (surfaceTexture.get()) {
+ surfaceTexture->incStrong(clazz);
+ }
+ if (p) {
+ p->decStrong(clazz);
+ }
+ env->SetIntField(clazz, st.surfaceTexture, (int)surfaceTexture.get());
+}
+
+sp<SurfaceTexture> getSurfaceTexture(JNIEnv* env, jobject clazz)
+{
+ sp<SurfaceTexture> surfaceTexture(
+ (SurfaceTexture*)env->GetIntField(clazz, st.surfaceTexture));
+ return surfaceTexture;
+}
+
+// ----------------------------------------------------------------------------
+
+static void SurfaceTexture_init(JNIEnv* env, jobject clazz, jint texName)
+{
+ sp<SurfaceTexture> surfaceTexture(new SurfaceTexture(texName));
+
+ if (surfaceTexture == 0) {
+ doThrow(env, OutOfResourcesException);
+ return;
+ }
+ setSurfaceTexture(env, clazz, surfaceTexture);
+}
+
+static void SurfaceTexture_updateTexImage(JNIEnv* env, jobject clazz)
+{
+ sp<SurfaceTexture> surfaceTexture(getSurfaceTexture(env, clazz));
+ surfaceTexture->updateTexImage();
+}
+
+// ----------------------------------------------------------------------------
+
+const char* const kSurfaceTextureClassPathName = "android/graphics/SurfaceTexture";
+static void nativeClassInit(JNIEnv* env, jclass clazz);
+
+static JNINativeMethod gSurfaceTextureMethods[] = {
+ {"nativeClassInit", "()V", (void*)nativeClassInit },
+ {"init", "(I)V", (void*)SurfaceTexture_init },
+ {"updateTexImage", "()V", (void*)SurfaceTexture_updateTexImage },
+};
+
+static void nativeClassInit(JNIEnv* env, jclass clazz)
+{
+ st.surfaceTexture = env->GetFieldID(clazz,
+ ANDROID_GRAPHICS_SURFACETEXTURE_JNI_ID, "I");
+}
+
+int register_android_graphics_SurfaceTexture(JNIEnv* env)
+{
+ int err = 0;
+ err = AndroidRuntime::registerNativeMethods(env, kSurfaceTextureClassPathName,
+ gSurfaceTextureMethods, NELEM(gSurfaceTextureMethods));
+ return err;
+}
+
+} // namespace android
diff --git a/core/jni/android_hardware_Camera.cpp b/core/jni/android_hardware_Camera.cpp
index 10fe583..9f70509 100644
--- a/core/jni/android_hardware_Camera.cpp
+++ b/core/jni/android_hardware_Camera.cpp
@@ -25,6 +25,7 @@
#include <utils/Vector.h>
+#include <gui/SurfaceTexture.h>
#include <surfaceflinger/Surface.h>
#include <camera/Camera.h>
#include <binder/IMemory.h>
@@ -34,6 +35,7 @@
struct fields_t {
jfieldID context;
jfieldID surface;
+ jfieldID surfaceTexture;
jfieldID facing;
jfieldID orientation;
jmethodID post_event;
@@ -393,6 +395,24 @@
}
}
+static void android_hardware_Camera_setPreviewTexture(JNIEnv *env,
+ jobject thiz, jobject jSurfaceTexture)
+{
+ LOGV("setPreviewTexture");
+ sp<Camera> camera = get_native_camera(env, thiz, NULL);
+ if (camera == 0) return;
+
+ sp<SurfaceTexture> surfaceTexture = NULL;
+ if (jSurfaceTexture != NULL) {
+ surfaceTexture = reinterpret_cast<SurfaceTexture*>(env->GetIntField(
+ jSurfaceTexture, fields.surfaceTexture));
+ }
+ if (camera->setPreviewTexture(surfaceTexture) != NO_ERROR) {
+ jniThrowException(env, "java/io/IOException",
+ "setPreviewTexture failed");
+ }
+}
+
static void android_hardware_Camera_startPreview(JNIEnv *env, jobject thiz)
{
LOGV("startPreview");
@@ -603,6 +623,9 @@
{ "setPreviewDisplay",
"(Landroid/view/Surface;)V",
(void *)android_hardware_Camera_setPreviewDisplay },
+ { "setPreviewTexture",
+ "(Landroid/graphics/SurfaceTexture;)V",
+ (void *)android_hardware_Camera_setPreviewTexture },
{ "startPreview",
"()V",
(void *)android_hardware_Camera_startPreview },
@@ -688,6 +711,8 @@
field fields_to_find[] = {
{ "android/hardware/Camera", "mNativeContext", "I", &fields.context },
{ "android/view/Surface", ANDROID_VIEW_SURFACE_JNI_ID, "I", &fields.surface },
+ { "android/graphics/SurfaceTexture",
+ ANDROID_GRAPHICS_SURFACETEXTURE_JNI_ID, "I", &fields.surfaceTexture },
{ "android/hardware/Camera$CameraInfo", "facing", "I", &fields.facing },
{ "android/hardware/Camera$CameraInfo", "orientation", "I", &fields.orientation },
};
@@ -708,4 +733,3 @@
return AndroidRuntime::registerNativeMethods(env, "android/hardware/Camera",
camMethods, NELEM(camMethods));
}
-
diff --git a/core/jni/android_view_GLES20Canvas.cpp b/core/jni/android_view_GLES20Canvas.cpp
index c3d3572..b4c868f 100644
--- a/core/jni/android_view_GLES20Canvas.cpp
+++ b/core/jni/android_view_GLES20Canvas.cpp
@@ -417,16 +417,21 @@
// Display lists
// ----------------------------------------------------------------------------
-static OpenGLRenderer* android_view_GLES20Canvas_createDisplayListRenderer(
- JNIEnv* env, jobject canvas) {
- return new DisplayListRenderer;
-}
-
-static DisplayList* android_view_GLES20Canvas_createDisplayList(JNIEnv* env,
+static DisplayList* android_view_GLES20Canvas_getDisplayList(JNIEnv* env,
jobject canvas, DisplayListRenderer* renderer) {
return renderer->getDisplayList();
}
+static OpenGLRenderer* android_view_GLES20Canvas_getDisplayListRenderer(JNIEnv* env,
+ jobject clazz, DisplayListRenderer* renderer) {
+ if (renderer == NULL) {
+ renderer = new DisplayListRenderer;
+ } else {
+ renderer->reset();
+ }
+ return renderer;
+}
+
static void android_view_GLES20Canvas_destroyDisplayList(JNIEnv* env,
jobject clazz, DisplayList* displayList) {
delete displayList;
@@ -517,9 +522,9 @@
{ "nGetClipBounds", "(ILandroid/graphics/Rect;)Z",
(void*) android_view_GLES20Canvas_getClipBounds },
- { "nCreateDisplayListRenderer", "()I", (void*) android_view_GLES20Canvas_createDisplayListRenderer },
- { "nCreateDisplayList", "(I)I", (void*) android_view_GLES20Canvas_createDisplayList },
+ { "nGetDisplayList", "(I)I", (void*) android_view_GLES20Canvas_getDisplayList },
{ "nDestroyDisplayList", "(I)V", (void*) android_view_GLES20Canvas_destroyDisplayList },
+ { "nGetDisplayListRenderer", "(I)I", (void*) android_view_GLES20Canvas_getDisplayListRenderer },
{ "nDrawDisplayList", "(II)V", (void*) android_view_GLES20Canvas_drawDisplayList },
#endif
diff --git a/core/jni/com_android_internal_os_ZygoteInit.cpp b/core/jni/com_android_internal_os_ZygoteInit.cpp
index ada4dd3..52e8f42 100644
--- a/core/jni/com_android_internal_os_ZygoteInit.cpp
+++ b/core/jni/com_android_internal_os_ZygoteInit.cpp
@@ -45,14 +45,10 @@
static jint com_android_internal_os_ZygoteInit_setreuid(
JNIEnv* env, jobject clazz, jint ruid, jint euid)
{
- int err;
-
- errno = 0;
- err = setreuid(ruid, euid);
-
- //LOGI("setreuid(%d,%d) err %d errno %d", ruid, euid, err, errno);
-
- return errno;
+ if (setreuid(ruid, euid) < 0) {
+ return errno;
+ }
+ return 0;
}
/*
@@ -62,14 +58,10 @@
static jint com_android_internal_os_ZygoteInit_setregid(
JNIEnv* env, jobject clazz, jint rgid, jint egid)
{
- int err;
-
- errno = 0;
- err = setregid(rgid, egid);
-
- //LOGI("setregid(%d,%d) err %d errno %d", rgid, egid, err, errno);
-
- return errno;
+ if (setregid(rgid, egid) < 0) {
+ return errno;
+ }
+ return 0;
}
/*
@@ -79,13 +71,10 @@
static jint com_android_internal_os_ZygoteInit_setpgid(
JNIEnv* env, jobject clazz, jint pid, jint pgid)
{
- int err;
-
- errno = 0;
-
- err = setpgid(pid, pgid);
-
- return errno;
+ if (setpgid(pid, pgid) < 0) {
+ return errno;
+ }
+ return 0;
}
/*
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 981661a..67adc28 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -85,8 +85,6 @@
<protected-broadcast android:name="android.hardware.action.USB_CONNECTED" />
<protected-broadcast android:name="android.hardware.action.USB_DISCONNECTED" />
<protected-broadcast android:name="android.hardware.action.USB_STATE" />
- <protected-broadcast android:name="android.hardware.action.USB_CAMERA_ATTACHED" />
- <protected-broadcast android:name="android.hardware.action.USB_CAMERA_DETACHED" />
<protected-broadcast android:name="android.nfc.action.LLCP_LINK_STATE_CHANGED" />
<protected-broadcast android:name="android.nfc.action.TRANSACTION_DETECTED" />
@@ -472,6 +470,15 @@
android:label="@string/permlab_accessUsb"
android:description="@string/permdesc_accessUsb" />
+ <!-- Allows an application to access the MTP USB kernel driver.
+ For use only by the device side MTP implementation.
+ @hide -->
+ <permission android:name="android.permission.ACCESS_MTP"
+ android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
+ android:protectionLevel="signatureOrSystem"
+ android:label="@string/permlab_accessMtp"
+ android:description="@string/permdesc_accessMtp" />
+
<!-- Allows access to hardware peripherals. Intended only for hardware testing -->
<permission android:name="android.permission.HARDWARE_TEST"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
@@ -533,7 +540,8 @@
android:description="@string/permdesc_sdcardWrite"
android:protectionLevel="dangerous" />
- <!-- Allows an application to write to internal media storage -->
+ <!-- Allows an application to write to internal media storage
+ @hide -->
<permission android:name="android.permission.WRITE_MEDIA_STORAGE"
android:permissionGroup="android.permission-group.STORAGE"
android:label="@string/permlab_mediaStorageWrite"
diff --git a/core/res/res/anim/animator_fade_out.xml b/core/res/res/anim/animator_fade_out.xml
deleted file mode 100644
index 6a3d5ee..0000000
--- a/core/res/res/anim/animator_fade_out.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2010, 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.
-*/
--->
-
-<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
- android:interpolator="@interpolator/accelerate_quad"
- android:valueFrom="1.0"
- android:valueTo="0.0"
- android:propertyName="alpha"
- android:duration="@android:integer/config_mediumAnimTime"
-/>
diff --git a/core/res/res/anim/fragment_close_enter.xml b/core/res/res/anim/fragment_close_enter.xml
deleted file mode 100644
index c0abbc5..0000000
--- a/core/res/res/anim/fragment_close_enter.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2010, 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.
-*/
--->
-<set xmlns:android="http://schemas.android.com/apk/res/android"
- android:zAdjustment="normal">
- <objectAnimator
- android:interpolator="@interpolator/decelerate_quint"
- android:valueFrom="0.975" android:valueTo="1.0"
- android:valueType="floatType"
- android:propertyName="scaleY"
- android:duration="@android:integer/config_activityDefaultDur"/>
- <objectAnimator
- android:interpolator="@interpolator/decelerate_quint"
- android:valueFrom="0.975" android:valueTo="1.0"
- android:valueType="floatType"
- android:propertyName="scaleX"
- android:duration="@android:integer/config_activityDefaultDur"/>
- <objectAnimator
- android:interpolator="@interpolator/decelerate_cubic"
- android:valueFrom="0.0" android:valueTo="1.0"
- android:valueType="floatType"
- android:propertyName="alpha"
- android:duration="@android:integer/config_activityDefaultDur"/>
-</set>
\ No newline at end of file
diff --git a/core/res/res/anim/fragment_close_exit.xml b/core/res/res/anim/fragment_close_exit.xml
deleted file mode 100644
index 9a5708c..0000000
--- a/core/res/res/anim/fragment_close_exit.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2010, 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.
-*/
--->
-<set xmlns:android="http://schemas.android.com/apk/res/android"
- android:zAdjustment="top">
- <objectAnimator
- android:interpolator="@interpolator/decelerate_quint"
- android:valueFrom="1.0" android:valueTo="1.075"
- android:valueType="floatType"
- android:propertyName="scaleY"
- android:duration="@android:integer/config_activityDefaultDur"/>
- <objectAnimator
- android:interpolator="@interpolator/decelerate_quint"
- android:valueFrom="1.0" android:valueTo="1.075"
- android:valueType="floatType"
- android:propertyName="scaleX"
- android:duration="@android:integer/config_activityDefaultDur"/>
- <objectAnimator
- android:interpolator="@interpolator/decelerate_cubic"
- android:valueFrom="1.0" android:valueTo="0.0"
- android:valueType="floatType"
- android:propertyName="alpha"
- android:duration="@android:integer/config_activityDefaultDur"/>
-</set>
\ No newline at end of file
diff --git a/core/res/res/anim/fragment_next_enter.xml b/core/res/res/anim/fragment_next_enter.xml
deleted file mode 100644
index 13b15f3..0000000
--- a/core/res/res/anim/fragment_next_enter.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2010, 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.
-*/
--->
-<set xmlns:android="http://schemas.android.com/apk/res/android"
- android:zAdjustment="top">
- <objectAnimator
- android:interpolator="@interpolator/decelerate_cubic"
- android:valueFrom="0"
- android:valueTo="1"
- android:valueType="floatType"
- android:propertyName="alpha"
- android:duration="@android:integer/config_activityDefaultDur"/>
-</set>
\ No newline at end of file
diff --git a/core/res/res/anim/fragment_next_exit.xml b/core/res/res/anim/fragment_next_exit.xml
deleted file mode 100644
index 503b7ad..0000000
--- a/core/res/res/anim/fragment_next_exit.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2010, 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.
-*/
--->
-<set xmlns:android="http://schemas.android.com/apk/res/android"
- android:zAdjustment="normal">
- <objectAnimator
- android:interpolator="@interpolator/decelerate_cubic"
- android:valueFrom="1"
- android:valueTo="0"
- android:valueType="floatType"
- android:propertyName="alpha"
- android:duration="@android:integer/config_activityShortDur"/>
-</set>
\ No newline at end of file
diff --git a/core/res/res/anim/fragment_open_enter.xml b/core/res/res/anim/fragment_open_enter.xml
deleted file mode 100644
index 6b16cb4..0000000
--- a/core/res/res/anim/fragment_open_enter.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2010, 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.
-*/
--->
-<set xmlns:android="http://schemas.android.com/apk/res/android">
- <objectAnimator
- android:interpolator="@interpolator/decelerate_quint"
- android:valueFrom="1.125" android:valueTo="1.0"
- android:valueType="floatType"
- android:propertyName="scaleY"
- android:duration="@android:integer/config_activityDefaultDur"/>
- <objectAnimator
- android:interpolator="@interpolator/decelerate_quint"
- android:valueFrom="1.125" android:valueTo="1.0"
- android:valueType="floatType"
- android:propertyName="scaleX"
- android:duration="@android:integer/config_activityDefaultDur"/>
- <objectAnimator
- android:interpolator="@interpolator/decelerate_cubic"
- android:valueFrom="0.0" android:valueTo="1.0"
- android:valueType="floatType"
- android:propertyName="alpha"
- android:duration="@android:integer/config_activityDefaultDur"/>
-</set>
\ No newline at end of file
diff --git a/core/res/res/anim/fragment_open_exit.xml b/core/res/res/anim/fragment_open_exit.xml
deleted file mode 100644
index d77ee8e..0000000
--- a/core/res/res/anim/fragment_open_exit.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2010, 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.
-*/
--->
-<set xmlns:android="http://schemas.android.com/apk/res/android">
- <objectAnimator
- android:interpolator="@interpolator/linear"
- android:valueFrom="1.0" android:valueTo="0.975"
- android:valueType="floatType"
- android:propertyName="scaleY"
- android:duration="@android:integer/config_activityDefaultDur"/>
- <objectAnimator
- android:interpolator="@interpolator/linear"
- android:valueFrom="1.0" android:valueTo="0.975"
- android:valueType="floatType"
- android:propertyName="scaleX"
- android:duration="@android:integer/config_activityDefaultDur"/>
- <objectAnimator
- android:interpolator="@interpolator/decelerate_cubic"
- android:valueFrom="1.0" android:valueTo="0.0"
- android:valueType="floatType"
- android:propertyName="alpha"
- android:duration="@android:integer/config_activityDefaultDur"/>
-</set>
\ No newline at end of file
diff --git a/core/res/res/anim/fragment_prev_enter.xml b/core/res/res/anim/fragment_prev_enter.xml
deleted file mode 100644
index 13b15f3..0000000
--- a/core/res/res/anim/fragment_prev_enter.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2010, 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.
-*/
--->
-<set xmlns:android="http://schemas.android.com/apk/res/android"
- android:zAdjustment="top">
- <objectAnimator
- android:interpolator="@interpolator/decelerate_cubic"
- android:valueFrom="0"
- android:valueTo="1"
- android:valueType="floatType"
- android:propertyName="alpha"
- android:duration="@android:integer/config_activityDefaultDur"/>
-</set>
\ No newline at end of file
diff --git a/core/res/res/anim/fragment_prev_exit.xml b/core/res/res/anim/fragment_prev_exit.xml
deleted file mode 100644
index 503b7ad..0000000
--- a/core/res/res/anim/fragment_prev_exit.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
-** Copyright 2010, 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.
-*/
--->
-<set xmlns:android="http://schemas.android.com/apk/res/android"
- android:zAdjustment="normal">
- <objectAnimator
- android:interpolator="@interpolator/decelerate_cubic"
- android:valueFrom="1"
- android:valueTo="0"
- android:valueType="floatType"
- android:propertyName="alpha"
- android:duration="@android:integer/config_activityShortDur"/>
-</set>
\ No newline at end of file
diff --git a/core/res/res/animator/fade_in.xml b/core/res/res/animator/fade_in.xml
index 2a28b4d..cff98cf 100644
--- a/core/res/res/animator/fade_in.xml
+++ b/core/res/res/animator/fade_in.xml
@@ -18,7 +18,7 @@
-->
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
- android:interpolator="@anim/accelerate_interpolator"
+ android:interpolator="@interpolator/accelerate_quad"
android:valueFrom="0"
android:valueTo="1"
android:propertyName="alpha"
diff --git a/core/res/res/animator/fade_out.xml b/core/res/res/animator/fade_out.xml
index 4db6591..6a3d5ee 100644
--- a/core/res/res/animator/fade_out.xml
+++ b/core/res/res/animator/fade_out.xml
@@ -18,7 +18,7 @@
-->
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
- android:interpolator="@anim/accelerate_interpolator"
+ android:interpolator="@interpolator/accelerate_quad"
android:valueFrom="1.0"
android:valueTo="0.0"
android:propertyName="alpha"
diff --git a/core/res/res/drawable-hdpi/dialog_bottom_holo_dark.9.png b/core/res/res/drawable-hdpi/dialog_bottom_holo_dark.9.png
index bbfb9f7..065cc9c 100644
--- a/core/res/res/drawable-hdpi/dialog_bottom_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/dialog_bottom_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_bottom_holo_light.9.png b/core/res/res/drawable-hdpi/dialog_bottom_holo_light.9.png
index af69ee5..94decee 100644
--- a/core/res/res/drawable-hdpi/dialog_bottom_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/dialog_bottom_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_full_holo.9.png b/core/res/res/drawable-hdpi/dialog_full_holo.9.png
deleted file mode 100644
index 5d2e4e1..0000000
--- a/core/res/res/drawable-hdpi/dialog_full_holo.9.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_full_holo_dark.9.png b/core/res/res/drawable-hdpi/dialog_full_holo_dark.9.png
index 59b9b13..f0b2041 100644
--- a/core/res/res/drawable-hdpi/dialog_full_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/dialog_full_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_full_holo_light.9.png b/core/res/res/drawable-hdpi/dialog_full_holo_light.9.png
index e1ec9dc..5b93be7 100644
--- a/core/res/res/drawable-hdpi/dialog_full_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/dialog_full_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_middle_holo_dark.9.png b/core/res/res/drawable-hdpi/dialog_middle_holo_dark.9.png
index a9f85ea..dc62ab2 100644
--- a/core/res/res/drawable-hdpi/dialog_middle_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/dialog_middle_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_middle_holo_light.9.png b/core/res/res/drawable-hdpi/dialog_middle_holo_light.9.png
index c4c4652..e78e134 100644
--- a/core/res/res/drawable-hdpi/dialog_middle_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/dialog_middle_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_top_holo.9.png b/core/res/res/drawable-hdpi/dialog_top_holo.9.png
deleted file mode 100644
index 0275c18..0000000
--- a/core/res/res/drawable-hdpi/dialog_top_holo.9.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_top_holo_dark.9.png b/core/res/res/drawable-hdpi/dialog_top_holo_dark.9.png
index 32c2cb4..ae223c8 100644
--- a/core/res/res/drawable-hdpi/dialog_top_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/dialog_top_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/dialog_top_holo_light.9.png b/core/res/res/drawable-hdpi/dialog_top_holo_light.9.png
index 7a8fb0e..7baced0 100644
--- a/core/res/res/drawable-hdpi/dialog_top_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/dialog_top_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_dialog_alert_holo_dark.png b/core/res/res/drawable-hdpi/ic_dialog_alert_holo_dark.png
new file mode 100644
index 0000000..f0ba889
--- /dev/null
+++ b/core/res/res/drawable-hdpi/ic_dialog_alert_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_dialog_alert_holo_light.png b/core/res/res/drawable-hdpi/ic_dialog_alert_holo_light.png
new file mode 100644
index 0000000..1374a53
--- /dev/null
+++ b/core/res/res/drawable-hdpi/ic_dialog_alert_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/ic_menu_help.png b/core/res/res/drawable-hdpi/ic_menu_help.png
index 4300e86..01a77da 100644
--- a/core/res/res/drawable-hdpi/ic_menu_help.png
+++ b/core/res/res/drawable-hdpi/ic_menu_help.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progress_bg_holo_dark.9.png b/core/res/res/drawable-hdpi/progress_bg_holo_dark.9.png
index 079de61..5aea3d9 100644
--- a/core/res/res/drawable-hdpi/progress_bg_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/progress_bg_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progress_bg_holo_light.9.png b/core/res/res/drawable-hdpi/progress_bg_holo_light.9.png
index 2272b41..5743d06 100644
--- a/core/res/res/drawable-hdpi/progress_bg_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/progress_bg_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progress_primary_holo_dark.9.png b/core/res/res/drawable-hdpi/progress_primary_holo_dark.9.png
index 16b7349..f134a59 100644
--- a/core/res/res/drawable-hdpi/progress_primary_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/progress_primary_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progress_primary_holo_light.9.png b/core/res/res/drawable-hdpi/progress_primary_holo_light.9.png
index 7229343..f134a59 100644
--- a/core/res/res/drawable-hdpi/progress_primary_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/progress_primary_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progress_secondary_holo_dark.9.png b/core/res/res/drawable-hdpi/progress_secondary_holo_dark.9.png
index 894dfcf..22d608a 100644
--- a/core/res/res/drawable-hdpi/progress_secondary_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/progress_secondary_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progress_secondary_holo_light.9.png b/core/res/res/drawable-hdpi/progress_secondary_holo_light.9.png
index f553ba6..22d608a 100644
--- a/core/res/res/drawable-hdpi/progress_secondary_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/progress_secondary_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progressbar_indeterminate_holo1.png b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo1.png
new file mode 100644
index 0000000..595e0a4
--- /dev/null
+++ b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo1.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progressbar_indeterminate_holo2.png b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo2.png
new file mode 100644
index 0000000..75ad3d6
--- /dev/null
+++ b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo2.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progressbar_indeterminate_holo3.png b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo3.png
new file mode 100644
index 0000000..74e90fd
--- /dev/null
+++ b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo3.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progressbar_indeterminate_holo4.png b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo4.png
new file mode 100644
index 0000000..7e6948a
--- /dev/null
+++ b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo4.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progressbar_indeterminate_holo5.png b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo5.png
new file mode 100644
index 0000000..38b376c
--- /dev/null
+++ b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo5.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progressbar_indeterminate_holo6.png b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo6.png
new file mode 100644
index 0000000..7cbdcf8
--- /dev/null
+++ b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo6.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progressbar_indeterminate_holo7.png b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo7.png
new file mode 100644
index 0000000..b362b20
--- /dev/null
+++ b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo7.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/progressbar_indeterminate_holo8.png b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo8.png
new file mode 100644
index 0000000..45f4f59
--- /dev/null
+++ b/core/res/res/drawable-hdpi/progressbar_indeterminate_holo8.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/scrubber_control_disabled_holo.png b/core/res/res/drawable-hdpi/scrubber_control_disabled_holo.png
new file mode 100644
index 0000000..401e904
--- /dev/null
+++ b/core/res/res/drawable-hdpi/scrubber_control_disabled_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/scrubber_control_holo.png b/core/res/res/drawable-hdpi/scrubber_control_holo.png
index 3a72307..175917e 100644
--- a/core/res/res/drawable-hdpi/scrubber_control_holo.png
+++ b/core/res/res/drawable-hdpi/scrubber_control_holo.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/scrubber_primary_holo.9.png b/core/res/res/drawable-hdpi/scrubber_primary_holo.9.png
new file mode 100644
index 0000000..3bc78a8
--- /dev/null
+++ b/core/res/res/drawable-hdpi/scrubber_primary_holo.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/scrubber_secondary_holo.9.png b/core/res/res/drawable-hdpi/scrubber_secondary_holo.9.png
new file mode 100644
index 0000000..8eadf00
--- /dev/null
+++ b/core/res/res/drawable-hdpi/scrubber_secondary_holo.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/scrubber_track_holo_dark.9.png b/core/res/res/drawable-hdpi/scrubber_track_holo_dark.9.png
index e6d7123..14ce985 100644
--- a/core/res/res/drawable-hdpi/scrubber_track_holo_dark.9.png
+++ b/core/res/res/drawable-hdpi/scrubber_track_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/scrubber_track_holo_light.9.png b/core/res/res/drawable-hdpi/scrubber_track_holo_light.9.png
index f75bfa0..5edaed5 100644
--- a/core/res/res/drawable-hdpi/scrubber_track_holo_light.9.png
+++ b/core/res/res/drawable-hdpi/scrubber_track_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-hdpi/toast_frame.9.png b/core/res/res/drawable-hdpi/toast_frame.9.png
index 8f5d811..7f830bc 100644
--- a/core/res/res/drawable-hdpi/toast_frame.9.png
+++ b/core/res/res/drawable-hdpi/toast_frame.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_default_normal.9.png b/core/res/res/drawable-mdpi/btn_default_normal.9.png
index a2d5ccd..7ff74b2 100644
--- a/core/res/res/drawable-mdpi/btn_default_normal.9.png
+++ b/core/res/res/drawable-mdpi/btn_default_normal.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_default_normal_disable.9.png b/core/res/res/drawable-mdpi/btn_default_normal_disable.9.png
index edd3a3e..d3e11b5 100644
--- a/core/res/res/drawable-mdpi/btn_default_normal_disable.9.png
+++ b/core/res/res/drawable-mdpi/btn_default_normal_disable.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_default_normal_disable_focused.9.png b/core/res/res/drawable-mdpi/btn_default_normal_disable_focused.9.png
index f506179..843ca7a 100644
--- a/core/res/res/drawable-mdpi/btn_default_normal_disable_focused.9.png
+++ b/core/res/res/drawable-mdpi/btn_default_normal_disable_focused.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_default_pressed.9.png b/core/res/res/drawable-mdpi/btn_default_pressed.9.png
index 033bf89..74fd58b 100644
--- a/core/res/res/drawable-mdpi/btn_default_pressed.9.png
+++ b/core/res/res/drawable-mdpi/btn_default_pressed.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_default_selected.9.png b/core/res/res/drawable-mdpi/btn_default_selected.9.png
index 1e900bf..415b145 100644
--- a/core/res/res/drawable-mdpi/btn_default_selected.9.png
+++ b/core/res/res/drawable-mdpi/btn_default_selected.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_default_small_normal.9.png b/core/res/res/drawable-mdpi/btn_default_small_normal.9.png
index bcedd5f..5dddd46 100644
--- a/core/res/res/drawable-mdpi/btn_default_small_normal.9.png
+++ b/core/res/res/drawable-mdpi/btn_default_small_normal.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_default_small_normal_disable.9.png b/core/res/res/drawable-mdpi/btn_default_small_normal_disable.9.png
index ac6260f..6ab5c4a 100644
--- a/core/res/res/drawable-mdpi/btn_default_small_normal_disable.9.png
+++ b/core/res/res/drawable-mdpi/btn_default_small_normal_disable.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_default_small_normal_disable_focused.9.png b/core/res/res/drawable-mdpi/btn_default_small_normal_disable_focused.9.png
index 4ee1b3f..c65bace 100644
--- a/core/res/res/drawable-mdpi/btn_default_small_normal_disable_focused.9.png
+++ b/core/res/res/drawable-mdpi/btn_default_small_normal_disable_focused.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_default_small_pressed.9.png b/core/res/res/drawable-mdpi/btn_default_small_pressed.9.png
index 25e38f4..43e82f9 100644
--- a/core/res/res/drawable-mdpi/btn_default_small_pressed.9.png
+++ b/core/res/res/drawable-mdpi/btn_default_small_pressed.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/btn_default_small_selected.9.png b/core/res/res/drawable-mdpi/btn_default_small_selected.9.png
index cc209c6..7a376a9 100644
--- a/core/res/res/drawable-mdpi/btn_default_small_selected.9.png
+++ b/core/res/res/drawable-mdpi/btn_default_small_selected.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_bottom_holo_dark.9.png b/core/res/res/drawable-mdpi/dialog_bottom_holo_dark.9.png
index 1e2d327..43e6528 100644
--- a/core/res/res/drawable-mdpi/dialog_bottom_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/dialog_bottom_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_bottom_holo_light.9.png b/core/res/res/drawable-mdpi/dialog_bottom_holo_light.9.png
index ac2d7a3..09a1cd8 100644
--- a/core/res/res/drawable-mdpi/dialog_bottom_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/dialog_bottom_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_full_holo.9.png b/core/res/res/drawable-mdpi/dialog_full_holo.9.png
deleted file mode 100644
index 0ec9421..0000000
--- a/core/res/res/drawable-mdpi/dialog_full_holo.9.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_full_holo_dark.9.png b/core/res/res/drawable-mdpi/dialog_full_holo_dark.9.png
index 9d93403..a71af8d 100644
--- a/core/res/res/drawable-mdpi/dialog_full_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/dialog_full_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_full_holo_light.9.png b/core/res/res/drawable-mdpi/dialog_full_holo_light.9.png
index 1c08e6a..4017bf7 100644
--- a/core/res/res/drawable-mdpi/dialog_full_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/dialog_full_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_middle_holo_dark.9.png b/core/res/res/drawable-mdpi/dialog_middle_holo_dark.9.png
index 741b8dc..8082ddd9 100644
--- a/core/res/res/drawable-mdpi/dialog_middle_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/dialog_middle_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_middle_holo_light.9.png b/core/res/res/drawable-mdpi/dialog_middle_holo_light.9.png
index 0854fe5..ccdcd1d 100644
--- a/core/res/res/drawable-mdpi/dialog_middle_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/dialog_middle_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_top_holo.9.png b/core/res/res/drawable-mdpi/dialog_top_holo.9.png
deleted file mode 100644
index 1ed519b..0000000
--- a/core/res/res/drawable-mdpi/dialog_top_holo.9.png
+++ /dev/null
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_top_holo_dark.9.png b/core/res/res/drawable-mdpi/dialog_top_holo_dark.9.png
index 43c0050..79aaffb 100644
--- a/core/res/res/drawable-mdpi/dialog_top_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/dialog_top_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/dialog_top_holo_light.9.png b/core/res/res/drawable-mdpi/dialog_top_holo_light.9.png
index bc5fc92..0740051 100644
--- a/core/res/res/drawable-mdpi/dialog_top_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/dialog_top_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_bullet_key_permission.png b/core/res/res/drawable-mdpi/ic_bullet_key_permission.png
index ccb010f..68ad039 100644
--- a/core/res/res/drawable-mdpi/ic_bullet_key_permission.png
+++ b/core/res/res/drawable-mdpi/ic_bullet_key_permission.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_dialog_alert_holo_dark.png b/core/res/res/drawable-mdpi/ic_dialog_alert_holo_dark.png
new file mode 100644
index 0000000..75d9db7
--- /dev/null
+++ b/core/res/res/drawable-mdpi/ic_dialog_alert_holo_dark.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_dialog_alert_holo_light.png b/core/res/res/drawable-mdpi/ic_dialog_alert_holo_light.png
new file mode 100644
index 0000000..9e7f0bd
--- /dev/null
+++ b/core/res/res/drawable-mdpi/ic_dialog_alert_holo_light.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/ic_menu_help.png b/core/res/res/drawable-mdpi/ic_menu_help.png
index 7c55dfd..12ca235 100644
--- a/core/res/res/drawable-mdpi/ic_menu_help.png
+++ b/core/res/res/drawable-mdpi/ic_menu_help.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progress_bg_holo_dark.9.png b/core/res/res/drawable-mdpi/progress_bg_holo_dark.9.png
index 0376e53..c5418f9 100644
--- a/core/res/res/drawable-mdpi/progress_bg_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/progress_bg_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progress_bg_holo_light.9.png b/core/res/res/drawable-mdpi/progress_bg_holo_light.9.png
index e825119..c943b2e 100644
--- a/core/res/res/drawable-mdpi/progress_bg_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/progress_bg_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progress_primary_holo_dark.9.png b/core/res/res/drawable-mdpi/progress_primary_holo_dark.9.png
index e525eaf..bac0a23 100644
--- a/core/res/res/drawable-mdpi/progress_primary_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/progress_primary_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progress_primary_holo_light.9.png b/core/res/res/drawable-mdpi/progress_primary_holo_light.9.png
index 0532f0e..bac0a23 100644
--- a/core/res/res/drawable-mdpi/progress_primary_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/progress_primary_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progress_secondary_holo_dark.9.png b/core/res/res/drawable-mdpi/progress_secondary_holo_dark.9.png
index 99f8f06..8be8656 100644
--- a/core/res/res/drawable-mdpi/progress_secondary_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/progress_secondary_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progress_secondary_holo_light.9.png b/core/res/res/drawable-mdpi/progress_secondary_holo_light.9.png
index 198d7d9..8be8656 100644
--- a/core/res/res/drawable-mdpi/progress_secondary_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/progress_secondary_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progressbar_indeterminate_holo1.png b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo1.png
new file mode 100644
index 0000000..c22a53a3
--- /dev/null
+++ b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo1.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progressbar_indeterminate_holo2.png b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo2.png
new file mode 100644
index 0000000..c288541
--- /dev/null
+++ b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo2.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progressbar_indeterminate_holo3.png b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo3.png
new file mode 100644
index 0000000..25df6b9
--- /dev/null
+++ b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo3.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progressbar_indeterminate_holo4.png b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo4.png
new file mode 100644
index 0000000..65718e1
--- /dev/null
+++ b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo4.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progressbar_indeterminate_holo5.png b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo5.png
new file mode 100644
index 0000000..39148e0
--- /dev/null
+++ b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo5.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progressbar_indeterminate_holo6.png b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo6.png
new file mode 100644
index 0000000..8ff7b24
--- /dev/null
+++ b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo6.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progressbar_indeterminate_holo7.png b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo7.png
new file mode 100644
index 0000000..a7302c1
--- /dev/null
+++ b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo7.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/progressbar_indeterminate_holo8.png b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo8.png
new file mode 100644
index 0000000..70bf210
--- /dev/null
+++ b/core/res/res/drawable-mdpi/progressbar_indeterminate_holo8.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/scrubber_control_disabled_holo.png b/core/res/res/drawable-mdpi/scrubber_control_disabled_holo.png
new file mode 100644
index 0000000..26f018f
--- /dev/null
+++ b/core/res/res/drawable-mdpi/scrubber_control_disabled_holo.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/scrubber_control_holo.png b/core/res/res/drawable-mdpi/scrubber_control_holo.png
index 8457833..242c16d 100644
--- a/core/res/res/drawable-mdpi/scrubber_control_holo.png
+++ b/core/res/res/drawable-mdpi/scrubber_control_holo.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/scrubber_primary_holo.9.png b/core/res/res/drawable-mdpi/scrubber_primary_holo.9.png
index 8582b13..ac63e7d 100644
--- a/core/res/res/drawable-mdpi/scrubber_primary_holo.9.png
+++ b/core/res/res/drawable-mdpi/scrubber_primary_holo.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/scrubber_secondary_holo.9.png b/core/res/res/drawable-mdpi/scrubber_secondary_holo.9.png
index 6ad876e..9590bdc 100644
--- a/core/res/res/drawable-mdpi/scrubber_secondary_holo.9.png
+++ b/core/res/res/drawable-mdpi/scrubber_secondary_holo.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/scrubber_track_holo_dark.9.png b/core/res/res/drawable-mdpi/scrubber_track_holo_dark.9.png
index baf70cd..017b593 100644
--- a/core/res/res/drawable-mdpi/scrubber_track_holo_dark.9.png
+++ b/core/res/res/drawable-mdpi/scrubber_track_holo_dark.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/scrubber_track_holo_light.9.png b/core/res/res/drawable-mdpi/scrubber_track_holo_light.9.png
index 6f31497..12c6e21 100644
--- a/core/res/res/drawable-mdpi/scrubber_track_holo_light.9.png
+++ b/core/res/res/drawable-mdpi/scrubber_track_holo_light.9.png
Binary files differ
diff --git a/core/res/res/drawable-mdpi/toast_frame.9.png b/core/res/res/drawable-mdpi/toast_frame.9.png
index 08c4f86..911f86d 100755
--- a/core/res/res/drawable-mdpi/toast_frame.9.png
+++ b/core/res/res/drawable-mdpi/toast_frame.9.png
Binary files differ
diff --git a/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_alarm.png b/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_alarm.png
index 336a820..97ac023 100644
--- a/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_alarm.png
+++ b/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_alarm.png
Binary files differ
diff --git a/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_charging.png b/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_charging.png
index ebef531..4210db2 100644
--- a/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_charging.png
+++ b/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_charging.png
Binary files differ
diff --git a/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_lock.png b/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_lock.png
index 405e218..1060f5a 100644
--- a/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_lock.png
+++ b/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_lock.png
Binary files differ
diff --git a/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_low_battery.png b/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_low_battery.png
index f349b63..72e4afa 100644
--- a/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_low_battery.png
+++ b/core/res/res/drawable-xlarge-mdpi/ic_lock_idle_low_battery.png
Binary files differ
diff --git a/core/res/res/drawable/progress_indeterminate_horizontal_holo.xml b/core/res/res/drawable/progress_indeterminate_horizontal_holo.xml
new file mode 100644
index 0000000..e99c35b
--- /dev/null
+++ b/core/res/res/drawable/progress_indeterminate_horizontal_holo.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+** Copyright 2011, 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.
+*/
+-->
+<animation-list
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:oneshot="false">
+ <item android:drawable="@drawable/progressbar_indeterminate_holo1" android:duration="50" />
+ <item android:drawable="@drawable/progressbar_indeterminate_holo2" android:duration="50" />
+ <item android:drawable="@drawable/progressbar_indeterminate_holo3" android:duration="50" />
+ <item android:drawable="@drawable/progressbar_indeterminate_holo4" android:duration="50" />
+ <item android:drawable="@drawable/progressbar_indeterminate_holo5" android:duration="50" />
+ <item android:drawable="@drawable/progressbar_indeterminate_holo6" android:duration="50" />
+ <item android:drawable="@drawable/progressbar_indeterminate_holo7" android:duration="50" />
+ <item android:drawable="@drawable/progressbar_indeterminate_holo8" android:duration="50" />
+</animation-list>
diff --git a/core/res/res/drawable/scrubber_control_selector_holo.xml b/core/res/res/drawable/scrubber_control_selector_holo.xml
new file mode 100644
index 0000000..c7b8854
--- /dev/null
+++ b/core/res/res/drawable/scrubber_control_selector_holo.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 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.
+-->
+
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_enabled="true" android:drawable="@android:drawable/scrubber_control_holo" />
+ <item android:drawable="@android:drawable/scrubber_control_disabled_holo" />
+</selector>
diff --git a/core/res/res/layout-xlarge/alert_dialog_holo.xml b/core/res/res/layout-xlarge/alert_dialog_holo.xml
index fca7c78..2ae8db7 100644
--- a/core/res/res/layout-xlarge/alert_dialog_holo.xml
+++ b/core/res/res/layout-xlarge/alert_dialog_holo.xml
@@ -33,7 +33,7 @@
<LinearLayout android:id="@+id/topPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:minHeight="48dip"
+ android:minHeight="64dip"
android:orientation="vertical">
<LinearLayout android:id="@+id/title_template"
android:layout_width="match_parent"
@@ -58,11 +58,13 @@
</LinearLayout>
<ImageView android:id="@+id/titleDivider"
android:layout_width="match_parent"
- android:layout_height="1dip"
+ android:layout_height="4dip"
android:visibility="gone"
android:scaleType="fitXY"
android:gravity="fill_horizontal"
- android:src="@android:drawable/divider_horizontal_dark" />
+ android:paddingLeft="16dip"
+ android:paddingRight="16dip"
+ android:src="@android:drawable/divider_strong_holo" />
<!-- If the client uses a customTitle, it will be added here. -->
</LinearLayout>
diff --git a/core/res/res/layout-xlarge/keyguard_screen_password_landscape.xml b/core/res/res/layout-xlarge/keyguard_screen_password_landscape.xml
index c2d87a2..4bc7292 100644
--- a/core/res/res/layout-xlarge/keyguard_screen_password_landscape.xml
+++ b/core/res/res/layout-xlarge/keyguard_screen_password_landscape.xml
@@ -22,18 +22,23 @@
android:layout_height="match_parent"
android:orientation="horizontal"
>
-
- <!-- left side: status and emergency call button -->
- <LinearLayout
- android:layout_height="match_parent"
- android:layout_weight="1"
- android:layout_width="0dip"
- android:orientation="vertical"
- android:gravity="center_vertical"
- >
- <include layout="@layout/keyguard_screen_status_land" />
- </LinearLayout>
-
+
+ <!-- left side: status -->
+ <RelativeLayout
+ android:layout_height="match_parent"
+ android:layout_weight="1"
+ android:layout_width="0dip">
+
+ <include layout="@layout/keyguard_screen_status_land"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginLeft="102dip"
+ android:layout_marginTop="320dip"
+ android:layout_alignParentTop="true"
+ android:layout_alignParentLeft="true"/>
+
+ </RelativeLayout>
+
<!-- right side: password -->
<LinearLayout
android:layout_width="0dip"
diff --git a/core/res/res/layout-xlarge/keyguard_screen_password_portrait.xml b/core/res/res/layout-xlarge/keyguard_screen_password_portrait.xml
index 0927e59..e63fb9b 100644
--- a/core/res/res/layout-xlarge/keyguard_screen_password_portrait.xml
+++ b/core/res/res/layout-xlarge/keyguard_screen_password_portrait.xml
@@ -19,21 +19,23 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
- android:orientation="vertical"
- >
-
- <!-- left side: status and emergency call button -->
- <LinearLayout
+ android:orientation="vertical">
+
+ <!-- top: status -->
+ <RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dip"
- android:layout_weight="1"
- android:orientation="vertical"
- android:gravity="center_vertical"
- >
- <include layout="@layout/keyguard_screen_status_land" />
- </LinearLayout>
-
- <!-- right side: password -->
+ android:layout_weight="1">
+ <include layout="@layout/keyguard_screen_status_port"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="134dip"
+ android:layout_marginLeft="266dip"
+ android:layout_alignParentTop="true"
+ android:layout_alignParentLeft="true"/>
+ </RelativeLayout>
+
+ <!-- bottom: password -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
diff --git a/core/res/res/layout-xlarge/keyguard_screen_status_land.xml b/core/res/res/layout-xlarge/keyguard_screen_status_land.xml
index f91fe4f..0a485e2 100644
--- a/core/res/res/layout-xlarge/keyguard_screen_status_land.xml
+++ b/core/res/res/layout-xlarge/keyguard_screen_status_land.xml
@@ -23,8 +23,6 @@
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_marginLeft="140dip"
- android:layout_marginTop="20dip"
android:gravity="left"
>
@@ -58,7 +56,7 @@
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="none"
- android:textSize="120sp"
+ android:textSize="98sp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@color/lockscreen_clock_background"
android:layout_marginBottom="6dip"
@@ -69,7 +67,7 @@
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="none"
- android:textSize="120sp"
+ android:textSize="98sp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@color/lockscreen_clock_foreground"
android:layout_alignLeft="@id/timeDisplayBackground"
@@ -92,15 +90,29 @@
</com.android.internal.widget.DigitalClock>
- <TextView
- android:id="@+id/date"
+ <LinearLayout
+ android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/time"
- android:layout_marginTop="10dip"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:textSize="22sp"
- />
+ android:layout_marginTop="10dip">
+
+ <TextView
+ android:id="@+id/date"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:textSize="17sp"/>
+
+ <TextView
+ android:id="@+id/alarm_status"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginLeft="30dip"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:textSize="17sp"/>
+
+ </LinearLayout>
<!-- Status2 is generally charge status -->
<TextView
@@ -109,18 +121,19 @@
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceMedium"
- android:textSize="22sp"
+ android:textSize="17sp"
android:layout_marginTop="10dip"
android:drawablePadding="4dip"
+ android:visibility="gone"
/>
- <!-- Status1 is generally alarm status -->
+ <!-- Status1 is generally battery status and informational messages -->
<TextView
android:id="@+id/status1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
- android:textSize="22sp"
+ android:textSize="17sp"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
@@ -130,9 +143,10 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
- android:textSize="22sp"
+ android:textSize="17sp"
android:layout_marginTop="20dip"
android:singleLine="false"
+ android:textColor="@color/lockscreen_owner_info"
android:visibility="invisible"
/>
</LinearLayout>
diff --git a/core/res/res/layout-xlarge/keyguard_screen_status_port.xml b/core/res/res/layout-xlarge/keyguard_screen_status_port.xml
index c529e0b..346b21e 100644
--- a/core/res/res/layout-xlarge/keyguard_screen_status_port.xml
+++ b/core/res/res/layout-xlarge/keyguard_screen_status_port.xml
@@ -44,8 +44,6 @@
<com.android.internal.widget.DigitalClock android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:layout_alignParentLeft="true"
android:layout_marginTop="8dip"
android:layout_marginBottom="8dip"
android_layout_marginLeft="-10dip">
@@ -57,7 +55,7 @@
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="none"
- android:textSize="120sp"
+ android:textSize="98sp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@color/lockscreen_clock_background"
android:layout_marginBottom="6dip"
@@ -68,7 +66,7 @@
android:layout_height="wrap_content"
android:singleLine="true"
android:ellipsize="none"
- android:textSize="120sp"
+ android:textSize="98sp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="@color/lockscreen_clock_foreground"
android:layout_marginBottom="6dip"
@@ -91,15 +89,29 @@
</com.android.internal.widget.DigitalClock>
- <TextView
- android:id="@+id/date"
+ <LinearLayout
+ android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/time"
- android:layout_marginTop="10dip"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:textSize="22sp"
- />
+ android:layout_marginTop="10dip">
+
+ <TextView
+ android:id="@+id/date"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:textSize="17sp"/>
+
+ <TextView
+ android:id="@+id/alarm_status"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginLeft="30dip"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:textSize="17sp"/>
+
+ </LinearLayout>
<!-- used for status such as the next alarm, and charging status. -->
<TextView
@@ -108,9 +120,10 @@
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceMedium"
- android:textSize="22sp"
+ android:textSize="17sp"
android:layout_marginTop="10dip"
android:drawablePadding="4dip"
+ android:visibility="gone"
/>
<TextView
@@ -118,7 +131,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
- android:textSize="22sp"
+ android:textSize="17sp"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
@@ -129,8 +142,9 @@
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:textAppearance="?android:attr/textAppearanceMedium"
- android:textSize="22sp"
+ android:textSize="17sp"
android:singleLine="false"
android:visibility="invisible"
+ android:textColor="@color/lockscreen_owner_info"
/>
</LinearLayout>
diff --git a/core/res/res/layout-xlarge/keyguard_screen_tab_unlock.xml b/core/res/res/layout-xlarge/keyguard_screen_tab_unlock.xml
index c76e833..1c7b7e2 100644
--- a/core/res/res/layout-xlarge/keyguard_screen_tab_unlock.xml
+++ b/core/res/res/layout-xlarge/keyguard_screen_tab_unlock.xml
@@ -29,15 +29,18 @@
android:id="@+id/root"
android:background="#70000000">
- <!-- left side: status and emergency call button -->
- <LinearLayout
+ <!-- top: status -->
+ <RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
- android:orientation="vertical"
- android:gravity="center_vertical">
- <include layout="@layout/keyguard_screen_status_port" />
- </LinearLayout>
+ android:orientation="vertical">
+ <include layout="@layout/keyguard_screen_status_port"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="134dip"
+ android:layout_marginLeft="266dip"/>
+ </RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
@@ -75,6 +78,7 @@
android:text="@string/emergency_calls_only"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="@color/white"
+ android:visibility="gone"
/>
<!-- emergency call button shown when sim is PUKd and tab_selector is
@@ -86,7 +90,7 @@
android:drawableLeft="@drawable/ic_emergency"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true"
- android:layout_marginBottom="80dip"
+ android:layout_marginBottom="90dip"
style="@style/Widget.Button.Transparent"
android:drawablePadding="8dip"
android:visibility="gone"
diff --git a/core/res/res/layout-xlarge/keyguard_screen_tab_unlock_land.xml b/core/res/res/layout-xlarge/keyguard_screen_tab_unlock_land.xml
index 6c99ccac..c24eecc 100644
--- a/core/res/res/layout-xlarge/keyguard_screen_tab_unlock_land.xml
+++ b/core/res/res/layout-xlarge/keyguard_screen_tab_unlock_land.xml
@@ -28,16 +28,21 @@
android:background="#70000000"
android:id="@+id/root">
- <!-- left side: status and emergency call button -->
- <LinearLayout
- android:layout_height="match_parent"
- android:layout_weight="1"
- android:layout_width="0dip"
- android:orientation="vertical"
- android:gravity="center_vertical"
- >
- <include layout="@layout/keyguard_screen_status_land" />
- </LinearLayout>
+ <!-- left side: status -->
+ <RelativeLayout
+ android:layout_height="match_parent"
+ android:layout_weight="1"
+ android:layout_width="0dip">
+
+ <include layout="@layout/keyguard_screen_status_land"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginLeft="102dip"
+ android:layout_marginTop="320dip"
+ android:layout_alignParentTop="true"
+ android:layout_alignParentLeft="true"/>
+
+ </RelativeLayout>
<!-- right side -->
<LinearLayout
diff --git a/core/res/res/layout-xlarge/keyguard_screen_unlock_landscape.xml b/core/res/res/layout-xlarge/keyguard_screen_unlock_landscape.xml
index 52be82c..ec7c272 100644
--- a/core/res/res/layout-xlarge/keyguard_screen_unlock_landscape.xml
+++ b/core/res/res/layout-xlarge/keyguard_screen_unlock_landscape.xml
@@ -26,81 +26,92 @@
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
- >
+ android:background="#70000000">
- <!-- left side: status and emergency call button -->
- <LinearLayout
- android:layout_height="match_parent"
- android:layout_weight="1"
- android:layout_width="0dip"
- android:orientation="vertical"
- android:gravity="center_vertical"
- >
-
- <include layout="@layout/keyguard_screen_status_land" />
+ <!-- left side: status -->
+ <RelativeLayout
+ android:layout_height="match_parent"
+ android:layout_weight="1"
+ android:layout_width="0dip">
- <!-- footer -->
- <FrameLayout
- android:layout_width="match_parent"
+ <include layout="@layout/keyguard_screen_status_land"
+ android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_marginLeft="140dip"
- >
+ android:layout_marginLeft="102dip"
+ android:layout_marginTop="320dip"
+ android:layout_alignParentTop="true"
+ android:layout_alignParentLeft="true"/>
- <!-- option 1: a single emergency call button -->
- <RelativeLayout android:id="@+id/footerNormal"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="left"
- >
- <Button android:id="@+id/emergencyCallAlone"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/lockscreen_emergency_call"
- style="@style/Widget.Button.Transparent"
- android:drawableLeft="@drawable/ic_emergency"
- android:drawablePadding="8dip"
- android:visibility="gone"
- />
- </RelativeLayout>
-
- <!-- option 2: an emergency call button, and a 'forgot pattern?' button -->
- <LinearLayout android:id="@+id/footerForgotPattern"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="left"
- >
- <Button android:id="@+id/forgotPattern"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- style="@style/Widget.Button.Transparent"
- />
- <Button android:id="@+id/emergencyCallTogether"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="@string/lockscreen_emergency_call"
- style="@style/Widget.Button.Transparent"
- android:drawableLeft="@drawable/ic_emergency"
- android:drawablePadding="8dip"
- android:visibility="gone"
- />
- </LinearLayout>
- </FrameLayout>
- </LinearLayout>
+ </RelativeLayout>
<!-- right side: lock pattern -->
- <LinearLayout
+ <RelativeLayout
android:layout_weight="1"
android:layout_width="0dip"
- android:layout_height="match_parent"
- android:gravity="center"
- >
+ android:layout_height="match_parent">
+
<com.android.internal.widget.LockPatternView android:id="@+id/lockPattern"
android:layout_width="354dip"
android:layout_height="354dip"
- android:layout_marginTop="90dip"
- android:layout_marginRight="90dip"
- />
- </LinearLayout>
+ android:layout_marginLeft="143dip"
+ android:layout_marginTop="201dip"
+ android:layout_gravity="center_vertical"
+ />
+
+ <!-- footer -->
+
+ <!-- option 1: a single emergency call button -->
+ <RelativeLayout android:id="@+id/footerNormal"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/lockPattern"
+ android:layout_alignLeft="@id/lockPattern"
+ android:layout_alignRight="@id/lockPattern"
+ android:layout_marginTop="28dip"
+ android:layout_marginLeft="28dip"
+ android:layout_marginRight="28dip"
+ >
+ <Button android:id="@+id/emergencyCallAlone"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/lockscreen_emergency_call"
+ style="@style/Widget.Button.Transparent"
+ android:drawableLeft="@drawable/ic_emergency"
+ android:drawablePadding="8dip"
+ android:visibility="gone"
+ />
+ </RelativeLayout>
+
+ <!-- option 2: an emergency call button, and a 'forgot pattern?' button -->
+ <LinearLayout android:id="@+id/footerForgotPattern"
+ android:orientation="vertical"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/footerNormal"
+ android:layout_alignLeft="@id/lockPattern"
+ android:layout_alignRight="@id/lockPattern"
+ android:layout_marginTop="28dip"
+ android:layout_marginLeft="28dip"
+ android:layout_marginRight="28dip">
+
+ <Button android:id="@+id/forgotPattern"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ style="@style/Widget.Button.Transparent"
+ />
+
+ <Button android:id="@+id/emergencyCallTogether"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="@string/lockscreen_emergency_call"
+ style="@style/Widget.Button.Transparent"
+ android:drawableLeft="@drawable/ic_emergency"
+ android:drawablePadding="8dip"
+ android:visibility="gone"
+ />
+
+ </LinearLayout>
+
+ </RelativeLayout>
</com.android.internal.widget.LinearLayoutWithDefaultTouchRecepient>
diff --git a/core/res/res/layout-xlarge/keyguard_screen_unlock_portrait.xml b/core/res/res/layout-xlarge/keyguard_screen_unlock_portrait.xml
index e170a76..84ddd6a 100644
--- a/core/res/res/layout-xlarge/keyguard_screen_unlock_portrait.xml
+++ b/core/res/res/layout-xlarge/keyguard_screen_unlock_portrait.xml
@@ -22,18 +22,21 @@
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
+ android:background="#70000000"
>
- <!-- left side: status and emergency call button -->
+ <!-- top: status -->
<LinearLayout
- android:layout_height="0dip"
- android:layout_weight="1"
- android:layout_width="match_parent"
- android:orientation="vertical"
- android:gravity="center_vertical"
- >
+ android:layout_height="0dip"
+ android:layout_weight="1"
+ android:layout_width="match_parent"
+ android:orientation="vertical">
- <include layout="@layout/keyguard_screen_status_port" />
+ <include layout="@layout/keyguard_screen_status_port"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="134dip"
+ android:layout_marginLeft="266dip"/>
<!-- footer -->
<FrameLayout
diff --git a/core/res/res/layout/action_menu_item_layout.xml b/core/res/res/layout/action_menu_item_layout.xml
index 94fcc2f..e502b1e 100644
--- a/core/res/res/layout/action_menu_item_layout.xml
+++ b/core/res/res/layout/action_menu_item_layout.xml
@@ -29,7 +29,11 @@
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"
- style="?attr/actionButtonStyle" />
+ android:paddingLeft="4dip"
+ android:paddingRight="4dip"
+ android:minHeight="56dip"
+ android:scaleType="center"
+ android:background="@null" />
<Button android:id="@+id/textButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
diff --git a/core/res/res/layout/alert_dialog_holo.xml b/core/res/res/layout/alert_dialog_holo.xml
index ea6e11e..07a2853 100644
--- a/core/res/res/layout/alert_dialog_holo.xml
+++ b/core/res/res/layout/alert_dialog_holo.xml
@@ -33,7 +33,7 @@
<LinearLayout android:id="@+id/topPanel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:minHeight="48dip"
+ android:minHeight="64dip"
android:orientation="vertical">
<LinearLayout android:id="@+id/title_template"
android:layout_width="match_parent"
@@ -58,11 +58,13 @@
</LinearLayout>
<ImageView android:id="@+id/titleDivider"
android:layout_width="match_parent"
- android:layout_height="1dip"
+ android:layout_height="4dip"
android:visibility="gone"
android:scaleType="fitXY"
android:gravity="fill_horizontal"
- android:src="@android:drawable/divider_horizontal_dark" />
+ android:paddingLeft="16dip"
+ android:paddingRight="16dip"
+ android:src="@android:drawable/divider_strong_holo" />
<!-- If the client uses a customTitle, it will be added here. -->
</LinearLayout>
diff --git a/core/res/res/layout/keyguard_screen_tab_unlock.xml b/core/res/res/layout/keyguard_screen_tab_unlock.xml
index 77ae0d3..8367157 100644
--- a/core/res/res/layout/keyguard_screen_tab_unlock.xml
+++ b/core/res/res/layout/keyguard_screen_tab_unlock.xml
@@ -117,11 +117,24 @@
android:textAppearance="?android:attr/textAppearanceMedium"
/>
+ <!-- TODO: Redo layout when we release on phones -->
+ <TextView
+ android:id="@+id/alarm_status"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:textSize="18sp"
+ android:drawablePadding="4dip"
+ android:layout_below="@id/date"
+ android:layout_marginTop="4dip"
+ android:layout_marginLeft="24dip"
+ />
+
<TextView
android:id="@+id/status1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_below="@id/date"
+ android:layout_below="@id/alarm_status"
android:layout_marginTop="4dip"
android:layout_marginLeft="24dip"
android:textAppearance="?android:attr/textAppearanceMedium"
diff --git a/core/res/res/layout/keyguard_screen_tab_unlock_land.xml b/core/res/res/layout/keyguard_screen_tab_unlock_land.xml
index e48df20..9547660 100644
--- a/core/res/res/layout/keyguard_screen_tab_unlock_land.xml
+++ b/core/res/res/layout/keyguard_screen_tab_unlock_land.xml
@@ -118,11 +118,24 @@
android:textAppearance="?android:attr/textAppearanceMedium"
/>
+ <!-- TODO: Redo layout when we release on phones -->
+ <TextView
+ android:id="@+id/alarm_status"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:textSize="18sp"
+ android:drawablePadding="4dip"
+ android:layout_below="@id/date"
+ android:layout_marginTop="4dip"
+ android:layout_marginLeft="24dip"
+ />
+
<TextView
android:id="@+id/status1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:layout_below="@id/date"
+ android:layout_below="@id/alarm_status"
android:layout_marginTop="6dip"
android:textAppearance="?android:attr/textAppearanceMedium"
android:drawablePadding="4dip"
diff --git a/core/res/res/layout/keyguard_screen_unlock_landscape.xml b/core/res/res/layout/keyguard_screen_unlock_landscape.xml
index c14afbf..759c906 100644
--- a/core/res/res/layout/keyguard_screen_unlock_landscape.xml
+++ b/core/res/res/layout/keyguard_screen_unlock_landscape.xml
@@ -38,6 +38,15 @@
android:layout_marginLeft="24dip"
android:gravity="left"
>
+
+ <TextView
+ android:id="@+id/alarm_status"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:textSize="18sp"
+ android:drawablePadding="4dip"
+ />
<TextView
android:id="@+id/status1"
android:layout_width="wrap_content"
diff --git a/core/res/res/layout/keyguard_screen_unlock_portrait.xml b/core/res/res/layout/keyguard_screen_unlock_portrait.xml
index 85e1db1..c438412 100644
--- a/core/res/res/layout/keyguard_screen_unlock_portrait.xml
+++ b/core/res/res/layout/keyguard_screen_unlock_portrait.xml
@@ -127,6 +127,15 @@
android:layout_marginLeft="12dip"
android:gravity="left"
>
+ <!-- TODO: Redo layout when we release on phones -->
+ <TextView
+ android:id="@+id/alarm_status"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:textAppearance="?android:attr/textAppearanceMedium"
+ android:textSize="18sp"
+ android:drawablePadding="4dip"
+ />
<TextView
android:id="@+id/status1"
android:layout_width="wrap_content"
diff --git a/core/res/res/layout/popup_menu_item_layout.xml b/core/res/res/layout/popup_menu_item_layout.xml
index c30c4f2..2bbb4d0 100644
--- a/core/res/res/layout/popup_menu_item_layout.xml
+++ b/core/res/res/layout/popup_menu_item_layout.xml
@@ -16,7 +16,9 @@
<com.android.internal.view.menu.ListMenuItemView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
- android:layout_height="?android:attr/listPreferredItemHeight">
+ android:layout_height="?android:attr/listPreferredItemHeight"
+ android:paddingLeft="16dip"
+ android:paddingRight="16dip">
<!-- Icon will be inserted here. -->
diff --git a/core/res/res/layout/search_view.xml b/core/res/res/layout/search_view.xml
index bb7f700..46d0341 100644
--- a/core/res/res/layout/search_view.xml
+++ b/core/res/res/layout/search_view.xml
@@ -45,6 +45,7 @@
android:layout_gravity="center_vertical"
android:background="?android:attr/selectableItemBackground"
android:src="?android:attr/searchViewSearchIcon"
+ style="?android:attr/actionButtonStyle"
/>
<LinearLayout
@@ -79,7 +80,7 @@
android:layout_height="36dip"
android:layout_width="0dp"
android:layout_weight="1"
- android:minWidth="100dp"
+ android:minWidth="@dimen/search_view_text_min_width"
android:layout_gravity="bottom"
android:paddingLeft="8dip"
android:paddingRight="6dip"
diff --git a/core/res/res/layout/volume_adjust.xml b/core/res/res/layout/volume_adjust.xml
index 946ca7e..c44ed0b 100644
--- a/core/res/res/layout/volume_adjust.xml
+++ b/core/res/res/layout/volume_adjust.xml
@@ -17,7 +17,7 @@
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:background="@android:drawable/panel_background"
+ android:background="@android:drawable/toast_frame"
android:orientation="vertical"
android:gravity="center_horizontal">
diff --git a/core/res/res/values-es-rUS-xlarge/strings.xml b/core/res/res/values-es-rUS-xlarge/strings.xml
new file mode 100644
index 0000000..cef8d12
--- /dev/null
+++ b/core/res/res/values-es-rUS-xlarge/strings.xml
@@ -0,0 +1,331 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <!-- XL -->
+ <string name="fileSizeSuffix" msgid="3468563433835560758">"Segmento <xliff:g id="NUMBER">%1$s</xliff:g><xliff:g id="UNIT">%2$s</xliff:g>"</string>
+ <!-- XL -->
+ <string name="unknownName" msgid="3202822008051920747">"(Desconocido)"</string>
+ <!-- XL -->
+ <string name="defaultVoiceMailAlphaTag" msgid="3668436100965334106">"Buzón de voz"</string>
+ <!-- XL -->
+ <string name="serviceClassVoice" msgid="7086876533404179039">"Google Voice"</string>
+ <!-- XL -->
+ <string name="cfTemplateNotForwarded" msgid="8534356655497306518">"<xliff:g id="BEARER_SERVICE_CODE">{0}</xliff:g>: no se ha reenviado"</string>
+ <!-- XL -->
+ <string name="cfTemplateRegistered" msgid="1255841210142514510">"<xliff:g id="BEARER_SERVICE_CODE">{0}</xliff:g>: no se ha reenviado"</string>
+ <!-- XL -->
+ <string name="cfTemplateRegisteredTime" msgid="7798907169190952367">"<xliff:g id="BEARER_SERVICE_CODE">{0}</xliff:g>: no se ha reenviado"</string>
+ <!-- XL -->
+ <string name="notification_title" msgid="5210128823045542445">"Error al acceder a <xliff:g id="ACCOUNT">%1$s</xliff:g>"</string>
+ <!-- XL -->
+ <string name="low_memory" product="tablet" msgid="4855646606241379548">"¡El espacio de almacenamiento de la tableta está completo! Elimina algunos archivos para liberar espacio."</string>
+ <string name="low_memory" product="default" msgid="9195238880281578473">"¡El espacio de almacenamiento está completo! Elimina algunos archivos para liberar espacio."</string>
+ <!-- XL -->
+ <string name="power_dialog" product="tablet" msgid="6884163545695410971">"Opciones de tableta"</string>
+ <string name="power_dialog" product="default" msgid="8882103237148972564">"Opciones de teléfono"</string>
+ <!-- XL -->
+ <string name="silent_mode" msgid="5687977677409351252">"Modo silencio"</string>
+ <!-- XL -->
+ <string name="shutdown_confirm" product="tablet" msgid="5776903973889956395">"Tu tableta se apagará."</string>
+ <string name="shutdown_confirm" product="default" msgid="3040950969577046278">"Tu teléfono se apagará."</string>
+ <!-- XL -->
+ <string name="global_actions" product="tablet" msgid="110297659383505180">"Opciones de tableta"</string>
+ <string name="global_actions" product="default" msgid="2108237350837066773">"Opciones de teléfono"</string>
+ <!-- XL -->
+ <string name="global_action_toggle_silent_mode" msgid="4538951049191334644">"Modo silencio"</string>
+ <!-- XL -->
+ <string name="global_action_silent_mode_off_status" msgid="9045822172493147761">"El sonido está ENCENDIDO"</string>
+ <!-- XL -->
+ <string name="global_actions_airplane_mode_on_status" msgid="7272433204482202219">"El modo avión está ENCENDIDO"</string>
+ <!-- XL -->
+ <string name="android_system_label" msgid="844561213652704593">"Sistema Androide"</string>
+ <!-- XL -->
+ <string name="permgroupdesc_costMoney" msgid="4836624191696189469">"Admitir que las aplicaciones realicen actividades que se cobran."</string>
+ <!-- XL -->
+ <string name="permgroupdesc_developmentTools" msgid="5514251182135739578">"Las funciones sólo son necesarias para los programadores de aplicaciones."</string>
+ <!-- XL -->
+ <string name="permgrouplab_storage" msgid="746210798053836644">"Almacenamiento"</string>
+ <!-- XL -->
+ <string name="permdesc_readSms" product="tablet" msgid="3026416194429353337">"Permite que la aplicación lea los mensajes SMS almacenados en tu tableta o tarjeta SIM. Las aplicaciones maliciosas pueden leer tus mensajes confidenciales."</string>
+ <string name="permdesc_readSms" product="default" msgid="191875931331016383">"Admite que la aplicación lea los mensajes SMS almacenados en tu teléfono o tarjeta SIM. Las aplicaciones maliciosas pueden leer tus mensajes confidenciales."</string>
+ <!-- XL -->
+ <string name="permdesc_writeSms" product="tablet" msgid="692041754996169941">"Permite que la aplicación escriba a los mensajes SMS almacenados en tu tableta o tarjeta SIM. Las aplicaciones maliciosas pueden borrar tus mensajes."</string>
+ <string name="permdesc_writeSms" product="default" msgid="1659315878254882599">"Admite que la aplicación escriba a los mensajes SMS almacenados en tu teléfono o tarjeta SIM. Las aplicaciones maliciosas pueden borrar tus mensajes."</string>
+ <!-- XL -->
+ <string name="permlab_forceStopPackages" msgid="1277034765943155677">"provocar la detención de otras aplicaciones"</string>
+ <!-- XL -->
+ <string name="permlab_forceBack" msgid="4272218642115232597">"cerrar la aplicación a la fuerza"</string>
+ <!-- XL -->
+ <string name="permdesc_injectEvents" product="tablet" msgid="6096352450860864899">"Permite que una aplicación ofrezca sus propios eventos de entrada (presionar teclas, etc.) a otras aplicaciones. Las aplicaciones maliciosas pueden utilizarlo para tomar el control de la tableta."</string>
+ <string name="permdesc_injectEvents" product="default" msgid="2842435693076075109">"Admite una aplicación que ofrece sus propios eventos de entrada (presionar teclas, etc.) a otras aplicaciones. Las aplicaciones maliciosas pueden utilizarlo para tomar el control del teléfono."</string>
+ <!-- XL -->
+ <string name="permdesc_clearAppCache" product="tablet" msgid="1147333973960547529">"Permite que una aplicación libere espacio de almacenamiento en la tableta eliminando archivos del directorio de memoria caché de la aplicación. En general, el acceso es muy restringido para el proceso del sistema."</string>
+ <string name="permdesc_clearAppCache" product="default" msgid="5790679870501740958">"Admite una aplicación que libera espacio de almacenamiento en el teléfono al eliminar archivos del directorio de memoria caché de la aplicación. En general, el acceso es muy restringido para el proceso del sistema."</string>
+ <!-- XL -->
+ <string name="permdesc_readLogs" product="tablet" msgid="3701009088710926065">"Permite que una aplicación lea diversos archivos de registro del sistema. Esto le permite descubrir información general acerca de lo que haces con la tableta, y puede potencialmente incluir información personal o privada."</string>
+ <string name="permdesc_readLogs" product="default" msgid="8520101632251038537">"Admite una aplicación que lee diversos archivos de registro del sistema. Esto te permite descubrir información general acerca de lo que haces con el teléfono, y puede potencialmente incluir información personal o privada."</string>
+ <!-- XL -->
+ <string name="permdesc_changeComponentState" product="tablet" msgid="1791075936446230356">"Permite que una aplicación cambie si se debe activar o no un componente de otra aplicación. Las aplicaciones maliciosas pueden utilizarlo para desactivar funciones importantes de la tableta. Se debe tener cuidado con el permiso, ya que es posible que los componentes de la aplicación alcancen un estado inservible, imperfecto e inestable."</string>
+ <string name="permdesc_changeComponentState" product="default" msgid="587130297076242796">"Permite que una aplicación cambie si se debe activar o no un componente de otra aplicación. Las aplicaciones maliciosas pueden utilizarlo para desactivar funciones importantes del teléfono. Se debe tener cuidado con el permiso, ya que es posible que los componentes de la aplicación alcancen un estado inservible, imperfecto e inestable."</string>
+ <!-- XL -->
+ <string name="permdesc_receiveBootCompleted" product="tablet" msgid="8660405432665162821">"Permite que una aplicación se inicie en cuanto el sistema haya finalizado la inicialización. Esto puede ocasionar que la tableta demore más en inicializar y que la aplicación retarde el funcionamiento total de la tableta al estar en ejecución constante."</string>
+ <string name="permdesc_receiveBootCompleted" product="default" msgid="1827765096700833418">"Admite una aplicación que se inicia cuando el sistema haya finalizado la inicialización. Esto puede ocasionar que se demore más tiempo en inicializar el teléfono y que la aplicación retarde el funcionamiento total del teléfono al estar en ejecución constante."</string>
+ <!-- XL -->
+ <string name="permdesc_readContacts" product="tablet" msgid="1611730857475623952">"Permite que una aplicación lea todos los datos de de contacto (direcciones) almacenados en tu tableta. Las aplicaciones maliciosas pueden utilizarlo para enviar tus datos a otras personas."</string>
+ <string name="permdesc_readContacts" product="default" msgid="6610535719925788049">"Admite una aplicación que lee todos los datos de (direcciones) de contactos almacenados en tu teléfono. Las aplicaciones maliciosas pueden utilizarlo para enviar tus eventos de calendario a otras personas."</string>
+ <!-- XL -->
+ <string name="permdesc_writeContacts" product="tablet" msgid="4572703488642353934">"Permite que una aplicación modifique los datos de (dirección) guardados en tu tableta. Las aplicaciones maliciosas pueden utilizarlo para borrar o modificar los datos de contacto."</string>
+ <string name="permdesc_writeContacts" product="default" msgid="714397557711969040">"Admite una aplicación que modifica los datos de (dirección de) contacto guardados en tu teléfono. Las aplicaciones maliciosas pueden utilizarlo para borrar o modificar los datos de contacto."</string>
+ <!-- XL -->
+ <string name="permdesc_readCalendar" product="tablet" msgid="2991522150157238929">"Permite que una aplicación lea todos los eventos de calendario almacenados en tu tableta. Las aplicaciones maliciosas pueden utilizarlo para enviar tus eventos de calendario a otras personas."</string>
+ <string name="permdesc_readCalendar" product="default" msgid="2618681024074734985">"Admite que una aplicación lea todos los eventos de calendario almacenados en tu teléfono. Las aplicaciones maliciosas pueden utilizarlo para enviar tus eventos de calendario a otras personas."</string>
+ <!-- XL -->
+ <string name="permdesc_accessFineLocation" product="tablet" msgid="9186984659787705379">"Accede a las fuentes de ubicación precisa, como el Sistema de posicionamiento global en la tableta, si está disponible. Las aplicaciones maliciosas pueden utilizarlo para determinar donde te encuentras y puede consumir energía adicional de la batería."</string>
+ <string name="permdesc_accessFineLocation" product="default" msgid="7130852247133907221">"Accede a las fuentes de ubicación precisa, como el Sistema de posicionamiento global en el teléfono, si está disponible. Las aplicaciones maliciosas pueden utilizarlo para determinar donde te encuentras y puede consumir energía adicional de la batería."</string>
+ <!-- XL -->
+ <string name="permdesc_accessCoarseLocation" product="tablet" msgid="2943949975553225591">"Accede a las fuentes de ubicación aproximada, como la base de datos de la red de celulares, para determinar la ubicación aproximada de un tableta, si está disponible. Las aplicaciones maliciosas pueden utilizarlo para determinar aproximadamente dónde te encuentras."</string>
+ <string name="permdesc_accessCoarseLocation" product="default" msgid="7474972764638621839">"Accede a las fuentes de ubicación aproximada, como la base de datos de la red de celulares, para determinar una ubicación telefónica aproximada, si está disponible. Las aplicaciones maliciosas pueden utilizarlo para determinar aproximadamente donde te encuentras."</string>
+ <!-- XL -->
+ <string name="permlab_brick" product="tablet" msgid="6967130388106614085">"inhabilitar tableta de forma permanente"</string>
+ <string name="permlab_brick" product="default" msgid="3120283238813720510">"desactivar teléfono de manera permanente"</string>
+ <!-- XL -->
+ <string name="permdesc_brick" product="tablet" msgid="8506097851567246888">"Permite que la aplicación desactive todo la tableta de manera permanente. Esto es muy peligroso."</string>
+ <string name="permdesc_brick" product="default" msgid="6696459767254028146">"Admite que la aplicación desactive todo el teléfono de manera permanente. Esto es muy peligroso."</string>
+ <!-- XL -->
+ <string name="permlab_reboot" product="tablet" msgid="8299304590708874992">"forzar reinicio de la tableta"</string>
+ <string name="permlab_reboot" product="default" msgid="7761230490609718232">"provocar el reinicio del teléfono"</string>
+ <!-- XL -->
+ <string name="permdesc_reboot" product="tablet" msgid="8289402537687518137">"Permite que la aplicación provoque el reinicio de la tableta."</string>
+ <string name="permdesc_reboot" product="default" msgid="2425170170087532554">"Admite que la aplicación provoque que el teléfono se reinicie."</string>
+ <!-- XL -->
+ <string name="permlab_performCdmaProvisioning" product="tablet" msgid="1602175938040327630">"iniciar directamente la configuración CDMA de la tableta"</string>
+ <string name="permlab_performCdmaProvisioning" product="default" msgid="2364447039211144234">"comienza directamente la configuración CDMA del teléfono"</string>
+ <!-- XL -->
+ <string name="permlab_checkinProperties" msgid="8770356116386811264">"acceder a las propiedades de registro"</string>
+ <!-- XL -->
+ <string name="permlab_bindGadget" msgid="2772444448613501375">"elegir controles"</string>
+ <!-- XL -->
+ <string name="permdesc_bindGadget" msgid="5172327215211875807">"Admite que la aplicación indique al sistema cuáles controles puede utilizar cada aplicación. Con este permiso, las aplicaciones pueden brindar acceso a los datos personales a otras aplicaciones. Las aplicaciones normales no deben utilizarlo."</string>
+ <!-- XL -->
+ <string name="permlab_wakeLock" product="tablet" msgid="8548785337425173690">"evitar que la tableta entre en estado de inactividad"</string>
+ <string name="permlab_wakeLock" product="default" msgid="7590534090355174805">"evitar que el teléfono entre en estado de inactividad"</string>
+ <!-- XL -->
+ <string name="permdesc_wakeLock" product="tablet" msgid="6871828582124115814">"Permite que una aplicación evite que la tableta entre en estado de inactividad."</string>
+ <string name="permdesc_wakeLock" product="default" msgid="1200311528451468554">"Admite una aplicación que evita que el teléfono entre en estado de inactividad."</string>
+ <!-- XL -->
+ <string name="permlab_devicePower" product="tablet" msgid="4737873025369971061">"apagar o encender la tableta"</string>
+ <string name="permlab_devicePower" product="default" msgid="6879460773734563850">"apagar o encender el teléfono"</string>
+ <!-- XL -->
+ <string name="permdesc_devicePower" product="tablet" msgid="5930342678996327905">"Permite que una aplicación encienda o apague la tableta."</string>
+ <string name="permdesc_devicePower" product="default" msgid="6653901512148320818">"Admite que la aplicación encienda o apague el teléfono."</string>
+ <!-- XL -->
+ <string name="permdesc_factoryTest" product="tablet" msgid="396653994609190055">"Se ejecuta como una prueba de fábrica de bajo nivel que permite un acceso completo al hardware de la tableta. Sólo disponible cuando la tableta se ejecuta en el modo de prueba de fábrica."</string>
+ <string name="permdesc_factoryTest" product="default" msgid="4581239666568781766">"Se ejecuta como una prueba de fábrica de bajo nivel que permite un acceso completo al hardware del teléfono. Sólo disponible cuando un teléfono se ejecuta en el modo de prueba de fábrica."</string>
+ <!-- XL -->
+ <string name="permlab_setWallpaper" msgid="845032615203772571">"establecer fondo de pantalla"</string>
+ <!-- XL -->
+ <string name="permdesc_setWallpaper" msgid="3378501759667797259">"Admite que la aplicación establezca el fondo de pantalla del sistema."</string>
+ <!-- XL -->
+ <string name="permlab_setWallpaperHints" msgid="4995885499848128983">"establecer sugerencias de tamaño del fondo de pantalla"</string>
+ <!-- XL -->
+ <string name="permdesc_setWallpaperHints" msgid="8857901708691279048">"Admite que la aplicación establezca las sugerencias de tamaño del fondo de pantalla del sistema."</string>
+ <!-- XL -->
+ <string name="permdesc_setTime" product="tablet" msgid="7329574196603775554">"Permite que una aplicación cambie la hora de la tableta."</string>
+ <string name="permdesc_setTime" product="default" msgid="7787175369529849526">"Permite a una aplicación cambiar la hora del teléfono."</string>
+ <!-- XL -->
+ <string name="permdesc_setTimeZone" product="tablet" msgid="3851480395450283316">"Permite que una aplicación cambie la zona horaria de la tableta."</string>
+ <string name="permdesc_setTimeZone" product="default" msgid="3231143515254577541">"Admite una aplicación que cambia la zona horaria del teléfono."</string>
+ <!-- XL -->
+ <string name="permdesc_getAccounts" product="tablet" msgid="374861616407073729">"Permite que una aplicación obtenga una la lista de cuentas conocidas por la tableta."</string>
+ <string name="permdesc_getAccounts" product="default" msgid="6356501268884684429">"Admite una aplicación que obtiene la lista de cuentas conocidas del teléfono."</string>
+ <!-- XL -->
+ <string name="permdesc_bluetoothAdmin" product="tablet" msgid="8034248164659819866">"Permite que una aplicación configure el Bluetooth local de la tableta, y descubra y se vincule con dispositivos remotos."</string>
+ <string name="permdesc_bluetoothAdmin" product="default" msgid="2555370145147752776">"Admite una aplicación que configura el teléfono Bluetooth local y descubre y se vincula con dispositivos remotos."</string>
+ <!-- XL -->
+ <string name="permdesc_bluetooth" product="tablet" msgid="4631562404621086816">"Permite que una aplicación vea la configuración de la tableta Bluetooth local, y que realice y acepte conexiones con dispositivos vinculados."</string>
+ <string name="permdesc_bluetooth" product="default" msgid="1202135959389935958">"Admite una aplicación que ve la configuración del teléfono Bluetooth local, y realiza y acepta conexiones con dispositivos vinculados."</string>
+ <!-- XL -->
+ <string name="policydesc_watchLogin" product="tablet" msgid="7927990389488709968">"Supervisar el número de contraseñas incorrectas ingresadas al desbloquear la pantalla, y bloquear la tableta o eliminar todos los datos del teléfono si se ingresan demasiadas contraseñas incorrectas."</string>
+ <string name="policydesc_watchLogin" product="default" msgid="4998594853332798741">"Supervisa el número de contraseñas incorrectas ingresadas al desbloquear la pantalla, y bloquee el teléfono o elimine todos los datos del teléfono si se ingresan demasiadas contraseñas incorrectas."</string>
+ <!-- XL -->
+ <string name="policydesc_wipeData" product="tablet" msgid="7871059407132175855">"Borrar los datos de la tableta sin advertencias, restableciendo la configuración de fábrica"</string>
+ <string name="policydesc_wipeData" product="default" msgid="6003127471292136411">"Borrar los datos del teléfono sin advertencias al restablecer la configuración original"</string>
+ <!-- XL -->
+ <string-array name="phoneTypes">
+ <item msgid="7066790683658405096">"Pantalla principal"</item>
+ <item msgid="5813675571320075289">"Teléfono móvil"</item>
+ <item msgid="1236863745322977021">"Trabajo"</item>
+ <item msgid="7018038125868933566">"Fax laboral"</item>
+ <item msgid="4280105707643078852">"Fax personal"</item>
+ <item msgid="6527083287534782580">"Localizador"</item>
+ <item msgid="706618935041239888">"Otro"</item>
+ <item msgid="8099625332540070724">"Personalizado"</item>
+ </string-array>
+ <!-- XL -->
+ <string-array name="emailAddressTypes">
+ <item msgid="8080673853442355385">"Pantalla principal"</item>
+ <item msgid="924798042157989715">"Trabajo"</item>
+ <item msgid="1959796935508361158">"Otro"</item>
+ <item msgid="756534161520555926">"Personalizado"</item>
+ </string-array>
+ <!-- XL -->
+ <string-array name="postalAddressTypes">
+ <item msgid="1166454994471190496">"Pantalla principal"</item>
+ <item msgid="3602955376664951787">"Trabajo"</item>
+ <item msgid="4646105398231575508">"Otro"</item>
+ <item msgid="8191179302220976184">"Personalizado"</item>
+ </string-array>
+ <!-- XL -->
+ <string-array name="imAddressTypes">
+ <item msgid="2528436635522549040">"Pantalla principal"</item>
+ <item msgid="5834207144511084508">"Trabajo"</item>
+ <item msgid="3796683891024584813">"Otro"</item>
+ <item msgid="6644316676098098833">"Personalizado"</item>
+ </string-array>
+ <!-- XL -->
+ <string-array name="organizationTypes">
+ <item msgid="6571823895277482483">"Trabajo"</item>
+ <item msgid="4013674940836786104">"Otro"</item>
+ <item msgid="8549998141814637453">"Personalizado"</item>
+ </string-array>
+ <!-- XL -->
+ <string name="phoneTypeHome" msgid="2087652870939635038">"Pantalla principal"</string>
+ <!-- XL -->
+ <string name="phoneTypeMobile" msgid="7084573626440935140">"Teléfono móvil"</string>
+ <!-- XL -->
+ <string name="emailTypeHome" msgid="1298773522695936612">"Pantalla principal"</string>
+ <!-- XL -->
+ <string name="emailTypeMobile" msgid="5515624509217674980">"Teléfono móvil"</string>
+ <!-- XL -->
+ <string name="postalTypeHome" msgid="7553888805834710738">"Pantalla principal"</string>
+ <!-- XL -->
+ <string name="imTypeHome" msgid="3732426015472142690">"Pantalla principal"</string>
+ <!-- XL -->
+ <string name="sipAddressTypeHome" msgid="8212230577724692911">"Pantalla principal"</string>
+ <!-- XL -->
+ <string name="lockscreen_pattern_instructions" msgid="9171665895877154059">"Extraer el patrón para desbloquear"</string>
+ <!-- XL -->
+ <string name="lockscreen_battery_short" msgid="891372653127247039">"Segmento <xliff:g id="NUMBER">%d</xliff:g><xliff:g id="PERCENT">%%</xliff:g>"</string>
+ <!-- XL -->
+ <string name="lockscreen_missing_sim_message" product="tablet" msgid="3961770350078423154">"No hay tarjeta SIM en la tableta."</string>
+ <string name="lockscreen_missing_sim_message" product="default" msgid="5997031739677800758">"No hay tarjeta SIM en el teléfono."</string>
+ <!-- XL -->
+ <string name="lockscreen_too_many_failed_attempts_dialog_message" msgid="2429599468920598896">"Has establecido incorrectamente tu gráfico de desbloqueo <xliff:g id="NUMBER_0">%d</xliff:g> veces. "\n\n"Vuelve a intentarlo en <xliff:g id="NUMBER_1">%d</xliff:g> segundos."</string>
+ <!-- XL -->
+ <string name="lockscreen_failed_attempts_almost_glogin" product="tablet" msgid="3211267232692817092">"Has establecido incorrectamente tu gráfico de desbloqueo <xliff:g id="NUMBER_0">%d</xliff:g> veces. Luego de <xliff:g id="NUMBER_1">%d</xliff:g> intentos incorrectos más, se te solicitará que desbloquees tu tableta al acceder a Google."\n\n" Vuelve a intentarlo en <xliff:g id="NUMBER_2">%d</xliff:g> segundos."</string>
+ <string name="lockscreen_failed_attempts_almost_glogin" product="default" msgid="7097890594752816076">"Has establecido incorrectamente tu gráfico de desbloqueo <xliff:g id="NUMBER_0">%d</xliff:g> veces. Luego de <xliff:g id="NUMBER_1">%d</xliff:g> intentos incorrectos, se te solicitará que desbloquees tu teléfono al acceder a Google. "\n\n" Vuelve a intentarlo en <xliff:g id="NUMBER_2">%d</xliff:g> segundos."</string>
+ <!-- XL -->
+ <string name="lockscreen_glogin_submit_button" msgid="4760302858316749698">"Acceder"</string>
+ <!-- XL -->
+ <string name="lockscreen_glogin_invalid_input" msgid="7265806099449246244">"Nombre de usuario o contraseña no válidos."</string>
+ <!-- XL -->
+ <string name="hour_ampm" msgid="6161399724998500216">"Segmento <xliff:g id="HOUR">%-l</xliff:g><xliff:g id="AMPM">%P</xliff:g>"</string>
+ <!-- XL -->
+ <string name="hour_cap_ampm" msgid="724197720606114012">"Segmento <xliff:g id="HOUR">%-l</xliff:g><xliff:g id="AMPM">%p</xliff:g>"</string>
+ <!-- XL -->
+ <string name="double_tap_toast" msgid="2893001600485832537">"Sugerencia: presiona dos veces para acercar y alejar"</string>
+ <!-- XL -->
+ <string name="autofill_address_name_separator" msgid="5171727678145785075">" Segmento "</string>
+ <!-- XL -->
+ <string name="permlab_readHistoryBookmarks" msgid="6148149152792104516">"leer historial y favoritos del navegador"</string>
+ <!-- XL -->
+ <string name="permdesc_readHistoryBookmarks" msgid="7371336472744100059">"Permite a la aplicación leer todas las URL que ha visitado el navegador y todos los favoritos del navegador."</string>
+ <!-- XL -->
+ <string name="permlab_writeHistoryBookmarks" msgid="1369319390968848231">"escribir historial y favoritos del navegador"</string>
+ <!-- XL -->
+ <string name="permdesc_writeHistoryBookmarks" product="tablet" msgid="3870229397949634482">"Permite que una aplicación modifique el historial de navegación y los favoritos del navegador almacenados en tu tableta. Las aplicaciones maliciosas pueden utilizarlo para borrar o modificar los datos en tu navegador."</string>
+ <string name="permdesc_writeHistoryBookmarks" product="default" msgid="6845659334691579933">"Permite a una aplicación modificar el historial y los favoritos del navegador almacenados en tu teléfono. Las aplicaciones maliciosas pueden utilizarlo para borrar o modificar tus datos."</string>
+ <!-- XL -->
+ <string name="permlab_setAlarm" msgid="8112208516527103653">"fija la alarma en el reloj de alarma"</string>
+ <!-- XL -->
+ <string name="permdesc_setAlarm" msgid="5454386032150297784">"Permite a la aplicación fijar una alarma en una aplicación de alarma. Es posible que algunas aplicaciones de alarma no implementen esta función."</string>
+ <!-- XL -->
+ <string name="menu_delete_shortcut_label" msgid="8482704027019632634">"eliminar"</string>
+ <!-- XL -->
+ <plurals name="num_minutes_ago">
+ <item quantity="one" msgid="468685153446407901">"hace 1 minuto"</item>
+ <item quantity="other" msgid="211907662145171054">"Hace <xliff:g id="COUNT">%d</xliff:g> minutos"</item>
+ </plurals>
+ <!-- XL -->
+ <plurals name="num_hours_ago">
+ <item quantity="one" msgid="2172827344495633666">"hace 1 hora"</item>
+ <item quantity="other" msgid="6094391999921908511">"Hace <xliff:g id="COUNT">%d</xliff:g> horas"</item>
+ </plurals>
+ <!-- XL -->
+ <plurals name="num_days_ago">
+ <item quantity="one" msgid="3766494702684657165">"ayer"</item>
+ <item quantity="other" msgid="5030316952487658828">"Hace <xliff:g id="COUNT">%d</xliff:g> días"</item>
+ </plurals>
+ <!-- XL -->
+ <plurals name="abbrev_num_seconds_ago">
+ <item quantity="one" msgid="1441918190525197797">"hace 1 s"</item>
+ <item quantity="other" msgid="3958332340802316933">"hace <xliff:g id="COUNT">%d</xliff:g> segundos"</item>
+ </plurals>
+ <!-- XL -->
+ <plurals name="abbrev_num_minutes_ago">
+ <item quantity="one" msgid="3404245071272952255">"hace 1 min"</item>
+ <item quantity="other" msgid="6004808520903389765">"hace <xliff:g id="COUNT">%d</xliff:g> min"</item>
+ </plurals>
+ <!-- XL -->
+ <plurals name="abbrev_num_hours_ago">
+ <item quantity="one" msgid="806010152744475654">"hace 1 hora"</item>
+ <item quantity="other" msgid="7553525762196895290">"Hace <xliff:g id="COUNT">%d</xliff:g> horas"</item>
+ </plurals>
+ <!-- XL -->
+ <plurals name="abbrev_num_days_ago">
+ <item quantity="one" msgid="5819444260187611238">"ayer"</item>
+ <item quantity="other" msgid="1069986768190052012">"Hace <xliff:g id="COUNT">%d</xliff:g> días"</item>
+ </plurals>
+ <!-- XL -->
+ <string name="preposition_for_time" msgid="3606608741888559522">"a la/s <xliff:g id="TIME">%s</xliff:g>"</string>
+ <!-- XL -->
+ <string name="minutes" msgid="1486240209627391507">"min"</string>
+ <!-- XL -->
+ <string name="selectAll" msgid="847570914566450966">"Seleccionar todos"</string>
+ <!-- XL -->
+ <string name="low_internal_storage_view_text" product="tablet" msgid="6497548813789342134">"Está quedando poco espacio de almacenamiento en la tableta."</string>
+ <string name="low_internal_storage_view_text" product="default" msgid="2901569701336868928">"Hay poco espacio de almacenamiento en el teléfono."</string>
+ <!-- XL -->
+ <string name="capital_on" msgid="5705918046896729554">"ENCENDIDO"</string>
+ <!-- XL -->
+ <string name="wait" msgid="8036803866051401072">"Espera"</string>
+ <!-- XL -->
+ <string name="heavy_weight_notification" msgid="5762367358298413602">"<xliff:g id="APP">%1$s</xliff:g> se está ejecutando"</string>
+ <!-- XL -->
+ <string name="ext_media_checking_notification_title" product="nosdcard" msgid="103298639852047758">"Preparando almacenamiento USB"</string>
+ <string name="ext_media_checking_notification_title" product="default" msgid="2111086053471573248">"Preparando la tarjeta SD"</string>
+ <!-- XL -->
+ <string name="ime_action_done" msgid="7200237418945571897">"Listo"</string>
+ <!-- XL -->
+ <string name="wallpaper_binding_label" msgid="6966627494441714436">"Fondo de pantalla"</string>
+ <!-- XL -->
+ <string name="websearch" msgid="904596193450917688">"Búsqueda web"</string>
+ <!-- XL -->
+ <string name="permlab_mediaStorageWrite" product="default" msgid="5585262071354704256">"modificar/eliminar los contenidos del almacenamientos de medios internos"</string>
+ <!-- XL -->
+ <string name="permdesc_mediaStorageWrite" product="default" msgid="2372999661142345443">"Permite que una aplicación modifique los contenidos del almacenamiento interno de medios."</string>
+ <!-- XL -->
+ <string name="autofill_address_summary_name_format" msgid="7531610259426153850">"$1$2$3"</string>
+ <!-- XL -->
+ <string name="autofill_address_summary_format" msgid="8398158823767723887">"$1$2$3"</string>
+ <!-- XL -->
+ <string name="gpsNotifTicker" msgid="6612390321359669319">"Solicitud de ubicación de <xliff:g id="NAME">%s</xliff:g>"</string>
+ <!-- XL -->
+ <string name="gpsNotifTitle" msgid="7533028619350196545">"Solicitud de ubicación"</string>
+ <!-- XL -->
+ <string name="gpsNotifMessage" msgid="5592972401593755530">"Solicitado por <xliff:g id="NAME">%1$s</xliff:g> (<xliff:g id="SERVICE">%2$s</xliff:g>)"</string>
+ <!-- XL -->
+ <string name="gpsVerifYes" msgid="1511016393202739483">"Sí"</string>
+ <!-- XL -->
+ <string name="gpsVerifNo" msgid="661731239940896232">"No"</string>
+ <!-- XL -->
+ <string name="sync_too_many_deletes" msgid="6088394702274114202">"Eliminar el límite excedido"</string>
+ <!-- XL -->
+ <string name="sync_too_many_deletes_desc" msgid="4794082462774743277">"Existen <xliff:g id="NUMBER_OF_DELETED_ITEMS">%1$d</xliff:g> artículos eliminados para <xliff:g id="TYPE_OF_SYNC">%2$s</xliff:g>, cuenta <xliff:g id="ACCOUNT_NAME">%3$s</xliff:g>. ¿Qué te gustaría hacer?"</string>
+ <!-- XL -->
+ <string name="sync_really_delete" msgid="7782215155483034729">"Eliminar artículos."</string>
+ <!-- XL -->
+ <string name="sync_undo_deletes" msgid="6501390120900825477">"Deshacer eliminaciones."</string>
+ <!-- XL -->
+ <string name="sync_do_nothing" msgid="612038572646360281">"No hagas nada por el momento."</string>
+</resources>
diff --git a/core/res/res/anim/animator_fade_in.xml b/core/res/res/values-xlarge-land/dimens.xml
similarity index 69%
rename from core/res/res/anim/animator_fade_in.xml
rename to core/res/res/values-xlarge-land/dimens.xml
index cff98cf..6a2b93f 100644
--- a/core/res/res/anim/animator_fade_in.xml
+++ b/core/res/res/values-xlarge-land/dimens.xml
@@ -16,11 +16,7 @@
** limitations under the License.
*/
-->
-
-<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
- android:interpolator="@interpolator/accelerate_quad"
- android:valueFrom="0"
- android:valueTo="1"
- android:propertyName="alpha"
- android:duration="@android:integer/config_mediumAnimTime"
-/>
+<resources>
+ <!-- Minimum width of the search view text entry area. -->
+ <dimen name="search_view_text_min_width">256dip</dimen>
+</resources>
diff --git a/core/res/res/values-xlarge/dimens.xml b/core/res/res/values-xlarge/dimens.xml
index 7353f16..18090ba 100644
--- a/core/res/res/values-xlarge/dimens.xml
+++ b/core/res/res/values-xlarge/dimens.xml
@@ -41,4 +41,6 @@
<!-- The standard size (both width and height) of an application icon that
will be displayed in the app launcher and elsewhere. -->
<dimen name="app_icon_size">64dip</dimen>
+ <!-- Minimum width of the search view text entry area. -->
+ <dimen name="search_view_text_min_width">192dip</dimen>
</resources>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index 14c8f46..b8b9e6c 100755
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -636,6 +636,8 @@
<attr name="dialogTheme" format="reference" />
<!-- Theme to use for alert dialogs spawned from this theme. -->
<attr name="alertDialogTheme" format="reference" />
+ <!-- Icon drawable to use for alerts -->
+ <attr name="alertDialogIcon" format="reference" />
<!-- Drawable to use for generic vertical dividers. -->
<attr name="dividerVertical" format="reference" />
@@ -1784,6 +1786,22 @@
<!-- Place the scroll bar on the right. -->
<enum name="right" value="2" />
</attr>
+
+ <!-- Specifies the type of layer backing this view. The default value is none.
+ Refer to {@link android.view.View#setLayerType(int, android.graphics.Paint)
+ for more information.-->
+ <attr name="layerType">
+ <!-- Don't use a layer. -->
+ <enum name="none" value="0" />
+ <!-- Use a software layer. Refer to
+ {@link android.view.View#setLayerType(int, android.graphics.Paint) for
+ more information. -->
+ <enum name="software" value="1" />
+ <!-- Use a hardware layer. Refer to
+ {@link android.view.View#setLayerType(int, android.graphics.Paint) for
+ more information. -->
+ <enum name="hardware" value="2" />
+ </attr>
</declare-styleable>
<!-- Attributes that can be used with a {@link android.view.ViewGroup} or any
@@ -2031,9 +2049,6 @@
will use only the number of items in the adapter and the number of items visible
on screen to determine the scrollbar's properties. -->
<attr name="smoothScrollbar" format="boolean" />
- <!-- A reference to an XML description of the adapter to attach to the list.
- XXX Should remove? -->
- <attr name="adapter" format="reference" />
<!-- Defines the choice behavior for the view. By default, lists do not have
any choice behavior. By setting the choiceMode to singleChoice, the list
allows up to one item to be in a chosen state. By setting the choiceMode to
@@ -4562,74 +4577,6 @@
<attr name="settingsActivity" />
</declare-styleable>
- <!-- =============================== -->
- <!-- Adapters attributes -->
- <!-- =============================== -->
- <eat-comment />
-
- <!-- Adapter used to bind cursors.
- @hide XXX should remove? -->
- <declare-styleable name="CursorAdapter">
- <!-- URI to get the cursor from. Optional. -->
- <attr name="uri" format="string" />
- <!-- Selection statement for the query. Optional. -->
- <attr name="selection" format="string" />
- <!-- Sort order statement for the query. Optional. -->
- <attr name="sortOrder" format="string" />
- <!-- Layout resource used to display each row from the cursor. Mandatory. -->
- <attr name="layout" />
- </declare-styleable>
-
- <!-- Attributes used in bind items for XML cursor adapters.
- @hide XXX should remove? -->
- <declare-styleable name="CursorAdapter_BindItem">
- <!-- The name of the column to bind from. Mandatory. -->
- <attr name="from" format="string" />
- <!-- The resource id of the view to bind to. Mandatory. -->
- <attr name="to" format="reference" />
- <!-- The type of binding. If this value is not specified, the type will be
- inferred from the type of the "to" target view. Mandatory.
-
- The type can be one of:
- <ul>
- <li>string, The content of the column is interpreted as a string.</li>
- <li>image, The content of the column is interpreted as a blob describing an image.</li>
- <li>image-uri, The content of the column is interpreted as a URI to an image.</li>
- <li>drawable, The content of the column is interpreted as a resource id to a drawable.</li>
- <li>A fully qualified class name, corresponding to an implementation of
- android.widget.Adapters.CursorBinder.</li>
- </ul>
- -->
- <attr name="as" format="string" />
- </declare-styleable>
-
- <!-- Attributes used in select items for XML cursor adapters.
- @hide XXX should remove? -->
- <declare-styleable name="CursorAdapter_SelectItem">
- <!-- The name of the column to select. Mandatory. -->
- <attr name="column" format="string" />
- </declare-styleable>
-
- <!-- Attributes used to map values to new values in XML cursor adapters' bind items.
- @hide XXX should remove? -->
- <declare-styleable name="CursorAdapter_MapItem">
- <!-- The original value from the column. Mandatory. -->
- <attr name="fromValue" format="string" />
- <!-- The new value from the column. Mandatory. -->
- <attr name="toValue" format="string" />
- </declare-styleable>
-
- <!-- Attributes used to map values to new values in XML cursor adapters' bind items.
- @hide XXX should remove? -->
- <declare-styleable name="CursorAdapter_TransformItem">
- <!-- The transformation expression. Mandatory if "withClass" is not specified. -->
- <attr name="withExpression" format="string" />
- <!-- The transformation class, an implementation of
- android.widget.Adapters.CursorTransformation. Mandatory if "withExpression"
- is not specified. -->
- <attr name="withClass" format="string" />
- </declare-styleable>
-
<!-- Attributes used to style the Action Bar. -->
<declare-styleable name="ActionBar">
<!-- The type of navigation to use. -->
diff --git a/core/res/res/values/attrs_manifest.xml b/core/res/res/values/attrs_manifest.xml
index fe6176d..5ff6212 100644
--- a/core/res/res/values/attrs_manifest.xml
+++ b/core/res/res/values/attrs_manifest.xml
@@ -234,8 +234,20 @@
the safe mode. -->
<attr name="vmSafeMode" format="boolean" />
- <!-- Flag indicating whether the application's rendering should be hardware
- accelerated if possible. -->
+ <!-- <p>Flag indicating whether the application's rendering should be hardware
+ accelerated if possible. This flag is turned off by default, both for
+ applications and activities.</p>
+ <p>This flag can be set on the application and any activity declared
+ in the manifest. When enabled for the application, each activity is
+ automatically assumed to be hardware accelerated. This flag can be
+ overriden in the activity tags, either turning it off (if on for the
+ application) or on (if off for the application.)</p>
+ <p>When this flag is turned on for an activity (either directly or via
+ the application tag), every window created from the activity, including
+ the activity's own window, will be hardware accelerated, if possible.</p>
+ <p>Please refer to the documentation of
+ {@link android.view.WindowManager.LayoutParams#FLAG_HARDWARE_ACCELERATED}
+ for more information on how to control this flag programmatically.</p> -->
<attr name="hardwareAccelerated" format="boolean" />
<!-- Flag indicating whether the given application component is available
diff --git a/core/res/res/values/colors.xml b/core/res/res/values/colors.xml
index a286265..1a6f404 100644
--- a/core/res/res/values/colors.xml
+++ b/core/res/res/values/colors.xml
@@ -91,7 +91,7 @@
<color name="search_url_text_selected">@android:color/black</color>
<color name="search_url_text_pressed">@android:color/black</color>
<color name="search_widget_corpus_item_background">@android:color/lighter_gray</color>
-
+
<!-- SlidingTab -->
<color name="sliding_tab_text_color_active">@android:color/black</color>
<color name="sliding_tab_text_color_shadow">@android:color/black</color>
@@ -104,9 +104,10 @@
<color name="keyguard_text_color_decline">#fe0a5a</color>
<!-- keyguard clock -->
- <color name="lockscreen_clock_background">#ff9a9a9a</color>
- <color name="lockscreen_clock_foreground">#ff666666</color>
+ <color name="lockscreen_clock_background">#b3ffffff</color>
+ <color name="lockscreen_clock_foreground">#7affffff</color>
<color name="lockscreen_clock_am_pm">#ff9a9a9a</color>
+ <color name="lockscreen_owner_info">#ff9a9a9a</color>
<!-- For holo theme -->
<drawable name="screen_background_holo_light">#fff3f3f3</drawable>
diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml
index 9daba4b..e124d9d 100644
--- a/core/res/res/values/public.xml
+++ b/core/res/res/values/public.xml
@@ -1420,6 +1420,8 @@
<public type="attr" name="editTextColor" />
<public type="attr" name="editTextBackground" />
<public type="attr" name="horizontalScrollViewStyle" />
+ <public type="attr" name="layerType" />
+ <public type="attr" name="alertDialogIcon" />
<!-- A simple fade-in animation. -->
<public type="animator" name="fade_in" id="0x010b0000" />
@@ -1456,9 +1458,6 @@
sinusoidal pattern. -->
<public type="interpolator" name="cycle" />
- <public type="anim" name="animator_fade_in" />
- <public type="anim" name="animator_fade_out" />
-
<!-- Acceleration curve matching a cubic ease in function. -->
<public type="anim" name="accelerate_cubic_interpolator" />
<!-- Acceleration curve matching a cubic ease out function. -->
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 09842f0..d005ed9 100755
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -1030,6 +1030,11 @@
<string name="permdesc_accessUsb">Allows the application to access USB devices.</string>
<!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+ <string name="permlab_accessMtp">implement MTP protocol</string>
+ <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
+ <string name="permdesc_accessMtp">Allows access to the kernel MTP driver to implement the MTP USB protocol.</string>
+
+ <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permlab_hardware_test">test hardware</string>
<!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
<string name="permdesc_hardware_test">Allows the application to control
@@ -2152,7 +2157,8 @@
<!-- Preference framework strings. -->
<string name="no">Cancel</string>
<!-- This is the generic "attention" string to be used in attention dialogs. Typically
- combined with setIcon(android.R.drawable.ic_dialog_alert) -->
+ combined with setIconAttribute(android.R.attr.alertDialogIcon)
+ (or setIcon(android.R.drawable.ic_dialog_alert) on legacy versions of the platform) -->
<string name="dialog_alert_title">Attention</string>
<!-- Text shown by list fragment when waiting for data to display. -->
diff --git a/core/res/res/values/styles.xml b/core/res/res/values/styles.xml
index 470fb36..920312b 100644
--- a/core/res/res/values/styles.xml
+++ b/core/res/res/values/styles.xml
@@ -81,14 +81,14 @@
<item name="wallpaperIntraOpenExitAnimation">@anim/wallpaper_intra_open_exit</item>
<item name="wallpaperIntraCloseEnterAnimation">@anim/wallpaper_intra_close_enter</item>
<item name="wallpaperIntraCloseExitAnimation">@anim/wallpaper_intra_close_exit</item>
- <item name="fragmentOpenEnterAnimation">@anim/fragment_open_enter</item>
- <item name="fragmentOpenExitAnimation">@anim/fragment_open_exit</item>
- <item name="fragmentCloseEnterAnimation">@anim/fragment_close_enter</item>
- <item name="fragmentCloseExitAnimation">@anim/fragment_close_exit</item>
- <item name="fragmentNextEnterAnimation">@anim/fragment_next_enter</item>
- <item name="fragmentNextExitAnimation">@anim/fragment_next_exit</item>
- <item name="fragmentPrevEnterAnimation">@anim/fragment_prev_enter</item>
- <item name="fragmentPrevExitAnimation">@anim/fragment_prev_exit</item>
+ <item name="fragmentOpenEnterAnimation">@animator/fragment_open_enter</item>
+ <item name="fragmentOpenExitAnimation">@animator/fragment_open_exit</item>
+ <item name="fragmentCloseEnterAnimation">@animator/fragment_close_enter</item>
+ <item name="fragmentCloseExitAnimation">@animator/fragment_close_exit</item>
+ <item name="fragmentNextEnterAnimation">@animator/fragment_next_enter</item>
+ <item name="fragmentNextExitAnimation">@animator/fragment_next_exit</item>
+ <item name="fragmentPrevEnterAnimation">@animator/fragment_prev_enter</item>
+ <item name="fragmentPrevExitAnimation">@animator/fragment_prev_exit</item>
</style>
<!-- Standard animations for a non-full-screen window or activity. -->
@@ -1030,9 +1030,10 @@
</style>
<style name="Widget.ActionButton">
- <item name="android:background">@null</item>
+ <item name="android:background">?android:attr/selectableItemBackground</item>
<item name="android:paddingLeft">16dip</item>
<item name="android:paddingRight">16dip</item>
+ <item name="android:minWidth">64dip</item>
</style>
<style name="Widget.ActionButton.Overflow">
@@ -1510,6 +1511,7 @@
<style name="Widget.Holo.ProgressBar.Horizontal" parent="Widget.ProgressBar.Horizontal">
<item name="android:progressDrawable">@android:drawable/progress_horizontal_holo_dark</item>
+ <item name="android:indeterminateDrawable">@android:drawable/progress_indeterminate_horizontal_holo</item>
<item name="android:minHeight">24dip</item>
<item name="android:maxHeight">24dip</item>
</style>
@@ -1540,7 +1542,7 @@
<item name="android:indeterminateDrawable">@android:drawable/scrubber_progress_horizontal_holo_dark</item>
<item name="android:minHeight">13dip</item>
<item name="android:maxHeight">13dip</item>
- <item name="android:thumb">@android:drawable/scrubber_control_holo</item>
+ <item name="android:thumb">@android:drawable/scrubber_control_selector_holo</item>
<item name="android:thumbOffset">16dip</item>
<item name="android:focusable">true</item>
</style>
@@ -1651,8 +1653,8 @@
</style>
<style name="Widget.Holo.ActionButton" parent="Widget.ActionButton">
- <item name="android:paddingLeft">4dip</item>
- <item name="android:paddingRight">4dip</item>
+ <item name="android:paddingLeft">16dip</item>
+ <item name="android:paddingRight">16dip</item>
<item name="android:minHeight">56dip</item>
<item name="android:scaleType">center</item>
</style>
@@ -1981,7 +1983,6 @@
<style name="Widget.Holo.Light.ActionButton.Overflow">
<item name="android:src">@android:drawable/ic_menu_moreoverflow_holo_light</item>
- <item name="android:background">?android:attr/selectableItemBackground</item>
<item name="android:paddingLeft">16dip</item>
<item name="android:paddingRight">16dip</item>
</style>
diff --git a/core/res/res/values/themes.xml b/core/res/res/values/themes.xml
index 231e570a..ed8b20d 100644
--- a/core/res/res/values/themes.xml
+++ b/core/res/res/values/themes.xml
@@ -144,6 +144,7 @@
<item name="dialogTheme">@android:style/Theme.Dialog</item>
<item name="alertDialogTheme">@android:style/Theme.Dialog.Alert</item>
<item name="alertDialogCenterButtons">true</item>
+ <item name="alertDialogIcon">@android:drawable/ic_dialog_alert</item>
<!-- Panel attributes -->
<item name="panelBackground">@android:drawable/menu_background</item>
@@ -808,6 +809,7 @@
<item name="dialogTheme">@android:style/Theme.Holo.Dialog</item>
<item name="alertDialogTheme">@android:style/Theme.Holo.Dialog.Alert</item>
<item name="alertDialogCenterButtons">false</item>
+ <item name="alertDialogIcon">@android:drawable/ic_dialog_alert_holo_dark</item>
<!-- Panel attributes -->
<item name="panelBackground">@android:drawable/menu_background</item>
@@ -1064,6 +1066,7 @@
<item name="alertDialogStyle">@android:style/AlertDialog.Holo.Light</item>
<item name="dialogTheme">@android:style/Theme.Holo.Light.Dialog</item>
<item name="alertDialogTheme">@android:style/Theme.Holo.Light.Dialog.Alert</item>
+ <item name="alertDialogIcon">@android:drawable/ic_dialog_alert_holo_light</item>
<!-- Panel attributes -->
<item name="panelBackground">@android:drawable/menu_background</item>
diff --git a/core/tests/coretests/apks/install_uses_feature/Android.mk b/core/tests/coretests/apks/install_uses_feature/Android.mk
new file mode 100644
index 0000000..c0a5067
--- /dev/null
+++ b/core/tests/coretests/apks/install_uses_feature/Android.mk
@@ -0,0 +1,11 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_PACKAGE_NAME := FrameworkCoreTests_install_uses_feature
+
+include $(BUILD_PACKAGE)
+
diff --git a/core/tests/coretests/apks/install_uses_feature/AndroidManifest.xml b/core/tests/coretests/apks/install_uses_feature/AndroidManifest.xml
new file mode 100644
index 0000000..ecbd7c4
--- /dev/null
+++ b/core/tests/coretests/apks/install_uses_feature/AndroidManifest.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2010 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.
+-->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.android.frameworks.coretests.install_uses_feature">
+
+ <uses-feature android:name="com.android.frameworks.coretests.nonexistent" />
+
+ <application android:hasCode="false">
+ </application>
+</manifest>
diff --git a/core/tests/coretests/apks/install_uses_feature/res/values/strings.xml b/core/tests/coretests/apks/install_uses_feature/res/values/strings.xml
new file mode 100644
index 0000000..3b8b3b1
--- /dev/null
+++ b/core/tests/coretests/apks/install_uses_feature/res/values/strings.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+
+<!-- Just need this dummy file to have something to build. -->
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string name="dummy">dummy</string>
+</resources>
diff --git a/core/tests/coretests/res/raw/install_uses_feature b/core/tests/coretests/res/raw/install_uses_feature
new file mode 100644
index 0000000..769a246
--- /dev/null
+++ b/core/tests/coretests/res/raw/install_uses_feature
Binary files differ
diff --git a/core/tests/coretests/src/android/content/pm/PackageManagerTests.java b/core/tests/coretests/src/android/content/pm/PackageManagerTests.java
index d5f385b..30a43c3 100755
--- a/core/tests/coretests/src/android/content/pm/PackageManagerTests.java
+++ b/core/tests/coretests/src/android/content/pm/PackageManagerTests.java
@@ -23,6 +23,7 @@
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
+import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
@@ -215,7 +216,7 @@
}
}
- public void invokeInstallPackageFail(Uri packageURI, int flags, int result) {
+ public void invokeInstallPackageFail(Uri packageURI, int flags, int expectedResult) {
PackageInstallObserver observer = new PackageInstallObserver();
try {
// Wait on observer
@@ -233,7 +234,7 @@
if(!observer.isDone()) {
fail("Timed out waiting for packageInstalled callback");
}
- assertEquals(observer.returnCode, result);
+ assertEquals(expectedResult, observer.returnCode);
}
} finally {
}
@@ -2838,6 +2839,13 @@
installFromRawResource("install.apk", rapk2, PackageManager.INSTALL_REPLACE_EXISTING, true,
fail, retCode, PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
}
+
+ @LargeTest
+ public void testUsesFeatureMissingFeature() {
+ int retCode = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
+ installFromRawResource("install.apk", R.raw.install_uses_feature, 0, true, true, retCode,
+ PackageInfo.INSTALL_LOCATION_UNSPECIFIED);
+ }
/*---------- Recommended install location tests ----*/
/*
* TODO's
diff --git a/core/tests/coretests/src/android/util/JsonReaderTest.java b/core/tests/coretests/src/android/util/JsonReaderTest.java
index 216a772..b5c2c27 100644
--- a/core/tests/coretests/src/android/util/JsonReaderTest.java
+++ b/core/tests/coretests/src/android/util/JsonReaderTest.java
@@ -16,11 +16,10 @@
package android.util;
-import java.util.Arrays;
-import junit.framework.TestCase;
-
import java.io.IOException;
import java.io.StringReader;
+import java.util.Arrays;
+import junit.framework.TestCase;
public final class JsonReaderTest extends TestCase {
@@ -677,7 +676,7 @@
try {
reader.nextString();
fail();
- } catch (IOException expected) {
+ } catch (MalformedJsonException expected) {
}
}
@@ -811,4 +810,50 @@
reader.nextNull();
reader.endArray();
}
+
+ public void testStrictMultipleTopLevelValues() throws IOException {
+ JsonReader reader = new JsonReader(new StringReader("[] []"));
+ reader.beginArray();
+ reader.endArray();
+ try {
+ reader.peek();
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public void testLenientMultipleTopLevelValues() throws IOException {
+ JsonReader reader = new JsonReader(new StringReader("[] true {}"));
+ reader.setLenient(true);
+ reader.beginArray();
+ reader.endArray();
+ assertEquals(true, reader.nextBoolean());
+ reader.beginObject();
+ reader.endObject();
+ assertEquals(JsonToken.END_DOCUMENT, reader.peek());
+ }
+
+ public void testStrictTopLevelValueType() {
+ JsonReader reader = new JsonReader(new StringReader("true"));
+ try {
+ reader.nextBoolean();
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public void testLenientTopLevelValueType() throws IOException {
+ JsonReader reader = new JsonReader(new StringReader("true"));
+ reader.setLenient(true);
+ assertEquals(true, reader.nextBoolean());
+ }
+
+ public void testStrictNonExecutePrefix() {
+ JsonReader reader = new JsonReader(new StringReader(")]}'\n []"));
+ try {
+ reader.beginArray();
+ fail();
+ } catch (IOException expected) {
+ }
+ }
}
diff --git a/core/tests/coretests/src/android/util/JsonWriterTest.java b/core/tests/coretests/src/android/util/JsonWriterTest.java
index fa84023..b29e2fd 100644
--- a/core/tests/coretests/src/android/util/JsonWriterTest.java
+++ b/core/tests/coretests/src/android/util/JsonWriterTest.java
@@ -16,10 +16,11 @@
package android.util;
-import junit.framework.TestCase;
-
import java.io.IOException;
import java.io.StringWriter;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import junit.framework.TestCase;
public final class JsonWriterTest extends TestCase {
@@ -119,7 +120,7 @@
JsonWriter jsonWriter = new JsonWriter(stringWriter);
jsonWriter.beginObject();
jsonWriter.name("a");
- jsonWriter.value(null);
+ jsonWriter.value((String) null);
jsonWriter.endObject();
assertEquals("{\"a\":null}", stringWriter.toString());
}
@@ -145,6 +146,27 @@
}
}
+ public void testNonFiniteBoxedDoubles() throws IOException {
+ StringWriter stringWriter = new StringWriter();
+ JsonWriter jsonWriter = new JsonWriter(stringWriter);
+ jsonWriter.beginArray();
+ try {
+ jsonWriter.value(new Double(Double.NaN));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ jsonWriter.value(new Double(Double.NEGATIVE_INFINITY));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ try {
+ jsonWriter.value(new Double(Double.POSITIVE_INFINITY));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
public void testDoubles() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
@@ -189,6 +211,22 @@
+ "9223372036854775807]", stringWriter.toString());
}
+ public void testNumbers() throws IOException {
+ StringWriter stringWriter = new StringWriter();
+ JsonWriter jsonWriter = new JsonWriter(stringWriter);
+ jsonWriter.beginArray();
+ jsonWriter.value(new BigInteger("0"));
+ jsonWriter.value(new BigInteger("9223372036854775808"));
+ jsonWriter.value(new BigInteger("-9223372036854775809"));
+ jsonWriter.value(new BigDecimal("3.141592653589793238462643383"));
+ jsonWriter.endArray();
+ jsonWriter.close();
+ assertEquals("[0,"
+ + "9223372036854775808,"
+ + "-9223372036854775809,"
+ + "3.141592653589793238462643383]", stringWriter.toString());
+ }
+
public void testBooleans() throws IOException {
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
diff --git a/core/tests/coretests/src/android/widget/TextViewWordLimitsTest.java b/core/tests/coretests/src/android/widget/TextViewWordLimitsTest.java
index fbc9e1f..20305bf 100644
--- a/core/tests/coretests/src/android/widget/TextViewWordLimitsTest.java
+++ b/core/tests/coretests/src/android/widget/TextViewWordLimitsTest.java
@@ -231,12 +231,22 @@
final String SURROGATE_SYMBOL = "\uD83D\uDE01\uD83D\uDE02\uD83D\uDE03"; // Three smileys
// Letter Other is included even when coded as surrogate pairs
- verifyWordLimits(SURROGATE_LETTER, 1, -1, -1);
- verifyWordLimits(SURROGATE_LETTER, 2, -1, -1);
+ verifyWordLimits(SURROGATE_LETTER, 0, 0, 6);
+ verifyWordLimits(SURROGATE_LETTER, 1, 0, 6);
+ verifyWordLimits(SURROGATE_LETTER, 2, 0, 6);
+ verifyWordLimits(SURROGATE_LETTER, 3, 0, 6);
+ verifyWordLimits(SURROGATE_LETTER, 4, 0, 6);
+ verifyWordLimits(SURROGATE_LETTER, 5, 0, 6);
+ verifyWordLimits(SURROGATE_LETTER, 6, 0, 6);
// Not included classes are ignored even when coded as surrogate pairs
+ verifyWordLimits(SURROGATE_SYMBOL, 0, -1, -1);
verifyWordLimits(SURROGATE_SYMBOL, 1, -1, -1);
verifyWordLimits(SURROGATE_SYMBOL, 2, -1, -1);
+ verifyWordLimits(SURROGATE_SYMBOL, 3, -1, -1);
+ verifyWordLimits(SURROGATE_SYMBOL, 4, -1, -1);
+ verifyWordLimits(SURROGATE_SYMBOL, 5, -1, -1);
+ verifyWordLimits(SURROGATE_SYMBOL, 6, -1, -1);
}
/**
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index f458576..8555be0 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -66,6 +66,10 @@
<group gid="usb" />
</permission>
+ <permission name="android.permission.ACCESS_MTP" >
+ <group gid="mtp" />
+ </permission>
+
<!-- The group that /cache belongs to, linked to the permission
set on the applications that can access /cache -->
<permission name="android.permission.ACCESS_CACHE_FILESYSTEM" >
diff --git a/data/fonts/AndroidClock.ttf b/data/fonts/AndroidClock.ttf
index 24a7f08..03e36cb 100644
--- a/data/fonts/AndroidClock.ttf
+++ b/data/fonts/AndroidClock.ttf
Binary files differ
diff --git a/data/fonts/AndroidClock_Highlight.ttf b/data/fonts/AndroidClock_Highlight.ttf
index 1e14a8f..8fb31ba 100644
--- a/data/fonts/AndroidClock_Highlight.ttf
+++ b/data/fonts/AndroidClock_Highlight.ttf
Binary files differ
diff --git a/docs/html/guide/appendix/api-levels.jd b/docs/html/guide/appendix/api-levels.jd
index 5898fe5..6ab0fc2 100644
--- a/docs/html/guide/appendix/api-levels.jd
+++ b/docs/html/guide/appendix/api-levels.jd
@@ -294,12 +294,11 @@
<p>To run your application against different platform versions in the emulator,
create an AVD for each platform version that you want to test. For more
information about AVDs, see <a
-href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>. If
+href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>. If
you are using a physical device for testing, ensure that you know the API Level
of the Android platform it runs. See the table at the top of this document for
a list of platform versions and their API Levels. </p>
-
<h2 id="provisional">Using a Provisional API Level</h2>
<p>In some cases, an "Early Look" Android SDK platform may be available. To let
diff --git a/docs/html/guide/appendix/glossary.jd b/docs/html/guide/appendix/glossary.jd
index 97669ba..06fdef2 100644
--- a/docs/html/guide/appendix/glossary.jd
+++ b/docs/html/guide/appendix/glossary.jd
@@ -91,8 +91,7 @@
with the SDK. It provides screen capture, log dump, and process
examination capabilities. If you are developing in Eclipse using the ADT
Plugin, DDMS is integrated into your development environment. See <a
- href="{@docRoot}guide/developing/tools/ddms.html">Dalvik Debug Monitor
- Server</a> to learn more about the program.</dd>
+ href="{@docRoot}guide/developing/debugging/ddms.html">Using DDMS</a> to learn more about the program.</dd>
<dt id="dialog">Dialog</dt> <dd> A floating window that that acts as a lightweight
form. A dialog can have button controls only and is intended to perform a
diff --git a/docs/html/guide/developing/building/building-cmdline.jd b/docs/html/guide/developing/building/building-cmdline.jd
index 934e936..f40ad04 100644
--- a/docs/html/guide/developing/building/building-cmdline.jd
+++ b/docs/html/guide/developing/building/building-cmdline.jd
@@ -1,4 +1,4 @@
-page.title=Building and Running Apps in Other IDEs
+page.title=Building and Running Apps on the Command Line
@jd:body
<div id="qv-wrapper">
diff --git a/docs/html/guide/developing/building/index.jd b/docs/html/guide/developing/building/index.jd
index 83a7bb3..b001ebc 100644
--- a/docs/html/guide/developing/building/index.jd
+++ b/docs/html/guide/developing/building/index.jd
@@ -1,4 +1,4 @@
-page.title=Building and Running Applications
+page.title=Building and Running Apps
@jd:body
<div id="qv-wrapper">
@@ -54,6 +54,7 @@
<p>The general process for a typical build is outlined below:</p>
<ul>
+
<li>The Android Asset Packaging Tool (aapt) takes your application resource files, such as the
<code>AndroidManifest.xml</code> file and the XML files for your Activities, and compiles them. An <code>R.java</code> is
also produced so you can reference your resources from your Java code.</li>
diff --git a/docs/html/guide/developing/debug-tasks.html b/docs/html/guide/developing/debug-tasks.html
new file mode 100644
index 0000000..4e738041
--- /dev/null
+++ b/docs/html/guide/developing/debug-tasks.html
@@ -0,0 +1,10 @@
+<html>
+<head>
+<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/debugging/index.html">
+<title>Redirecting...</title>
+</head>
+<body>
+<p>You should be redirected. Please <a
+href="http://developer.android.com/guide/developing/debugging/index.html">click here</a>.</p>
+</body>
+</html>
\ No newline at end of file
diff --git a/docs/html/guide/developing/debug-tasks.jd b/docs/html/guide/developing/debug-tasks.jd
deleted file mode 100644
index 8f40b48..0000000
--- a/docs/html/guide/developing/debug-tasks.jd
+++ /dev/null
@@ -1,232 +0,0 @@
-page.title=Debugging Tasks
-@jd:body
-
-<div id="qv-wrapper">
-<div id="qv">
- <h2>In this document</h2>
- <ol>
- <li><a href="#tools">Tools</a></li>
- <li><a href="#additionaldebugging">Debug with Dev Tools</a></li>
- <li><a href="#DebuggingWebPages">Debugging Web Pages</a></li>
- <li><a href="#toptips">Top Debugging Tips</a></li>
- <li><a href="#ide-debug-port">Configuring Your IDE to Attach to the Debugging Port</a></li>
- </ol>
-</div>
-</div>
-
-<p>This document offers some helpful guidance to debugging applications on Android.
-
-
-<h2 id="tools">Tools</h2>
-
-<p>The Android SDK includes a set of tools to help you debug and profile
-your applications. Here are some tools that you'll use most often:</p>
-
-<dl>
- <dt><strong><a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge
-(ADB)</a></strong></dt>
- <dd>Provides various device management capabilities, including
- moving and syncing files to the emulator, forwarding ports, and running a UNIX
- shell on the emulator.</dd>
- <dt><strong><a href="{@docRoot}guide/developing/tools/ddms.html">Dalvik Debug Monitor Server
-(DDMS)</a></strong></dt>
- <dd>A graphical program that
- supports port forwarding (so you can set up breakpoints in your code in your
- IDE), screen captures on the emulator, thread and stack information,
- and many other features. You can also run logcat to retrieve your Log messages.</dd>
- </dd>
- <dt><strong><a href="{@docRoot}guide/developing/tools/traceview.html">Traceview</a></strong></dt>
- <dd>A graphical viewer that displays trace file data for method calls and times saved by
- your application, which can help you profile the performance of your application.</dd>
- <dt><strong><a href="{@docRoot}guide/developing/tools/ddms.html#logcat">logcat</a></strong></dt>
- <dd>Dumps a log of system
- messages. The messages include a stack trace when the device throws an error,
- as well as {@link android.util.Log} messages you've written from your application. To run
- logcat, execute <code>adb logcat</code> from your Android SDK {@code platform-tools/}
-directory or, from DDMS, select <strong>Device > Run
- logcat</strong>. When using the <a href="{@docRoot}sdk/eclipse-adt.html">ADT plugin for
-Eclipse</a>, you can also view logcat messages by opening the Logcat view, available from
-<strong>Window > Show View > Other > Android > Logcat</strong>.
- <p>{@link android.util.Log} is a logging
- class you can use to print out messages to the logcat. You can read messages
- in real time if you run logcat on DDMS (covered next). Common logging methods include:
- {@link android.util.Log#v(String,String)} (verbose), {@link
- android.util.Log#d(String,String)} (debug), {@link android.util.Log#i(String,String)}
- (information), {@link android.util.Log#w(String,String)} (warning) and {@link
- android.util.Log#e(String,String)} (error). For example:</p>
-<pre class="no-pretty-print">
-Log.i("MyActivity", "MyClass.getView() — get item number " + position);
-</pre>
- <p>The logcat will then output something like:</p>
-<pre class="no-pretty-print">
-I/MyActivity( 1557): MyClass.getView() — get item number 1
-</pre>
- <p>Logcat is also the place to look when debugging a web page in the Android Browser app. See
-<a href="#DebuggingWebPages">Debugging Web Pages</a> below.</p>
-</dl>
-
-<p>For more information about all the development tools provided with the Android SDK, see the <a
-href="{@docRoot}guide/developing/tools/index.html">Tools</a> document.</p>
-
-<p>In addition to the above tools, you may also find the following useful for debugging:
-<dl>
- <dt><a href="{@docRoot}guide/developing/eclipse-adt.html"><strong>Eclipse ADT
-plugin</strong></a></dt>
- <dd>The ADT Plugin for Eclipse integrates a number of the Android development tools (ADB, DDMS,
-logcat output, and other functionality), so that you won't work with them directly but will utilize
-them through the Eclipse IDE.</dd>
- <dt><strong>Developer Settings in the Dev Tools app</strong></dt>
- <dd>The Dev Tools application included in the emulator system image exposes several settings
- that provide useful information such as CPU usage and frame rate. See <a
-href="#additionaldebugging">Debugging and Testing with Dev Tools</a> below.</dd>
-</dl>
-
-<h2 id="additionaldebugging">Debugging and Testing with Dev Tools</h2>
-
-<p>With the Dev Tools application, you can enable a number of settings on your device that will
-make it easier to test and debug your applications.</p>
-
-<p>The Dev Tools application is installed by default
-on all system images included with the SDK, so you can use it with the Android Emulator. If you'd
-like to install the Dev Tools application on a real development device, you can copy the
-application from your emulator and then install it on your device using ADB. To copy the
-application from a running emulator, execute:
-</p>
-<pre>
-adb -e pull /system/app/Development.apk ./Development.apk
-</pre>
-<p>This copies the .apk file into the current directory. Then install it on your connected device
-with:</p>
-<pre>
-adb -d install Development.apk
-</pre>
-
-<p>To get started, launch the Dev Tools application and
-select Development Settings. This will open the Development Settings page with the
-following options (among others):</p>
-
-<dl>
- <dt><strong>Debug app</strong></dt>
- <dd>Lets you select the application to debug. You do not need to set this to attach a debugger,
- but setting this value has two effects:
- <ul>
- <li>It will prevent Android from throwing an error if you pause on
- a breakpoint for a long time while debugging.</li>
- <li>It will enable you to select the <em>Wait for Debugger</em> option
- to pause application startup until your debugger attaches (described
- next). </li>
- </ul>
- </dd>
- <dt><strong>Wait for debugger</strong></dt>
- <dd>Blocks the selected application from loading until a debugger attaches. This
- way you can set a breakpoint in onCreate(), which is important to debug
- the startup process of an Activity. When you change this option, any
- currently running instances of the selected application will be killed.
- In order to check this box, you must have selected a debug application
- as described in the previous option. You can do the same thing by adding
- {@link android.os.Debug#waitForDebugger()} to your code.</dd>
- <dt><strong>Show screen updates</strong></dt>
- <dd>Flashes a momentary pink rectangle on any screen sections that are being
- redrawn. This is very useful for discovering unnecessary screen drawing.</dd>
- <dt><strong>Immediately destroy activities</strong></dt>
- <dd>Tells the
- system to destroy an activity as soon as it is stopped (as if Android had to
- reclaim memory). This is very useful for testing the {@link android.app.Activity#onSaveInstanceState}
- / {@link android.app.Activity#onCreate(android.os.Bundle)} code path, which would
- otherwise be difficult to force. Choosing this option will probably reveal
- a number of problems in your application due to not saving state.</dd>
- <dt><strong>Show CPU usage</strong></dt>
- <dd>Displays CPU meters at the
- top of the screen, showing how much the CPU is being used. The top red bar
- shows overall CPU usage, and the green bar underneath it shows the CPU time
- spent in compositing the screen. <em>Note: You cannot turn this feature off
- once it is on, without restarting the emulator.</em> </dd>
- <dt><strong>Show background</strong></dt>
- <dd>Displays a background pattern
- when no activity screens are visible. This typically does not happen, but
- can happen during debugging.</dd>
-</dl>
-
-<p>These settings will be remembered across emulator restarts.</p>
-
-<h2 id="DebuggingWebPages">Debugging Web Pages</h2>
-
-<p>See the <a href="{@docRoot}guide/webapps/debugging.html">Debugging Web Apps</a> document.</p>
-
-
-<h2 id="toptips">Top Debugging Tips</h2>
-
-<dl>
-<dt><strong>Dump the stack trace</strong></dt>
-<dd>To obtain a stack dump from emulator, you can log
-in with <code>adb shell</code>, use "ps" to find the process you
-want, and then "kill -3 ". The stack trace appears in the log file.
-</dd>
-
-<dt><strong>Display useful info on the emulator screen</strong></dt>
-<dd>The device can display useful information such as CPU usage or highlights
-around redrawn areas. Turn these features on and off in the developer settings
-window as described in <a href="#additionaldebugging">Setting debug and test
-configurations on the emulator</a>.
-</dd>
-
-<dt><strong>Get system state information from the emulator (dumpstate)</strong></dt>
-<dd>You can access dumpstate information from the Dalvik Debug Monitor Service
-tool. See <a href="{@docRoot}guide/developing/tools/adb.html#dumpsys">dumpsys and
-dumpstate</a> on the adb topic page.</dd>
-
-<dt><strong>Get application state information from the emulator (dumpsys)</strong></dt>
-<dd>You can access dumpsys information from the Dalvik Debug Monitor Service
-tool. See <a href="{@docRoot}guide/developing/tools/adb.html#dumpsys">dumpsys and
-dumpstate</a> on the adb topic page.</dd>
-
-<dt><strong>Get wireless connectivity information</strong></dt>
-<dd>You can get information about wireless connectivity using the Dalvik Debug
-Monitor Service tool. From the <strong>Device</strong> menu, select "Dump
-radio state".</dd>
-
-<dt><strong>Log trace data</strong></dt>
-<dd>You can log method calls and other tracing data in an activity by calling
-{@link android.os.Debug#startMethodTracing(String) startMethodTracing()}. See <a
-href="{@docRoot}guide/developing/tools/traceview.html">Running the Traceview Debugging
-Program</a> for details. </dd>
-
-<dt><strong>Log radio data</strong></dt>
-<dd>By default, radio information is not logged to the system (it is a lot of
-data). However, you can enable radio logging using the following commands:
-
-<pre class="no-pretty-print">
-adb shell
-logcat -b radio
-</pre>
-</dd>
-
-<dt><strong>Capture screenshots</strong></dt>
-<dd>The Dalvik Debug Monitor Server (DDMS) can capture screenshots from the emulator. Select
-<strong>Device > Screen capture</strong>.</dd>
-
-<dt><strong>Use debugging helper classes</strong></dt>
-<dd>Android provides debug helper classes such as {@link android.util.Log
- util.Log} and {@link android.os.Debug} for your convenience. </dd>
-</dl>
-
-<p>Also see the <a href="{@docRoot}resources/faq/troubleshooting.html">Troubleshooting</a> document
-for answers to some common developing and debugging issues.</p>
-
-
-<h2 id="ide-debug-port">Configuring Your IDE to Attach to the Debugging Port</h2>
-
-<p>DDMS will assign a specific debugging port to every virtual machine that it
- finds on the emulator. You must either attach your IDE to that
- port (listed on the Info tab for that VM), or you can use a default port 8700
- to connect to whatever application is currently selected on the list of discovered
- virtual machines.</p>
-<p>Your IDE should attach to your application running on the emulator, showing you
- its threads and allowing you to suspend them, inspect their state, and set breakpoints.
- If you selected "Wait for debugger" in the Development settings panel
- the application will run when Eclipse connects, so you will need to set any breakpoints
- you want before connecting.</p>
-<p>Changing either the application being debugged or the "Wait for debugger"
- option causes the system to kill the selected application if it is currently
- running. You can use this to kill your application if it is in a bad state
- by simply going to the settings and toggling the checkbox.</p>
diff --git a/docs/html/guide/developing/debugging/ddms.jd b/docs/html/guide/developing/debugging/ddms.jd
index d22ad2f..8f5e706 100644
--- a/docs/html/guide/developing/debugging/ddms.jd
+++ b/docs/html/guide/developing/debugging/ddms.jd
@@ -280,5 +280,5 @@
</ul>
For more information about providing mock location data, see
- <a href="guide/topics/location/obtaining-user-location.html#MockData">Obtaining User Location</a>.
+ <a href="{@docRoot}guide/topics/location/obtaining-user-location.html#MockData">Obtaining User Location</a>.
diff --git a/docs/html/guide/developing/debugging/debugging-tracing.jd b/docs/html/guide/developing/debugging/debugging-tracing.jd
index cfa1bb1..dcc889d 100644
--- a/docs/html/guide/developing/debugging/debugging-tracing.jd
+++ b/docs/html/guide/developing/debugging/debugging-tracing.jd
@@ -204,9 +204,9 @@
<h2 id="creatingtracefiles">Creating Trace Files</h2>
<p>To use Traceview, you need to generate log files containing the trace information you want to
- analyze.<p>
+ analyze.</p>
- <p>There are two ways to generate trace logs:<p>
+ <p>There are two ways to generate trace logs:</p>
<ul>
<li>Include the {@link android.os.Debug} class in your code and call its
methods to start and stop logging of trace information to disk. This method is very precise because
@@ -293,7 +293,7 @@
<p class="note"><strong>Note:</strong> If you are trying to view the trace logs of an application
that is built with ProGuard enabled (release mode build), some method and member names might be obfuscated.
You can use the Proguard <code>mapping.txt</code> file to figure out the original unobfuscated names. For more information
- on this file, see the <a href="{@docRoot}/guide/developing/tools/proguard.html>Proguard</a> documentation.</p>
+ on this file, see the <a href="{@docRoot}guide/developing/tools/proguard.html">Proguard</a> documentation.</p>
<h2 id="dmtracedump">Using dmtracdedump</h2>
@@ -308,7 +308,7 @@
"{@docRoot}images/tracedump.png"
width="485"
height="401" />
- <p class="image-caption><strong>Figure 3.</strong> Screenshot of dmtracedump</p>
+ <p class="image-caption"><strong>Figure 3.</strong> Screenshot of dmtracedump</p>
<p>For each node, dmtracedump shows <code><ref>
<em>callname</em> (<inc-ms>, <exc-ms>,<numcalls>)</code>, where</p>
@@ -378,8 +378,6 @@
is 20%.</td>
</tr>
</table>
- </dd>
- </dl>
diff --git a/docs/html/guide/developing/debugging/debugging-ui.jd b/docs/html/guide/developing/debugging/debugging-ui.jd
index eba5bf1..9b02d34 100644
--- a/docs/html/guide/developing/debugging/debugging-ui.jd
+++ b/docs/html/guide/developing/debugging/debugging-ui.jd
@@ -9,9 +9,10 @@
<li>
<a href="#hierarchyViewer">Debugging and Optimizing User Interfaces with Hierarchy
Viewer</a>
- <ul>
+ <ol>
<li><a href="#layoutview">Layout View</a></li>
-
+ <li><a href="#pixelperfect">Pixel Perfect View</a></li>
+ </ol>
</li>
<li><a href="#layoutopt">Optimizing Layouts with <code>layoutopt</code></a></li>
@@ -94,7 +95,7 @@
automatically refresh. You must reload the Layout View by clicking <strong>Load View
Hierarchy</strong>.</p>
- <h3>Pixel Perfect View</h3>
+ <h3 id="pixelperfect">Pixel Perfect View</h3>
<p>The Pixel Perfect View provides a magnified look at the current device window. It helps you
design your UI better by giving you a closer look at your UI's image quality, alignment, and other
@@ -190,7 +191,7 @@
<p>
For more information on running the tool, see the
-<a href="${@docRoot}guide/developing/tools/layoutopt.html">layoutopt</a> reference.</p>
+<a href="${@docRoot}guide/developing/debugging/debugging-ui.html#layoutopt">layoutopt</a> reference.</p>
diff --git a/docs/html/guide/developing/debugging/index.jd b/docs/html/guide/developing/debugging/index.jd
index 362f459..f9202ce 100644
--- a/docs/html/guide/developing/debugging/index.jd
+++ b/docs/html/guide/developing/debugging/index.jd
@@ -32,19 +32,19 @@
UNIX shell on the device or emulator, and providing a general means to communicate with
connected emulators and devices.</dd>
- <dt><a href="{@docRoot}guide/developing/tools/ddms.html"><strong>Dalvik Debug Monitor
+ <dt><a href="{@docRoot}guide/developing/debugging/ddms.html"><strong>Dalvik Debug Monitor
Server</strong></a></dt>
<dd>DDMS is a graphical program that communicates with your devices through <code>adb</code>. DDMS can
capture screenshots, gather thread and stack information, spoof incoming calls and SMS
messages, and has many other features.</dd>
- <dt><a href="{@docRoot}guide/developing/devices/avds-devices.html"><strong>Device or
- Emulator</strong></a></dt>
+ <dt><strong><a href="{@docRoot}guide/developing/device.html">Device</a> or
+ <a href="{@docRoot}guide/developing/devices/index.html">Android Virtual Device</a></strong></dt>
- <dd>Your application must run in a device or emulator so that it can be debugged. An <code>adb</code> device
+ <dd>Your application must run in a device or in an AVD so that it can be debugged. An <code>adb</code> device
daemon runs on the device or emulator and provides a means for the <code>adb</code> host daemon to
- communicate with the device.</dd>
+ communicate with the device or emulator.</dd>
<dt><strong>JDWP debugger</strong></dt>
diff --git a/docs/html/guide/developing/device.jd b/docs/html/guide/developing/device.jd
index 3b5b400..4bed963c 100644
--- a/docs/html/guide/developing/device.jd
+++ b/docs/html/guide/developing/device.jd
@@ -31,16 +31,17 @@
Android-powered devices are available.</p>
<p>If you want a SIM-unlocked phone, then you might consider either an Android Dev Phone or the
-Google Nexus One. Both are SIM-unlocked so that you can use them on any GSM network using a SIM
+Google Nexus S. These are SIM-unlocked so that you can use them on any GSM network using a SIM
card. The Android Dev Phones also feature an unlocked bootloader so you can install custom system
-images (great for developing and installing custom versions of the Android platform). To purchase a
-Nexus One, visit <a href="http://www.google.com/phone">google.com/phone</a>. To purchase an Android
+images (great for developing and installing custom versions of the Android platform). To find a
+a place you can purchase the Nexus S, visit <a
+href="http://www.google.com/phone/detail/nexus-s">google.com/phone</a>. To purchase an Android
Dev Phone, see the <a href="http://market.android.com/publish">Android Market</a> site
(requires a developer account).</p>
<p class="note"><strong>Note:</strong> When developing on a device, keep in mind that you should
still use the <a
-href="{@docRoot}guide/developing/tools/emulator.html">Android emulator</a> to test your application
+href="{@docRoot}guide/developing/devices/emulator.html">Android emulator</a> to test your application
on configurations that are not equivalent to those of your real device. Although the emulator
does not allow you to test every device feature (such as the accelerometer), it does
allow you to verify that your application functions properly on different versions of the Android
diff --git a/docs/html/guide/developing/devices/emulator.jd b/docs/html/guide/developing/devices/emulator.jd
index 08fb89d..a3cd5c5 100644
--- a/docs/html/guide/developing/devices/emulator.jd
+++ b/docs/html/guide/developing/devices/emulator.jd
@@ -33,7 +33,6 @@
</div>
</div>
-
<img src="/images/emulator-wvga800l.png" alt="Image of the Android Emulator"
width="367" height="349" style="margin-left:2em;float:right;"/>
<p>The Android SDK includes a virtual mobile device emulator
@@ -119,9 +118,10 @@
it automatically loads the user data and SD card data from the AVD directory. By default,
the emulator stores the user data, SD card data, and cache in the AVD directory.</p>
-<p>To create and manage AVDs you use the android tool, a command-line utility
-included in the SDK. For complete information about how to set up AVDs, see <a
-href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.</p>
+<p>To create and manage AVDs you use the AVD Manager UI or the <code>android</code> tool
+that is included in the SDK.
+For complete information about how to set up AVDs, see <a
+href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>.</p>
<a name="starting"></a>
@@ -352,8 +352,8 @@
<td><strong>Required</strong>. Specifies the AVD to load for this emulator
instance.</td>
<td>You must create an AVD configuration before launching the emulator. For
- information, see <a href="{@docRoot}guide/developing/tools/avd.html">Android
- Virtual Devices</a>.</td>
+ information, see <a href="{@docRoot}guide/developing/devices/managing-avds.html">Creating and Managing
+ Virtual Devices with AVD Manager</a>.</td>
<tr>
<td rowspan="7">Disk Images</td>
<td><code>-cache <filepath></code></td>
@@ -708,7 +708,8 @@
results, since the density with which to render the skin may not be defined.
AVDs let you associate each skin with a default density and override the default
as needed. For more information, see <a
-href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.
+href="{@docRoot}guide/developing/devices/managing-avds.html">Creating and Managing Virtual Devices
+with AVD Manager</a>.
</td>
</tr>
<tr>
@@ -718,15 +719,6 @@
</table>
-
-
-
-
-
-
-
-
-
<a name="diskimages"></a>
<h2>Working with Emulator Disk Images</h2>
@@ -892,7 +884,7 @@
<p>You can also use the android tool to automatically create an SD Card image
for you, when creating an AVD. For more information, see <a
-href="{@docRoot}guide/developing/tools/avd.html#options">Command-line options for AVDs</a>.
+href="{@docRoot}guide/developing/devices/managing-avds.html">Creating and Managing Virtual Devices with AVD Manager</a>.
<a name="temporaryimages"></a>
<h3>Temporary Images</h3>
@@ -1643,7 +1635,7 @@
<h2>Using Emulator Skins</h2>
<p>The Android SDK includes several Emulator skins that you can use to control the resolution and density of the emulated device's screen. To select a specific skin for running the emulator, create an AVD that uses that skin. Please do not use deprecated emulator options such as <code>-skin</code> to control the skin used by an emulator instance. For more information about AVDs, see <a
-href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>. </p>
+href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>.</p>
<a name="multipleinstances"></a>
@@ -1662,9 +1654,9 @@
<p>If you don't have access to Eclipse or the ADT Plugin, you can install
your application on the emulator <a href="{@docRoot}guide/developing/tools/adb.html#move">using
-the adb utility</a>. Before installing the application, you need to package it
-in a .apk file using the <a href="{@docRoot}guide/developing/tools/aapt.html">Android Asset Packaging Tool</a>.
-Once the application is installed, you can start the emulator from the command
+the adb utility</a>. Before installing the application, you need to build and package it
+into an <code>.apk</code> as described in <a href="{@docRoot}guide/developing/building/index.html">Building and
+Running Apps</a>. Once the application is installed, you can start the emulator from the command
line, as described in this document, using any startup options necessary.
When the emulator is running, you can also connect to the emulator instance's
console to issue commands as needed.</p>
@@ -1707,7 +1699,7 @@
<p>You can also use the <code>-c</code> option to specify a path to an SD card
image to use in the new AVD. For more information, see <a
-href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.
+href="{@docRoot}guide/developing/devices/managing-avds-cmdline.html">Creating and Managing Virtual Devices on the Command Line</a>.
</p>
<h3 id="creatingm">Creating an SD card image using mksdcard</h3>
@@ -1722,7 +1714,7 @@
<pre>mksdcard 1024M sdcard1.iso</pre>
-<p>For more information, see <a href="{@docRoot}guide/developing/tools/othertools.html">Other Tools</a>. </p>
+<p>For more information, see <a href="{@docRoot}guide/developing/tools/mksdcard.html"><code>mksdcard</code></a>.</p>
<a name="copying"></a>
<h3>Copying Files to a Disk Image</h3>
diff --git a/docs/html/guide/developing/devices/managing-avds.jd b/docs/html/guide/developing/devices/managing-avds.jd
index 73a6b6c..27d2b55 100644
--- a/docs/html/guide/developing/devices/managing-avds.jd
+++ b/docs/html/guide/developing/devices/managing-avds.jd
@@ -6,7 +6,11 @@
<h2>In this document</h2>
<ol>
- <li><a href="#AVDEclipse">Creating an AVD</a></li>
+ <li><a href="#createavd">Creating an AVD</a>
+ <ol>
+ <li><a href="#hardwareopts">Hardware options</a></li>
+ </ol>
+ </li>
</ol>
</div>
</div>
@@ -25,7 +29,7 @@
of each AVD. </p>
- <h2>Creating an AVD</h2>
+ <h2 id="createavd">Creating an AVD</h2>
<p>You can create as many AVDs as you would like to test on. It is recommended that you test your
applications on all API levels higher than the target API level for your application.</p>
diff --git a/docs/html/guide/developing/eclipse-adt.html b/docs/html/guide/developing/eclipse-adt.html
new file mode 100644
index 0000000..879a356
--- /dev/null
+++ b/docs/html/guide/developing/eclipse-adt.html
@@ -0,0 +1,10 @@
+<html>
+<head>
+<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/projects/projects-eclipse.html">
+<title>Redirecting...</title>
+</head>
+<body>
+<p>You should be redirected. Please <a
+href="http://developer.android.com/guide/developing/projects/projects-eclipse.html">click here</a>.</p>
+</body>
+</html>
\ No newline at end of file
diff --git a/docs/html/guide/developing/eclipse-adt.jd b/docs/html/guide/developing/eclipse-adt.jd
deleted file mode 100644
index f8d32e7..0000000
--- a/docs/html/guide/developing/eclipse-adt.jd
+++ /dev/null
@@ -1,860 +0,0 @@
-page.title=Developing In Eclipse, with ADT
-@jd:body
-
-<div id="qv-wrapper">
- <div id="qv">
- <h2>In this document</h2>
- <ol>
- <li><a href="#CreatingAProject">Creating an Android Project</a></li>
- <li><a href="#AVD">Creating an AVD</a></li>
- <li><a href="#Running">Running Your Application</a>
- <ol>
- <li><a href="#RunningOnEmulator">Running on the emulator</a></li>
- <li><a href="#RunningOnDevice">Running on a device</a></li>
- </ol>
- </li>
- <li><a href="#RunConfig">Creating a Run Configuration</a></li>
- <li><a href="#Signing">Setting Up Application Signing</a></li>
- <li><a href="#libraryProject">Working with Library Projects</a>
- <ol>
- <li><a href="#libraryReqts">Development requirements</a></li>
- <li><a href="#librarySetup">Setting up a library project</a></li>
- <li><a href="#libraryReference">Referencing a library project</a></li>
- <li><a href="#considerations">Development considerations</a></li>
- <li><a href="#libraryMigrating">Migrating library projects to ADT 0.9.8</a></li>
- </ol>
- </li>
- <li><a href="#Tips">Eclipse Tips</a></li>
- </div>
-</div>
-
-
-<p>The Android Development Tools (ADT) plugin for Eclipse adds powerful extensions to the Eclipse
-integrated development environment. It allows you to create and debug Android applications easier
-and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android
-applications:</p>
-
-<ul>
- <li>It gives you access to other Android development tools from inside the Eclipse IDE. For
-example, ADT lets you access the many capabilities of the DDMS tool: take screenshots, manage
-port-forwarding, set breakpoints, and view thread and process information directly from
-Eclipse.</li>
- <li>It provides a New Project Wizard, which helps you quickly create and set up all of the
-basic files you'll need for a new Android application.</li>
- <li>It automates and simplifies the process of building your Android application.</li>
- <li>It provides an Android code editor that helps you write valid XML for your Android
-manifest and resource files.</li>
- <li>It will even export your project into a signed APK, which can be distributed to users.</li>
-</ul>
-
-<p>To begin developing Android applications in the Eclipse IDE with ADT, you first need to
-download the Eclipse IDE and then download and install the ADT plugin. To do so, follow the
-steps given in <a href="{@docRoot}sdk/eclipse-adt.html#installing">Installing
-the ADT Plugin</a>.</p>
-
-<p>If you are already developing applications using a version of ADT earlier than 0.9, make
-sure to upgrade to the latest version before continuing. See the guide to
-<a href="{@docRoot}sdk/eclipse-adt.html#updating">Updating Your ADT Plugin</a>.</p>
-
-<p class="note"><strong>Note:</strong> This guide assumes you are using the latest version of
-the ADT plugin. While most of the information covered also applies to previous
-versions, if you are using an older version, you may want to consult this document from
-the set of documentation included in your SDK package (instead of the online version).</p>
-
-
-<h2 id="CreatingAProject">Creating an Android Project</h2>
-
-<p>The ADT plugin provides a New Project Wizard that you can use to quickly create a new
-Android project (or a project from existing code). To create a new project:</p>
-
-<ol>
- <li>Select <strong>File</strong> > <strong>New</strong> > <strong>Project</strong>.</li>
- <li>Select <strong>Android</strong> > <strong>Android Project</strong>, and click
- <strong>Next</strong>.</li>
- <li>Select the contents for the project:
- <ul>
- <li>Enter a <em>Project Name</em>. This will be the name of the folder where your
- project is created.</li>
- <li>Under Contents, select <strong>Create new project in workspace</strong>.
- Select your project workspace location.</li>
- <li>Under Target, select an Android target to be used as the project's Build Target.
- The Build Target
- specifies which Android platform you'd like your application built against.
- <p>Unless you know that you'll be using new APIs introduced in the latest SDK, you should
- select a target with the lowest platform version possible.</p>
- <p class="note"><strong>Note:</strong> You can change your the Build Target for your
- project at any time: Right-click the project in the Package Explorer, select
- <strong>Properties</strong>, select <strong>Android</strong> and then check
- the desired Project Target.</p>
- </li>
- <li>Under Properties, fill in all necessary fields.
- <ul>
- <li>Enter an <em>Application name</em>. This is the human-readable title for your
- application — the name that will appear on the Android device.</li>
- <li>Enter a <em>Package name</em>. This is the package namespace (following the same rules
- as for packages in the Java programming language) where all your source code
- will reside.</li>
- <li>Select <em>Create Activity</em> (optional, of course, but common) and enter a name
- for your main Activity class.</li>
- <li>Enter a <em>Min SDK Version</em>. This is an integer that indicates
- the minimum API Level required to properly run your application.
- Entering this here automatically sets the <code>minSdkVersion</code> attribute in the
- <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html"><uses-sdk></a>
- of your Android Manifest file. If you're unsure of the appropriate <a
-href="{@docRoot}guide/appendix/api-levels.html">API Level</a> to use,
- copy the API Level listed for the Build Target you selected in the Target tab.</li>
- </ul>
- </li>
- </ul>
- </li>
- <li>Click <strong>Finish</strong>.</li>
-</ol>
-
-<p class="note"><strong>Tip:</strong>
-You can also start the New Project Wizard from the <em>New</em> icon in the toolbar.</p>
-
-<p>Once you complete the New Project Wizard, ADT creates the following
-folders and files in your new project:</p>
- <dl>
- <dt><code>src/</code></dt>
- <dd>Includes your stub Activity Java file. All other Java files for your application
- go here.</dd>
- <dt><code><em><Android Version></em>/</code> (e.g., <code>Android 1.1/</code>)</dt>
- <dd>Includes the <code>android.jar</code> file that your application will build against.
- This is determined by the build target that you have chosen in the <em>New Project
- Wizard</em>.</dd>
- <dt><code>gen/</code></dt>
- <dd>This contains the Java files generated by ADT, such as your <code>R.java</code> file
- and interfaces created from AIDL files.</dd>
- <dt><code>assets/</code></dt>
- <dd>This is empty. You can use it to store raw asset files. </dd>
- <dt><code>res/</code></dt>
- <dd>A folder for your application resources, such as drawable files, layout files, string
- values, etc. See
- <a href="{@docRoot}guide/topics/resources/index.html">Application Resources</a>.</dd>
- <dt><code>AndroidManifest.xml</code></dt>
- <dd>The Android Manifest for your project. See
- <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">The AndroidManifest.xml
- File</a>.</dd>
- <dt><code>default.properties</code></dt>
- <dd>This file contains project settings, such as the build target. This files is integral
- to the project, as such, it should be maintained in a Source Revision Control system.
- It should never be edited manually — to edit project properties,
- right-click the project folder and select "Properties".</dd>
- </dl>
-
-
-<h2 id="AVD">Creating an AVD</h2>
-
-<p>An Android Virtual Device (AVD) is a device configuration for the emulator that
-allows you to model real world devices. In order to run an instance of the emulator, you must create
-an AVD.</p>
-
-<p>To create an AVD from Eclipse:</p>
-
-<ol>
- <li>Select <strong>Window > Android SDK and AVD Manager</strong>, or click the Android SDK and
-AVD Manager icon in the Eclipse toolbar.</p>
- </li>
- <li>In the <em>Virtual Devices</em> panel, you'll see a list of existing AVDs. Click
-<strong>New</strong> to create a new AVD.</li>
- <li>Fill in the details for the AVD.
- <p>Give it a name, a platform target, an SD card size, and
- a skin (HVGA is default).</p>
- <p class="note"><strong>Note:</strong> Be sure to define
- a target for your AVD that satisfies your application's Build Target (the AVD
- platform target must have an API Level equal to or greater than the API Level that your
-application compiles against).</p>
- </li>
- <li>Click <strong>Create AVD</strong>.</li>
-</ol>
-
-<p>Your AVD is now ready and you can either close the SDK and AVD Manager, create more AVDs, or
-launch an emulator with the AVD by selecting a device and clicking <strong>Start</strong>.</p>
-
-<p>For more information about AVDs, read the
-<a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>
-documentation.</p>
-
-
-<h2 id="Running">Running Your Application</h2>
-
-<div class="sidebox-wrapper">
-<div class="sidebox">
-<h2>Use the Emulator to Test Different Configurations</h2>
-<p>Create multiple AVDs that each define a different device configuration with which your
-application is compatible, then launch each AVD into a new emulator from the SDK and AVD Manager.
-Set the target mode in your app's run configuration to manual, so that when you run your
-application, you can select from the available virtual devices.</p>
-</div>
-</div>
-
-<p>Running your application from Eclipse will usually require just a couple clicks, whether you're
-running it on the emulator or on an attached device. The information below describes how to get
-set up and run your application from Eclipse.</p>
-
-<h3 id="RunningOnEmulator">Running on the emulator</h3>
-
-<p>Before you can run your application on the Android Emulator,
-you <strong>must</strong> <a href="#AVD">create an AVD</a>.</p>
-
-<p>To run (or debug) your application, select <strong>Run</strong> > <strong>Run</strong> (or
-<strong>Run</strong> > <strong>Debug</strong>) from the Eclipse menu bar. The ADT plugin
-will automatically create a default launch configuration for the project. Eclipse will then perform
-the following:</p>
-
-<ol>
- <li>Compile the project (if there have been changes since the last build).</li>
- <li>Create a default launch configuration (if one does not already exist for the
-project).</li>
- <li>Install and start the application on an emulator (or device), based on the Deployment
-Target
- defined by the run configuration.
- <p>By default, Android run configurations use an "automatic target" mode for
- selecting a device target. For information on how automatic target mode selects a
- deployment target, see <a href="#AutoAndManualTargetModes">Automatic and manual
- target modes</a> below.</p>
- </li>
-</ol>
-
-<p>If debugging, the application will start in the "Waiting For Debugger" mode. Once the
-debugger is attached, Eclipse will open the Debug perspective.</p>
-
-<p>To set or change the launch configuration used for your project, use the launch configuration
-manager.
-See <a href="#RunConfig">Creating a Run Configuration</a> for information.</p>
-
-<p>Be certain to create multiple AVDs upon which to test your application. You should have one AVD
-for each platform and screen type with which your application is compatible. For
-instance, if your application compiles against the Android 1.5 (API Level 3) platform, you should
-create an AVD for each platform equal to and greater than 1.5 and an AVD for each <a
-href="{@docRoot}guide/practices/screens_support.html">screen type</a> you support, then test
-your application on each one.</p>
-
-
-<h3 id="RunningOnDevice">Running on a device</h3>
-
-<p>Before you can run your application on a device, you must perform some basic setup for your
-device:</p>
-
-<ul>
- <li>Declare your application as debuggable in your manifest</li>
- <li>Enable USB Debugging on your device</li>
- <li>Ensure that your development computer can detect your device when connected via USB</li>
-</ul>
-<p>Read <a href="{@docRoot}guide/developing/device.html#setting-up">Setting up a Device for
-Development</a> for more information.</p>
-
-<p>Once set up and your device is connected via USB, install your application on the device by
-selecting <strong>Run</strong> > <strong>Run</strong> (or
-<strong>Run</strong> > <strong>Debug</strong>) from the Eclipse menu bar.</p>
-
-
-
-<h2 id="RunConfig">Creating a Run Configuration</h2>
-
-<p>The run configuration specifies the project to run, the Activity
-to start, the emulator or connected device to use, and so on. When you first run a project
-as an <em>Android Application</em>, ADT will automatically create a run configuration.
-The default run configuration will
-launch the default project Activity and use automatic target mode for device selection
-(with no preferred AVD). If the default settings don't suit your project, you can
-customize the launch configuration or even create a new.</p>
-
-<p>To create or modify a launch configuration, follow these steps as appropriate
-for your Eclipse version:</p>
-
-<ol>
- <li>Open the run configuration manager.
- <ul>
- <li>In Eclipse 3.3 (Europa), select <strong>Run</strong> >
- <strong>Open Run Dialog</strong> (or <strong>Open Debug Dialog</strong>)
- </li>
- <li>In Eclipse 3.4 (Ganymede), select <strong>Run </strong>>
- <strong>Run Configurations</strong> (or
- <strong>Debug Configurations</strong>)
- </li>
- </ul>
- </li>
- <li>Expand the <strong>Android Application</strong> item and create a new
- configuration or open an existing one.
- <ul>
- <li>To create a new configuration:
- <ol>
- <li>Select <strong>Android Application</strong> and click the <em>New launch
-configuration</em>
- icon above the list (or, right-click <strong>Android Application</strong> and click
- <strong>New</strong>).</li>
- <li>Enter a Name for your configuration.</li>
- <li>In the Android tab, browse and select the project you'd like to run with the
- configuration.</li>
- </ol>
- <li>To open an existing configuration, select the configuration name from the list
- nested below <strong>Android Application</strong>.</li>
- </ul>
- </li>
- <li>Adjust your desired launch configuration settings.
- <p>In the Target tab, consider whether you'd like to use Manual or Automatic mode
- when selecting an AVD to run your application.
- See the following section on <a href="#AutoAndManualTargetModes">Automatic and manual target
- modes</a>).</p>
- <p>You can specify any emulator options to the Additional Emulator Command
- Line Options field. For example, you could add <code>-scale 96dpi</code> to
- scale the AVD's screen to an accurate size, based on the dpi of your
- computer monitor. For a full list of emulator options, see the <a
- href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a>
-document.</p>
- </li>
-</ol>
-
-
-<h3 id="AutoAndManualTargetModes">Automatic and manual target modes</h3>
-
-<p>By default, a run configuration uses the <strong>automatic</strong> target mode in order to
-select an AVD. In this mode, ADT will select an AVD for the application in the following manner:</p>
-
-<ol>
- <li>If there's a device or emulator already running and its AVD configuration
- meets the requirements of the application's build target, the application is installed
- and run upon it.</li>
- <li>If there's more than one device or emulator running, each of which meets the requirements
- of the build target, a "device chooser" is shown to let you select which device to use.</li>
- <li>If there are no devices or emulators running that meet the requirements of the build target,
- ADT looks at the available AVDs. If one meets the requirements of the build target,
- the AVD is used to launch a new emulator, upon which the application is installed and run.</li>
- <li>If all else fails, the application will not be run and you will see a console error warning
- you that there is no existing AVD that meets the build target requirements.</li>
-</ol>
-
-<p>However, if a "preferred AVD" is selected in the run configuration, then the application
-will <em>always</em> be deployed to that AVD. If it's not already running, then a new emulator
-will be launched.</p>
-
-<p>If your run configuration uses <strong>manual</strong> mode, then the "device chooser"
-is presented every time that your application is run, so that you can select which AVD to use.</p>
-
-
-<h2 id="Signing">Signing your Applications</h2>
-
-<p>As you begin developing Android applications, understand that all
-Android applications must be digitally signed before the system will install
-them on an emulator or an actual device. There are two ways to do this:
-with a debug key (for immediate testing on an emulator or development device)
-or with a private key (for application distribution).</p>
-
-<p>The ADT plugin helps you get started quickly by signing your .apk files with
-a debug key, prior to installing them on an emulator or development device. This means that you can
-quickly run your application from Eclipse without having to
-generate your own private key. No specific action on your part is needed,
-provided ADT has access to Keytool.However, please note that if you intend
-to publish your application, you <strong>must</strong> sign the application with your
-own private key, rather than the debug key generated by the SDK tools.</p>
-
-<p>Please read <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your
-Applications</a>, which provides a thorough guide to application signing on Android
-and what it means to you as an Android application developer. The document also includes
-a guide to exporting and signing your application with the ADT's Export Wizard.</p>
-
-
-<h2 id="libraryProject">Working with Library Projects</h2>
-
-<div class="sidebox-wrapper">
-<div class="sidebox">
-<h2>Library project example code</h2>
-
-<p>The SDK includes an example application called TicTacToeMain that shows how a
-dependent application can use code and resources from an Android Library
-project. The TicTacToeMain application uses code and resources from an example
-library project called TicTacToeLib.
-
-<p style="margin-top:1em;">To download the sample applications and run them as
-projects in your environment, use the <em>Android SDK and AVD Manager</em> to
-download the "Samples for SDK API 8" component into your SDK. </p>
-
-<p style="margin-top:1em;">For more information and to browse the code of the
-samples, see the <a
-href="{@docRoot}resources/samples/TicTacToeMain/index.html">TicTacToeMain
-application</a>.</p>
-</div>
-</div>
-
-<p>An Android <em>library project</em> is a development project that holds
-shared Android source code and resources. Other Android application projects can
-reference the library project and, at build time, include its compiled sources
-in their <code>.apk</code> files. Multiple application projects can reference
-the same library project and any single application project can reference
-multiple library projects. </p>
-
-<p>If you have source code and resources that are common to multiple application
-projects, you can move them to a library project so that it is easier to
-maintain across applications and versions. Here are some common scenarios in
-which you could make use of library projects: </p>
-
-<ul>
-<li>If you are developing multiple related applications that use some of the
-same components, you could move the redundant components out of their respective
-application projects and create a single, reuseable set of the same components
-in a library project. </li>
-<li>If you are creating an application that exists in both free and paid
-versions, you could move the part of the application that is common to both versions
-into a library project. The two dependent projects, with their different package
-names, will reference the library project and provide only the difference
-between the two application versions.</li>
-</ul>
-
-<p>Structurally, a library project is similar to a standard Android application
-project. For example, it includes a manifest file at the project root, as well
-as <code>src/</code>, <code>res/</code> and similar directories. The project can
-contain the same types of source code and resources as a standard
-Android project, stored in the same way. For example, source code in the library
-project can access its own resources through its <code>R</code> class. </p>
-
-<p>However, a library project differs from an standard Android application
-project in that you cannot compile it directly to its own <code>.apk</code> or
-run it on the Android platform. Similarly, you cannot export the library project
-to a self-contained JAR file, as you would do for a true library. Instead, you
-must compile the library indirectly, by referencing the library from a dependent
-application's build path, then building that application. </p>
-
-<p>When you build an application that depends on a library project, the SDK
-tools compile the library and merge its sources with those in the main project,
-then use the result to generate the <code>.apk</code>. In cases where a resource
-ID is defined in both the application and the library, the tools ensure that the
-resource declared in the application gets priority and that the resource in the
-library project is not compiled into the application <code>.apk</code>. This
-gives your application the flexibility to either use or redefine any resource
-behaviors or values that are defined in any library.</p>
-
-<p>To organize your code further, your application can add references to
-multiple library projects, then specify the relative priority of the resources
-in each library. This lets you build up the resources actually used in your
-application in a cumulative manner. When two libraries referenced from an
-application define the same resource ID, the tools select the resource from the
-library with higher priority and discard the other. </p>
-
-<p>ADT lets you add references to library projects and set their relative
-priority from the application project's Properties. As shown in Figure 2,
-below, once you've added a reference to a library project, you can use the
-<strong>Up</strong> and <strong>Down</strong> controls to change the ordering,
-with the library listed at the top getting the higher priority. At build time,
-the libraries are merged with the application one at a time, starting from the
-lowest priority to the highest. </p>
-
-<p>Note that a library project cannot itself reference another library project
-and that, at build time, library projects are <em>not</em> merged with each
-other before being merged with the application. However, note that a library can
-import an external library (JAR) in the normal way.</p>
-
-<p>The sections below describe how to use ADT to set up and manage library your
-projects. Once you've set up your library projects and moved code into them, you
-can import library classes and resources to your application in the normal way.
-</p>
-
-
-<h3 id="libraryReqts">Development requirements</h3>
-
-<p>Android library projects are a build-time construct, so you can use them to
-build a final application <code>.apk</code> that targets any API level and is
-compiled against any version of the Android library. </p>
-
-<p>However, to use library projects, you need to update your development
-environment to use the latest tools and platforms, since older releases of the
-tools and platforms do not support building with library projects. Specifically,
-you need to download and install the versions listed below:</p>
-
-<p class="table-caption"><strong>Table 1.</strong> Minimum versions of SDK tools
-and plaforms on which you can develop library projects.</p>
-
-<table>
-<tr>
-<th>Component</th>
-<th>Minimum Version</th>
-</tr>
-<tr>
-<td>SDK Tools</td>
-<td>r6 (or higher)</td>
-</tr>
-<tr><td>Android 2.2 platform</td><td>r1 (or higher)</td></tr>
-<tr><td>Android 2.1 platform</td><td>r2 (or higher)</td></tr>
-<tr><td style="color:gray">Android 2.0.1 platform</td><td style="color:gray"><em>not supported</em></td></tr>
-<tr><td style="color:gray">Android 2.0 platform</td><td style="color:gray"><em>not supported</em></td></tr>
-<tr><td>Android 1.6 platform</td><td>r3 (or higher)</td></tr>
-<tr><td>Android 1.5 platform</td><td>r4 (or higher)</td></tr>
-<tr><td>ADT Plugin</td><td>0.9.7 (or higher)</td></tr>
-</table>
-
-<p>You can download the tools and platforms using the <em>Android SDK and AVD
-Manager</em>, as described in <a href="{@docRoot}sdk/adding-components.html">Adding SDK
-Components</a>. To install or update ADT, use the Eclipse Updater as described
-in <a href="{@docRoot}sdk/eclipse-adt.html">ADT Plugin for Eclipse</a>.</p>
-
-
-<h3 id="librarySetup">Setting up a library project</h3>
-
-<p>A library project is a standard Android project, so you can create a new one in the
-same way as you would a new application project. Specifically, you can use
-the New Project Wizard, as described in <a href="#CreatingAProject">Creating an
-Android Project</a>, above. </p>
-
-<p>When you are creating the library project, you can select any application
-name, package, and set other fields as needed, as shown in the diagram below.
-Click Finish to create the project in the workspace.</p>
-
-<p>Next, set the project's Properties to indicate that it is a library project:</p>
-
-<ol>
-<li>In the <strong>Package Explorer</strong>, right-click the library project
-and select <strong>Properties</strong>.</li>
-<li>In the <strong>Properties</strong> window, select the "Android" properties
-group at left and locate the <strong>Library</strong> properties at right. </li>
-<li>Select the "is Library" checkbox and click <strong>Apply</strong>.</li>
-<li>Click <strong>OK</strong> to close the <strong>Properties</strong> window.</li>
-</ol>
-
-<p>The new project is now marked as a library project. You can begin moving
-source code and resources into it, as described in the sections below. </p>
-
-<p>You can also convert an existing application project into a library. To do
-so, simply open the Properties for the project and select the "is Library"
-checkbox. Other application projects can now reference the existing project as a
-library project.</p>
-
-<img src="{@docRoot}images/developing/adt-props-isLib.png" style="margin:0;padding:0;" />
-<p class="img-caption" style="margin-left:3em;margin-bottom:2em;"><strong>Figure 1.</strong>
-Marking a project as an Android library project. </p>
-
-<h4>Creating the manifest file</h4>
-
-<p>A library project's manifest file must declare all of the shared components
-that it includes, just as would a standard Android application. For more
-information, see the documentation for <a
-href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p>
-
-<p>For example, the <a
-href="{@docRoot}resources/samples/TicTacToeLib/AndroidManifest.html">TicTacToeLib</a>
-example library project declares the Activity <code>GameActivity</code>: </p>
-
-<pre><manifest>
- ...
- <application>
- ...
- <activity android:name="GameActivity" />
- ...
- </application>
-</manifest></pre>
-
-
-<h3 id="libraryReference">Referencing a library project from an application</h3>
-
-<p>If you are developing an application and want to include the shared code or
-resources from a library project, you can do so easily by adding a reference to
-the library project in the application project's Properties.</p>
-
-<p>To add a reference to a library project, follow these steps: </p>
-
-<ol>
-<li>In the <strong>Package Explorer</strong>, right-click the dependent project
-and select <strong>Properties</strong>.</li>
-<li>In the <strong>Properties</strong> window, select the "Android" properties group
-at left and locate the <strong>Library</strong> properties at right.</li>
-<li>Click <strong>Add</strong> to open the <strong>Project Selection</strong>
-dialog. </li>
-<li>From the list of available library projects, select a project and click
-<strong>OK</strong>.</li>
-<li>When the dialog closes, click <strong>Apply</strong> in the
-<strong>Properties</strong> window.</li>
-<li>Click <strong>OK</strong> to close the <strong>Properties</strong> window.</li>
-</ol>
-
-<p>As soon as the Properties dialog closes, Eclipse rebuilds the project,
-including the contents of the library project. </p>
-
-<p>The figure below shows the Properties dialog that lets you add library
-references and move them up and down in priority. </p>
-
-<img src="{@docRoot}images/developing/adt-props-libRef.png" style="margin:0;padding:0;" />
-<p class="img-caption" style="margin-left:3em;margin-bottom:2em;"><strong>Figure 2.</strong>
-Adding a reference to a library project in the properties of an application project. </p>
-
-<p>If you are adding references to multiple libraries, note that you can set
-their relative priority (and merge order) by selecting a library and using the
-<strong>Up</strong> and <strong>Down</strong> controls. The tools merge the
-referenced libraries with your application starting from lowest priority (bottom
-of the list) to highest (top of the list). If more than one library defines the
-same resource ID, the tools select the resource from the library with higher
-priority. The application itself has highest priority and its resources are
-always used in preference to identical resource IDs defined in libraries.</p>
-
-<h4>Declaring library components in the the manifest file</h4>
-
-<p>In the manifest file of the application project, you must add declarations
-of all components that the application will use that are imported from a library
-project. For example, you must declare any <code><activity></code>,
-<code><service></code>, <code><receiver></code>,
-<code><provider></code>, and so on, as well as
-<code><permission></code>, <code><uses-library></code>, and similar
-elements.</p>
-
-<p>Declarations should reference the library components by their fully-qualified
-package names, where appropriate. </p>
-
-<p>For example, the <a
-href="{@docRoot}resources/samples/TicTacToeMain/AndroidManifest.html">TicTacToeMain</a>
-example application declares the library Activity <code>GameActivity</code>
-like this: </p>
-
-<pre><manifest>
- ...
- <application>
- ...
- <activity android:name="com.example.android.tictactoe.library.GameActivity" />
- ...
- </application>
-</manifest></pre>
-
-<p>For more information about the manifest file, see the documentation for <a
-href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p>
-
-
-<h3 id="considerations">Development considerations</h3>
-
-<p>As you develop your library project and dependent applications, keep the
-points listed below in mind.</p>
-
-<p><strong>Resource conflicts</strong></p>
-
-<p>Since the tools merge the resources of a library project with those of a
-dependent application project, a given resource ID might be defined in both
-projects. In this case, the tools select the resource from the application, or
-the library with highest priority, and discard the other resource. As you
-develop your applications, be aware that common resource IDs are likely to be
-defined in more than one project and will be merged, with the resource from the
-application or highest-priority library taking precedence.</p>
-
-<p><strong>Using prefixes to avoid resource conflicts</strong></p>
-
-<p>To avoid resource conflicts for common resource IDs, consider using a prefix
-or other consistent naming scheme that is unique to the project (or is unique
-across all projects). </p>
-
-<p><strong>No export of library project to JAR</strong></p>
-
-<p>A library cannot be distributed as a binary file (such as a jar file). This
-is because the library project is compiled by the main project to use the
-correct resource IDs.</p>
-
-<p><strong>A library project can include a JAR library</strong></p>
-
-<p>You can develop a library project that itself includes a JAR library, however
-you need to manually edit the dependent application project's build path and add
-a path to the JAR file. </p>
-
-<p><strong>A library project can depend on an external JAR library</strong></p>
-
-<p>You can develop a library project that depends on an external library (for
-example, the Maps external library). In this case, the dependent application
-must build against a target that includes the external library (for example, the
-Google APIs Add-On). Note also that both the library project and the dependent
-application must declare the external library their manifest files, in a <a
-href="{@docRoot}guide/topics/manifest/uses-library-element.html"><code><uses-library></code></a>
-element. </p>
-
-<p><strong>Library project can not include raw assets</strong></p>
-
-<p>The tools do not support the use of raw asset files in a library project.
-Any asset resources used by an application must be stored in the
-<code>assets/</code> directory of the application project
-itself.</p>
-
-<p><strong>Targeting different Android platform versions in library project and
-application project</strong></p>
-
-<p>A library is compiled as part of the dependent application project, so the
-API used in the library project must be compatible with the version of the
-Android library used to compile the application project. In general, the library
-project should use an <a href="{@docRoot}guide/appendix/api-levels.html">API level</a>
-that is the same as — or lower than — that used by the application.
-If the library project uses an API level that is higher than that of the
-application, the application project will fail to compile. It is perfectly
-acceptable to have a library that uses the Android 1.5 API (API level 3) and
-that is used in an Android 1.6 (API level 4) or Android 2.1 (API level 7)
-project, for instance.</p>
-
-<p><strong>No restriction on library package name</strong></p>
-
-<p>There is no requirement for the package name of a library to be the same as
-that of applications that use it.</p>
-
-<p><strong>Multiple R classes in gen/ folder of application project</strong></p>
-
-<p>When you build the dependent application project, the code of any libraries
-is compiled and merged to the application project. Each library has its own
-<code>R</code> class, named according to the library's package name. The
-<code>R</code> class generated from the resources of the main project and of the
-library is created in all the packages that are needed including the main
-project’s package and the libraries’ packages.</p>
-
-<p><strong>Testing a library project</strong></p>
-
-<p>There are two recommended ways of setting up testing on code and resources in
-a library project: </p>
-
-<ul>
-<li>You can set up a <a
-href="{@docRoot}guide/developing/testing/testing_otheride.html">test project</a>
-that instruments an application project that depends on the library project. You
-can then add tests to the project for library-specific features.</li>
-<li>You can set up a set up a standard application project that depends on the
-library and put the instrumentation in that project. This lets you create a
-self-contained project that contains both the tests/instrumentations and the
-code to test.</li>
-</ul>
-
-<p><strong>Library project storage location</strong></p>
-
-<p>There are no specific requirements on where you should store a library
-project, relative to a dependent application project, as long as the application
-project can reference the library project by a relative link. You can place the
-library project What is important is that the main project can reference the
-library project through a relative link.</p>
-
-<h3 id="libraryMigrating">Migrating library projects to ADT 0.9.8</h3>
-
-<p>This section provides information about how to migrate a library project
-created with ADT 0.9.7 to ADT 0.9.8 (or higher). The migration is needed only if
-you are developing in Eclipse with ADT and assumes that you have also upgraded
-to SDK Tools r7 (or higher). </p>
-
-<p>The way that ADT handles library projects has changed between
-ADT 0.9.7 and ADT 0.9.8. Specifically, in ADT 0.9.7, the <code>src/</code>
-source folder of the library was linked into the dependent application project
-as a folder that had the same name as the library project. This worked because
-of two restrictions on the library projects:</p>
-
-<ul>
-<li>The library was only able to contain a single source folder (excluding the
-special <code>gen/</code> source folder), and</li>
-<li>The source folder was required to have the name <code>src/</code> and be
-stored at the root of the project.</li>
-</ul>
-
-<p>In ADT 0.9.8, both of those restrictions were removed. A library project can
-have as many source folders as needed and each can have any name. Additionally,
-a library project can store source folders in any location of the project. For
-example, you could store sources in a <code>src/java/</code> directory. In order
-to support this, the name of the linked source folders in the main project are
-now called <<em>library-name</em>>_<<em>folder-name</em>> For
-example: <code>MyLibrary_src/</code> or <code>MyLibrary_src_java/</code>.</p>
-
-<p>Additionally, the linking process now flags those folders in order for ADT to
-recognize that it created them. This will allow ADT to automatically migrate the
-project to new versions of ADT, should they contain changes to the handling of
-library projects. ADT 0.9.7 did not flag the linked source folders, so ADT 0.9.8
-cannot be sure whether the old linked folders can be removed safely. After
-upgrading ADT to 0.9.8, you will need to remove the old linked folders manually
-in a simple two-step process, as described below.</p>
-
-<p>Before you begin, make sure to create a backup copy of your application or
-save the latest version to your code version control system. This ensures that
-you will be able to easily revert the migration changes in case there is a
-problem in your environment.</p>
-
-<p>When you first upgrade to ADT 0.9.8, your main project will look as shown
-below, with two linked folders (in this example, <code>MyLibrary</code> and
-<code>MyLibrary_src</code> — both of which link to
-<code>MyLibrary/src</code>. Eclipse shows an error on one of them because they
-are duplicate links to a single class.</p>
-
-<img src="{@docRoot}images/developing/lib-migration-0.png" alt="">
-
-<p>To fix the error, remove the linked folder that <em>does not</em> contain the
-<code>_src</code> suffix. </p>
-
-<ol>
-<li>Right click the folder that you want to remove (in this case, the
-<code>MyLibrary</code> folder) and choose <strong>Build Path</strong> >
-<strong>Remove from Build Path</strong>, as shown below.</li>
-
-<img src="{@docRoot}images/developing/lib-migration-1.png" style="height:600px"
-alt="">
-
-<li>Next, When asked about unlinking the folder from the project, select
-<strong>Yes</strong>, as shown below.</li>
-
-<img src="{@docRoot}images/developing/lib-migration-2.png" alt="">
-</ol>
-
-<p>This should resolve the error and migrate your library project to the new
-ADT environment. </p>
-
-<h2 id="Tips">Eclipse Tips</h2>
-
-<h3 id="arbitraryexpressions">Executing arbitrary Java expressions in Eclipse</h3>
-
-<p>You can execute arbitrary code when paused at a breakpoint in Eclipse. For example,
- when in a function with a String argument called "zip", you can get
- information about packages and call class methods. You can also invoke arbitrary
- static methods: for example, entering <code>android.os.Debug.startMethodTracing()</code> will
- start dmTrace. </p>
-<p>Open a code execution window, select <strong>Window</strong> > <strong>Show
- View</strong> > <strong>Display</strong> from the main menu to open the
- Display window, a simple text editor. Type your expression, highlight the
- text, and click the 'J' icon (or CTRL + SHIFT + D) to run your
- code. The code runs in the context of the selected thread, which must be
- stopped at a breakpoint or single-step point. (If you suspend the thread
- manually, you have to single-step once; this doesn't work if the thread is
- in Object.wait().)</p>
-<p>If you are currently paused on a breakpoint, you can simply highlight and execute
- a piece of source code by pressing CTRL + SHIFT + D. </p>
-<p>You can highlight a block of text within the same scope by pressing ALT +SHIFT
- + UP ARROW to select larger and larger enclosing blocks, or DOWN ARROW to select
- smaller blocks. </p>
-<p>Here are a few sample inputs and responses in Eclipse using the Display window.</p>
-
-<table width="100%" border="1">
- <tr>
- <th scope="col">Input</th>
- <th scope="col">Response</th>
- </tr>
- <tr>
- <td><code>zip</code></td>
- <td><code>(java.lang.String)
- /work/device/out/linux-x86-debug/android/app/android_sdk.zip</code></td>
- </tr>
- <tr>
- <td><code>zip.endsWith(".zip")</code></td>
- <td><code>(boolean) true</code></td>
- </tr>
- <tr>
- <td><code>zip.endsWith(".jar")</code></td>
- <td><code>(boolean) false</code></td>
- </tr>
-</table>
-<p>You can also execute arbitrary code when not debugging by using a scrapbook page.
- Search the Eclipse documentation for "scrapbook".</p>
-
-
-<h3>Running DDMS Manually</h3>
-
-<p>Although the recommended way to debug is to use the ADT plugin, you can manually run
-DDMS and configure Eclipse to debug on port 8700. (<strong>Note: </strong>Be sure that you
-have first started <a href="{@docRoot}guide/developing/tools/ddms.html">DDMS</a>). </p>
-
-
-
-
-<!-- TODO: clean this up and expand it to cover more wizards and features
-<h3>ADT Wizards</h3>
-
-<p>Notice that the "New Android Project" wizard has been expanded to use the multi-platform
-capabilities of the new SDK.</p>
-
-<p>There is now a "New XML File" wizard that lets you create skeleton XML resource
-files for your Android projects. This makes it easier to create a new layout, a new menu, a
-new strings file, etc.</p>
-
-<p>Both wizards are available via <strong>File > New</strong> and new icons in the main
-Eclipse toolbar (located to the left of the Debug and Run icons).
-If you do not see the new icons, you may need to select <strong>Window > Reset
-Perspective</strong> from the Java perspective.</p>
--->
diff --git a/docs/html/guide/developing/index.jd b/docs/html/guide/developing/index.jd
index 879986c..f19f97e 100644
--- a/docs/html/guide/developing/index.jd
+++ b/docs/html/guide/developing/index.jd
@@ -23,32 +23,33 @@
before continuing.</p>
</li>
- <li>
- <a href="{@docRoot}guide/developing/devices/avds-devices.html">Set up Android Virtual Devices
- or hardware devices</a>.
+ <li>Set up Android Virtual Devices or hardware devices</a>.
<p>You need to create Android Virtual Devices (AVD) or connect hardware devices on which
you will install your applications.</p>
+
+ <p>See <a href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>
+ and <a href="{@docRoot}guide/developing/device.html">Connecting Hardware Devices</a> for more information.
</li>
<li>
- <a href="{@docRoot}guide/developing/projects/projects.html">Create an Android project</a>.
+ <a href="{@docRoot}guide/developing/projects/index.html">Create an Android project</a>.
<p>An Android project contains all source code and resource files for your application. It is
built into an <code>.apk</code> package that you can install on Android devices.</p>
</li>
<li>
- <a href="{@docRoot}guide/developing/building/building.html">Build and run your
+ <a href="{@docRoot}guide/developing/building/index.html">Build and run your
application</a>.
<p>If you are using Eclipse, builds are generated each time you save changes and you can install
your application on a device by clicking <strong>Run</strong>. If you're using another IDE, you can build your
- project using Ant and install it on a device using ADB.</p>
+ project using Ant and install it on a device using <code>adb</code>.</p>
</li>
<li>
- <a href="{@docRoot}guide/developing/debugging/debugging.html">Debug your application with the
+ <a href="{@docRoot}guide/developing/debugging/index.html">Debug your application with the
SDK debugging and logging tools</a>.
<p>Debugging your application involves using a JDWP-compliant debugger along with the
@@ -110,6 +111,6 @@
Eclipse, such as the <code>adb</code> shell commands. You might also need to call Keytool and Jarsigner to
sign your applications, but you can set up Eclipse to do this automatically as well.</p>
- <p>For more information on these tools, see the <a href="@{docRoot}guide/developing/tools/index.html">
- Tools</a> section of the documentation.</p>
+ <p>For more information on the tools provided with the Android SDK, see the
+ <a href="{@docRoot}guide/developing/tools/index.html">Tools</a> section of the documentation.</p>
diff --git a/docs/html/guide/developing/other-ide.html b/docs/html/guide/developing/other-ide.html
new file mode 100644
index 0000000..41dba05
--- /dev/null
+++ b/docs/html/guide/developing/other-ide.html
@@ -0,0 +1,10 @@
+<html>
+<head>
+<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/projects/projects-cmdline.html">
+<title>Redirecting...</title>
+</head>
+<body>
+<p>You should be redirected. Please <a
+href="http://developer.android.com/guide/developing/projects/projects-cmdline.html">click here</a>.</p>
+</body>
+</html>
\ No newline at end of file
diff --git a/docs/html/guide/developing/other-ide.jd b/docs/html/guide/developing/other-ide.jd
deleted file mode 100644
index d309f47..0000000
--- a/docs/html/guide/developing/other-ide.jd
+++ /dev/null
@@ -1,937 +0,0 @@
-page.title=Developing In Other IDEs
-@jd:body
-
-<div id="qv-wrapper">
-<div id="qv">
- <h2>In this document</h2>
- <ol>
- <li><a href="#CreatingAProject">Creating an Android Project</a></li>
- <li><a href="#Signing">Preparing to Sign Your Application</a></li>
- <li><a href="#Building">Building Your Application</a>
- <ol>
- <li><a href="#DebugMode">Building in debug mode</a></li>
- <li><a href="#ReleaseMode">Building in release mode</a></li>
- </ol>
- </li>
- <li><a href="#AVD">Creating an AVD</a></li>
- <li><a href="#Running">Running Your Application</a>
- <ol>
- <li><a href="#RunningOnEmulator">Running on the emulator</a></li>
- <li><a href="#RunningOnDevice">Running on a device</a></li>
- </ol>
- </li>
- <li><a href="#libraryProject">Working with Library Projects</a>
- <ol>
- <li><a href="#libraryReqts">Development requirements</a></li>
- <li><a href="#librarySetup">Setting up a library project</a></li>
- <li><a href="#libraryReference">Referencing a library project</a></li>
- <li><a href="#depAppBuild">Building a dependent application project</a></li>
- <li><a href="#considerations">Development considerations</a></li>
- </ol>
- </li>
- <li><a href="#AttachingADebugger">Attaching a Debugger to Your Application</a></li>
- </ol>
-
- <h2>See also</h2>
- <ol>
- <li><a href="{@docRoot}guide/developing/tools/othertools.html#android">android Tool</a></li>
- <li><a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a></li>
- <li><a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a></li>
- </ol>
-</div>
-</div>
-
-<p>The recommended way to develop an Android application is to use
-<a href="{@docRoot}guide/developing/eclipse-adt.html">Eclipse with the ADT plugin</a>.
-The ADT plugin provides editing, building, debugging, and .apk packaging and signing functionality
-integrated right into the IDE.</p>
-
-<p>However, if you'd rather develop your application in another IDE, such as IntelliJ,
-or in a basic editor, such as Emacs, you can do that instead. The SDK
-includes all the tools you need to set up an Android project, build it, debug it and then
-package it for distribution. This document is your guide to using these tools.</p>
-
-
-<h2 id="EssentialTools">Essential Tools</h2>
-
-<p>When developing in IDEs or editors other than Eclipse, you'll require
-familiarity with the following Android SDK tools:</p>
-
-<dl>
- <dt><a href="{@docRoot}guide/developing/tools/othertools.html#android">android</a></dt>
- <dd>To create/update Android projects and to create/move/delete AVDs.</dd>
- <dt><a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a></dt>
- <dd>To run your Android applications on an emulated Android platform.</dd>
- <dt><a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a></dt>
- <dd>To interface with your emulator or connected device (install apps,
- shell the device, issue commands, etc.).
- </dd>
-</dl>
-
-<p>In addition to the above tools, included with the SDK, you'll use the following
-open source and third-party tools:</p>
-
-<dl>
- <dt>Ant</dt>
- <dd>To compile and build your Android project into an installable .apk file.</dd>
- <dt>Keytool</dt>
- <dd>To generate a keystore and private key, used to sign your .apk file.</dd>
- <dt>Jarsigner (or similar signing tool)</dt>
- <dd>To sign your .apk file with a private key generated by keytool.</dd>
-</dl>
-
-<p>In the topics that follow, you'll be introduced to each of these tools as necessary.
-For more advanced operations, please read the respective documentation for each tool.</p>
-
-
-<h2 id="CreatingAProject">Creating an Android Project</h2>
-
-<p>To create an Android project, you must use the <code>android</code> tool. When you create
-a new project with <code>android</code>, it will generate a project directory
-with some default application files, stub files, configuration files and a build file.</p>
-
-
-<h3 id="CreatingANewProject">Creating a new Project</h3>
-
-<p>If you're starting a new project, use the <code>android create project</code>
-command to generate all the necessary files and folders.</p>
-
-<p>To create a new Android project, open a command-line,
-navigate to the <code>tools/</code> directory of your SDK and run:</p>
-<pre>
-android create project \
---target <em><target_ID></em> \
---name <em><your_project_name></em> \
---path <em>path/to/your/project</em> \
---activity <em><your_activity_name></em> \
---package <em><your_package_namespace></em>
-</pre>
-
-<ul>
- <li><code>target</code> is the "build target" for your application. It corresponds
- to an Android platform library (including any add-ons, such as Google APIs) that you would like to
- build your project against. To see a list of available targets and their corresponding IDs,
- execute: <code>android list targets</code>.</li>
- <li><code>name</code> is the name for your project. This is optional. If provided, this name will
-be used
- for your .apk filename when you build your application.</li>
- <li><code>path</code> is the location of your project directory. If the directory does not exist,
- it will be created for you.</li>
- <li><code>activity</code> is the name for your default {@link android.app.Activity} class. This
-class file
- will be created for you inside
-
-<code><em><path_to_your_project></em>/src/<em><your_package_namespace_path></em>/</code>
-.
- This will also be used for your .apk filename unless you provide a the <code>name</code>.</li>
- <li><code>package</code> is the package namespace for your project, following the same rules as
-for
- packages in the Java programming language.</li>
-</ul>
-
-<p>Here's an example:</p>
-<pre>
-android create project \
---target 1 \
---name MyAndroidApp \
---path ./MyAndroidAppProject \
---activity MyAndroidAppActivity \
---package com.example.myandroid
-</pre>
-
-<p>The tool generates the following files and directories:</p>
-
-<ul>
- <li><code>AndroidManifest.xml</code> - The application manifest file,
- synced to the specified Activity class for the project.</li>
- <li><code>build.xml</code> - Build file for Ant.</li>
- <li><code>default.properties</code> - Properties for the build system. <em>Do not modify
- this file</em>.</li>
- <li><code>build.properties</code> - Customizable properties for the build system. You can edit
-this
- file to override default build settings used by Ant and provide a pointer to your keystore and key
-alias
- so that the build tools can sign your application when built in release mode.</li>
- <li><code>src<em>/your/package/namespace/ActivityName</em>.java</code> - The Activity class
- you specified during project creation.</li>
- <li><code>bin/</code> - Output directory for the build script.</li>
- <li><code>gen/</code> - Holds <code>Ant</code>-generated files, such as <code>R.java</code>.
-</li>
- <li><code>libs/</code> - Holds private libraries.</li>
- <li><code>res/</code> - Holds project resources.</li>
- <li><code>src/</code> - Holds source code.</li>
- <li><code>tests/</code> - Holds a duplicate of all-of-the-above, for testing purposes.</li>
-</ul>
-
-<p>Once you've created your project, you're ready to begin development.
-You can move your project folder wherever you want for development, but keep in mind
-that you must use the <a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a>
-(adb) — located in the SDK <code>platform-tools/</code> directory — to send your
-application
-to the emulator (discussed later). So you need access between your project solution and
-the <code>platform-tools/</code> folder.</p>
-
-<p class="caution"><strong>Caution:</strong> You should refrain from moving the
-location of the SDK directory, because this will break the build scripts. (They
-will need to be manually updated to reflect the new SDK location before they will
-work again.)</p>
-
-
-<h3 id="UpdatingAProject">Updating a project</h3>
-
-<p>If you're upgrading a project from an older version of the Android SDK or want to create
-a new project from existing code, use the
-<code>android update project</code> command to update the project to the new development
-environment. You can also use this command to revise the build target of an existing project
-(with the <code>--target</code> option) and the project name (with the <code>--name</code>
-option). The <code>android</code> tool will generate any files and
-folders (listed in the previous section) that are either missing or need to be updated,
-as needed for the Android project.</p>
-
-<p>To update an existing Android project, open a command-line
-and navigate to the <code>tools/</code> directory of your SDK. Now run:</p>
-<pre>
-android update project --name <em><project_name></em> --target <em><target_ID></em>
---path <em><path_to_your_project></em>
-</pre>
-
-<ul>
- <li><code>target</code> is the "build target" for your application. It corresponds to
- an Android platform library (including any add-ons, such as Google APIs) that you would
- like to build your project against. To see a list of available targets and their corresponding
-IDs,
- execute: <code>android list targets</code>.</li>
- <li><code>path</code> is the location of your project directory.</li>
- <li><code>name</code> is the name for the project. This is optional—if you're not
- changing the project name, you don't need this.</li>
-</ul>
-
-<p>Here's an example:</p>
-<pre>
-android update project --name MyApp --target 2 --path ./MyAppProject
-</pre>
-
-
-<h2 id="Signing">Preparing to Sign Your Application</h2>
-
-<p>As you begin developing Android applications, understand that all
-Android applications must be digitally signed before the system will install
-them on an emulator or device. There are two ways to do this:
-with a <em>debug key</em> (for immediate testing on an emulator or development device)
-or with a <em>private key</em> (for application distribution).</p>
-
-<p>The Android build tools help you get started by automatically signing your .apk
-files with a debug key at build time. This means
-that you can compile your application and install it on the emulator without
-having to generate your own private key. However, please note that if you intend
-to publish your application, you <strong>must</strong> sign the application with your
-own private key, rather than the debug key generated by the SDK tools. </p>
-
-<p>Please read <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your
-Applications</a>, which provides a thorough guide to application signing on Android
-and what it means to you as an Android application developer.</p>
-
-
-
-<h2 id="Building">Building Your Application</h2>
-
-<p>There are two ways to build your application: one for testing/debugging your application
-— <em>debug mode</em> — and one for building your final package for release —
-<em>release mode</em>. As described in the previous
-section, your application must be signed before it can be installed on an emulator
-or device.</p>
-
-<p>Whether you're building in debug mode or release mode, you
-need to use the Ant tool to compile and build your project. This will create the .apk file
-that is installed onto the emulator or device. When you build in debug mode, the .apk
-file is automatically signed by the SDK tools with a debug key, so it's instantly ready for
-installation
-(but only onto an emulator or attached development device).
-When you build in release mode, the .apk file is <em>unsigned</em>, so you must manually
-sign it with your own private key, using Keytool and Jarsigner.</p>
-
-<p>It's important that you read and understand
-<a href="{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>, particularly
-once you're ready to release your application and share it with end-users. That document describes
-the procedure for generating a private key and then using it to sign your .apk file.
-If you're just getting started, however,
-you can quickly run your applications on an emulator or your own development device by building in
-debug mode.</p>
-
-<p>If you don't have Ant, you can obtain it from the
-<a href="http://ant.apache.org/">Apache Ant home page</a>. Install it and make
-sure it is in your executable PATH. Before calling Ant, you need to declare the JAVA_HOME
-environment variable to specify the path to where the JDK is installed.</p>
-
-<p class="note"><strong>Note:</strong> When installing JDK on Windows, the default is to install
-in the "Program Files" directory. This location will cause <code>ant</code> to fail, because of
-the space. To fix the problem, you can specify the JAVA_HOME variable like this:
-<code>set JAVA_HOME=c:\Progra~1\Java\<jdkdir></code>. The easiest solution, however, is to
-install JDK in a non-space directory, for example: <code>c:\java\jdk1.6.0_02</code>.</p>
-
-
-<h3 id="DebugMode">Building in debug mode</h3>
-
-<p>For immediate application testing and debugging, you can build your application
-in debug mode and immediately install it on an emulator. In debug mode, the build tools
-automatically sign your application with a debug key and optimize the package with
-{@code zipalign}. However, you can (and should) also test your
-application in release mode. Debug mode simply allows you to run your application without
-manually signing the application.</p>
-
-<p>To build in debug mode:</p>
-
-<ol>
- <li>Open a command-line and navigate to the root of your project directory.</li>
- <li>Use Ant to compile your project in debug mode:
- <pre>ant debug</pre>
- <p>This creates your debug .apk file inside the project <code>bin/</code>
- directory, named <code><em><your_project_name></em>-debug.apk</code>. The file
- is already signed with the debug key and has been aligned with {@code zipalign}.</p>
- </li>
-</ol>
-
-<p>Each time you change a source file or resource, you must run Ant
-again in order to package up the latest version of the application.</p>
-
-<p>To install and run your application on an emulator, see the following section
-about <a href="#Running">Running Your Application</a>.</p>
-
-
-<h3 id="ReleaseMode">Building in release mode</h3>
-
-<p>When you're ready to release and distribute your application to end-users, you must build
-your application in release mode. Once you have built in release mode, it's a good idea to perform
-additional testing and debugging with the final .apk.</p>
-
-<p>Before you start building your application in release mode, be aware that you must sign
-the resulting application package with your private key, and should then align it using the
-{@code zipalign} tool. There are two approaches to building in release mode:
-build an unsigned package in release mode and then manually sign and align
-the package, or allow the build script
-to sign and align the package for you.</p>
-
-<h4 id="ManualReleaseMode">Build unsigned</h4>
-
-<p>If you build your application <em>unsigned</em>, then you will need to
-manually sign and align the package.</p>
-
-<p>To build an <em>unsigned</em> .apk in release mode:</p>
-
-<ol>
- <li>Open a command-line and navigate to the root of your project directory.</li>
- <li>Use Ant to compile your project in release mode:
- <pre>ant release</pre>
- </li>
-</ol>
-
-<p>This creates your Android application .apk file inside the project <code>bin/</code>
-directory, named <code><em><your_project_name></em>-unsigned.apk</code>.</p>
-
-<p class="note"><strong>Note:</strong> The .apk file is <em>unsigned</em> at this point
-and can't be installed until signed with your private key.</p>
-
-<p>Once you have created the unsigned .apk, your next step is to sign the .apk
-with your private key and then align it with {@code zipalign}. To complete this procedure,
-read <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>.</p>
-
-<p>When your .apk has been signed and aligned, it's ready to be distributed to end-users.</p>
-
-<h4 id="AutoReleaseMode">Build signed and aligned</h4>
-
-<p>If you would like, you can configure the Android build script to automatically
-sign and align your application package. To do so, you must provide the path to your keystore
-and the name of your key alias in your project's {@code build.properties} file. With this
-information provided, the build script will prompt you for your keystore and alias password
-when you build in release mode and produce your final application package, which will be ready
-for distribution.</p>
-
-<p class="caution"><strong>Caution:</strong> Due to the way Ant handles input, the password that
-you enter during the build process <strong>will be visible</strong>. If you are
-concerned about your keystore and alias password being visible on screen, then you
-may prefer to perform the application signing manually, via Jarsigner (or a similar tool). To
-instead
-perform the signing procedure manually, <a href="#ManualReleaseMode">build unsigned</a> and then
-continue
-with <a href="{@docRoot}guide/publishing/app-signing.html">Signing Your Applications</a>.</p>
-
-<p>To specify your keystore and alias, open the project {@code build.properties} file (found in the
-root of the project directory) and add entries for {@code key.store} and {@code key.alias}.
-For example:</p>
-
-<pre>
-key.store=path/to/my.keystore
-key.alias=mykeystore
-</pre>
-
-<p>Save your changes. Now you can build a <em>signed</em> .apk in release mode:</p>
-
-<ol>
- <li>Open a command-line and navigate to the root of your project directory.</li>
- <li>Use Ant to compile your project in release mode:
- <pre>ant release</pre>
- </li>
- <li>When prompted, enter you keystore and alias passwords.
- <p class="caution"><strong>Caution:</strong> As described above,
- your password will be visible on the screen.</p>
- </li>
-</ol>
-
-<p>This creates your Android application .apk file inside the project <code>bin/</code>
-directory, named <code><em><your_project_name></em>-release.apk</code>.
-This .apk file has been signed with the private key specified in
-{@code build.properties} and aligned with {@code zipalign}. It's ready for
-installation and distribution.</p>
-
-
-<h4>Once built and signed in release mode</h4>
-
-<p>Once you have signed your application with a private key, you can install it on an
-emulator or device as discussed in the following section about
-<a href="#Running">Running Your Application</a>.
-You can also try installing it onto a device from a web server.
-Simply upload the signed APK to a web site, then load the .apk URL in your Android web browser to
-download the application and begin installation.
-(On your device, be sure you have enabled <em>Settings > Applications > Unknown sources</em>.)</p>
-
-
-<h2 id="AVD">Creating an AVD</h2>
-
-<p>An Android Virtual Device (AVD) is a device configuration for the emulator that
-allows you to model real world devices. In order to run an instance of the emulator, you must create
-an AVD.</p>
-
-<p>To create an AVD using the SDK tools:</p>
-
-<ol>
- <li>Navigate to your SDK's <code>tools/</code> directory and execute the {@code android}
-tool with no arguments:
- <pre>android</pre>
- <p>This will launch the SDK and AVD Manager GUI.</p>
- </li>
- <li>In the <em>Virtual Devices</em> panel, you'll see a list of existing AVDs. Click
-<strong>New</strong>
- to create a new AVD.</li>
- <li>Fill in the details for the AVD.
- <p>Give it a name, a platform target, an SD card size, and
- a skin (HVGA is default).</p>
- <p class="note"><strong>Note:</strong> Be sure to define
- a target for your AVD that satisfies your application's build target (the AVD
- platform target must have an API Level equal to or greater than the API Level that your
-application compiles against).</p>
- </li>
- <li>Click <strong>Create AVD</strong>.</li>
-</ol>
-
-<p>Your AVD is now ready and you can either close the AVD Manager, create more AVDs, or
-launch an emulator with the AVD by clicking <strong>Start</strong>.</p>
-
-<p>For more information about AVDs, read the
-<a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>
-documentation.</p>
-
-
-<h2 id="Running">Running Your Application</h2>
-
-<div class="sidebox-wrapper">
-<div class="sidebox">
-<h2>Use the Emulator to Test Different Configurations</h2>
-<p>Create multiple AVDs that each define a different device configuration with which your
-application is compatible, then launch each AVD into a new emulator from the SDK and AVD Manager.
-Set the target mode in your app's run configuration to manual, so that when you run your
-application, you can select from the available virtual devices.</p>
-</div>
-</div>
-
-<p>Running your application on a virtual or real device takes just a couple steps. Remember to
-first <a href="#Building">build your application</a>.</p>
-
-<h3 id="RunningOnEmulator">Running on the emulator</h3>
-
-<p>Before you can run your application on the Android Emulator,
-you must <a href="#AVD">create an AVD</a>.</p>
-
-<p>To run your application:</p>
-<ol>
- <li><strong>Open the SDK and AVD Manager and launch a virtual device</strong></li>
- <p>From your SDK's <code>tools/</code> directory, execute the {@code android} tool with no
-arguments:
- <pre>android</pre>
- <p>In the <em>Virtual Devices</em> view, select an AVD and click <strong>Start</strong>.</p>
- </li>
-
- <li><strong>Install your application</strong>
- <p>From your SDK's <code>platform-tools/</code> directory, install the {@code .apk} on the
-emulator:
- <pre>adb install <em><path_to_your_bin></em>.apk</pre>
- <p>Your APK file (signed with either a release or debug key) is in your project {@code bin/}
-directory after you <a href="#Building">build your application</a>.</p>
- <p>If there is more than one emulator running, you must specify the emulator upon which to
-install the application, by its serial number, with the <code>-s</code> option. For example:</p>
- <pre>adb -s emulator-5554 install <em>path/to/your/app</em>.apk</pre>
- <p>To see a list of available device serial numbers, execute {@code adb devices}.</p>
- </li>
-</ol>
-
-<p>If you don't see your application on the emulator. Try closing the emulator and launching the
-virtual device again from the SDK and AVD Manager. Sometimes when you install an Activity for the
-first time, it won't show up in the application launcher or be accessible by other
-applications. This is because the package manager usually examines manifests
-completely only on emulator startup.</p>
-
-<p>Be certain to create multiple AVDs upon which to test your application. You should have one AVD
-for each platform and screen type with which your application is compatible. For
-instance, if your application compiles against the Android 1.5 (API Level 3) platform, you should
-create an AVD for each platform equal to and greater than 1.5 and an AVD for each <a
-href="{@docRoot}guide/practices/screens_support.html">screen type</a> you support, then test
-your application on each one.</p>
-
-<p class="note"><strong>Tip:</strong> If you have <em>only one</em> emulator running,
-you can build your application and install it on the emulator in one simple step.
-Navigate to the root of your project directory and use Ant to compile the project
-with <em>install mode</em>:
-<code>ant install</code>. This will build your application, sign it with the debug key,
-and install it on the currently running emulator.</p>
-
-
-<h3 id="RunningOnDevice">Running on a device</h3>
-
-<p>Before you can run your application on a device, you must perform some basic setup for your
-device:</p>
-
-<ul>
- <li>Declare your application as debuggable in your manifest</li>
- <li>Enable USB Debugging on your device</li>
- <li>Ensure that your development computer can detect your device when connected via USB</li>
-</ul>
-<p>Read <a href="{@docRoot}guide/developing/device.html#setting-up">Setting up a Device for
-Development</a> for more information.</p>
-
-<p>Once your device is set up and connected via USB, navigate to your
-SDK's <code>platform-tools/</code> directory and install the <code>.apk</code> on the device:
- <pre>adb -d install <em>path/to/your/app</em>.apk</pre>
- <p>The {@code -d} flag specifies that you want to use the attached device (in case you also
-have an emulator running).</p>
-
-<p>For more information on the tools used above, please see the following documents:</p>
-<ul>
- <li><a href="{@docRoot}guide/developing/tools/othertools.html#android">android Tool</a></li>
- <li><a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a></li>
- <li><a href="{@docRoot}guide/developing/tools/adb.html">Android Debug Bridge</a> (ADB)</li>
-</ul>
-
-<h2 id="libraryProject">Working with Library Projects</h2>
-
-<div class="sidebox-wrapper">
-<div class="sidebox">
-<h2>Library project example code</h2>
-
-<p>The SDK includes an example application called TicTacToeMain that shows how a
-dependent application can use code and resources from an Android Library
-project. The TicTacToeMain application uses code and resources from an example
-library project called TicTacToeLib.
-
-<p style="margin-top:1em;">To download the sample applications and run them as
-projects in your environment, use the <em>Android SDK and AVD Manager</em> to
-download the "Samples for SDK API 8" component into your SDK. </p>
-
-<p style="margin-top:1em;">For more information and to browse the code of the
-samples, see the <a
-href="{@docRoot}resources/samples/TicTacToeMain/index.html">TicTacToeMain
-application</a>.</p>
-</div>
-</div>
-
-<p>An Android <em>library project</em> is a development project that holds
-shared Android source code and resources. Other Android application projects can
-reference the library project and, at build time, include its compiled sources
-in their <code>.apk</code> files. Multiple application projects can reference
-the same library project and any single application project can reference
-multiple library projects. </p>
-
-<p>If you have source code and resources that are common to multiple application
-projects, you can move them to a library project so that it is easier to
-maintain across applications and versions. Here are some common scenarios in
-which you could make use of library projects: </p>
-
-<ul>
-<li>If you are developing multiple related applications that use some of the
-same components, you could move the redundant components out of their respective
-application projects and create a single, reuseable set of the same components
-in a library project. </li>
-<li>If you are creating an application that exists in both free and paid
-versions, you could move the part of the application that is common to both versions
-into a library project. The two dependent projects, with their different package
-names, will reference the library project and provide only the difference
-between the two application versions.</li>
-</ul>
-
-<p>Structurally, a library project is similar to a standard Android application
-project. For example, it includes a manifest file at the project root, as well
-as <code>src/</code>, <code>res/</code> and similar directories. The project can
-contain the same types of source code and resources as a standard
-Android project, stored in the same way. For example, source code in the library
-project can access its own resources through its <code>R</code> class. </p>
-
-<p>However, a library project differs from an standard Android application
-project in that you cannot compile it directly to its own <code>.apk</code> or
-run it on the Android platform. Similarly, you cannot export the library project
-to a self-contained JAR file, as you would do for a true library. Instead, you
-must compile the library indirectly, by referencing the library from a dependent
-application's build path, then building that application. </p>
-
-<p>When you build an application that depends on a library project, the SDK
-tools compile the library and merge its sources with those in the main project,
-then use the result to generate the <code>.apk</code>. In cases where a resource
-ID is defined in both the application and the library, the tools ensure that the
-resource declared in the application gets priority and that the resource in the
-library project is not compiled into the application <code>.apk</code>. This
-gives your application the flexibility to either use or redefine any resource
-behaviors or values that are defined in any library.</p>
-
-<p>To organize your code further, your application can add references to
-multiple library projects, then specify the relative priority of the resources
-in each library. This lets you build up the resources actually used in your
-application in a cumulative manner. When two libraries referenced from an
-application define the same resource ID, the tools select the resource from the
-library with higher priority and discard the other.
-
-<p>Once you've have added references, the tools let you set their relative
-priority by editing the application project's build properties. At build time,
-the tools merge the libraries with the application one at a time, starting from
-the lowest priority to the highest. </p>
-
-<p>Note that a library project cannot itself reference another library project
-and that, at build time, library projects are <em>not</em> merged with each
-other before being merged with the application. However, note that a library can
-import an external library (JAR) in the normal way.</p>
-
-<p>The sections below describe how to use ADT to set up and manage library your
-projects. Once you've set up your library projects and moved code into them, you
-can import library classes and resources to your application in the normal way.
-</p>
-
-
-<h3 id="libraryReqts">Development requirements</h3>
-
-<p>Android library projects are a build-time construct, so you can use them to
-build a final application <code>.apk</code> that targets any API level and is
-compiled against any version of the Android library. </p>
-
-<p>However, to use library projects, you need to update your development
-environment to use the latest tools and platforms, since older releases of the
-tools and platforms do not support building with library projects. Specifically,
-you need to download and install the versions listed below:</p>
-
-<p class="table-caption"><strong>Table 1.</strong> Minimum versions of SDK tools
-and plaforms on which you can develop library projects.</p>
-
-<table>
-<tr>
-<th>Component</th>
-<th>Minimum Version</th>
-</tr>
-<tr>
-<td>SDK Tools</td>
-<td>r6 (or higher)</td>
-</tr>
-<tr><td>Android 2.2 platform</td><td>r1 (or higher)</td></tr>
-<tr><td>Android 2.1 platform</td><td>r2 (or higher)</td></tr>
-<tr><td style="color:gray">Android 2.0.1 platform</td><td style="color:gray"><em>not supported</em></td></tr>
-<tr><td style="color:gray">Android 2.0 platform</td><td style="color:gray"><em>not supported</em></td></tr>
-<tr><td>Android 1.6 platform</td><td>r3 (or higher)</td></tr>
-<tr><td>Android 1.5 platform</td><td>r4 (or higher)</td></tr>
-<tr><td>ADT Plugin</td><td>0.9.7 (or higher)</td></tr>
-</table>
-
-<p>You can download the tools and platforms using the <em>Android SDK and AVD
-Manager</em>, as described in <a href="{@docRoot}sdk/adding-components.html">Adding SDK
-Components</a>.</p>
-
-
-<h3 id="librarySetup">Setting up a new library project</h3>
-
-<p>A library project is a standard Android project, so you can create a new one in the
-same way as you would a new application project. Specifically, you can use
-the <code>android</code> tool to generate a new library project with all of the
-necessary files and folders. </p>
-
-<h4>Creating a library project</h4>
-
-<p>To create a new library project, navigate to the <code><sdk>/tools/</code> directory
-and use this command:</p>
-
-<pre class="no-pretty-print" style="color:black">
-android create lib-project --name <em><your_project_name></em> \
---target <em><target_ID></em> \
---path <em>path/to/your/project</em> \
---package <em><your_library_package_namespace></em>
-</pre>
-
-<p>The <code>create lib-project</code> command creates a standard project
-structure that includes preset property that indicates to the build system that
-the project is a library. It does this by adding this line to the project's
-<code>default.properties</code> file: </p>
-
-<pre class="no-pretty-print" style="color:black">android.library=true</pre>
-
-<p>Once the command completes, the library project is created and you can begin moving
-source code and resources into it, as described in the sections below.</p>
-
-<p>If you want to convert an existing application project to a library project,
-so that other applications can use it, you can do so by adding a the
-<code>android.library=true</code> property to the application's
-<code>default.properties</code> file. </p>
-
-<h4>Creating the manifest file</h4>
-
-<p>A library project's manifest file must declare all of the shared components
-that it includes, just as would a standard Android application. For more
-information, see the documentation for <a
-href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p>
-
-<p>For example, the <a
-href="{@docRoot}resources/samples/TicTacToeLib/AndroidManifest.html">TicTacToeLib</a>
-example library project declares the Activity <code>GameActivity</code>: </p>
-
-<pre><manifest>
- ...
- <application>
- ...
- <activity android:name="GameActivity" />
- ...
- </application>
-</manifest></pre>
-
-<h4>Updating a library project</h4>
-
-<p>If you want to update the build properties (build target, location) of the
-library project, use this command: </p>
-
-<pre>
-android update lib-project \
---target <em><target_ID></em> \
---path <em>path/to/your/project</em>
-</pre>
-
-
-<h3 id="libraryReference">Referencing a library project from an application</h3>
-
-<p>If you are developing an application and want to include the shared code or
-resources from a library project, you can do so easily by adding a reference to
-the library project in the application project's build properties.</p>
-
-<p>To add a reference to a library project, navigate to the <code><sdk>/tools/</code> directory
-and use this command:</p>
-
-<pre>
-android update lib-project \
---target <em><target_ID></em> \
---path <em>path/to/your/project</em>
---library <em>path/to/library_projectA</em>
-</pre>
-
-<p>This command updates the application project's build properties to include a
-reference to the library project. Specifically, it adds an
-<code>android.library.reference.<em>n</em></code> property to the project's
-<code>default.properties</code> file. For example: </p>
-
-<pre class="no-pretty-print" style="color:black">
-android.library.reference.1=path/to/library_projectA
-</pre>
-
-<p>If you are adding references to multiple libraries, note that you can set
-their relative priority (and merge order) by manually editing the
-<code>default.properties</code> file and adjusting the each reference's
-<code>.<em>n</em></code> index as appropriate. For example, assume these
-references: </p>
-
-<pre class="no-pretty-print" style="color:black">
-android.library.reference.1=path/to/library_projectA
-android.library.reference.2=path/to/library_projectB
-android.library.reference.3=path/to/library_projectC
-</pre>
-
-<p>You can reorder the references to give highest priority to
-<code>library_projectC</code> in this way:</p>
-
-<pre class="no-pretty-print" style="color:black">
-android.library.reference.2=path/to/library_projectA
-android.library.reference.3=path/to/library_projectB
-android.library.reference.1=path/to/library_projectC
-</pre>
-
-<p>Note that the <code>.<em>n</em></code> index in the references
-must begin at "1" and increase uniformly without "holes". References
-appearing in the index after a hole are ignored. </p>
-
-<p>At build time, the libraries are merged with the application one at a time,
-starting from the lowest priority to the highest. Note that a library cannot
-itself reference another library and that, at build time, libraries are not
-merged with each other before being merged with the application.</p>
-
-
-<h4>Declaring library components in the the manifest file</h4>
-
-<p>In the manifest file of the application project, you must add declarations
-of all components that the application will use that are imported from a library
-project. For example, you must declare any <code><activity></code>,
-<code><service></code>, <code><receiver></code>,
-<code><provider></code>, and so on, as well as
-<code><permission></code>, <code><uses-library></code>, and similar
-elements.</p>
-
-<p>Declarations should reference the library components by their fully-qualified
-package names, where appropriate. </p>
-
-<p>For example, the
-<a href="{@docRoot}resources/samples/TicTacToeMain/AndroidManifest.html">TicTacToeMain</a>
-example application declares the library Activity <code>GameActivity</code>
-like this: </p>
-
-<pre><manifest>
- ...
- <application>
- ...
- <activity android:name="com.example.android.tictactoe.library.GameActivity" />
- ...
- </application>
-</manifest></pre>
-
-<p>For more information about the manifest file, see the documentation for <a
-href="{@docRoot}guide/topics/manifest/manifest-intro.html">AndroidManifest.xml</a>.</p>
-
-<h3 id="depAppBuild">Building a dependent application</h3>
-
-<p>To build an application project that depends on one or more library projects,
-you can use the standard Ant build commands and compile modes, as described in
-<a href="#Building">Building Your Application</a>, earlier in this document. The
-tools compile and merge all libraries referenced by the application as part
-of compiling the dependent application project. No additional commands or steps
-are necessary. </p>
-
-<h3 id="considerations">Development considerations</h3>
-
-<p>As you develop your library project and dependent applications, keep the
-points listed below in mind.</p>
-
-<p><strong>Resource conflicts</strong></p>
-
-<p>Since the tools merge the resources of a library project with those of a
-dependent application project, a given resource ID might be defined in both
-projects. In this case, the tools select the resource from the application, or
-the library with highest priority, and discard the other resource. As you
-develop your applications, be aware that common resource IDs are likely to be
-defined in more than one project and will be merged, with the resource from the
-application or highest-priority library taking precedence.</p>
-
-<p><strong>Using prefixes to avoid resource conflicts</strong></p>
-
-<p>To avoid resource conflicts for common resource IDs, consider using a prefix
-or other consistent naming scheme that is unique to the project (or is unique
-across all projects). </p>
-
-<p><strong>No export of library project to JAR</strong></p>
-
-<p>A library cannot be distributed as a binary file (such as a jar file). This
-is because the library project is compiled by the main project to use the
-correct resource IDs.</p>
-
-<p><strong>A library project can include a JAR library</strong></p>
-
-<p>You can develop a library project that itself includes a JAR library. When
-you build the dependent application project, the tools automatically locate and
-include the library in the application <code>.apk</code>. </p>
-
-<p><strong>A library project can depend on an external JAR library</strong></p>
-
-<p>You can develop a library project that depends on an external library (for
-example, the Maps external library). In this case, the dependent application
-must build against a target that includes the external library (for example, the
-Google APIs Add-On). Note also that both the library project and the dependent
-application must declare the external library their manifest files, in a <a
-href="{@docRoot}guide/topics/manifest/uses-library-element.html"><code><uses-library></code></a>
-element. </p>
-
-<p><strong>Library project cannot include raw assets</strong></p>
-
-<p>The tools do not support the use of raw asset files in a library project.
-Any asset resources used by an application must be stored in the
-<code>assets/</code> directory of the application project
-itself.</p>
-
-<p><strong>Targeting different Android platform versions in library project and
-application project</strong></p>
-
-<p>A library is compiled as part of the dependent application project, so the
-API used in the library project must be compatible with the version of the
-Android library used to compile the application project. In general, the library
-project should use an <a href="{@docRoot}guide/appendix/api-levels.html">API level</a>
-that is the same as — or lower than — that used by the application.
-If the library project uses an API level that is higher than that of the
-application, the application project will fail to compile. It is perfectly
-acceptable to have a library that uses the Android 1.5 API (API level 3) and
-that is used in an Android 1.6 (API level 4) or Android 2.1 (API level 7)
-project, for instance.</p>
-
-<p><strong>No restriction on library package name</strong></p>
-
-<p>There is no requirement for the package name of a library to be the same as
-that of applications that use it.</p>
-
-<p><strong>Multiple R classes in gen/ folder of application project</strong></p>
-
-<p>When you build the dependent application project, the code of any libraries
-is compiled and merged to the application project. Each library has its own
-<code>R</code> class, named according to the library's package name. The
-<code>R</code> class generated from the resources of the main project and of the
-library is created in all the packages that are needed including the main
-project’s package and the libraries’ packages.</p>
-
-<p><strong>Testing a library project</strong></p>
-
-<p>There are two recommended ways of setting up testing on code and resources in
-a library project: </p>
-
-<ul>
-<li>You can set up a <a
-href="{@docRoot}guide/developing/testing/testing_otheride.html">test project</a>
-that instruments an application project that depends on the library project. You
-can then add tests to the project for library-specific features.</li>
-<li>You can set up a set up a standard application project that depends on the
-library and put the instrumentation in that project. This lets you create a
-self-contained project that contains both the tests/instrumentations and the
-code to test.</li>
-</ul>
-
-<p><strong>Library project storage location</strong></p>
-
-<p>There are no specific requirements on where you should store a library
-project, relative to a dependent application project, as long as the application
-project can reference the library project by a relative link. You can place the
-library project What is important is that the main project can reference the
-library project through a relative link.</p>
-
-<h2 id="AttachingADebugger">Attaching a Debugger to Your Application</h2>
-
-<p>This section describes how to display debug information on the screen (such
- as CPU usage), as well as how to hook up your IDE to debug running applications
- on the emulator. </p>
-
-<p>Attaching a debugger is automated using the Eclipse plugin,
- but you can configure other IDEs to listen on a debugging port to receive debugging
- information:</p>
-<ol>
- <li><strong>Start the <a href="{@docRoot}guide/developing/tools/ddms.html">Dalvik Debug Monitor
- Server (DDMS)</a> tool, </strong> which
- acts as a port forwarding service between your IDE and the emulator.</li>
- <li><strong>Set
- optional debugging configurations on
- your emulator</strong>, such as blocking application startup for an Activity
- until a debugger is attached. Note that many of these debugging options
- can be used without DDMS, such as displaying CPU usage or screen refresh
- rate on the emulator.</li>
- <li><strong>Configure your IDE to attach to port 8700 for debugging.</strong> Read
- about <a href="{@docRoot}guide/developing/debug-tasks.html#ide-debug-port">
- Configuring Your IDE to Attach to the Debugging Port</a>. </li>
-</ol>
diff --git a/docs/html/guide/developing/projects/index.jd b/docs/html/guide/developing/projects/index.jd
index 1daf738..45fd5a1 100644
--- a/docs/html/guide/developing/projects/index.jd
+++ b/docs/html/guide/developing/projects/index.jd
@@ -8,7 +8,11 @@
<ol>
<li><a href="#ApplicationProjects">Android Projects</a></li>
- <li><a href="#LibraryProjects">Library Projects</a></li>
+ <li><a href="#LibraryProjects">Library Projects</a>
+ <ol>
+ <li><a href="#libraryMigrating">Migrating library projects to ADT 0.9.8 or higher</a></li>
+ </ol>
+ </li>
<li><a href="#TestProjects">Test Projects</a></li>
</ol>
@@ -418,6 +422,81 @@
project can reference the library project through a relative link.</p></li>
</ul>
+
+
+ <h3 id="libraryMigrating">Migrating library projects to ADT 0.9.8 or higher</h3>
+
+<p>This section provides information about how to migrate a library project
+created with ADT 0.9.7 to ADT 0.9.8 or higher. The migration is needed only if
+you are developing in Eclipse with ADT and assumes that you have also upgraded
+to SDK Tools r7 (or higher). </p>
+
+<p>The way that ADT handles library projects has changed between
+ADT 0.9.7 and ADT 0.9.8. Specifically, in ADT 0.9.7, the <code>src/</code>
+source folder of the library was linked into the dependent application project
+as a folder that had the same name as the library project. This worked because
+of two restrictions on the library projects:</p>
+
+<ul>
+<li>The library was only able to contain a single source folder (excluding the
+special <code>gen/</code> source folder), and</li>
+<li>The source folder was required to have the name <code>src/</code> and be
+stored at the root of the project.</li>
+</ul>
+
+<p>In ADT 0.9.8, both of those restrictions were removed. A library project can
+have as many source folders as needed and each can have any name. Additionally,
+a library project can store source folders in any location of the project. For
+example, you could store sources in a <code>src/java/</code> directory. In order
+to support this, the name of the linked source folders in the main project are
+now called <library-name>_<folder-name> For
+example: <code>MyLibrary_src/</code> or <code>MyLibrary_src_java/</code>.</p>
+
+<p>Additionally, the linking process now flags those folders in order for ADT to
+recognize that it created them. This will allow ADT to automatically migrate the
+project to new versions of ADT, should they contain changes to the handling of
+library projects. ADT 0.9.7 did not flag the linked source folders, so ADT 0.9.8
+cannot be sure whether the old linked folders can be removed safely. After
+upgrading ADT to 0.9.8, you will need to remove the old linked folders manually
+in a simple two-step process, as described below.</p>
+
+<p>Before you begin, make sure to create a backup copy of your application or
+save the latest version to your code version control system. This ensures that
+you will be able to easily revert the migration changes in case there is a
+problem in your environment.</p>
+
+<p>When you first upgrade to ADT 0.9.8, your main project will look as shown
+in figure 1, with two linked folders (in this example, <code>MyLibrary</code> and
+<code>MyLibrary_src</code> — both of which link to
+<code>MyLibrary/src</code>. Eclipse shows an error on one of them because they
+are duplicate links to a single class.</p>
+
+<img src="/images/developing/lib-migration-0.png" alt="">
+<p class="img-caption"><strong>Figure 1.</strong> Library project migration error</p>
+<p>To fix the error, remove the linked folder that <em>does not</em> contain the
+<code>_src</code> suffix. </p>
+
+<ol>
+<li>Right click the folder that you want to remove (in this case, the
+<code>MyLibrary</code> folder) and choose <strong>Build Path</strong> >
+<strong>Remove from Build Path</strong>, as shown in figure 2.</li>
+
+<img src="/images/developing/lib-migration-1.png" style="height:600px"
+alt="">
+<p class="img-caption"><strong>Figure 2.</strong> Remove from Build Path menu item</p>
+
+<li>Next, when asked about unlinking the folder from the project, select
+<strong>Yes</strong>, as shown in figure 3.</li>
+
+<img src="/images/developing/lib-migration-2.png" alt="">
+
+<p class="img-caption"><strong>Figure 3.</strong> Unlink folder confirmation window</p>
+</ol>
+
+<p>This should resolve the error and migrate your library project to the new
+ADT environment. </p>
+
+
<h2 id="TestProjects">Test Projects</h2>
diff --git a/docs/html/guide/developing/testing/testing_eclipse.jd b/docs/html/guide/developing/testing/testing_eclipse.jd
index 370c142..1b9c6b1 100644
--- a/docs/html/guide/developing/testing/testing_eclipse.jd
+++ b/docs/html/guide/developing/testing/testing_eclipse.jd
@@ -12,9 +12,10 @@
</div>
<p>
This topic explains how create and run tests of Android applications in Eclipse with ADT.
- Before you read this topic, you should read about how to create a Android application with the
+ Before you read this topic, you should read about how to create an Android application with the
basic processes for creating and running applications with ADT, as described in
- <a href="{@docRoot}guide/developing/eclipse-adt.html">Developing In Eclipse, with ADT</a>.
+ <a href="{@docRoot}guide/developing/projects/projects-eclipse.html">Creating and Managing Projects in Eclipse</a>
+ and <a href="guide/developing/building/building-eclipse.html">Building and Running Apps in Eclipse</a>.
You may also want to read
<a href="{@docRoot}guide/topics/testing/testing_android.html">Testing Fundamentals</a>,
which provides an overview of the Android testing framework.
diff --git a/docs/html/guide/developing/testing/testing_otheride.jd b/docs/html/guide/developing/testing/testing_otheride.jd
index adb0efa..48fa032 100644
--- a/docs/html/guide/developing/testing/testing_otheride.jd
+++ b/docs/html/guide/developing/testing/testing_otheride.jd
@@ -133,7 +133,7 @@
This creates a new test project with the appropriate directories and build files. The directory
structure and build file contents are identical to those in a regular Android application
project. They are described in detail in the topic
- <a href="{@docRoot}guide/developing/other-ide.html">Developing In Other IDEs</a>.
+ <a href="{@docRoot}guide/developing/projects/index.html">Creating and Managing Projects</a>.
</p>
<p>
The operation also creates an <code>AndroidManifest.xml</code> file with instrumentation
diff --git a/docs/html/guide/developing/tools/aapt.html b/docs/html/guide/developing/tools/aapt.html
new file mode 100644
index 0000000..e66a201
--- /dev/null
+++ b/docs/html/guide/developing/tools/aapt.html
@@ -0,0 +1,10 @@
+<html>
+<head>
+<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/building/index.html#detailed-build">
+<title>Redirecting...</title>
+</head>
+<body>
+<p>You should be redirected. Please <a
+href="http://developer.android.com/guide/developing/building/index.html#detailed-build">click here</a>.</p>
+</body>
+</html>
\ No newline at end of file
diff --git a/docs/html/guide/developing/tools/aapt.jd b/docs/html/guide/developing/tools/aapt.jd
deleted file mode 100644
index 40a209d..0000000
--- a/docs/html/guide/developing/tools/aapt.jd
+++ /dev/null
@@ -1,20 +0,0 @@
-page.title=Using aapt
-@jd:body
-
-<p><strong>aapt</strong> stands for Android Asset Packaging Tool and is included in the <code>tools/</code> directory of the SDK. This tool allows you to view, create, and update Zip-compatible archives (zip, jar, apk). It can also compile resources into binary assets.
-</p>
-<p>
-Though you probably won't often use <strong>aapt</strong> directly, build scripts and IDE plugins can utilize this tool to package the apk file that constitutes an Android application.
-</p>
-<p>
-For more usage details, open a terminal, go to the <code>tools/</code> directory, and run the command:
-</p>
-<ul>
- <li><p>Linux or Mac OS X:</p>
- <pre>./aapt</pre>
- </li>
- <li><p>Windows:</p>
- <pre>aapt.exe</pre>
- </li>
-</ul>
-
diff --git a/docs/html/guide/developing/tools/adb.jd b/docs/html/guide/developing/tools/adb.jd
index 3c6351e..bcdc2e6 100644
--- a/docs/html/guide/developing/tools/adb.jd
+++ b/docs/html/guide/developing/tools/adb.jd
@@ -171,7 +171,7 @@
<pre>adb install <path_to_apk></pre>
-<p>For more information about how to create an .apk file that you can install on an emulator/device instance, see <a href="{@docRoot}guide/developing/tools/aapt.html">Android Asset Packaging Tool</a> (aapt). </p>
+<p>For more information about how to create an .apk file that you can install on an emulator/device instance, see <a href="{@docRoot}guide/developing/building/index.html">Building and Running Apps</a></p>
<p>Note that, if you are using the Eclipse IDE and have the ADT plugin installed, you do not need to use adb (or aapt) directly to install your application on the emulator/device. Instead, the ADT plugin handles the packaging and installation of the application for you. </p>
@@ -465,7 +465,8 @@
<tr>
<td><code>dumpsys</code></td>
<td>Dumps system data to the screen.</td>
-<td rowspan=4">The <a href="{@docRoot}guide/developing/tools/ddms.html">Dalvik Debug Monitor Service</a> (DDMS) tool offers integrated debug environment that you may find easier to use.</td>
+<td rowspan=4">The <a href="{@docRoot}guide/developing/debugging/ddms.html">Dalvik Debug Monitor Server</a>
+(DDMS) tool offers integrated debug environment that you may find easier to use.</td>
</tr>
<tr>
diff --git a/docs/html/guide/developing/tools/avd.html b/docs/html/guide/developing/tools/avd.html
new file mode 100644
index 0000000..c8455db
--- /dev/null
+++ b/docs/html/guide/developing/tools/avd.html
@@ -0,0 +1,10 @@
+<html>
+<head>
+<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/devices/index.html">
+<title>Redirecting...</title>
+</head>
+<body>
+<p>You should be redirected. Please <a
+href="http://developer.android.com/guide/developing/devices/index.html">click here</a>.</p>
+</body>
+</html>
\ No newline at end of file
diff --git a/docs/html/guide/developing/tools/avd.jd b/docs/html/guide/developing/tools/avd.jd
deleted file mode 100644
index ca197cf..0000000
--- a/docs/html/guide/developing/tools/avd.jd
+++ /dev/null
@@ -1,447 +0,0 @@
-page.title=Android Virtual Devices
-@jd:body
-
-<div id="qv-wrapper">
-<div id="qv">
-
- <h2>AVD quickview</h2>
- <ul>
- <li>You need to create an AVD to run any app in the Android emulator</li>
- <li>Each AVD is a completely independent virtual device, with its own
- hardware options, system image, and data storage.
- <li>You create AVD configurations to model different device environments
- in the Android emulator.</li>
- <li>You can launch a graphical Android AVD Manager either through Eclipse or
-through the <code>android</code> tool. The <code>android</code> tool also offers
-a command-line interface for creating and managing AVDs.</li> </ul>
- <h2>In this document</h2>
- <ol>
- <li><a href="#creating">Creating an AVD</a>
- <ol>
- <li><a href="#hardwareopts">Setting hardware emulation options</a></li>
- <li><a href="#location">Default location of the AVD files</a></li>
- </ol>
- </li>
- <li><a href="#managing">Managing AVDs</a>
- <ol>
- <li><a href="#moving">Moving an AVD</a></li>
- <li><a href="#updating">Updating an AVD</a></li>
- <li><a href="#deleting">Deleting an AVD</a></li>
- </ol>
- </li>
- <li><a href="#options">Command-line options</a></li>
- </ol>
- <h2>See Also</h2>
- <ol>
- <li><a href="{@docRoot}guide/developing/tools/emulator.html">Android
- Emulator</a></li>
- </ol>
-</div>
-</div>
-
-<p>Android Virtual Devices (AVDs) are configurations of emulator options that let
-you better model an actual device.</p>
-
-<p>Each AVD is made up of: </p>
-
-<ul>
-<li>A hardware profile. You can set options to define the hardware
-features of the virtual device. For example, you can define whether the device
-has a camera, whether it uses a physical QWERTY keyboard or a dialing pad, how
-much memory it has, and so on. </li>
-<li>A mapping to a system image. You can define what version of the
-Android platform will run on the virtual device. You can choose a version of the
-standard Android platform or the system image packaged with an SDK add-on.</li>
-<li>Other options. You can specify the emulator skin you want to use
-with the AVD, which lets you control the screen dimensions, appearance, and so
-on. You can also specify the emulated SD card to use with the AVD.</li>
-<li>A dedicated storage area on your development machine, in which is stored the
-device's user data (installed applications, settings, and so on) and emulated SD
-card.</li>
-</ul>
-
-<p>You can create as many AVDs as you need, based on the types of devices you
-want to model and the Android platforms and external libraries you want to run
-your application on. </p>
-
-<p>In addition to the options in an AVD configuration, you can also
-specify emulator command-line options at launch or by using the emulator
-console to change behaviors or characteristics at run time. For a complete
-reference of emulator options, please see the <a
-href="{@docRoot}guide/developing/tools/emulator.html">Emulator</a>
-documentation. </p>
-
-<p>The easiest way to create an AVD is to use the graphical AVD Manager, which
-you can launch from Eclipse or from the command line using the
-<code>android</code> tool. The <code>android</code> tool is provided in the
-<code>tools/</code> directory of the Android SDK. When you run the
-<code>android</code> tool without options, it launches the graphical AVD
-Manager.</p>
-
-<p>For more information about how to work with AVDs from inside your development
-environment, see <a
-href="{@docRoot}guide/developing/eclipse-adt.html">Developing in Eclipse with
-ADT</a> or <a href="{@docRoot}guide/developing/other-ide.html">Developing in
-Other IDEs</a>, as appropriate for your environment.</p>
-
-<h2 id="creating">Creating an AVD</h2>
-
-<div class="sidebox-wrapper">
-<div class="sidebox">
-<p>The Android SDK does not include any preconfigured AVDs, so
-you need to create an AVD before you can run any application in the emulator
-(even the Hello World application).</p>
-</div>
-</div>
-<p>The easiest way to create an AVD is to use the graphical AVD Manager, but the
-<code>android</code> tool also offers a <a href="#options">command line option</a>.</p>
-<p>To create an AVD:</p>
-<ol>
- <li>In Eclipse, choose <strong>Window > Android SDK and AVD Manager</strong>. </li>
- <p>Alternatively, you can launch the graphical AVD Manager by running the
-<code>android</code> tool with no options.</p>
- <li>Select <strong>Virtual Devices</strong> in the left panel.</li>
-
- <li>Click <strong>New</strong>. </li>
-
-<p>The <strong>Create New AVD</strong> dialog appears.</p> <a
-href="{@docRoot}images/developing/avd-dialog.png"><img
-src="{@docRoot}images/developing/avd-dialog.png" alt="AVD
-Dialog" /></a>
-
- <li>Type the name of the AVD, such as "my_avd".</li>
- <li>Choose a target. </li>
-<p>The target is the system image that you want to run on the emulator,
-from the set of platforms that are installed in your SDK environment. You can
-choose a version of the standard Android platform or an SDK add-on. For more
-information about how to add platforms to your SDK, see <a
-href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>. </p>
- <li>Optionally specify any additional settings: </li>
- <dl>
- <dt><em>SD Card</em></dt> <dd>The path to the SD card image to use with this
-AVD, or the size of a new SD card image to create for this AVD.</dd> </dl>
-<dt><em>Skin</em></dt>
- <dd>The skin to use for this AVD, identified by name or dimensions.</dd>
-<dt><em>Hardware</em></dt>
- <dd>The hardware emulation options for the device. For a list of the options, see
-<a href="#hardwareopts">Setting hardware emulation options</a>.</dd>
- </dl>
- <li>Click <strong>Create AVD</strong>.</li>
-</ol>
-
-<h3 id="hardwareopts">Setting hardware emulation options</h3>
-
-<p>When you create a new AVD that uses a standard Android system image ("Type:
-platform"), the AVD Manager
- lets you set hardware emulation
-options for your virtual device.
-The table below lists the options available and the
-default values, as well as the names of properties that store the emulated
-hardware options in the AVD's configuration file (the <code>config.ini</code> file in the
-AVD's local directory). </p>
-
-<table>
-<tr>
-<th>Characteristic</th>
-<th>Description</th>
-<th>Property</th>
-</tr>
-
-<tr>
-<td>Device ram size</td>
-<td>The amount of physical RAM on the device, in megabytes. Default value is "96".
-<td>hw.ramSize</td>
-</tr>
-
-<tr>
-<td>Touch-screen support</td>
-<td>Whether there is a touch screen or not on the device. Default value is "yes".</td>
-<td>hw.touchScreen
-
-<tr>
-<td>Trackball support </td>
-<td>Whether there is a trackball on the device. Default value is "yes".</td>
-<td>hw.trackBall</td>
-</tr>
-
-<tr>
-
-<td>Keyboard support</td>
-<td>Whether the device has a QWERTY keyboard. Default value is "yes".</td>
-<td>hw.keyboard</td>
-</tr>
-
-<tr>
-<td>DPad support</td>
-<td>Whether the device has DPad keys. Default value is "yes".</td>
-<td>hw.dPad</td>
-</tr>
-
-<tr>
-<td>GSM modem support</td>
-<td>Whether there is a GSM modem in the device. Default value is "yes".</td>
-<td>hw.gsmModem</td>
-</tr>
-
-<tr>
-<td>Camera support</td>
-<td>Whether the device has a camera. Default value is "no".</td>
-<td>hw.camera</td>
-</tr>
-
-<tr>
-<td>Maximum horizontal camera pixels</td>
-<td>Default value is "640".</td>
-<td>hw.camera.maxHorizontalPixels</td>
-</tr>
-
-<tr>
-<td>Maximum vertical camera pixels</td>
-<td>Default value is "480".</td>
-<td>hw.camera.maxVerticalPixels</td>
-
-</tr>
-
-<tr>
-<td>GPS support</td>
-<td>Whether there is a GPS in the device. Default value is "yes".</td>
-<td>hw.gps</td>
-</tr>
-
-<tr>
-<td>Battery support</td>
-<td>Whether the device can run on a battery. Default value is "yes".</td>
-<td>hw.battery</td>
-
-</tr>
-
-<tr>
-<td>Accelerometer</td>
-<td>Whether there is an accelerometer in the device. Default value is "yes".</td>
-<td>hw.accelerometer</td>
-</tr>
-
-<tr>
-<td>Audio recording support</td>
-<td>Whether the device can record audio. Default value is "yes".</td>
-<td>hw.audioInput</td>
-
-</tr>
-
-<tr>
-<td>Audio playback support</td>
-<td>Whether the device can play audio. Default value is "yes".</td>
-<td>hw.audioOutput</td>
-</tr>
-
-<tr>
-<td>SD Card support</td>
-<td>Whether the device supports insertion/removal of virtual SD Cards. Default value is "yes".</td>
-<td>hw.sdCard</td>
-
-</tr>
-
-<tr>
-<td>Cache partition support</td>
-<td>Whether we use a /cache partition on the device. Default value is "yes".</td>
-<td>disk.cachePartition</td>
-</tr>
-
-<tr>
-<td>Cache partition size</td>
-<td>Default value is "66MB".</td>
-<td>disk.cachePartition.size </td>
-
-</tr>
-
-<tr>
-<td>Abstracted LCD density</td>
-<td>Sets the generalized density characteristic used by the AVD's screen. Most
-skins come with a value (which you can modify), but if a skin doesn't provide
-its own value, the default is 160. </td>
-<td>hw.lcd.density </td>
-</tr>
-
-<tr>
-<td>Max VM application heap size</td>
-<td>The maximum heap size a Dalvik application might allocate before being
-killed by the system. Value is in megabytes. Most skins come with a value (which
-you can modify), but if a skin doesn't provide its own value, the default is
-16.</td>
-<td>vm.heapSize</td>
-</tr>
-
-</table>
-
-<h3 id="location">Default location of the AVD files</h3>
-
-<p>When you create an AVD, the AVD Manager creates a dedicated directory for it
-on your development computer. The directory contains the AVD configuration file,
-the user data image and SD card image (if available), and any other files
-associated with the device. Note that the directory does not contain a system
-image — instead, the AVD configuration file contains a mapping to the
-system image, which it loads when the AVD is launched. </p>
-
-<p>The AVD Manager also creates a <code><AVD name>.ini</code> file for the
-AVD at the root of the <code>.android/avd</code> directory on your computer. The file
-specifies the location of the AVD directory and always remains at the root the
-.android directory.</p>
-
-<p>By default, the AVD Manager creates the AVD directory inside
-<code>~/.android/avd/</code> (on Linux/Mac), <code>C:\Documents and
-Settings\<user>\.android\</code> on Windows XP, and
-<code>C:\Users\<user>\.android\</code> on Windows Vista.
-If you want to use a custom location for the AVD directory, you
-can do so by using the <code>-p <path></code> option when
-you create the AVD (command line tool only): </p>
-
-<pre>android create avd -n my_android1.5 -t 2 -p path/to/my/avd</pre>
-
-<p>If the <code>.android</code> directory is hosted on a network drive, we recommend using
-the <code>-p</code> option to place the AVD directory in another location.
-The AVD's <code>.ini</code> file remains in the <code>.android</code> directory on the network
-drive, regardless of the location of the AVD directory. </p>
-
-<h2 id="managing">Managing AVDs</h2>
-
-<p>The sections below provide more information about how to manage AVDs once you've created them. </p>
-
-<h3 id="moving">Moving an AVD</h3>
-
-<p>If you want to move or rename an AVD, you can do so using this command:</p>
-
-<pre>android move avd -n <name> [-<option> <value>] ...</pre>
-
-<p>The options for this command are listed in <a href="#options">Command-line
-options for AVDs</a> at the bottom of this page. </p>
-
-<h3 id="updating">Updating an AVD</h3>
-
-<p>
-If you rename or move the root directory of a platform (or add-on), an AVD configured to use that platform will no longer be able to load the system image properly. To fix the AVD, use the <strong>Repair...</strong> button in the AVD Manager. From the command line, you can also use the <code>android update avd</code> command to recompute the path to the system images.</p>
-
-<h3 id="deleting">Deleting an AVD</h3>
-
-<p>You can delete an AVD in the AVD Manager by selecting the
-AVD and clicking <strong>Delete</strong>.</p>
-
-<p>Alternatively, you can use the <code>android</code> tool to delete an AVD. Here is the command usage:</p>
-
-<pre>android delete avd -n <name> </pre>
-
-<p>When you issue the command, the <code>android</code> tool looks for an AVD matching the
-specified name deletes the AVD's directory and files. </p>
-
-
-<h2 id="options">Command-line options</h2>
-
-<p>You can use the <code>android</code> tool to create and manage AVDs.</p>
-
-<p>The command line for creating an AVD has the following syntax:</p>
-
-<pre>
-android create avd -n <name> -t <targetID> [-<option> <value>] ...
-</pre>
-
-<p>Here's an example that creates an AVD with the name "my_android2.2" and target ID "3":</p>
-
-<pre>
-android create avd -n my_android2.2 -t 3
-</pre>
-
-<p>The table below lists the command-line options you can use with the
-<code>android</code> tool. </p>
-
-
-<table>
-<tr>
- <th width="15%">Action</th>
- <th width="20%">Option</th>
- <th width="30%">Description</th>
- <th>Comments</th>
-</tr>
-
-
-<tr>
- <td><code>list avds</code></td>
- <td> </td>
- <td>List all known AVDs, with name, path, target, and skin. </td>
- <td> </td>
-</tr>
-<tr>
- <td rowspan="6"><code>create avd</code></td>
- <td><code>-n <name> or <br></code></td>
- <td>The name for the AVD.</td>
- <td>Required</td>
-</tr>
-<tr>
- <td><code>-t <targetID></code></td>
- <td>Target ID of the system image to use with the new AVD.</td>
- <td>Required. To obtain a list of available targets, use <code>android list
- targets</code>.</td>
-</tr>
-<tr>
- <td><code>-c <path></code> or <br>
- <code>-c <size>[K|M]</code></td>
- <td>The path to the SD card image to use with this AVD or the size of a new SD
- card image to create for this AVD.</td>
- <td>Examples: <code>-c path/to/sdcard</code> or <code>-c 1000M</code></td>
-</tr>
-<tr>
- <td><code>-f</code></td>
- <td>Force creation of the AVD</td>
- <td>By default, if the name of the AVD being created matches that of an
- existing AVD, the <code>android</code> tool will not create the new AVD or overwrite
- the existing AVD. If you specify the <code>-f</code> option, however, the
- <code>android</code> tool will automatically overwrite any existing AVD that has the
- same name as the new AVD. The files and data of the existing AVD are
- deleted. </td>
-</tr>
-
-<tr>
- <td><code>-p <path></code></td>
- <td>Path to the location at which to create the directory for this AVD's
-files.</td>
- <td> </td>
-</tr>
-<tr>
- <td><code>-s <name></code> or <br>
- <code>-s <width>-<height></code> </td>
- <td>The skin to use for this AVD, identified by name or dimensions.</td>
- <td>The <code>android</code> tool scans for a matching skin by name or dimension in the
-<code>skins/</code> directory of the target referenced in the <code>-t
-<targetID></code> argument. Example: <code>-s HVGA-L</code></td>
-</tr>
-<tr>
- <td><code>delete avd</code></td>
- <td><code>-n <name></code></td>
- <td>Delete the specified AVD.</td>
- <td>Required</td>
-</tr>
-<tr>
- <td rowspan="3"><code>move avd</code></td>
- <td><code>-n <name></code></td>
- <td>The name of the AVD to move.</td>
- <td>Required</td>
-</tr>
-<tr>
- <td><code>-p <path></code></td>
- <td>The path to the new location for the AVD.</td>
- <td> </td>
-</tr>
-<tr>
- <td><code>-r <new-name></code></td>
- <td>Rename the AVD.</td>
- <td> </td>
-</tr>
-<tr>
- <td><code>update avds</code></td>
- <td> </td>
- <td>Recompute the paths to all system images.</td>
- <td> </td>
-</tr>
-
-
-
-</table>
-
diff --git a/docs/html/guide/developing/tools/ddms.html b/docs/html/guide/developing/tools/ddms.html
new file mode 100644
index 0000000..052ccc9
--- /dev/null
+++ b/docs/html/guide/developing/tools/ddms.html
@@ -0,0 +1,10 @@
+<html>
+<head>
+<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/debugging/ddms.html">
+<title>Redirecting...</title>
+</head>
+<body>
+<p>You should be redirected. Please <a
+href="http://developer.android.com/guide/developing/debugging/ddms.html">click here</a>.</p>
+</body>
+</html>
\ No newline at end of file
diff --git a/docs/html/guide/developing/tools/ddms.jd b/docs/html/guide/developing/tools/ddms.jd
deleted file mode 100644
index f55940d..0000000
--- a/docs/html/guide/developing/tools/ddms.jd
+++ /dev/null
@@ -1,251 +0,0 @@
-page.title=Using the Dalvik Debug Monitor
-@jd:body
-
-<p>Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS),
- which provides port-forwarding services, screen capture on the device, thread
- and heap information on the device, logcat, process, and radio state information,
- incoming call and SMS spoofing, location data spoofing, and more. This page
- provides a modest discussion of DDMS features; it is not an exhaustive exploration of
- all the features and capabilities.</p>
-
-<p>DDMS ships in the <code>tools/</code> directory of the SDK.
- Enter this directory from a terminal/console and type <code>ddms</code> (or <code>./ddms</code>
- on Mac/Linux) to run it. DDMS will work with both the emulator and a connected device. If both are
- connected and running simultaneously, DDMS defaults to the emulator.</p>
-
-<h2 id="how-ddms-works">How DDMS works</h2>
-<p>DDMS acts as a middleman to connect the IDE to the applications running on
-the device. On Android, every application runs in its own process,
-each of which hosts its own virtual machine (VM). And each process
-listens for a debugger on a different port.</p>
-
-<p>When it starts, DDMS connects to <a href="{@docRoot}guide/developing/tools/adb.html">adb</a> and
-starts a device monitoring service between the two, which will notify DDMS when a device is
-connected or disconnected. When a device is connected, a VM monitoring service is created
-between adb and DDMS, which will notify DDMS when a VM on the device is started
-or terminated. Once a VM is running, DDMS retrieves the the VM's process ID (pid), via adb,
-and opens a connection to the VM's debugger, through the adb daemon (adbd) on the device.
-DDMS can now talk to the VM using a custom wire protocol.</p>
-
-<p>For each VM on the device, DDMS opens a port upon which it will listen for a debugger. For the first VM, DDMS listens for a debugger on port 8600, the next on 8601, and so on. When a debugger connects to one of these ports, all traffic is forwarded between the debugger and the associated VM. Debugging can then process like any remote debugging session.</p>
-
-<p>DDMS also opens another local port, the DDMS "base port" (8700, by default), upon which it also listens for a debugger. When a debugger connects to this base port, all traffic is forwarded to the VM currently selected in DDMS, so this is typically where you debugger should connect.</p>
-
-<p>For more information on port-forwarding with DDMS,
-read <a href="{@docRoot}guide/developing/debug-tasks.html#ide-debug-port">Configuring your IDE to attach
-to port 8700 for debugging</a>.</p>
-
-<p class="note"><strong>Tip:</strong>
-You can set a number of DDMS preferences in <strong>File</strong> > <strong>Preferences</strong>.
-Preferences are saved to "$HOME/.ddmsrc". </p>
-
-<p class="warning"><strong>Known debugging issues with Dalvik</strong><br/>
-Debugging an application in the Dalvik VM should work the same as it does
-in other VMs. However, when single-stepping out of synchronized code, the "current line"
-cursor may jump to the last line in the method for one step.</p>
-
-
-<h2 id="left-pane">Left Pane</h2>
-<p>The left side of the Debug Monitor shows each emulator/device currently found, with a list of
- all the VMs currently running within each.
- VMs are identified by the package name of the application it hosts.</p>
-<p>Use this list to find and attach to the VM
- running the activity(ies) that you want to debug. Next to each VM in the
- list is a "debugger pass-through" port (in the right-most column).
- If you connect your debugger to one of the the ports listed, you
- will be connected to the corresponding VM on the device. However, when using
- DDMS, you need only connect to port 8700, as DDMS forwards all traffic here to the
- currently selected VM. (Notice, as you select a VM in the list, the listed port includes 8700.)
- This way, there's no need to reconfigure the debugger's port each time you switch between VMs.</p>
-<p>When an application running on the device calls {@link android.os.Debug#waitForDebugger()}
- (or you select this option in the <a href="{@docRoot}guide/developing/debug-tasks.html#additionaldebugging">developer
- options</a>), a red icon will be shown next to the client name, while it waits for the
- debugger to attach to the VM. When a debugger is connected, the icon will turn green. </p>
-<p>If you see a crossed-out bug icon, this means that the DDMS was unable to complete a
-connection between the debugger and the VM because it was unable to open the VM's local port.
-If you see this for all VMs on the device, it is likely because you have another instance of
-DDMS running (this includes the Eclipse plugin).</p>
-<p>If you see a question mark in place of an application package, this means that,
-once DDMS received the application pid from adb, it
-somehow failed to make a successful handshake with the VM process. Try restarting DDMS.</p>
-
-
-<h2 id="right-pane">Right pane</h2>
-<p>On the right side, the Debug Monitor provides tabs that display useful information
-and some pretty cool tools.</p>
-
-<h3 id="info">Info</h3>
-<p>This view shows some general information about the selected VM, including the process
- ID, package name, and VM version.</p>
-
-<h3 id="threads">Threads</h3>
-<p> The threads view has a list of threads running in the process of the target VM.
- To reduce the amount
- of data sent over the wire, the thread updates are only sent when explicitly
- enabled by toggling the "threads" button
- in the toolbar. This toggle is maintained per VM. This tab includes the following
- information: </p>
-<ul>
- <li> <strong>ID</strong> - a VM-assigned unique thread ID. In Dalvik, these are
- odd numbers starting from 3. </li>
- <li> <strong>Tid</strong> - the Linux thread ID. For the main thread in a process,
- this will match the process ID. </li>
- <li> <strong>Status</strong> - the VM thread status. Daemon threads are
- shown with an asterisk (*). This will be one of the following:
- <ul>
- <li> <em>running</em> - executing application code </li>
- <li> <em>sleeping</em> - called Thread.sleep() </li>
- <li> <em>monitor</em> - waiting to acquire a monitor lock </li>
- <li> <em>wait</em> - in Object.wait() </li>
- <li> <em>native</em> - executing native code </li>
- <li> <em>vmwait</em> - waiting on a VM resource </li>
- <li> <em>zombie</em> - thread is in the process of dying </li>
- <li> <em>init</em> - thread is initializing (you shouldn't see this) </li>
- <li> <em>starting</em> - thread is about to start (you shouldn't see
- this either) </li>
- </ul>
- </li>
- <li> <strong>utime</strong> - cumulative time spent executing user code, in "jiffies" (usually
- 10ms). </li>
- <li> <strong>stime</strong> - cumulative time spent executing system code, in "jiffies" (usually
- 10ms). </li>
- <li> <strong>Name</strong> - the name of the thread</li>
-</ul>
-<p> "ID" and "Name" are set when the thread is started. The remaining
- fields are updated periodically (default is every 4 seconds). </p>
-
-<h3 id="vm-heap">VM Heap</h3>
-<p> Displays some heap stats, updated during garbage collection. If, when a VM is selected,
-the VM Heap view says that heap updates are not enabled, click the "Show heap updates" button,
-located in the top-left toolbar. Back in the VM Heap view, click <strong>Cause GC</strong>
-to perform garbage collection and update the heap stats.</p>
-
-
-<h3 id="allocation-tracker">Allocation Tracker</h3>
-<p>In this view, you can track the memory allocation of each virtual machine.
-With a VM selected in the left pane, click <strong>Start Tracking</strong>, then
-<strong>Get Allocations</strong> to view all allocations since tracking started.
-The table below will be filled with all the relevant
-data. Click it again to refresh the list.</p>
-
-
-<h3 id="emulator-control">Emulator Control</h3>
-<p>With these controls, you can simulate special device states and activities.
-Features include:</p>
-<ul>
-<li><strong>Telephony Status</strong> - change the state of the phone's Voice and Data plans
- (home, roaming, searching, etc.), and simulate different kinds of network Speed and Latency
- (GPRS, EDGE, UTMS, etc.).</li>
-<li><strong>Telephony Actions</strong> - perform simulated phone calls and SMS messages to the emulator.</li>
-<li><strong>Location Controls</strong> - send mock location data to the emulator so that you can perform
- location-aware operations like GPS mapping.
-
-<p>To use the Location Controls, launch your application in the Android emulator and open DDMS.
-Click the Emulator Controls tab and scroll down to Location Controls.
-From here, you can:</p>
-<ul class="listhead">
- <li>Manually send individual longitude/latitude coordinates to the device.
- <p>Click <strong>Manual</strong>,
- select the coordinate format, fill in the fields and click <strong>Send</strong>.
- </p>
- </li>
- <li>Use a GPX file describing a route for playback to the device.
- <p>Click <strong>GPX</strong> and load the file. Once loaded,
- click the play button to playback the route for your location-aware application.</p>
- <p>When performing playback from GPX, you can adjust the speed of
- playback from the DDMS panel and control playback with the pause and skip buttons.
- DDMS will parse both the waypoints (<code><wpt></code>, in the first table),
- and the tracks (<code><trk></code>,
- in the second table, with support for multiple segments, <code><trkseg></code>,
- although they are simply
- concatenated). Only the tracks can be played. Clicking a waypoint in the first list simply
- sends its coordinate to the device, while selecting a track lets you play it.</p>
- </li>
- <li>Use a KML file describing individual placemarks for sequenced playback to the device.
- <p>Click <strong>KML</strong> and load the file. Once loaded,
- click the play button to send the coordinates to your location-aware application.</p>
- <p>When using a KML file, it is parsed for a <code><coordinates></code>
- element. The value of which should be a single
- set of longitude, latitude and altitude figures. For example:</p>
- <pre><coordinates>-122.084143,37.421972,4</coordinates></pre>
- <p>In your file, you may include multiple <code><Placemark></code> elements, each containing
- a <code><coordinates></code> element. When you do so, the collection of placemarks will
- be added as tracks. DDMS will send one placemark per second to the device.</p>
- <p>One way to generate a suitable KML file is to find a location in Google Earth.
- Right-click the location entry that appears on the left and select "Save place as..."
- with the save format set to Kml.</p>
-<p class="note"><strong>Note:</strong> DDMS does not support routes created with the
-<code><MultiGeometry><LineString>lat1, long1, lat2, long2, ....</LineString></MultiGeometry></code> methods.
- There is also currently no support for the <code><TimeStamp></code> node inside
- the <code><Placemark></code>.
- Future releases may support timed placement and routes within a single coordinate element.</p>
- </li>
- </ul>
- <p>For <em>additional</em> methods of setting up mocks of location-based data, see the
- <a href="{@docRoot}guide/topics/location/index.html">Location</a> topic.</p>
- </li>
-</ul>
-
-
-<!-- <h4>Event Log</h4> -->
-
-
-<h2 id="file-explorer">File Explorer</h2>
-<p>With the File Explorer, you can view the device file system and perform basic management,
-like pushing and pulling files. This circumvents using the <a href="{@docRoot}guide/developing/tools/adb.html">adb</a>
-<code>push</code> and <code>pull</code> commands, with a GUI experience.</p>
-<p>With DDMS open, select <strong>Device</strong> > <strong>File Explorer...</strong> to open the
-File Explorer window. You can drag-and-drop into the device directories, but cannot drag <em>out</em> of them.
-To copy files from the device, select the file and click the <strong>Pull File from Device</strong>
-button in the toolbar. To delete files, use the <strong>Delete</strong> button in the toolbar.</p>
-<p>If you're interested in using an SD card image on the emulator, you're still required to use
-the <code>mksdcard</code> command to create an image, and then mount it during emulator bootup.
-For example, from the <code>/tools</code> directory, execute:</p>
-<pre>
-<b>$</b> mksdcard 1024M ./img
-<b>$</b> emulator -sdcard ./img
-</pre>
-<p>Now, when the emulator is running, the DDMS File Explorer will be able to read and write to the
-sdcard directory. However, your files may not appear automatically. For example, if you add an
-MP3 file to the sdcard, the media player won't see them until you restart the emulator. (When restarting
-the emulator from command line, be sure to mount the sdcard again.)</p>
-<p>For more information on creating an SD card image, see the
-<a href="{@docRoot}guide/developing/tools/othertools.html#mksdcard">Other Tools</a> document.</p>
-
-<h2 id="screen-capture">Screen Capture</h2>
-<p>You can capture screen images on the device or emulator by selecting <strong>Device</strong>
- > <strong>Screen capture...</strong> in the menu bar, or press CTRL-S.
- Be sure to select a device first.</p>
-
-<h2 id="exploring-processes">Exploring Processes</h2>
-<p>You can see the output of <code>ps -x</code> for a specific VM by selecting <strong>Device</strong>
- > <strong>Show process status</strong>... in the menu bar.</p>
-
-<h2 id="cause-a-gc-to-occur">Cause a GC to Occur</h2>
-<p>Cause garbage collection to occur in the selected application by pressing the trash can button on the toolbar. </p>
-
-<h2 id="running-dumpsys-and-dumpstate">Running Dumpsys and Dumpstate on the Device (logcat)<a name="logcat" id="logcat"></a> </h2>
-<ul>
- <li>To run <strong>dumpsys</strong> (logcat) from Dalvik, select <strong>Device</strong> >
- <strong>Run logcat...</strong> in the menu bar.</li>
- <li>To run <strong>dumpstate</strong> from Dalvik, select <strong>Device</strong> > <strong>Dump device
- state...</strong> in the menu bar. </li>
-</ul>
-
-<h2 id="examine-radio-state">Examine Radio State</h2>
-<p>By default, radio state is not output during a standard logcat (it is a lot of
- information). To see radio information, either click <strong>Device</strong> > <strong>Dump radio
- state...</strong> or run logcat as described in <a href="{@docRoot}guide/developing/debug-tasks.html#logradio">Logging
- Radio Information</a>. </p>
-
-<h2 id="stop-a-vitrual-machine">Stop a Virtual Machine </h2>
-<p>You can stop a virtual machine by selecting <strong>Actions</strong> > <strong>Halt
-VM</strong>. Pressing this button causes the VM to call <code>Runtime.halt(1)</code>.</p>
-
-<h2 id="known-issues" style="color:#FF0000">Known issues with DDMS </h2>
-<p>DDMS has the following known limitations:</p>
-<ul>
- <li>If you connect and disconnect a debugger, ddms drops and reconnects the
- client so the VM realizes that the debugger has gone away. This will be fixed
- eventually. </li>
-</ul>
diff --git a/docs/html/guide/developing/tools/emulator.jd b/docs/html/guide/developing/tools/emulator.jd
index e255087..9baf1a1 100644
--- a/docs/html/guide/developing/tools/emulator.jd
+++ b/docs/html/guide/developing/tools/emulator.jd
@@ -12,7 +12,7 @@
<p>This document is a reference to the available command line options and the keyboard mapping to device keys.
For a complete guide to using the Android Emulator, see
-<a href="${@docRoot}guide/developing/devices/emulator.html">Using the Android Emulator</a>.
+<a href="{@docRoot}guide/developing/devices/emulator.html">Using the Android Emulator</a>.
<h2 id="startup-options">Emulator Startup Options</h2>
@@ -85,8 +85,8 @@
<td><strong>Required</strong>. Specifies the AVD to load for this emulator
instance.</td>
<td>You must create an AVD configuration before launching the emulator. For
- information, see <a href="{@docRoot}guide/developing/tools/avd.html">Android
- Virtual Devices</a>.</td>
+ information, see <a href="{@docRoot}guide/developing/devices/managing-avds.html#createavd">
+ Creating and Managing AVDs with AVD Manager</a>.</td>
<tr>
<td rowspan="7">Disk Images</td>
<td><code>-cache <filepath></code></td>
@@ -439,7 +439,8 @@
results, since the density with which to render the skin may not be defined.
AVDs let you associate each skin with a default density and override the default
as needed. For more information, see <a
-href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.
+href="{@docRoot}guide/developing/devices/managing-avds.html#createavd">
+Creating and Managing Virtual Devices with AVD Manager</a>.
</td>
</tr>
<tr>
diff --git a/docs/html/guide/developing/tools/hierarchy-viewer.jd b/docs/html/guide/developing/tools/hierarchy-viewer.jd
index 431008c..ce660fc 100644
--- a/docs/html/guide/developing/tools/hierarchy-viewer.jd
+++ b/docs/html/guide/developing/tools/hierarchy-viewer.jd
@@ -1,98 +1,16 @@
page.title=Hierarchy Viewer
@jd:body
-<p>The Hierarchy Viewer application allows you to debug and optimize your user
+<p>Hierarchy Viewer allows you to debug and optimize your user
interface. It provides a visual representation of the layout's View hierarchy
(the Layout View) and a magnified inspector of the display (the Pixel Perfect View).
</p>
-<p>To get the Hierarchy Viewer started:</p>
-<ol>
- <li>Connect your device or launch an emulator.</li>
- <li>From a terminal, launch <code>hierarchyviewer</code> from your SDK
- <code>/tools</code> directory.
- </li>
- <li>In the window that opens, you'll see a list of <strong>Devices</strong>. When a device is
- selected, a list of currently active <strong>Windows</strong> is displayed
- on the right. The <em><Focused Window></em> is the window currently in
- the foreground, and also the default window loaded if you do not select another.
- </li>
- <li>Select the window that you'd like to inspect and click
- <strong>Load View Hierarchy</strong>. The Layout View will be loaded.
- You can then load the Pixel Perfect View by clicking the second
- icon at the bottom-left of the window.
- </li>
+<p>To start Hierarchy Viewer, enter the following command from the SDK <code>tools/</code> directory:</p>
+ <pre>hierarchyviewer</pre>
</ol>
-<p>If you've navigated to a different window on the device, press <strong>Refresh Windows</strong>
-to refresh the list of available windows on the right.</p>
-
-<h2>Layout View</h2>
-<p>The Layout View offers a look at the View layout and properties. It has three views:</p>
-<ul>
- <li>Tree View: a hierarchy diagram of the Views, on the left.</li>
- <li>Properties View: a list of the selected View's properties, on the top-right.</li>
- <li>Wire-frame View: a wire-frame drawing of the layout, on the bottom-right.</li>
-</ul>
-<br/>
-<img src="{@docRoot}images/hierarchyviewer-layout.png" alt="" height="509" width="700" />
-
-<p>Select a node in the Tree View to display the properties of that element in
-the Properties View. When a node is selected, the Wire-frame View
-also indicates the bounds of the element with a red rectangle.
-Double click a node in the tree (or select it, and click <strong>Display
-View</strong>) to open a new window with a rendering of that element.</p>
-
-<p>The Layout View includes a couple other helpful features for debugging your layout:
-<strong>Invalidate</strong> and <strong>Request Layout</strong>. These buttons execute the
-respective View calls, {@link android.view.View#invalidate()} and {@link android.view.View#requestLayout()},
-on the View element currently selected in the tree. Calling these methods on any View can
-be very useful when simultaneously running a debugger on your application.</p>
-
-<p>The Tree View can be resized by adjusting the zoom slider, below
-the diagram. The number of View elements in the window is also given here. You
-should look for ways to minimize the number of Views. The fewer View elements there
-are in a window, the faster it will perform.</p>
-
-<p>If you interact with the device and change the focused View, the diagram will not automatically refresh.
-You must reload the Layout View by clicking <strong>Load View Hierarchy</strong>.
-
-
-<h2>Pixel Perfect View</h2>
-<p>The Pixel Perfect View provides a magnified look at the current device window. It has three views:</p>
-<ul>
- <li>Explorer View: shows the View hierarchy as a list, on the left.</li>
- <li>Normal View: a normal view of the device window, in the middle.</li>
- <li>Loupe View: a magnified, pixel-grid view of the device window, on the right.</li>
-</ul>
-<br/>
-<img src="{@docRoot}images/hierarchyviewer-pixelperfect.png" alt="" height="509" width="700" />
-
-<p>Click on an element in the Explorer View and a "layout box" will be drawn in the
-Normal View to indicate the layout position of that element. The layout box uses multiple rectangles, to indicate the normal bounds, the padding and the margin (as needed). The purple or green rectangle indicates
-the normal bounds of the element (the height and width). The inner white or black rectangle indicates
-the content bounds, when padding is present. A black or white rectangle outside the normal purple/green
-rectangle indicates any present margins.
-(There are two colors for each rectangle, in order to provide the best contrast
-based on the colors currently in the background.)</p>
-
-<p>A very handy feature for designing your UI is the ability to overlay an image in the Normal and Loupe
-Views. For example, you might have a mock-up image of how you'd like to layout your interface.
-By selecting <strong>Load...</strong> from the controls in the Normal View, you can choose the
-image from your computer and it will be placed atop the preview. Your chosen image will anchor at the bottom left corner of the screen. You can then adjust the opacity of the overlay and begin fine-tuning your layout to match the mock-up.</p>
-
-<p>The Normal View and Loupe View refresh at regular intervals (5 seconds by default), but the
-Explorer View does not. If you navigate away and focus on a different View, then you should refresh the
-Explorer's hierarchy by clicking <strong>Load View Hierarchy</strong>. This is even true
-when you're working in a window that holds multiple Views that are not always visible. If you do not,
-although the previews will refresh, clicking a View in the Explorer will not provide the proper layout box
-in the Normal View, because the hierarchy believes you are still focused on the prior View.</p>
-
-<p>Optional controls include:</p>
-<ul>
- <li><strong>Overlay</strong>: Load an overlay image onto the view and adjust its opacity.</li>
- <li><strong>Refresh Rate</strong>: Adjust how often the Normal and Loupe View refresh their display.</li>
- <li><strong>Zoom</strong>: Adjust the zoom level of the Loupe View.</li>
-</ul>
-
+<p>For more information on how to use Hierarchy Viewer, see
+<a href="{@docRoot}guide/developing/debugging/debugging-ui.html">Debugging and Profiling UIs</a>
+</p>
diff --git a/docs/html/guide/developing/tools/index.jd b/docs/html/guide/developing/tools/index.jd
index f20e016b..c603780 100644
--- a/docs/html/guide/developing/tools/index.jd
+++ b/docs/html/guide/developing/tools/index.jd
@@ -10,75 +10,76 @@
applications on the emulator. </p>
<dl>
- <dt><a href="{@docRoot}sdk/eclipse-adt.html">Android Development Tools Plugin</a> (for the Eclipse IDE)</dt>
- <dd>The ADT plugin adds powerful extensions to the Eclipse integrated environment,
- making creating and debugging your Android applications easier and faster.</dd>
+ <dt><a href="adb.html">Android Debug Bridge</a></dt>
+ <dd>A versatile tool lets you manage the state of an emulator instance
+ or Android-powered device.</dd>
+
+ <dt><a href="android.html">android</a></dt>
+ <dd>Lets you manage AVDs, projects, and the installed components of the SDK.
+ </dd>
+
+ <dt><a href="bmgr.html">bmgr</a></dt>
+
+ <dd>Lets you interact with the Backup Manager on Android devices
+ supporting API Level 8 or greater. It provides commands to invoke backup and restore operations
+ so that you don't need to repeatedly wipe data or take similar intrusive steps in order to test
+ your application's backup agent. These commands are accessed via the adb shell.
+ </dd>
+
+ <dt><a href="dmtracedump.html">dmtracedump</a></dt>
+
+ <dd>Generates graphical call-stack diagrams from trace log files.
+ The tool uses the Graphviz Dot utility to create the graphical output, so you need to install
+ Graphviz before running <code>dmtracedump</code>. For more information on using <code>dmtracedump</code>, see
+ <a href="{@docRoot}guide/developing/debugging/debugging-tracing.html#dmtracedump">Profiling with
+ Traceview and dmtracedump</a>
+ </dd>
+
+ <dt><a href="draw9patch.html">Draw 9-patch</a></dt>
+ <dd>Allows you to easily create a {@link android.graphics.NinePatch} graphic using a WYSIWYG editor.
+ It also previews stretched versions of the image, and highlights the area in which content is allowed.
+ </dd>
+
<dt><a href="emulator.html">Android Emulator</a></dt>
<dd>A QEMU-based device-emulation tool that you can use to design,
debug, and test your applications in an actual Android run-time environment. </dd>
+ <dt><a href="hprof-conv.html">hprof-conv</a></dt>
- <dt><a href="bmgr.html">bmgr</a></dt>
+ <dd>Converts the HPROF file that is generated by the Android SDK tools to a
+ standard format so you can view the file in a profiling tool of your choice.</dd>
- <dd>A shell tool you can use to interact with the Backup Manager on Android devices
- supporting API Level 8 or greater. It provides commands to invoke backup and restore operations
- so that you don't need to repeatedly wipe data or take similar intrusive steps in order to test
- your application's backup agent. These commands are accessed via the adb shell.
- </dd>
-
- <dt><a href="layoutopt.html">layoutopt</a></dt>
- <dd>This tool lets you quickly analyze your application's layouts in order to
+ <dt><a href="layoutopt.html">layoutopt</a></dt>
+ <dd>Lets you quickly analyze your application's layouts in order to
optimize them for efficiency.
</dd>
-
- <dt><a href="draw9patch.html">Draw 9-patch</a></dt>
- <dd>The Draw 9-patch tool allows you to easily create a
- {@link android.graphics.NinePatch} graphic using a WYSIWYG editor. It also previews stretched
- versions of the image, and highlights the area in which content is allowed.
- </dd>
-
-
- <dt><a href="adb.html" >Android Debug Bridge</a> (adb)</dt>
- <dd>The adb tool lets you install your application's .apk files on an
- emulator or device and access the emulator or device from a command line.
- You can also use it to link a standard debugger to application code running
- on an Android emulator or device.
- <p>This is located in {@code <sdk>/platform-tools/}.</p></dd>
-
- <dt><a href="hprof-conv.html">hprof-conv</a></dt>
-
- <dd>A tool that converts the HPROF file that is generated by the Android SDK tools to a
- standard format so you can view the file in a profiling tool of your choice.</dd>
-
- <dt><a href="sqlite3.html">sqlite3</a></dt>
- <dd>Included as a convenience, this tool lets you access the SQLite data
- files created and used by Android applications.</dd>
+ <dt><a href="mksdcard.html">logcat</a></dt>
+ <dd>Lets you read system log messages that are output on an Android device or emulator.</dd>
<dt><a href="mksdcard.html">mksdcard</a></dt>
- <dd>Helps you create a disk image that you can use with the emulator,
- to simulate the presence of an external storage card (such as an SD card).</dd>
-
- <dt><a href="monkey.html">UI/Application
+ <dd>Helps you create a disk image that you can use with the emulator,
+ to simulate the presence of an external storage card (such as an SD card).</dd>
- Exerciser Monkey</a></dt>
- <dd>A program that runs on your emulator or device and generates pseudo-random
+ <dt><a href="monkey.html">Monkey</a></dt>
+ <dd>Runs on your emulator or device and generates pseudo-random
streams of user events such as clicks, touches, or gestures, as well as a number of system-level events.
You can use the Monkey to stress-test applications that you are developing, in a random yet repeatable manner.</dd>
+ <dt><a href="monkeyrunner_concepts.html">monkeyrunner</a></dt>
+ <dd>Provides an API for writing programs that control an Android device
+ or emulator from outside of Android code.</dd>
- <dt><a href="android.html">android</a></dt>
- <dd>A script that lets you manage AVDs and generate <a
- href="http://ant.apache.org/" title="Ant">Ant</a> build files that
- you can use to compile your Android applications. </dd>
+ <dt><a href="proguard.html">ProGuard</a></dt>
+ <dd>Shrinks, optimizes, and obfuscates your code by removing unused code and renaming classes,
+ fields, and methods with semantically obscure names.</dd>
- <dt><a href="zipalign.html">zipalign</a></dt>
- <dd>An important .apk optimization tool. This tool ensures that all uncompressed data starts
+ <dt><a href="sqlite3.html">sqlite3</a></dt>
+ <dd>Lets you access the SQLite data files created and used by Android applications.</dd>
+
+ <dt><a href="zipalign.html">zipalign</a></dt>
+ <dd>Optimizes <code>.apk</code> files by ensuring that all uncompressed data starts
with a particular alignment relative to the start of the file. This should always be used
to align .apk files after they have been signed.</dd>
-
-
-
-
</dl>
diff --git a/docs/html/guide/developing/tools/monkey.jd b/docs/html/guide/developing/tools/monkey.jd
index 9a2ab6f..6c05934 100644
--- a/docs/html/guide/developing/tools/monkey.jd
+++ b/docs/html/guide/developing/tools/monkey.jd
@@ -185,7 +185,7 @@
<td>If set, this option will generate profiling reports immediately before and after
the Monkey event sequence.
This will generate large (~5Mb) files in data/misc, so use with care. See
-<a href="{@docRoot}guide/developing/tools/traceview.html" title="traceview">Traceview</a> for more information
+<a href="{@docRoot}guide/developing/debugging/debugging-tracing.html" title="traceview">Traceview</a> for more information
on trace files.</td>
</tr>
diff --git a/docs/html/guide/developing/tools/othertools.html b/docs/html/guide/developing/tools/othertools.html
new file mode 100644
index 0000000..a074f33
--- /dev/null
+++ b/docs/html/guide/developing/tools/othertools.html
@@ -0,0 +1,10 @@
+<html>
+<head>
+<meta http-equiv="refresh" content="0;url=http://developer.android.com/guide/developing/tools/index.html">
+<title>Redirecting...</title>
+</head>
+<body>
+<p>You should be redirected. Please <a
+href="http://developer.android.com/guide/developing/tools/index.html">click here</a>.</p>
+</body>
+</html>
\ No newline at end of file
diff --git a/docs/html/guide/developing/tools/othertools.jd b/docs/html/guide/developing/tools/othertools.jd
deleted file mode 100644
index 00f0b8d6..0000000
--- a/docs/html/guide/developing/tools/othertools.jd
+++ /dev/null
@@ -1,95 +0,0 @@
-page.title=Other Tools
-@jd:body
-
-<p>The sections below describe other tools that you can use when building
-Android applications. </p>
-
-<p>All of the tools are included in the Android SDK and are accessible from the
-<code><sdk>/tools/</code> directory.</p>
-
-<h2>Contents</h2>
-
-<dl>
- <dt><a href="#android">android</a></dd>
- <dt><a href="#mksdcard">mksdcard</a></dt>
- <dt><a href="#dx">dx</a></dt>
-</dl>
-
-<a name="activitycreator"></a>
-<h2 id="android">android</h2>
-
-<p>{@code android} is an important development tool that lets you:</p>
-
-<ul>
- <li>Create, delete, and view Android Virtual Devices (AVDs). See
- <a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.</li>
- <li>Create and update Android projects. See
- <a href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.</li>
- <li>Update your Android SDK with new platforms, add-ons, and documentation. See
- <a href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>.</li>
-</ul>
-
-<p>If you develop in Eclipse with the ADT plugin, you can perform
-these tasks directly from the IDE. To create
-Android projects and AVDs from Eclipse, see <a href="{@docRoot}guide/developing/eclipse-adt.html">Developing
-In Eclipse</a>. To update your SDK from Eclipse, see
-<a href="{@docRoot}sdk/adding-components.html">Adding SDK Components</a>.
-</p>
-
-
-<a name="mksdcard"></a>
-
-<h2>mksdcard</h2>
-
-<p>The mksdcard tool lets you quickly create a FAT32 disk image that you can
-load in the emulator, to simulate the presence of an SD card in the device.
-Here is the usage for mksdcard:</p>
-
-<pre>mksdcard [-l label] <size>[K|M] <file></pre>
-
-<p>The table below lists the available options/arguments</p>
-
-<table>
-<tr>
- <th>Argument</th>
- <th>Description</th>
-</tr>
-
-<tr>
- <td><code>-l</code></td>
- <td>A volume label for the disk image to create. </td>
-</tr>
-
-<tr>
- <td><code>size</code></td>
- <td>An integer that specifies the size (in bytes) of disk image to create.
-You can also specify size in kilobytes or megabytes, by appending a "K" or "M" to
-<size>. For example, <code>1048576K</code>, <code>1024M</code>.</td>
-</tr>
-
-<tr>
- <td><code>file</code></td>
- <td>The path/filename of the disk image to create. </td>
-</tr>
-
-</table>
-
-<p>Once you have created the disk image file, you can load it in the emulator at
-startup using the emulator's -sdcard option. For more information, see
-<a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a>.</p>
-
-<pre>emulator -sdcard <file></pre>
-
-<a name="dx"></a>
-
-<h2>dx</h2>
-
-<p>The dx tool lets you generate Android bytecode from .class files. The tool
-converts target files and/or directories to Dalvik executable format (.dex) files,
-so that they can run in the Android environment. It can also dump the class files
-in a human-readable format and run a target unit test. You can get the usage and
-options for this tool by using <code>dx --help</code>.</p>
-
-
-
-
diff --git a/docs/html/guide/developing/tools/traceview.jd b/docs/html/guide/developing/tools/traceview.jd
index 95ae823..422fe00 100644
--- a/docs/html/guide/developing/tools/traceview.jd
+++ b/docs/html/guide/developing/tools/traceview.jd
@@ -1,319 +1,14 @@
-page.title=Traceview: A Graphical Log Viewer
+page.title=Traceview
@jd:body
-<div id="qv-wrapper">
-<div id="qv">
+<p>Traceview is a graphical viewer for execution logs saved by your application.
+Traceview can help you debug your application and profile its performance.</p>
- <h2>In this document</h2>
-<ol>
- <li><a href="#creatingtracefiles">Creating Trace Files</a></li>
- <li><a href="#copyingfiles">Copying Trace Files to a Host Machine</a></li>
- <li><a href="#runningtraceview">Viewing Trace Files in Traceview</a>
- <ol>
- <li><a href="#timelinepanel">Timeline Panel</a></li>
- <li><a href="#profilepanel">Profile Panel</a></li>
- </ol></li>
- <li><a href="#format">Traceview File Format</a>
- <ol>
- <li><a href="#datafileformat">Data File Format</a></li>
- <li><a href="#keyfileformat">Key File Format</a></li>
- </ol></li>
- <li><a href="#knownissues">Traceview Known Issues</a></li>
- <li><a href="#dmtracedump">Using dmtracedump</a></li>
+<p>To start Traceview, enter the following command from the SDK <code>tools/</code> directory:</p>
+ <pre>traceview</pre>
</ol>
-</div>
-</div>
-<p>Traceview is a graphical viewer for execution logs
-saved by your application. Traceview can help you debug your application and
-profile its performance. The sections below describe how to use the program. </p>
-
-<a name="creatingtracefiles"></a>
-
-<h2>Creating Trace Files</h2>
-
-<p>To use Traceview, you need to generate log files containing the trace information you want to analyze. To do that, you include the {@link android.os.Debug}
- class in your code and call its methods to start and stop logging of trace information
- to disk. When your application quits, you can then use Traceview to examine the log files
- for useful run-time information such
- as method calls and run times. </p>
-<p>To create the trace files, include the {@link android.os.Debug} class and call one
- of the {@link android.os.Debug#startMethodTracing() startMethodTracing()} methods.
- In the call, you specify a base name for the trace files that the system generates.
- To stop tracing, call {@link android.os.Debug#stopMethodTracing() stopMethodTracing()}.
- These methods start and stop method tracing across the entire virtual machine. For
- example, you could call startMethodTracing() in your activity's onCreate()
- method, and call stopMethodTracing() in that activity's onDestroy() method.</p>
-
-<pre>
- // start tracing to "/sdcard/calc.trace"
- Debug.startMethodTracing("calc");
- // ...
- // stop tracing
- Debug.stopMethodTracing();
-</pre>
-
-<p>When your application calls startMethodTracing(), the system creates a
-file called <code><trace-base-name>.trace</code>. This contains the
-binary method trace data and a mapping table with thread and method names.</p>
-
-<p>The system then begins buffering the generated trace data, until your application calls
- stopMethodTracing(), at which time it writes the buffered data to the
- output file.
- If the system reaches the maximum buffer size before stopMethodTracing()
- is called, the system stops tracing and sends a notification
- to the console. </p>
-
-<p>Interpreted code will run more slowly when profiling is enabled. Don't
-try to generate absolute timings from the profiler results (i.e. "function
-X takes 2.5 seconds to run"). The times are only
-useful in relation to other profile output, so you can see if changes
-have made the code faster or slower. </p>
-
-<p>When using the Android emulator, you must create an SD card image upon which
-the trace files will be written. For example, from the <code>/tools</code> directory, you
-can create an SD card image named "imgcd" and mount it when launching the emulator like so:</p>
-<pre>
-<b>$</b> mksdcard 1024M ./imgcd
-<b>$</b> emulator -sdcard ./imgcd
-</pre>
-<p>For more information, read about the
-<a href="{@docRoot}guide/developing/tools/othertools.html#mksdcard">mksdcard tool</a>.</p>
-
-<p>The format of the trace files is described <a href="#format">later
- in this document</a>. </p>
-
-<a name="copyingfiles"></a>
-
-<h2>Copying Trace Files to a Host Machine</h2>
-<p>After your application has run and the system has created your trace files <code><trace-base-name>.trace</code>
- on a device or emulator, you must copy those files to your development computer. You can use <code>adb pull</code> to copy
- the files. Here's an example that shows how to copy an example file,
- calc.trace, from the default location on the emulator to the /tmp directory on
-the emulator host machine:</p>
-<pre>adb pull /sdcard/calc.trace /tmp</pre>
-
-
-<a name="runningtraceview"></a>
-
-<h2>Viewing Trace Files in Traceview</h2>
-<p>To run traceview and view the trace files, enter <code>traceview <trace-base-name></code>.
- For example, to run Traceview on the example files copied in the previous section,
- you would use: </p>
- <pre>traceview /tmp/calc</pre>
-
- <p>Traceview loads the log files and displays their data in a window that has two panels:</p>
- <ul>
- <li>A <a href="#timelinepanel">timeline panel</a> -- describes when each thread
- and method started and stopped</li>
- <li>A <a href="#timelinepanel">profile panel</a> -- provides a summary of what happened inside a method</li>
- </ul>
- <p>The sections below provide addition information about the traceview output panes. </p>
-
-<a name="timelinepanel"></a>
-
-<h3>Timeline Panel </h3>
-<p>The image below shows a close up of the timeline panel. Each thread’s
- execution is shown in its own row, with time increasing to the right. Each method
- is shown in another color (colors are reused in a round-robin fashion starting
- with the methods that have the most inclusive time). The thin lines underneath
- the first row show the extent (entry to exit) of all the calls to the selected
- method. The method in this case is LoadListener.nativeFinished() and it was
- selected in the profile view. </p>
-<p><img src="/images/traceview_timeline.png" alt="Traceview timeline panel" width="893" height="284"></p>
-<a name="profilepanel"></a>
-<h3>Profile Panel</h3>
-<p>The image below shows the profile pane. The profile pane shows a
- summary of all the time spent in a method. The table shows
- both the inclusive and exclusive times (as well as the percentage of the total
- time). Exclusive time is the time spent in the method. Inclusive time is the
- time spent in the method plus the time spent in any called functions. We refer
- to calling methods as "parents" and called methods as "children."
- When a method is selected (by clicking on it), it expands to show the parents
- and children. Parents are shown with a purple background and children
- with a yellow background. The last column in the table shows the number of calls
- to this method plus the number of recursive calls. The last column shows the
- number of calls out of the total number of calls made to that method. In this
- view, we can see that there were 14 calls to LoadListener.nativeFinished(); looking
- at the timeline panel shows that one of those calls took an unusually
- long time.</p>
-<p><img src="/images/traceview_profile.png" alt="Traceview profile panel." width="892" height="630"></p>
-
-<a name="format"></a>
-<h2>Traceview File Format</h2>
-<p>Tracing creates two distinct pieces of output: a <em>data</em> file,
- which holds the trace data, and a <em>key</em> file, which
- provides a mapping from binary identifiers to thread and method names.
- The files are concatenated when tracing completes, into a
- single <em>.trace</em> file. </p>
-
-<p class="note"><strong>Note:</strong> The previous version of Traceview did not concatenate
-these files for you. If you have old key and data files that you'd still like to trace, you
-can concatenate them yourself with <code>cat mytrace.key mytrace.data > mytrace.trace</code>.</p>
-
-<a name="datafileformat"></a>
-
-<h3>Data File Format</h3>
-<p>The data file is binary, structured as
- follows (all values are stored in little-endian order):</p>
-<pre>* File format:
-* header
-* record 0
-* record 1
-* ...
-*
-* Header format:
-* u4 magic 0x574f4c53 ('SLOW')
-* u2 version
-* u2 offset to data
-* u8 start date/time in usec
-*
-* Record format:
-* u1 thread ID
-* u4 method ID | method action
-* u4 time delta since start, in usec
-</pre>
-<p>The application is expected to parse all of the header fields, then seek
- to "offset to data" from the start of the file. From there it just
- reads
- 9-byte records until EOF is reached.</p>
-<p><em>u8 start date/time in usec</em> is the output from gettimeofday().
- It's mainly there so that you can tell if the output was generated yesterday
- or three months ago.</p>
-<p><em>method action</em> sits in the two least-significant bits of the
- <em>method</em> word. The currently defined meanings are: </p>
-<ul>
- <li>0 - method entry </li>
- <li>1 - method exit </li>
- <li>2 - method "exited" when unrolled by exception handling </li>
- <li>3 - (reserved)</li>
-</ul>
-<p>An unsigned 32-bit integer can hold about 70 minutes of time in microseconds.
+<p>For more information on how to use Traceview, see
+<a href="{@docRoot}guide/developing/debugging/debugging-tracing.html">Profiling with Traceview and dmtracedump</a>
</p>
-<a name="keyfileformat"></a>
-
-<h3>Key File Format</h3>
-<p>The key file is a plain text file divided into three sections. Each
- section starts with a keyword that begins with '*'. If you see a '*' at the start
- of a line, you have found the start of a new section.</p>
-<p>An example file might look like this:</p>
-<pre>*version
-1
-clock=global
-*threads
-1 main
-6 JDWP Handler
-5 Async GC
-4 Reference Handler
-3 Finalizer
-2 Signal Handler
-*methods
-0x080f23f8 java/io/PrintStream write ([BII)V
-0x080f25d4 java/io/PrintStream print (Ljava/lang/String;)V
-0x080f27f4 java/io/PrintStream println (Ljava/lang/String;)V
-0x080da620 java/lang/RuntimeException <init> ()V
-[...]
-0x080f630c android/os/Debug startMethodTracing ()V
-0x080f6350 android/os/Debug startMethodTracing (Ljava/lang/String;Ljava/lang/String;I)V
-*end</pre>
-<dl>
- <dt><em>version section</em></dt>
- <dd>The first line is the file version number, currently
- 1.
- The second line, <code>clock=global</code>, indicates that we use a common
- clock across all threads. A future version may use per-thread CPU time counters
- that are independent for every thread.</dd>
- <dt><em>threads section</em></dt>
- <dd>One line per thread. Each line consists of two parts: the thread ID, followed
- by a tab, followed by the thread name. There are few restrictions on what
- a valid thread name is, so include everything to the end of the line.</dd>
- <dt><em>methods section </em></dt>
- <dd>One line per method entry or exit. A line consists of four pieces,
- separated by tab marks: <em>method-ID</em> [TAB] <em>class-name</em> [TAB]
- <em>method-name</em> [TAB]
- <em>signature</em> . Only
- the methods that were actually entered or exited are included in the list.
- Note that all three identifiers are required to uniquely identify a
- method.</dd>
-</dl>
-<p>Neither the threads nor methods sections are sorted.</p>
-
-<a name="knownissues"></a>
-<h2>Traceview Known Issues</h2>
-<dl>
- <dt>Threads</dt>
- <dd>Traceview logging does not handle threads well, resulting in these two problems:
-<ol>
- <li> If a thread exits during profiling, the thread name is not emitted; </li>
- <li>The VM reuses thread IDs. If a thread stops and another starts, they
- may get the same ID. </li>
-</ol>
-</dd>
-
-<a name="dmtracedump"></a>
-
-<h2>Using dmtracedump</h2>
-
-<p>The Android SDK includes dmtracedump, a tool that gives you an alternate way
- of generating graphical call-stack diagrams from trace log files. The tool
- uses the Graphviz Dot utility to create the graphical output, so you need to
- install Graphviz before running dmtracedump.</p>
-
-<p>The dmtracedump tool generates the call stack data as a tree diagram, with each call
- represented as a node. It shows call flow (from parent node to child nodes) using
- arrows. The diagram below shows an example of dmtracedump output.</p>
-
-<img src="{@docRoot}images/tracedump.png" width="485" height="401" style="margin-top:1em;"/>
-
-<p style="margin-top:1em;">For each node, dmtracedump shows <code><ref> <em>callname</em> (<inc-ms>,
- <exc-ms>,<numcalls>)</code>, where</p>
-
-<ul>
- <li><code><ref></code> -- Call reference number, as used in trace logs</li>
- <li><code><inc-ms></code> -- Inclusive elapsed time (milliseconds spent in method, including all child methods)</li>
- <li><code><exc-ms></code> -- Exclusive elapsed time (milliseconds spent in method, not including any child methods)</li>
- <li><code><numcalls></code> -- Number of calls</li>
-</ul>
-
-<p>The usage for dmtracedump is: </p>
-
-<pre>dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name></pre>
-
-<p>The tool then loads trace log data from <trace-base-name>.data and <trace-base-name>.key.
- The table below lists the options for dmtracedump.</p>
-
-<table>
-<tr>
- <th>Option</td>
- <th>Description</th>
-</tr>
-
- <tr>
- <td><code>-d <trace-base-name> </code></td>
- <td>Diff with this trace name</td>
- </tr>
- <tr>
- <td><code>-g <outfile> </code></td>
- <td>Generate output to <outfile></td>
- </tr>
- <tr>
- <td><code>-h </code></td>
- <td>Turn on HTML output</td>
- </tr>
- <tr>
- <td><code>-o </code></td>
- <td>Dump the trace file instead of profiling</td>
- </tr>
- <tr>
- <td><code>-d <trace-base-name> </code></td>
- <td>URL base to the location of the sortable javascript file</td>
- </tr>
- <tr>
- <td><code>-t <percent> </code></td>
- <td>Minimum threshold for including child nodes in the graph (child's inclusive
- time as a percentage of parent inclusive time). If this option is not used,
- the default threshold is 20%. </td>
- </tr>
-
-</table>
diff --git a/docs/html/guide/guide_toc.cs b/docs/html/guide/guide_toc.cs
index 4842589..a984acd 100644
--- a/docs/html/guide/guide_toc.cs
+++ b/docs/html/guide/guide_toc.cs
@@ -262,7 +262,7 @@
</li>
<li><a href="<?cs var:toroot?>guide/topics/admin/device-admin.html">
<span class="en">Device Administration</span>
- </a> <span class="new">new!</span>
+ </a>
</li>
<li class="toggle-list">
<div>
@@ -274,27 +274,22 @@
<li>
<a href="<?cs var:toroot?>guide/topics/testing/testing_android.html">
<span class="en">Testing Fundamentals</span></a>
- <span class="new">new!</span>
</li>
<li>
<a href="<?cs var:toroot?>guide/topics/testing/activity_testing.html">
<span class="en">Activity Testing</span></a>
- <span class="new">new!</span>
</li>
<li>
<a href="<?cs var:toroot?>guide/topics/testing/contentprovider_testing.html">
<span class="en">Content Provider Testing</span></a>
- <span class="new">new!</span>
</li>
<li>
<a href="<?cs var:toroot?>guide/topics/testing/service_testing.html">
<span class="en">Service Testing</span></a>
- <span class="new">new!</span>
</li>
<li>
<a href="<?cs var:toroot ?>guide/topics/testing/what_to_test.html">
<span class="en">What To Test</span></a>
- <span class="new">new!</span>
</li>
</ul>
@@ -316,7 +311,7 @@
<!--<li><a href="">Developing for Android</a></li>
signing, upgrading, selecting a package name, select device profile, touch, trackball, dpad available, etc. -->
<li>
- <a href="<?cs var:toroot ?>guide/developing/overview.html">
+ <a href="<?cs var:toroot ?>guide/developing/index.html">
<span class="en">Overview</span></a>
</li>
@@ -359,7 +354,7 @@
<ul>
<li>
<a href="<?cs var:toroot ?>guide/developing/projects/projects-eclipse.html">
- <span class="en">In Eclipse</span>
+ <span class="en">In Eclipse with ADT</span>
</a>
</li>
<li>
@@ -378,9 +373,9 @@
</div>
<ul>
<li><a href="<?cs var:toroot ?>guide/developing/building/building-eclipse.html">
- <span class="en">In Eclipse</span>
+ <span class="en">In Eclipse with ADT</span>
</a></li>
- <li><a href="<?cs var:toroot ?>guide/developing/building/building-cmdline.html"><span class="en">In Other IDEs</span></a></li>
+ <li><a href="<?cs var:toroot ?>guide/developing/building/building-cmdline.html"><span class="en">On the Command Line</span></a></li>
</ul>
</li>
@@ -393,7 +388,7 @@
<ul>
<li>
<a href="<?cs var:toroot ?>guide/developing/debugging/debugging-projects.html">
- <span class="en">In Eclipse</span>
+ <span class="en">In Eclipse with ADT</span>
</a>
</li>
<li>
@@ -438,13 +433,13 @@
<ul>
<li>
<a href="<?cs var:toroot ?>guide/developing/testing/testing_eclipse.html">
- <span class="en">Testing in Eclipse, with ADT</span>
+ <span class="en">In Eclipse with ADT</span>
</a>
</li>
<li>
<a href="<?cs var:toroot ?>guide/developing/testing/testing_otheride.html">
- <span class="en">Testing in Other IDEs</span>
+ <span class="en">In Other IDEs</span>
</a>
</li>
</ul>
@@ -462,41 +457,40 @@
<li><a href="<?cs var:toroot ?>guide/developing/tools/dmtracedump.html">dmtracedump</a></li>
<li><a href="<?cs var:toroot ?>guide/developing/tools/draw9patch.html" >Draw 9-Patch</a></li>
<li><a href="<?cs var:toroot ?>guide/developing/tools/emulator.html">Emulator</a></li>
+ <li><a href="<?cs var:toroot ?>guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a></li>
<li><a href="<?cs var:toroot ?>guide/developing/tools/hprof-conv.html">hprof-conv</a></li>
<li><a href="<?cs var:toroot ?>guide/developing/tools/layoutopt.html">layoutopt</a></li>
<li><a href="<?cs var:toroot ?>guide/developing/tools/logcat.html">logcat</a></li>
<li><a href="<?cs var:toroot ?>guide/developing/tools/mksdcard.html">mksdcard</a></li>
- <li><a href="/guide/developing/tools/monkey.html">Monkey</a></li>
- <li class="toggle-list">
- <div>
- <a href="/guide/developing/tools/monkeyrunner_concepts.html">
- <span class="en">monkeyrunner</span>
- </a>
- <span class="new">new!</span>
- </div>
- <ul>
- <li>
- <a href="/guide/developing/tools/MonkeyDevice.html">
- <span class="en">MonkeyDevice</span>
- </a>
- <span class="new">new!</span>
- </li>
- <li>
- <a href="/guide/developing/tools/MonkeyImage.html">
- <span class="en">MonkeyImage</span>
- </a>
- <span class="new">new!</span>
- </li>
- <li>
- <a href="/guide/developing/tools/MonkeyRunner.html">
- <span class="en">MonkeyRunner</span>
- </a>
- <span class="new">new!</span>
- </li>
- </ul>
- </li>
- <li><a href="/guide/developing/tools/proguard.html">ProGuard</a> <span class="new">new!</span></li>
- <li><a href="/guide/developing/tools/adb.html#sqlite">sqlite3</a></li>
+
+ <li><a href="/guide/developing/tools/monkey.html">Monkey</a></li>
+ <li class="toggle-list">
+ <div>
+ <a href="/guide/developing/tools/monkeyrunner_concepts.html">
+ <span class="en">monkeyrunner</span>
+ </a>
+ </div>
+ <ul>
+ <li>
+ <a href="/guide/developing/tools/MonkeyDevice.html">
+ <span class="en">MonkeyDevice</span>
+ </a>
+ </li>
+ <li>
+ <a href="/guide/developing/tools/MonkeyImage.html">
+ <span class="en">MonkeyImage</span>
+ </a>
+ </li>
+ <li>
+ <a href="/guide/developing/tools/MonkeyRunner.html">
+ <span class="en">MonkeyRunner</span>
+ </a>
+ </li>
+ </ul>
+ </li>
+ <li><a href="/guide/developing/tools/proguard.html">ProGuard</a></li>
+ <li><a href="/guide/developing/tools/adb.html#sqlite">sqlite3</a></li>
+ <li><a href="/guide/developing/tools/traceview.html">Traceview</a></li>
<li><a href="<?cs var:toroot ?>guide/developing/tools/zipalign.html">zipalign</a></li>
</ul>
</li>
@@ -536,7 +530,7 @@
</a></li>
<li><a href="<?cs var:toroot ?>guide/publishing/licensing.html">
<span class="en">Licensing Your Applications</span>
- </a> <span class="new">new!</span></li>
+ </a></li>
<li><a href="<?cs var:toroot ?>guide/publishing/preparing.html">
<span class="en">Preparing to Publish</span>
<span class="de" style="display:none">Vorbereitung auf die Veröffentlichung</span>
@@ -631,19 +625,19 @@
<ul>
<li><a href="<?cs var:toroot ?>guide/webapps/index.html">
<span class="en">Web Apps Overview</span>
- </a> <span class="new">new!</span><!-- 11/1/10 --></li>
+ </a></li>
<li><a href="<?cs var:toroot ?>guide/webapps/targeting.html">
<span class="en">Targeting Screens from Web Apps</span>
- </a> <span class="new">new!</span><!-- 11/1/10 --></li>
+ </a></li>
<li><a href="<?cs var:toroot ?>guide/webapps/webview.html">
<span class="en">Building Web Apps in WebView</span>
- </a> <span class="new">new!</span><!-- 11/1/10 --></li>
+ </a></li>
<li><a href="<?cs var:toroot ?>guide/webapps/debugging.html">
<span class="en">Debugging Web Apps</span>
- </a> <span class="new">new!</span><!-- 11/1/10 --></li>
+ </a></li>
<li><a href="<?cs var:toroot ?>guide/webapps/best-practices.html">
<span class="en">Best Practices for Web Apps</span>
- </a> <span class="new">new!</span><!-- 11/1/10 --></li>
+ </a></li>
</ul>
</li>
diff --git a/docs/html/guide/practices/design/performance.jd b/docs/html/guide/practices/design/performance.jd
index f5588ac..97b31cf 100644
--- a/docs/html/guide/practices/design/performance.jd
+++ b/docs/html/guide/practices/design/performance.jd
@@ -425,7 +425,7 @@
to run your own microbenchmarks.</p>
<p>You may also find
-<a href="{@docRoot}guide/developing/tools/traceview.html">Traceview</a> useful
+<a href="{@docRoot}guide/developing/debugging/debugging-tracing.html">Traceview</a> useful
for profiling, but it's important to realize that it currently disables the JIT,
which may cause it to misattribute time to code that the JIT may be able to win
back. It's especially important after making changes suggested by Traceview
diff --git a/docs/html/guide/practices/screens_support.jd b/docs/html/guide/practices/screens_support.jd
index 5738bd6..520bd28 100644
--- a/docs/html/guide/practices/screens_support.jd
+++ b/docs/html/guide/practices/screens_support.jd
@@ -38,7 +38,7 @@
<li><a
href="{@docRoot}guide/topics/resources/providing-resources.html#AlternativeResources">
Providing Alternative Resources</a></li>
- <li><a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a></li>
+ <li><a href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a></li>
</ol>
</div>
@@ -1205,7 +1205,7 @@
Manager or the <code>android</code> tool to create AVDs that use the various
emulator skins and you can also set up custom AVDs to test densities other than
the defaults. For general information about working with AVDs, see
-<a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual
+<a href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual
Devices</a>.</p>
<p>The Android SDK provides a set of default emulator skins that you can use for
diff --git a/docs/html/guide/publishing/app-signing.jd b/docs/html/guide/publishing/app-signing.jd
index c7e1c79..93077a0 100644
--- a/docs/html/guide/publishing/app-signing.jd
+++ b/docs/html/guide/publishing/app-signing.jd
@@ -240,8 +240,8 @@
compile your app, the build script generates a keystore/key and signs the .apk for you.
The script then also aligns the .apk with the <code>zipalign</code> tool.
No other action on your part is needed. Read
-<a href="{@docRoot}guide/developing/other-ide.html#DebugMode">Developing In Other IDEs: Building
-in debug mode</a> for more information.</p>
+<a href="{@docRoot}guide/developing/building/building-cmdline.html#DebugMode">Building and Running Apps
+on the Command Line</a> for more information.</p>
<h3 id="debugexpiry">Expiry of the Debug Certificate</h3>
@@ -259,7 +259,7 @@
<p>In Eclipse/ADT, you will see a similar error in the Android console.</p>
<p>To fix this problem, simply delete the <code>debug.keystore</code> file.
-The default storage location for AVDs is in <code>~/.android/avd</code> on OS X and Linux,
+The default storage location for AVDs is in <code>~/.android/</code> on OS X and Linux,
in <code>C:\Documents and Settings\<user>\.android\</code> on Windows XP, and in
<code>C:\Users\<user>\.android\</code> on Windows Vista.</p>
@@ -441,8 +441,8 @@
<code><em><your_project_name></em>-release.apk</code>. With these steps
automated for you, you're able to skip the manual procedures below (steps 3 and 4).
To learn how to specify your keystore and alias in the {@code build.properties} file,
-see <a href="{@docRoot}guide/developing/other-ide.html#ReleaseMode">Developing In Other
-IDEs: Building in release mode</a>.</p>
+see <a href="{@docRoot}guide/developing/building/building-cmdline.html#ReleaseMode">
+Building and Running Apps on the Command Line</a>.</p>
diff --git a/docs/html/guide/publishing/licensing.jd b/docs/html/guide/publishing/licensing.jd
index 40439f0..e099413 100644
--- a/docs/html/guide/publishing/licensing.jd
+++ b/docs/html/guide/publishing/licensing.jd
@@ -518,7 +518,7 @@
</ol>
<p>If you are not familiar with AVDs or how to use them, see <a
-href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>.</p>
+href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>.</p>
<h4 id="project-update">Updating your project configuration</h4>
@@ -628,12 +628,9 @@
share its code and resources across multiple applications. </p>
<p style="margin-top:.5em;">If you aren't familiar with library projects or how
-to use them, read more in <a
-href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing in
-Eclipse with ADT</a> or <a
-href="{@docRoot}guide/developing/other-ide.html#libraryProject">Developing in
-Other IDEs</a>, as appropriate for your environment.</p>
-
+to use them, see <a href="{@docRoot}guide/developing/projects/index.html#LibraryProjects">
+Creating and Managing Projects</a>.
+</p>
</div>
</div>
@@ -669,9 +666,8 @@
no further configuration is needed. </p>
<p>For more information about how to create an application project or work with
-library projects in Eclipse, see <a
-href="{@docRoot}guide/developing/eclipse-adt.html#CreatingAProject">Developing
-in Eclipse with ADT</a>.</p>
+library projects in Eclipse, see <a href="{@docRoot}guide/developing/projects/projects-eclipse.html">
+Creating and Managing Projects in Eclipse</a></p>.
<h4>Copying the LVL sources to your application</h4>
@@ -701,9 +697,9 @@
<p>Next, open the application's project properties window, as shown below.
Select the "Android" properties group and click <strong>Add</strong>, then
choose the LVL library project (com_android_vending_licensing) and click
-<strong>OK</strong>. For more information, see
-<a href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing
-in Eclipse with ADT</a></p>
+<strong>OK</strong>. For more information, see
+<a href="{@docRoot}developing/projects/projects-eclipse.html#SettingUpLibraryProject">
+Creating and Managing Projects in Eclipse</a></p>.
<div style="margin-bottom:2em;">
@@ -730,11 +726,9 @@
--library <em>path/to/my/library_project</em>
</pre>
-<p>For more information about working with library projects, see <a
-href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing
-in Eclipse with ADT</a> or <a
-href="{@docRoot}guide/developing/other-ide.html#libraryProject">Developing in
-Other IDEs</a>, as appropriate for your environment.</p>
+<p>For more information about working with library projects,
+see <a href="{@docRoot}developing/projects/projects-cmdline.html#SettingUpLibraryProject">
+Creating and Managing Projects on the Command Line</a></p>.
<h2 id="app-integration">Integrating the LVL with Your Application</h2>
diff --git a/docs/html/guide/topics/fragments/index.jd b/docs/html/guide/topics/fragments/index.jd
index 766146e..d07daf4 100644
--- a/docs/html/guide/topics/fragments/index.jd
+++ b/docs/html/guide/topics/fragments/index.jd
@@ -277,13 +277,13 @@
which to place the fragment.</p>
<p>To make any fragment transactions in your activity (such as add, remove, or replace a
fragment), you must use APIs from {@link android.app.FragmentTransaction}. You can get an instance
-of {@link android.app.FragmentTransaction} from your {@link android.app.Activity} using {@link
-android.app.Activity#openFragmentTransaction()}. You can then add a fragment using the {@link
+of {@link android.app.FragmentTransaction} from your {@link android.app.FragmentManager} using {@link
+android.app.FragmentManager#openTransaction()}. You can then add a fragment using the {@link
android.app.FragmentTransaction#add add()} method, specifying the fragment to add and the view in
which to insert it. For example:</p>
<pre>
MyFragment fragment = new MyFragment();
-openFragmentTransaction().add(R.id.fragment_container, fragment).commit();
+getFragmentManager().openTransaction().add(R.id.fragment_container, fragment).commit();
</pre>
<p>The first argument passed to {@link android.app.FragmentTransaction#add add()}
is the {@link android.view.ViewGroup} in which the fragment should be placed, specified by
@@ -372,8 +372,8 @@
operations on a fragment as the user interacts with the activity, alowing for more rich user
experiences without changing activities. In order to perform these operations, you must use {@link
android.app.FragmentTransaction} to perform fragment "transactions." You can acquire {@link
-android.app.FragmentTransaction} from your activity with {@link
-android.app.Activity#openFragmentTransaction}.</p>
+android.app.FragmentTransaction} from your FragmentManager with {@link
+android.app.FragmentManager#openTransaction}.</p>
<p>Common transactions you can perform with fragments include:</p>
@@ -397,7 +397,7 @@
<pre>
// Create new fragment
Fragment newFragment = new MyFragment();
-FragmentTransaction ft = openFragmentTransaction();
+FragmentTransaction ft = getFragmentManager().openTransaction();
// Replace and add to back stack
ft.replace(R.id.myfragment, newFragment);
ft.addToBackStack(null);
@@ -519,7 +519,7 @@
<p>Likewise, your activity can call public methods in the fragment when you have a reference to the
{@link android.app.Fragment}. You can acquire a reference to the fragment with {@link
-android.app.Activity#findFragmentById findFragmentById()} and cast it to your implementation of
+android.app.FragmentManager#findFragmentById findFragmentById()} and cast it to your implementation of
{@link android.app.Fragment}. For example:</p>
<pre>
diff --git a/docs/html/guide/topics/fundamentals.jd b/docs/html/guide/topics/fundamentals.jd
index fffc1cd..1658fa6 100644
--- a/docs/html/guide/topics/fundamentals.jd
+++ b/docs/html/guide/topics/fundamentals.jd
@@ -52,10 +52,9 @@
<p>
Android applications are written in the Java programming language.
The compiled Java code — along with any data and resource
-files required by the application — is bundled by the
-<a href="{@docRoot}guide/developing/tools/aapt.html"><code>aapt</code>
-tool</a> into an <i>Android package</i>, an archive file
-marked by an {@code .apk} suffix. This file is the vehicle
+files required by the application — is bundled into an
+<i>Android package</i>, an archive file
+marked by an {@code .apk} suffix. This file is the vehicle
for distributing the application and installing it on mobile devices;
it's the file users download to their devices. All the code in a
single {@code .apk} file is considered to be one <i>application</i>.
@@ -425,7 +424,7 @@
<code><a href="{@docRoot}guide/topics/manifest/provider-element.html"><provider></a></code>
elements for content providers. Activities, services, and content providers
that are not declared in the manifest are not visible to the system and are
-consequently never run. However, broadcast receivers can either be
+consequently never run. However, broadcast receivers can either be
declared in the manifest, or they can be created dynamically in code
(as {@link android.content.BroadcastReceiver} objects)
and registered with the system by calling
diff --git a/docs/html/guide/topics/graphics/2d-graphics.jd b/docs/html/guide/topics/graphics/2d-graphics.jd
index 5759be5..05f4023 100644
--- a/docs/html/guide/topics/graphics/2d-graphics.jd
+++ b/docs/html/guide/topics/graphics/2d-graphics.jd
@@ -61,7 +61,7 @@
<p class="note"><strong>Note:</strong> Image resources placed in <code>res/drawable/</code> may be
automatically optimized with lossless image compression by the
-<a href="{@docRoot}guide/developing/tools/aapt.html">aapt</a> tool. For example, a true-color PNG that does
+<code>aapt</code> tool during the build process. For example, a true-color PNG that does
not require more than 256 colors may be converted to an 8-bit PNG with a color palette. This
will result in an image of equal quality but which requires less memory. So be aware that the
image binaries placed in this directory can change during the build. If you plan on reading
diff --git a/docs/html/guide/topics/location/obtaining-user-location.jd b/docs/html/guide/topics/location/obtaining-user-location.jd
index bc782d2..3b450f0 100644
--- a/docs/html/guide/topics/location/obtaining-user-location.jd
+++ b/docs/html/guide/topics/location/obtaining-user-location.jd
@@ -421,8 +421,8 @@
<li>Use a KML file describing individual place marks for sequenced playback to the device.</li>
</ul>
-<p>For more information on using DDMS to spoof location data, see the
-<a href="{@docRoot}guide/developing/tools/ddms.html#emulator-control">Using DDMS guide</a>.
+<p>For more information on using DDMS to spoof location data, see
+<a href="{@docRoot}guide/developing/debugging/ddms.html">Using DDMS</a>.
<h3 id="MockGeo">Using the "geo" command in the emulator console</h3>
@@ -451,4 +451,4 @@
</ol>
<p>For information about how to connect to the emulator console, see
-<a href="{@docRoot}guide/developing/tools/emulator.html#console">Using the Emulator Console</a>.</p>
+<a href="{@docRoot}guide/developing/devices/emulator.html#console">Using the Emulator Console</a>.</p>
diff --git a/docs/html/guide/topics/resources/drawable-resource.jd b/docs/html/guide/topics/resources/drawable-resource.jd
index d9f619f..cee8fc3 100644
--- a/docs/html/guide/topics/resources/drawable-resource.jd
+++ b/docs/html/guide/topics/resources/drawable-resource.jd
@@ -74,7 +74,7 @@
alias resource ID in XML.</p>
<p class="note"><strong>Note:</strong> Bitmap files may be automatically optimized with lossless
-image compression by the <a href="{@docRoot}guide/developing/tools/aapt.html">aapt</a> tool. For
+image compression by the <code>aapt</code> tool during the build process. For
example, a true-color PNG that does not require more than 256 colors may be converted to an 8-bit
PNG with a color palette. This will result in an image of equal quality but which requires less
memory. So be aware that the image binaries placed in this directory can change during the build. If
diff --git a/docs/html/guide/topics/testing/testing_android.jd b/docs/html/guide/topics/testing/testing_android.jd
index d4b0dcc..6f3048c 100755
--- a/docs/html/guide/topics/testing/testing_android.jd
+++ b/docs/html/guide/topics/testing/testing_android.jd
@@ -625,9 +625,8 @@
</p>
<p>
When possible, you should run these tests on an actual device. If this is not possible, you can
- use the <a href="{@docRoot}guide/developing/tools/emulator.html">Android Emulator</a> with
- <a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a> configured for
- the hardware, screens, and versions you want to test.
+ use the <a href="{@docRoot}guide/developing/devices/emulator.html">Android Emulator</a> with
+ Android Virtual Devices configured for the hardware, screens, and versions you want to test.
</p>
<h2 id="NextSteps">Next Steps</h2>
<p>
diff --git a/docs/html/guide/topics/ui/declaring-layout.jd b/docs/html/guide/topics/ui/declaring-layout.jd
index 843414a..c348767 100644
--- a/docs/html/guide/topics/ui/declaring-layout.jd
+++ b/docs/html/guide/topics/ui/declaring-layout.jd
@@ -47,11 +47,11 @@
Plugin for Eclipse</a> offers a layout preview of your XML —
with the XML file opened, select the <strong>Layout</strong> tab.</li>
<li>You should also try the
- <a href="{@docRoot}guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a> tool,
+ <a href="{@docRoot}guide/developing/debugging/debugging-ui.html#hierarchyViewer">Hierarchy Viewer</a> tool,
for debugging layouts — it reveals layout property values,
draws wireframes with padding/margin indicators, and full rendered views while
you debug on the emulator or device.</li>
- <li>The <a href="{@docRoot}guide/developing/tools/layoutopt.html">layoutopt</a> tool lets
+ <li>The <a href="{@docRoot}guide/developing/debugging/debugging-ui.html#layoutopt">layoutopt</a> tool lets
you quickly analyze your layouts and hierarchies for inefficiencies or other problems.</li>
</div>
</div>
diff --git a/docs/html/guide/tutorials/hello-world.jd b/docs/html/guide/tutorials/hello-world.jd
index 6e315b2..11e6497 100644
--- a/docs/html/guide/tutorials/hello-world.jd
+++ b/docs/html/guide/tutorials/hello-world.jd
@@ -23,9 +23,11 @@
great plugin that handles your project creation and management to greatly speed-up your
development cycles.</p>
-<p>If you're not using Eclipse, that's okay. Familiarize yourself with
-<a href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.
-You can then return to this tutorial and ignore anything about Eclipse.</p>
+<p>If you are not using Eclipse, the tools provided by the Android SDK are accessible
+on the command line, so you can choose your IDE or text editor.
+For more information about developing with the Android SDK tools, see
+the <a href="{@docRoot}guide/developing/index.html">Overview</a>
+section for developing on Android.</p>
<p>Before you start, you should already have the very latest SDK installed, and if you're using
Eclipse, you should have installed the ADT plugin as well. If you have not installed these, see
@@ -562,5 +564,6 @@
<p>This creates the required folders and files for the project at the location
defined by the <em>path</em>.</p>
- <p>For more information on how to use the SDK tools to create and build projects, please read
-<a href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.</p>
+ <p>For more information on how to use the SDK tools to create and build projects on the command line, read
+<a href="{@docRoot}guide/developing/projects/index.html">Creating and Managing Projects on the Command Line</a> and
+<a href="{@docRoot}guide/developing/building/building-cmdline.html">Building and Running Apps on the Command Line</a>.</p>
diff --git a/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd b/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd
index 0d59b56..34f7063 100644
--- a/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd
+++ b/docs/html/guide/tutorials/notepad/notepad-extra-credit.jd
@@ -65,6 +65,6 @@
<p>The Android Eclipse plugin not only offers excellent debugging support for
your application development, but also superb profiling support. You can also
-try using <a href="{@docRoot}guide/developing/tools/traceview.html">Traceview</a> to profile your application. If your application is running too slow, this can help you
+try using <a href="{@docRoot}guide/developing/debugging/debugging-tracing.html">Traceview</a> to profile your application. If your application is running too slow, this can help you
find the bottlenecks and fix them.</p>
diff --git a/docs/html/guide/webapps/debugging.jd b/docs/html/guide/webapps/debugging.jd
index ee4b723..c0dce48 100644
--- a/docs/html/guide/webapps/debugging.jd
+++ b/docs/html/guide/webapps/debugging.jd
@@ -18,7 +18,7 @@
<h2>See also</h2>
<ol>
- <li><a href="{@docRoot}guide/developing/debug-tasks.html">Debugging Tasks</a></li>
+ <li><a href="{@docRoot}guide/developing/debugging/index.html">Debugging</a></li>
</ol>
</div>
@@ -46,8 +46,8 @@
<strong>Device > Run logcat</strong>. When using the <a href="{@docRoot}sdk/eclipse-adt.html">ADT
plugin for Eclipse</a>, you can also view logcat messages by opening the Logcat view, available from
<strong>Window > Show View > Other > Android > Logcat</strong>.</p>
- <p>See <a href="{@docRoot}guide/developing/debug-tasks.html">Debugging
-Tasks</a> for more information about logcat.</p>
+ <p>See <a href="{@docRoot}guide/developing/debugging/debugging-log.html">Debugging</a>
+ for more information about <codelogcat</code>.</p>
</div>
</div>
diff --git a/docs/html/resources/articles/backward-compatibility.jd b/docs/html/resources/articles/backward-compatibility.jd
index 4b1a34c..ad64dfc 100644
--- a/docs/html/resources/articles/backward-compatibility.jd
+++ b/docs/html/resources/articles/backward-compatibility.jd
@@ -245,6 +245,6 @@
to do this easily by creating "Android Virtual Devices" with different API
levels. Once you create the AVDs, you can test your application with old and new
versions of the system, perhaps running them side-by-side to see the
-differences. More information about emulator AVDs can be found <a
-href="{@docRoot}guide/developing/tools/avd.html">in the AVD documentation</a> and
+differences. More information about emulator AVDs can be found in <a
+href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a> and
from <code>emulator -help-virtual-device</code>.</p>
\ No newline at end of file
diff --git a/docs/html/resources/articles/layout-tricks-merge.jd b/docs/html/resources/articles/layout-tricks-merge.jd
index 00e0479..95409e4 100644
--- a/docs/html/resources/articles/layout-tricks-merge.jd
+++ b/docs/html/resources/articles/layout-tricks-merge.jd
@@ -44,7 +44,7 @@
<div style="text-align: center;"><img src="images/merge1.jpg" alt="A FrameLayout is used to overlay a title on top of an image"></div>
<p>Things get more interesting when you inspect the result with <a
-href="{@docRoot}guide/developing/tools/hierarchy-viewer.html">HierarchyViewer</a>.
+href="{@docRoot}guide/developing/debugging/debugging-ui.html#hierarchyViewer">HierarchyViewer</a>.
If you look closely at the resulting tree, you will notice that the
<code>FrameLayout</code> defined in our XML file (highlighted in blue below) is
the sole child of another <code>FrameLayout</code>:</p>
diff --git a/docs/html/resources/dashboard/platform-versions.jd b/docs/html/resources/dashboard/platform-versions.jd
index 7416764..21d1ffb 100644
--- a/docs/html/resources/dashboard/platform-versions.jd
+++ b/docs/html/resources/dashboard/platform-versions.jd
@@ -52,8 +52,7 @@
<div class="dashboard-panel">
<img alt="" height="250" width="460"
-src="http://chart.apis.google.com/chart?&cht=p&chs=460x250&chd=t:6.3,10.6,0.1,39.6,43.4&chl
-=Android%201.5|Android%201.6|Other*|Android%202.1|Android%202.2&chco=c4df9b,6fad0c" />
+src="http://chart.apis.google.com/chart?&cht=p&chs=460x250&chd=t:4.7,7.9,35.2,51.8,0.4&chl=Android%201.5|Android%201.6|Android%202.1|Android%202.2|Android%202.3&chco=c4df9b,6fad0c" />
<table>
<tr>
@@ -61,15 +60,17 @@
<th>API Level</th>
<th>Distribution</th>
</tr>
-<tr><td>Android 1.5</td><td>3</td><td>6.3%</td></tr>
-<tr><td>Android 1.6</td><td>4</td><td>10.6%</td></tr>
-<tr><td>Android 2.1</td><td>7</td><td>39.6%</td></tr>
-<tr><td>Android 2.2</td><td>8</td><td>43.4%</td></tr>
+<tr><td>Android 1.5</td><td>3</td><td>4.7%</td></tr>
+<tr><td>Android 1.6</td><td>4</td><td>7.9%</td></tr>
+<tr><td>Android 2.1</td><td>7</td><td>35.2%</td></tr>
+<tr><td>Android 2.2</td><td>8</td><td>51.8%</td></tr>
+<tr><td>Android 2.3</td><td>9</td><td>0.4%</td></tr>
</table>
-<p><em>Data collected during two weeks ending on December 1, 2010</em></p>
+<p><em>Data collected during two weeks ending on January 4, 2011</em></p>
+<!--
<p style="font-size:.9em">* <em>Other: 0.1% of devices running obsolete versions</em></p>
-
+-->
</div><!-- end dashboard-panel -->
@@ -95,17 +96,9 @@
<div class="dashboard-panel">
<img alt="" height="250" width="660" style="padding:5px;background:#fff"
-src="http://chart.apis.google.com/chart?&cht=lc&chs=660x250&chxt=x,y,r&chxr=0,0,12|1,0,100|2,0,100&
-chxl=0:|2010/06/01|06/15|07/01|07/15|08/01|08/15|09/01|09/15|10/01|10/15|11/01|11/15|2010/12/01|1:|0
-%25|25%25|50%25|75%25|100%25|2:|0%25|25%25|50%25|75%25|100%25&chxp=0,0,1,2,3,4,5,6,7,8,9,10,11,12&
-chxtc=0,5&chd=t:100.3,100.8,99.7,99.8,99.8,99.7,99.8,99.9,99.9,99.9,99.9,99.9,99.9|72.7,76.1,78.4,80
-.9,84.3,86.5,87.9,89.2,90.2,91.1,92.0,92.7,93.6|45.9,51.0,54.9,58.8,64.0,68.1,70.3,72.1,73.8,75.3,77
-.0,79.0,83.0|0.8,1.2,1.8,3.3,4.3,11.3,27.8,32.1,33.4,34.5,36.2,38.3,43.4&chm=tAndroid%201.5,7caa36,0
-,0,15,,t::-5|b,c3df9b,0,1,0|tAndroid%201.6,5b831d,1,0,15,,t::-5|b,aadb5e,1,2,0|tAndroid%202.1,38540b
-,2,0,15,,t::-5|b,91da1e,2,3,0|tAndroid%202.2,131d02,3,5,15,,t::-5|B,6fad0c,3,4,0&chg=7,25&chdl=
-Android%201.5|Android%201.6|Android%202.1|Android%202.2&chco=add274,94d134,73ad18,507d08" />
+src="http://chart.apis.google.com/chart?&cht=lc&chs=660x250&chxt=x,x,y,r&chxr=0,0,12|1,0,12|2,0,100|3,0,100&chxl=0%3A%7C07/01%7C07/15%7C08/01%7C08/15%7C09/01%7C09/15%7C10/01%7C10/15%7C11/01%7C11/15%7C12/01%7C12/15%7C01/01%7C1%3A%7C2010%7C%7C%7C%7C%7C%7C%7C%7C%7C%7C%7C%7C2011%7C2%3A%7C0%25%7C25%25%7C50%25%7C75%25%7C100%25%7C3%3A%7C0%25%7C25%25%7C50%25%7C75%25%7C100%25&chxp=0,0,1,2,3,4,5,6,7,8,9,10,11,12&chxtc=0,5&chd=t:99.7,99.8,99.8,99.7,99.8,99.9,99.9,99.9,100.0,99.9,99.8,99.7,99.6|78.4,80.9,84.3,86.5,87.9,89.2,90.2,91.1,92.0,92.7,93.4,94.1,94.8|54.9,58.8,64.0,68.1,70.3,72.1,73.8,75.3,77.4,79.6,82.2,84.4,86.8|1.8,3.3,4.3,11.3,27.8,32.1,33.4,34.5,37.1,40.5,44.3,47.7,51.4&chm=tAndroid 1.5,7caa36,0,0,15,,t::-5|b,c3df9b,0,1,0|tAndroid 1.6,5b831d,1,0,15,,t::-5|b,aadb5e,1,2,0|tAndroid 2.1,38540b,2,0,15,,t::-5|b,91da1e,2,3,0|tAndroid 2.2,131d02,3,3,15,,t::-5|B,6fad0c,3,4,0&chg=7,25&chdl=Android 1.5|Android 1.6|Android 2.1|Android 2.2&chco=add274,94d134,73ad18,507d08" />
-<p><em>Last historical dataset collected during two weeks ending on December 1, 2010</em></p>
+<p><em>Last historical dataset collected during two weeks ending on January 4, 2011</em></p>
</div><!-- end dashboard-panel -->
diff --git a/docs/html/resources/faq/commontasks.jd b/docs/html/resources/faq/commontasks.jd
index 1173725..807df08 100644
--- a/docs/html/resources/faq/commontasks.jd
+++ b/docs/html/resources/faq/commontasks.jd
@@ -97,7 +97,7 @@
the device, are described below.
The list of files you'll need for your application are described in <a href="#filelist">List
of Files for an Android Application</a>. </li>
- <li><strong><a href="{@docRoot}guide/developing/other-ide.html#buildingwithant">Build and install your
+ <li><strong><a href="{@docRoot}guide/developing/building/building-cmdline.html">Build and install your
package</a>.</strong> The Android SDK has some nice tools for generating
projects and debugging code. </li>
</ol>
diff --git a/docs/html/resources/faq/troubleshooting.jd b/docs/html/resources/faq/troubleshooting.jd
index f3252b0..05a7ddab 100644
--- a/docs/html/resources/faq/troubleshooting.jd
+++ b/docs/html/resources/faq/troubleshooting.jd
@@ -5,7 +5,8 @@
<p>Here are some tips and tricks for common Android errors. Don't forget to use the
- ddms logcat capability to get a deeper view when errors occur. See <a href="{@docRoot}guide/developing/debug-tasks.html">Debugging</a> for more debugging tips. </p>
+ ddms logcat capability to get a deeper view when errors occur.
+ See the <a href="{@docRoot}guide/developing/debugging/index.html">Debugging</a> documentation for more information.</p>
<ul>
<li><a href="#installeclipsecomponents">ADT Installation Error: "requires plug-in org.eclipse.wst.sse.ui".</a></li>
<li><a href="#nodevice">ADB reports "no device" when an emulator is running</a></li>
@@ -282,9 +283,10 @@
<p>If you get an error message such as "Could not load /sdcard/gestures.
Make sure you have a mounted SD card," be sure that your target AVD has an
-SD card. To create an AVD that has an SD card, use the
-<a href="{@docRoot}guide/developing/tools/avd.html#options"><code>-c</code>
-option</a> in the <code>android create avd</code> command.</p>
+SD card. To create an AVD that has an SD card, specify one when creating
+an AVD with the AVD manager. See
+<a href="{@docRoot}guide/developing/devices/managing-avds.html#createavd">
+Creating and Managing AVDs with AVD Manager</a> for more information.</p>
<h2 id="signingcalendar">I can't compile my app because the build tools generated an expired debug certificate</h2>
diff --git a/docs/html/resources/resources_toc.cs b/docs/html/resources/resources_toc.cs
index 1c1ece9..a2580a6 100644
--- a/docs/html/resources/resources_toc.cs
+++ b/docs/html/resources/resources_toc.cs
@@ -87,8 +87,7 @@
?>
<li>
- <h2><span class="en">More</span>
- </h2>
+ <h2><span class="en">More</span></h2>
<ul>
<li><a href="<?cs var:toroot ?>resources/faq/commontasks.html">
<span class="en">Common Tasks </span>
diff --git a/docs/html/resources/samples/index.jd b/docs/html/resources/samples/index.jd
index cbe6ca3..beecd67 100644
--- a/docs/html/resources/samples/index.jd
+++ b/docs/html/resources/samples/index.jd
@@ -18,6 +18,13 @@
-->
<dl>
+ <dt><a href="AccelerometerPlay/index.html">Accelerometer Play</a></dt>
+ <dd>An example that demonstrates how to use accelerometer readings
+ in an application.</dd>
+
+ <dt><a href="AccessibilityService/index.html">Accessibility Service</a></dt>
+ <dd>An example that demonstrates the use of accessibility APIs.</dd>
+
<dt><a href="ApiDemos/index.html">API Demos</a></dt>
<dd>A variety of small applications that demonstrate an extensive collection of
framework topics.</dd>
diff --git a/docs/html/resources/tutorials/testing/activity_test.jd b/docs/html/resources/tutorials/testing/activity_test.jd
index ec878d2..afb9e3c 100644
--- a/docs/html/resources/tutorials/testing/activity_test.jd
+++ b/docs/html/resources/tutorials/testing/activity_test.jd
@@ -239,7 +239,8 @@
<p>
In this tutorial, you will use the Android emulator to run applications. The emulator needs
an Android Virtual Device (AVD) with an API level equal to or higher than the one you set for the projects in the previous step.
- To find out how to check this and create the right AVD if necessary, see <a href="{@docRoot}guide/developing/eclipse-adt.html#AVD">Creating an AVD</a>.
+ To find out how to check this and create the right AVD if necessary,
+ see <a href="{@docRoot}guide/developing/devices/managing-avds.html">Creating an AVD</a>.
</p>
<p>
As a test of the AVD and emulator, run the SpinnerActivity application in Eclipse with ADT. When it starts,
@@ -1237,7 +1238,7 @@
also use this tool to run the test application from the command line.
</li>
<li>
- <a href="{@docRoot}guide/developing/tools/othertools.html#android">android</a> - Manages projects and test projects. This tool also manages AVDs and Android platforms.
+ <a href="{@docRoot}guide/developing/tools/android.html">android</a> - Manages projects and test projects. This tool also manages AVDs and Android platforms.
</li>
</ul>
<p>
diff --git a/docs/html/resources/tutorials/views/hello-mapview.jd b/docs/html/resources/tutorials/views/hello-mapview.jd
index a3fa548..836d22c 100644
--- a/docs/html/resources/tutorials/views/hello-mapview.jd
+++ b/docs/html/resources/tutorials/views/hello-mapview.jd
@@ -17,13 +17,13 @@
<p>After installing the Google APIs add-on in your SDK, set your project properties to use the build
target called "Google APIs by Google Inc.". See the instructions for setting a build
-target in <a href="{@docRoot}guide/developing/eclipse-adt.html">Developing in
-Eclipse with ADT</a> or <a
-href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>,
-as appropriate for your environment. </p>
+target in <a href="{@docRoot}guide/developing/projects/projects-eclipse.html#CreatingAProject">
+Creating and Managing Projects in Eclipse</a> or <a
+href="{@docRoot}guide/developing/projects/projects-cmdline.html#CreatingAProject">
+Creating and Managing Projects on the Command Line</a>, as appropriate for your environment.</p>
<p>You will also need to set up a new AVD that uses the same Google APIs deployment target. See <a
-href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a> for
+href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a> for
more information.</p>
<p>For reference material, see the <a
@@ -127,7 +127,7 @@
</pre>
</li>
<li>That's all there is to it. Run the application. (Remember, you must have an <a
-href="{@docRoot}guide/developing/tools/avd.html">AVD</a> configured to use the Google APIs
+href="{@docRoot}guide/developing/devices/index.html">AVD</a> configured to use the Google APIs
target, or be using a development device that includes the Maps library.)</li>
</ol>
@@ -223,7 +223,7 @@
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
- dialog.setMessage(item.getSnippet())
+ dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
diff --git a/docs/html/sdk/RELEASENOTES.jd b/docs/html/sdk/RELEASENOTES.jd
index a94eba7..bf091e9 100644
--- a/docs/html/sdk/RELEASENOTES.jd
+++ b/docs/html/sdk/RELEASENOTES.jd
@@ -64,7 +64,7 @@
skins. </li>
<li>Android SDK and AVD Manager, a graphical UI to let you manage your
SDK and AVD environments more easily. The tool lets you create and manage
-your <a href="{@docRoot}guide/developing/tools/avd.html">Android Virtual
+your <a href="{@docRoot}guide/developing/devices/managing-avds.html">Android Virtual
Devices</a> and download new SDK packages (such as platform versions and
add-ons) into your environment.</li>
<li>Improved support for test packages in New Project Wizard</li>
@@ -222,7 +222,7 @@
density for each skin, to create any combination of resolution/density (WVGA
with medium density, for instance). To do so, use the <code>android</code> tool
command line to create a new AVD that uses a custom hardware configuration. See
-<a href="{@docRoot}guide/developing/tools/avd.html#createavd">Creating an
+<a href="{@docRoot}guide/developing/devices/managing-avds.html#createavd">Creating an
AVD</a> for more information.</p>
<h3>Other Notes and Resolved Issues</h3>
@@ -330,7 +330,7 @@
Android 1.5). The tools are updated to let you deploy your application
on any platform in the SDK, which helps you ensure forward-compatibility and,
if applicable, backward-compatibility.</li>
- <li>Introduces <a href="{@docRoot}guide/developing/tools/avd.html">Android
+ <li>Introduces <a href="{@docRoot}guide/developing/devices/managing-avds.html">Android
Virtual Devices</a> — (AVD) configurations of options that you
run in the emulator to better model actual devices. Each AVD gets its
own dedicated storage area, making it much easier to work with multiple emulators
@@ -407,7 +407,7 @@
available to use.</p>
<p>For more information about AVDs, see <a
-href="{@docRoot}guide/developing/tools/avd.html">Android Virtual Devices</a>
+href="{@docRoot}guide/developing/devices/index.html">Creating and Managing Virtual Devices</a>
<h3>Other Notes</h3>
@@ -585,8 +585,7 @@
<p>The USB driver files are located in the
<code><SDK>/usb_driver</code> directory. For details and
installation instructions, see <a
-href="{@docRoot}guide/developing/device.html#setting-up">Setting Up a
-Device for Development</a>.</p>
+href="{@docRoot}guide/developing/device.html#setting-up">Connecting Hardware Devices</a>.</p>
</p>
<h3>Resolved Issues, Changes</h3>
diff --git a/docs/html/sdk/android-2.3-highlights.jd b/docs/html/sdk/android-2.3-highlights.jd
index 1a603af..d8614d3 100644
--- a/docs/html/sdk/android-2.3-highlights.jd
+++ b/docs/html/sdk/android-2.3-highlights.jd
@@ -40,18 +40,18 @@
<div class="video">
<object width="278" height="180">
-<param name="movie" value="http://www.youtube.com/v/yAZYSVr2Bhc&hl=en&fs=1&"></param>
+<param name="movie" value="http://www.youtube.com/v/Jx3pdWBlZ34?hl=en&fs=1"></param>
<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess"
value="always"></param>
-<embed src="http://www.youtube.com/v/yAZYSVr2Bhc&hl=en&fs=1&" type="application/x-shockwave-flash"
+<embed src="http://www.youtube.com/v/Jx3pdWBlZ34?hl=en&fs=1" type="application/x-shockwave-flash"
allowscriptaccess="always" allowfullscreen="true" width="278" height="180"></embed>
</object>
</div>
<p>The Android 2.3 platform introduces many new and exciting features for
-users and developers. This document provides a glimpse at some of the new user features
+users and developers. This document provides a glimpse at some of the new features
and technologies in Android 2.3. For detailed information about the new developer APIs, see the <a
-href="android-2.3.html#api">Android 2.3 version notes</a>.</p>
+href="android-2.3.html">Android 2.3 version notes</a>.</p>
<ul>
<li><a href="#UserFeatures">New User Features</a></li>
@@ -251,7 +251,8 @@
to recognize complex user gestures and motions, such as tilt, spin, thrust, and
slice. </p>
-<p style="margin-top:1.25em;margin-bottom:.75em;"><strong>Low-latency native
+
+<p style="margin-top:1.25em;margin-bottom:.75em;"><strong>Open API for native
audio</strong></p>
<p>The platform provides a software implementation of <a
@@ -405,7 +406,7 @@
<ul>
<li>Dalvik VM:
<ul>
-<li>Concurrent Garbage Collector (target sub-3ms pauses)</li>
+<li>Concurrent garbage collector (target sub-3ms pauses)</li>
<li>Adds further JIT (code-generation) optimizations</li>
<li>Improved code verification</li>
<li>StrictMode debugging, for identifying performance and memory issues</li>
@@ -438,5 +439,5 @@
</ul>
<p>For more information about the new developer APIs, see the <a
-href="android-2.3.html#api">Android 2.3 version notes</a> and the <a
+href="android-2.3.html">Android 2.3 version notes</a> and the <a
href="{@docRoot}sdk/api_diff/9/changes.html">API Differences Report</a>.</p>
diff --git a/docs/html/sdk/android-2.3.jd b/docs/html/sdk/android-2.3.jd
index e00674f..734d97b 100644
--- a/docs/html/sdk/android-2.3.jd
+++ b/docs/html/sdk/android-2.3.jd
@@ -225,7 +225,7 @@
android:name="android.hardware.sensor.gyroscope"
android:required="true"></code> to the application manifest.</p>
-<p>For API details, see {@link android.hardware.Sensor}</p>
+<p>For API details, see {@link android.hardware.Sensor}.</p>
<h3 id="cameras">Multiple cameras support</h3>
@@ -242,9 +242,9 @@
android.hardware.Camera#getCameraInfo(int,CameraInfo) getCameraInfo()} methods in the {@link
android.hardware.Camera} class let applications query for the cameras available
and open the camera that they need.</li>
-<li>New {@link android.media.CamcorderProfile get(int,int) method lets
-applications retrieve a CamcorderProfile for a specific camera. </li>
-<li>New {@link android media.CameraProfile#getJpegEncodingQualityParameter(int, int)
+<li>New {@link android.media.CamcorderProfile#get get()} method lets
+applications retrieve a {@link android.media.CamcorderProfile} for a specific camera. </li>
+<li>New {@link android.media.CameraProfile#getJpegEncodingQualityParameter(int, int)
getJpegEncodingQualityParameter()} lets applications obtain the still-image
capture quality level for a specific camera.</li>
</ul>
@@ -389,19 +389,19 @@
touch filtering is appropriate to ensure the security of user actions such as
granting a permission request, making a purchase, or clicking on an
advertisement. For details, see the <a
-href="{@docRoot}reference/android/view/View.html#security">View class
+href="{@docRoot}reference/android/view/View.html#Security">View class
documentation</a>.</li>
<li>New <code>filterTouchesWhenObscured</code> attribute for view elements,
which declares whether to filter touches when the view's window is obscured by
another visible window. When set to <code>"true"</code>, the view will not
receive touches whenever a toast, dialog or other window appears above the
view's window. Refer to <a
-href="{@docRoot}reference/android/view/View.html#security">View security
+href="{@docRoot}reference/android/view/View.html#Security">View security
documentation</a> for details.</li>
</ul>
<p class="note">To look at sample code for touch filtering, see
-<a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/SecureView.html">SurfaceView.java</a>
+<a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/view/SecureView.html">SecureView.java</a>
in the ApiDemos sample application.</p>
</li>
diff --git a/docs/html/sdk/eclipse-adt.jd b/docs/html/sdk/eclipse-adt.jd
index 0144eb4..d0fa727 100644
--- a/docs/html/sdk/eclipse-adt.jd
+++ b/docs/html/sdk/eclipse-adt.jd
@@ -152,9 +152,9 @@
"export signed/unsigned application package", ADT does <em>not</em> insert it.
If you manually set <code>debuggable="true"</code> in the manifest file, then release builds will
actually create a debug build (it does not remove it if you placed it there).</p></li>
- <li>Automatic <a href="{@docRoot}guide/developing/tools/proguard.html">Proguard</a> support in
-release builds. For it to work, you need to have a <code>proguard.config</code>
- property in the <code>default.properties</code> file that points to a proguard config file.</li>
+ <li>Automatic <a href="{@docRoot}guide/developing/tools/proguard.html">ProGuard</a> support in
+ release builds. For it to work, you need to have a <code>proguard.config</code>
+ property in the <code>default.properties</code> file that points to a ProGuard config file.</li>
<li>Completely rewritten Visual Layout Editor. (This is still a work in progress.) Now includes:
<ul>
<li>Full drag and drop from palette to layout for all Layout classes.</li>
@@ -225,7 +225,7 @@
with no name restriction. They can even be in subfolder such as
<code>src/java</code>. If you are already working with library projects created
in ADT 0.9.7, see <a
-href="{@docRoot}guide/developing/eclipse-adt.html#libraryMigrating">Migrating
+href="{@docRoot}guide/developing/projects/index.html#libraryMigrating">Migrating
library projects to ADT 0.9.8</a> for important information about moving
to the new ADT environment.</li>
<li>Adds support for library projects that depend on other library
@@ -263,8 +263,7 @@
library project from other Android projects and, at build time, the tools
compile the shared code and resources as part of the dependent applications.
More information about this feature is available in the <a
-href="{@docRoot}guide/developing/eclipse-adt.html#libraryProject">Developing
-in Eclipse with ADT</a> document. </p>
+href="{@docRoot}guide/developing/projects/index.html#LibraryProjects">Creating and Managing Projects</a> document. </p>
<p>If you are not developing in Eclipse, <a
href="tools-notes.html">SDK Tools r6</a> provides the equivalent library
project support through the Ant build system.</p>
diff --git a/docs/html/sdk/index.jd b/docs/html/sdk/index.jd
index 4153951..4113463 100644
--- a/docs/html/sdk/index.jd
+++ b/docs/html/sdk/index.jd
@@ -2,20 +2,20 @@
sdk.redirect=0
sdk.win_installer=installer_r08-windows.exe
-sdk.win_installer_bytes=TODO
-sdk.win_installer_checksum=TODO
+sdk.win_installer_bytes=32746192
+sdk.win_installer_checksum=04ce87b10a8361a1f63cf2238bbc1ee3
sdk.win_download=android-sdk_r08-windows.zip
-sdk.win_bytes=TODO
-sdk.win_checksum=TODO
+sdk.win_bytes=32696391
+sdk.win_checksum=3e0b08ade5bfa9624bce9ddc164a48cb
-sdk.mac_download=android-sdk_r08-mac_x86.zip
-sdk.mac_bytes=TODO
-sdk.mac_checksum=TODO
+sdk.mac_download=android-sdk_r08-mac_86.zip
+sdk.mac_bytes=28797617
+sdk.mac_checksum=d2e392c4e4680cbf2dfd6dbf82b662c7
-sdk.linux_download=android-sdk_r08-linux_x86.tgz
-sdk.linux_bytes=TODO
-sdk.linux_checksum=TODO
+sdk.linux_download=android-sdk_r08-linux_86.tgz
+sdk.linux_bytes=26817291
+sdk.linux_checksum=3b626645b223d137d27beefbda0c94bc
@jd:body
diff --git a/docs/html/sdk/installing.jd b/docs/html/sdk/installing.jd
index 9de247a..e8d97e7 100644
--- a/docs/html/sdk/installing.jd
+++ b/docs/html/sdk/installing.jd
@@ -148,8 +148,9 @@
<p>If you prefer to work in a different IDE, you do not need to
install Eclipse or ADT, instead, you can directly use the SDK tools to build and
-debug your application. The developer guide has more information about <a
-href="{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.</p>
+debug your application. The <a href="{@docRoot}guide/developing/index.html">Overview</a>
+section of the developer guide outlines the major steps that you need to complete
+when developing in Eclipse or other IDEs.</p>
@@ -547,9 +548,9 @@
<li>Get an overview of the <a
href="{@docRoot}guide/developing/tools/index.html">development
tools</a> that are available to you</li>
- <li>Read how to develop <a
- href="{@docRoot}guide/developing/eclipse-adt.html">in Eclipse/ADT</a> or
- <a href="{@docRoot}guide/developing/other-ide.html">in other IDEs</a>
+ <li>Read the <a
+ href="{@docRoot}guide/developing/index.html">Overview</a>
+ for how to develop an Android application.
</li>
<li>Read <a href="{@docRoot}guide/developing/device.html">Developing on a Device</a> to set up an
Android-powered device to run and test your application.</li>
diff --git a/docs/html/sdk/ndk/index.jd b/docs/html/sdk/ndk/index.jd
index 19f4d02..8b27f37 100644
--- a/docs/html/sdk/ndk/index.jd
+++ b/docs/html/sdk/ndk/index.jd
@@ -1,16 +1,16 @@
ndk=true
-ndk.win_download=android-ndk-r4b-windows.zip
-ndk.win_bytes=45792835
-ndk.win_checksum=e397145e155a639be53ee4b6db8ad511
+ndk.win_download=android-ndk-r5-windows.zip
+ndk.win_bytes=62217450
+ndk.win_checksum=59cbb02d91d74e9c5c7278d94c989e80
-ndk.mac_download=android-ndk-r4b-darwin-x86.zip
-ndk.mac_bytes=50586041
-ndk.mac_checksum=41dbd54335fb828ee408eab17103a1b0
+ndk.mac_download=android-ndk-r5-darwin-x86.tar.bz2
+ndk.mac_bytes=50210863
+ndk.mac_checksum=9dee8e4cb529a5619e9b8d1707478c32
-ndk.linux_download=android-ndk-r4b-linux-x86.zip
-ndk.linux_bytes=49464776
-ndk.linux_checksum=2deabcb125c219b34140975b710f00ec
+ndk.linux_download=android-ndk-r5-linux-x86.tar.bz2
+ndk.linux_bytes=44362746
+ndk.linux_checksum=49d5c35ec02bafc074842542c58b7eb3
page.title=Android NDK
@jd:body
@@ -64,7 +64,7 @@
onclick="return toggleDiv(this)"><img src="{@docRoot}assets/images/triangle-opened.png"
class="toggle-img"
height="9px"
- width="9px" /> Android NDK, Revision 5</a> <em>(November 2010)</em>
+ width="9px" /> Android NDK, Revision 5</a> <em>(December 2010)</em>
<div class="toggleme">
<p>This release of the NDK includes many new APIs, most of which are introduced to
diff --git a/docs/html/sdk/ndk/overview.jd b/docs/html/sdk/ndk/overview.jd
index 56b9201..2562a25 100644
--- a/docs/html/sdk/ndk/overview.jd
+++ b/docs/html/sdk/ndk/overview.jd
@@ -275,16 +275,19 @@
<li>If you are developing in Eclipse with ADT, use the New Project Wizard to create a new
Android project for each sample, using the "Import from Existing Source" option and importing
the source from <code><ndk>/apps/<app_name>/project/</code>. Then, set up an AVD,
- if necessary, and build/run the application in the emulator. For more information about
- creating a new Android project in Eclipse, see <a href=
- "{@docRoot}guide/developing/eclipse-adt.html">Developing in Eclipse</a>.</li>
+ if necessary, and build/run the application in the emulator.</li>
<li>If you are developing with Ant, use the <code>android</code> tool to create the build file
for each of the sample projects at <code><ndk>/apps/<app_name>/project/</code>.
Then set up an AVD, if necessary, build your project in the usual way, and run it in the
- emulator. For more information, see <a href=
- "{@docRoot}guide/developing/other-ide.html">Developing in Other IDEs</a>.</li>
+ emulator.</li>
+
</ul>
+
+ <p>For more information about developing with the Android SDK tools and what
+ you need to do to create, build, and run your applications, see
+ the <a href="{@docRoot}guide/developing/index.html">Overview</a>
+ section for developing on Android.</p>
<h4 id="hello-jni">Exploring the hello-jni Sample</h4>
diff --git a/docs/html/sdk/sdk_toc.cs b/docs/html/sdk/sdk_toc.cs
index 9c7ad89..9e1ff9c 100644
--- a/docs/html/sdk/sdk_toc.cs
+++ b/docs/html/sdk/sdk_toc.cs
@@ -98,7 +98,7 @@
<ul>
<li><a href="<?cs var:toroot ?>sdk/tools-notes.html">SDK Tools, r8</a> <span class="new">new!</span></li>
<li><a href="<?cs var:toroot ?>sdk/win-usb.html">USB Driver for
- Windows, r3</a>
+ Windows, r4</a> <span class="new">new!</span>
</li>
</ul>
</li>
diff --git a/docs/html/sdk/tools-notes.jd b/docs/html/sdk/tools-notes.jd
index f8d7071..fb8636e 100644
--- a/docs/html/sdk/tools-notes.jd
+++ b/docs/html/sdk/tools-notes.jd
@@ -183,9 +183,8 @@
library project from other Android projects and, at build time, the tools
compile the shared code and resources as part of the dependent applications.
More information about this feature is available in the <a
-href="{@docRoot}guide/developing/other-ide.html#libraryProject">Developing
-in Other IDEs</a> document.</p>
-<p>If you are developing in Eclipse, <a href="eclipse-adt.html">ADT 0.9.7</a>
+href="{@docRoot}guide/developing/projects/index.html#LibraryProjects">Creating and Managing Projects</a> document.</p>
+<p>If you are developing in Eclipse, <a href="eclipse-adt.html">ADT</a>
provides the equivalent library project support.</p>
</dd>
</dl>
diff --git a/docs/html/sdk/win-usb.jd b/docs/html/sdk/win-usb.jd
index bb0dde6..1f74ffe 100644
--- a/docs/html/sdk/win-usb.jd
+++ b/docs/html/sdk/win-usb.jd
@@ -82,7 +82,21 @@
<div class="toggleable opened">
<a href="#" onclick="return toggleDiv(this)">
- <img src="{@docRoot}assets/images/triangle-opened.png" class="toggle-img" height="9px" width="9px" />
+ <img src="{@docRoot}assets/images/triangle-opened.png" class="toggle-img" height="9px"
+width="9px" />
+USB Driver for Windows, Revision 4</a> <em>(December 2010)</em>
+ <div class="toggleme">
+
+<dl>
+<dt><p>Adds support for the Nexus S.</p></dt>
+</dl>
+ </div>
+</div>
+
+<div class="toggleable closed">
+ <a href="#" onclick="return toggleDiv(this)">
+ <img src="{@docRoot}assets/images/triangle-closed.png" class="toggle-img" height="9px"
+width="9px" />
USB Driver for Windows, Revision 3</a> <em>(January 2010)</em>
<div class="toggleme">
@@ -126,10 +140,11 @@
Android-powered
devices:</p>
<ul>
- <li>T-Mobile G1* / ADP1</li>
- <li>T-Mobile myTouch 3G* / Google Ion</li>
+ <li>ADP1 / T-Mobile G1*</li>
+ <li>ADP2 / Google Ion / T-Mobile myTouch 3G*</li>
<li>Verizon Droid*</li>
<li>Nexus One</li>
+ <li>Nexus S</li>
</ul>
<p>* <em>Or similar hardware on other carriers</em></p>
<p>Any additional devices will require Windows drivers provided by
diff --git a/graphics/java/android/graphics/Canvas.java b/graphics/java/android/graphics/Canvas.java
index 66c6d81..184620b 100644
--- a/graphics/java/android/graphics/Canvas.java
+++ b/graphics/java/android/graphics/Canvas.java
@@ -85,8 +85,12 @@
@Override
protected void finalize() throws Throwable {
- if (mNativeCanvas != 0) {
- finalizer(mNativeCanvas);
+ try {
+ if (mNativeCanvas != 0) {
+ finalizer(mNativeCanvas);
+ }
+ } finally {
+ super.finalize();
}
}
}
@@ -137,6 +141,8 @@
* Returns null.
*
* @deprecated This method is not supported and should not be invoked.
+ *
+ * @hide
*/
@Deprecated
protected GL getGL() {
diff --git a/graphics/java/android/graphics/SurfaceTexture.java b/graphics/java/android/graphics/SurfaceTexture.java
new file mode 100644
index 0000000..883c4eb
--- /dev/null
+++ b/graphics/java/android/graphics/SurfaceTexture.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2010 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.graphics;
+
+/**
+ * Captures frames from an image stream as an OpenGL ES texture.
+ *
+ * <p>The image stream may come from either video playback or camera preview. A SurfaceTexture may
+ * be used in place of a SurfaceHolder when specifying the output destination of a MediaPlayer or
+ * Camera object. This will cause all the frames from that image stream to be sent to the
+ * SurfaceTexture object rather than to the device's display. When {@link #updateTexImage} is
+ * called, the contents of the texture object specified when the SurfaceTexture was created is
+ * updated to contain the most recent image from the image stream. This may cause some frames of
+ * the stream to be skipped.
+ *
+ * <p>The texture object uses the GL_TEXTURE_EXTERNAL_OES texture target, which is defined by the
+ * OES_EGL_image_external OpenGL ES extension. This limits how the texture may be used.
+ */
+public class SurfaceTexture {
+
+ @SuppressWarnings("unused")
+ private int mSurfaceTexture;
+
+ /**
+ * Callback interface for being notified that a new stream frame is available.
+ */
+ public interface OnFrameAvailableListener {
+ void onFrameAvailable(SurfaceTexture surfaceTexture);
+ }
+
+ /**
+ * Exception thrown when a surface couldn't be created or resized
+ */
+ public static class OutOfResourcesException extends Exception {
+ public OutOfResourcesException() {
+ }
+ public OutOfResourcesException(String name) {
+ super(name);
+ }
+ }
+
+ /**
+ * Construct a new SurfaceTexture to stream images to a given OpenGL texture.
+ *
+ * @param texName the OpenGL texture object name (e.g. generated via glGenTextures)
+ */
+ public SurfaceTexture(int texName) {
+ init(texName);
+ }
+
+ /**
+ * Register a callback to be invoked when a new image frame becomes available to the
+ * SurfaceTexture. Note that this callback may be called on an arbitrary thread, so it is not
+ * safe to call {@link #updateTexImage} without first binding the OpenGL ES context to the
+ * thread invoking the callback.
+ */
+ public void setOnFrameAvailableListener(OnFrameAvailableListener l) {
+ // TODO: Implement this!
+ }
+
+ /**
+ * Update the texture image to the most recent frame from the image stream. This may only be
+ * called while the OpenGL ES context that owns the texture is bound to the thread. It will
+ * implicitly bind its texture to the GL_TEXTURE_EXTERNAL_OES texture target.
+ */
+ public native void updateTexImage();
+
+ private native void init(int texName);
+
+ /*
+ * We use a class initializer to allow the native code to cache some
+ * field offsets.
+ */
+ private static native void nativeClassInit();
+ static { nativeClassInit(); }
+}
diff --git a/graphics/java/android/renderscript/Allocation.java b/graphics/java/android/renderscript/Allocation.java
index a4ce947..7a47c3b 100644
--- a/graphics/java/android/renderscript/Allocation.java
+++ b/graphics/java/android/renderscript/Allocation.java
@@ -53,19 +53,6 @@
public static final int USAGE_GRAPHICS_CONSTANTS = 0x0008;
- public enum CubemapLayout {
- VERTICAL_FACE_LIST (0),
- HORIZONTAL_FACE_LIST (1),
- VERTICAL_CROSS (2),
- HORIZONTAL_CROSS (3);
-
- int mID;
- CubemapLayout(int id) {
- mID = id;
- }
- }
-
-
public enum MipmapControl {
MIPMAP_NONE(0),
MIPMAP_FULL(1),
@@ -126,7 +113,7 @@
for (int ct=0; ct < d.length; ct++) {
i[ct] = d[ct].getID();
}
- subData1D(0, mType.getCount(), i);
+ copy1DRangeFrom(0, mType.getCount(), i);
}
private void validateBitmap(Bitmap b) {
@@ -139,32 +126,35 @@
public void copyFrom(int[] d) {
mRS.validate();
- subData1D(0, mType.getCount(), d);
+ copy1DRangeFrom(0, mType.getCount(), d);
}
public void copyFrom(short[] d) {
mRS.validate();
- subData1D(0, mType.getCount(), d);
+ copy1DRangeFrom(0, mType.getCount(), d);
}
public void copyFrom(byte[] d) {
mRS.validate();
- subData1D(0, mType.getCount(), d);
+ copy1DRangeFrom(0, mType.getCount(), d);
}
public void copyFrom(float[] d) {
mRS.validate();
- subData1D(0, mType.getCount(), d);
+ copy1DRangeFrom(0, mType.getCount(), d);
}
public void copyFrom(Bitmap b) {
validateBitmap(b);
mRS.nAllocationCopyFromBitmap(getID(), b);
}
- public void copyTo(Bitmap b) {
- validateBitmap(b);
- mRS.nAllocationCopyToBitmap(getID(), b);
- }
-
-
- public void subData(int xoff, FieldPacker fp) {
+ /**
+ * @hide
+ *
+ * This is only intended to be used by auto-generate code reflected from the
+ * renderscript script files.
+ *
+ * @param xoff
+ * @param fp
+ */
+ public void setOneElement(int xoff, FieldPacker fp) {
int eSize = mType.mElement.getSizeBytes();
final byte[] data = fp.getData();
@@ -178,7 +168,17 @@
}
- public void subElementData(int xoff, int component_number, FieldPacker fp) {
+ /**
+ * @hide
+ *
+ * This is only intended to be used by auto-generate code reflected from the
+ * renderscript script files.
+ *
+ * @param xoff
+ * @param component_number
+ * @param fp
+ */
+ public void setOneComponent(int xoff, int component_number, FieldPacker fp) {
if (component_number >= mType.mElement.mElements.length) {
throw new RSIllegalArgumentException("Component_number " + component_number + " out of range.");
}
@@ -214,44 +214,75 @@
}
}
- public void subData1D(int off, int count, int[] d) {
+ public void copy1DRangeFrom(int off, int count, int[] d) {
int dataSize = mType.mElement.getSizeBytes() * count;
data1DChecks(off, count, d.length * 4, dataSize);
mRS.nAllocationData1D(getID(), off, 0, count, d, dataSize);
}
- public void subData1D(int off, int count, short[] d) {
+ public void copy1DRangeFrom(int off, int count, short[] d) {
int dataSize = mType.mElement.getSizeBytes() * count;
data1DChecks(off, count, d.length * 2, dataSize);
mRS.nAllocationData1D(getID(), off, 0, count, d, dataSize);
}
- public void subData1D(int off, int count, byte[] d) {
+ public void copy1DRangeFrom(int off, int count, byte[] d) {
int dataSize = mType.mElement.getSizeBytes() * count;
data1DChecks(off, count, d.length, dataSize);
mRS.nAllocationData1D(getID(), off, 0, count, d, dataSize);
}
- public void subData1D(int off, int count, float[] d) {
+ public void copy1DRangeFrom(int off, int count, float[] d) {
int dataSize = mType.mElement.getSizeBytes() * count;
data1DChecks(off, count, d.length * 4, dataSize);
mRS.nAllocationData1D(getID(), off, 0, count, d, dataSize);
}
- public void subData2D(int xoff, int yoff, int w, int h, int[] d) {
+ public void copy2DRangeFrom(int xoff, int yoff, int w, int h, byte[] d) {
+ mRS.validate();
+ mRS.nAllocationData2D(getID(), xoff, yoff, 0, 0, w, h, d, d.length);
+ }
+
+ public void copy2DRangeFrom(int xoff, int yoff, int w, int h, short[] d) {
+ mRS.validate();
+ mRS.nAllocationData2D(getID(), xoff, yoff, 0, 0, w, h, d, d.length * 2);
+ }
+
+ public void copy2DRangeFrom(int xoff, int yoff, int w, int h, int[] d) {
mRS.validate();
mRS.nAllocationData2D(getID(), xoff, yoff, 0, 0, w, h, d, d.length * 4);
}
- public void subData2D(int xoff, int yoff, int w, int h, float[] d) {
+ public void copy2DRangeFrom(int xoff, int yoff, int w, int h, float[] d) {
mRS.validate();
mRS.nAllocationData2D(getID(), xoff, yoff, 0, 0, w, h, d, d.length * 4);
}
- public void readData(int[] d) {
+ public void copy2DRangeFrom(int xoff, int yoff, Bitmap b) {
+ mRS.validate();
+ mRS.nAllocationData2D(getID(), xoff, yoff, 0, 0, b);
+ }
+
+
+ public void copyTo(Bitmap b) {
+ validateBitmap(b);
+ mRS.nAllocationCopyToBitmap(getID(), b);
+ }
+
+ public void copyTo(byte[] d) {
mRS.validate();
mRS.nAllocationRead(getID(), d);
}
- public void readData(float[] d) {
+ public void copyTo(short[] d) {
+ mRS.validate();
+ mRS.nAllocationRead(getID(), d);
+ }
+
+ public void copyTo(int[] d) {
+ mRS.validate();
+ mRS.nAllocationRead(getID(), d);
+ }
+
+ public void copyTo(float[] d) {
mRS.validate();
mRS.nAllocationRead(getID(), d);
}
@@ -372,33 +403,41 @@
USAGE_GRAPHICS_TEXTURE);
}
+ /**
+ * Creates a cubemap allocation from a bitmap containing the
+ * horizontal list of cube faces. Each individual face must be
+ * the same size and power of 2
+ *
+ * @param rs
+ * @param b bitmap with cubemap faces layed out in the following
+ * format: right, left, top, bottom, front, back
+ * @param mips specifies desired mipmap behaviour for the cubemap
+ * @param usage bitfield specifying how the cubemap is utilized
+ *
+ **/
static public Allocation createCubemapFromBitmap(RenderScript rs, Bitmap b,
MipmapControl mips,
- CubemapLayout layout,
int usage) {
rs.validate();
int height = b.getHeight();
int width = b.getWidth();
- if (layout != CubemapLayout.VERTICAL_FACE_LIST) {
- throw new RSIllegalArgumentException("Only vertical face list supported");
- }
- if (height % 6 != 0) {
+ if (width % 6 != 0) {
throw new RSIllegalArgumentException("Cubemap height must be multiple of 6");
}
- if (height / 6 != width) {
+ if (width / 6 != height) {
throw new RSIllegalArgumentException("Only square cobe map faces supported");
}
- boolean isPow2 = (width & (width - 1)) == 0;
+ boolean isPow2 = (height & (height - 1)) == 0;
if (!isPow2) {
throw new RSIllegalArgumentException("Only power of 2 cube faces supported");
}
Element e = elementFromBitmap(rs, b);
Type.Builder tb = new Type.Builder(rs, e);
- tb.setX(width);
- tb.setY(width);
+ tb.setX(height);
+ tb.setY(height);
tb.setFaces(true);
tb.setMipmaps(mips == MipmapControl.MIPMAP_FULL);
Type t = tb.create();
@@ -410,10 +449,9 @@
return new Allocation(id, rs, t, usage);
}
- static public Allocation createCubemapFromBitmap(RenderScript rs, Bitmap b,
- CubemapLayout layout) {
+ static public Allocation createCubemapFromBitmap(RenderScript rs, Bitmap b) {
return createCubemapFromBitmap(rs, b, MipmapControl.MIPMAP_NONE,
- layout, USAGE_GRAPHICS_TEXTURE);
+ USAGE_GRAPHICS_TEXTURE);
}
static public Allocation createFromBitmapResource(RenderScript rs,
diff --git a/graphics/java/android/renderscript/FileA3D.java b/graphics/java/android/renderscript/FileA3D.java
index c3e5faf..01a9a82 100644
--- a/graphics/java/android/renderscript/FileA3D.java
+++ b/graphics/java/android/renderscript/FileA3D.java
@@ -167,47 +167,57 @@
return mFileEntries[index];
}
- // API cleanup stand-ins
- // TODO: implement ermaining loading mechanisms
- static public FileA3D createFromAsset(RenderScript rs, AssetManager mgr, String path)
- throws IllegalArgumentException {
- return null;
+ static public FileA3D createFromAsset(RenderScript rs, AssetManager mgr, String path) {
+ rs.validate();
+ int fileId = rs.nFileA3DCreateFromAsset(mgr, path);
+
+ if(fileId == 0) {
+ throw new RSRuntimeException("Unable to create a3d file from asset " + path);
+ }
+ FileA3D fa3d = new FileA3D(fileId, rs, null);
+ fa3d.initEntries();
+ return fa3d;
}
- static public FileA3D createFromFile(RenderScript rs, String path)
- throws IllegalArgumentException {
- return null;
+ static public FileA3D createFromFile(RenderScript rs, String path) {
+ int fileId = rs.nFileA3DCreateFromFile(path);
+
+ if(fileId == 0) {
+ throw new RSRuntimeException("Unable to create a3d file from " + path);
+ }
+ FileA3D fa3d = new FileA3D(fileId, rs, null);
+ fa3d.initEntries();
+ return fa3d;
}
- static public FileA3D createFromFile(RenderScript rs, File path)
- throws IllegalArgumentException {
+ static public FileA3D createFromFile(RenderScript rs, File path) {
return createFromFile(rs, path.getAbsolutePath());
}
- static public FileA3D createFromResource(RenderScript rs, Resources res, int id)
- throws IllegalArgumentException {
+ static public FileA3D createFromResource(RenderScript rs, Resources res, int id) {
rs.validate();
InputStream is = null;
try {
- final TypedValue value = new TypedValue();
- is = res.openRawResource(id, value);
-
- int asset = ((AssetManager.AssetInputStream) is).getAssetInt();
-
- int fileId = rs.nFileA3DCreateFromAssetStream(asset);
-
- if(fileId == 0) {
- throw new IllegalStateException("Load failed.");
- }
- FileA3D fa3d = new FileA3D(fileId, rs, is);
- fa3d.initEntries();
- return fa3d;
-
+ is = res.openRawResource(id);
} catch (Exception e) {
- // Ignore
+ throw new RSRuntimeException("Unable to open resource " + id);
}
- return null;
+ int fileId = 0;
+ if (is instanceof AssetManager.AssetInputStream) {
+ int asset = ((AssetManager.AssetInputStream) is).getAssetInt();
+ fileId = rs.nFileA3DCreateFromAssetStream(asset);
+ } else {
+ throw new RSRuntimeException("Unsupported asset stream");
+ }
+
+ if(fileId == 0) {
+ throw new RSRuntimeException("Unable to create a3d file from resource " + id);
+ }
+ FileA3D fa3d = new FileA3D(fileId, rs, is);
+ fa3d.initEntries();
+ return fa3d;
+
}
}
diff --git a/graphics/java/android/renderscript/Font.java b/graphics/java/android/renderscript/Font.java
index 0f7c24d..ae209fa 100644
--- a/graphics/java/android/renderscript/Font.java
+++ b/graphics/java/android/renderscript/Font.java
@@ -129,41 +129,62 @@
/**
* Takes a specific file name as an argument
*/
- static public Font createFromFile(RenderScript rs, Resources res, String path, float pointSize)
- throws IllegalArgumentException {
-
+ static public Font createFromFile(RenderScript rs, Resources res, String path, float pointSize) {
rs.validate();
- try {
- int dpi = res.getDisplayMetrics().densityDpi;
- int fontId = rs.nFontCreateFromFile(path, pointSize, dpi);
+ int dpi = res.getDisplayMetrics().densityDpi;
+ int fontId = rs.nFontCreateFromFile(path, pointSize, dpi);
- if(fontId == 0) {
- throw new IllegalStateException("Failed loading a font");
- }
- Font rsFont = new Font(fontId, rs);
-
- return rsFont;
-
- } catch (Exception e) {
- // Ignore
+ if(fontId == 0) {
+ throw new RSRuntimeException("Unable to create font from file " + path);
}
+ Font rsFont = new Font(fontId, rs);
- return null;
+ return rsFont;
}
- static public Font createFromFile(RenderScript rs, Resources res, File path, float pointSize)
- throws IllegalArgumentException {
+ static public Font createFromFile(RenderScript rs, Resources res, File path, float pointSize) {
return createFromFile(rs, res, path.getAbsolutePath(), pointSize);
}
- static public Font createFromAsset(RenderScript rs, Resources res, AssetManager mgr, String path, float pointSize)
- throws IllegalArgumentException {
- return null;
+ static public Font createFromAsset(RenderScript rs, Resources res, String path, float pointSize) {
+ rs.validate();
+ AssetManager mgr = res.getAssets();
+ int dpi = res.getDisplayMetrics().densityDpi;
+
+ int fontId = rs.nFontCreateFromAsset(mgr, path, pointSize, dpi);
+ if(fontId == 0) {
+ throw new RSRuntimeException("Unable to create font from asset " + path);
+ }
+ Font rsFont = new Font(fontId, rs);
+ return rsFont;
}
- static public Font createFromResource(RenderScript rs, Resources res, int id, float pointSize)
- throws IllegalArgumentException {
- return null;
+ static public Font createFromResource(RenderScript rs, Resources res, int id, float pointSize) {
+ String name = "R." + Integer.toString(id);
+
+ rs.validate();
+ InputStream is = null;
+ try {
+ is = res.openRawResource(id);
+ } catch (Exception e) {
+ throw new RSRuntimeException("Unable to open resource " + id);
+ }
+
+ int dpi = res.getDisplayMetrics().densityDpi;
+
+ int fontId = 0;
+ if (is instanceof AssetManager.AssetInputStream) {
+ int asset = ((AssetManager.AssetInputStream) is).getAssetInt();
+ fontId = rs.nFontCreateFromAssetStream(name, pointSize, dpi, asset);
+ } else {
+ throw new RSRuntimeException("Unsupported asset stream created");
+ }
+
+ if(fontId == 0) {
+ throw new RSRuntimeException("Unable to create font from resource " + id);
+ }
+ Font rsFont = new Font(fontId, rs);
+ return rsFont;
}
/**
@@ -175,8 +196,7 @@
* "monospace" "courier" "courier new" "monaco"
* Returns default font if no match could be found
*/
- static public Font create(RenderScript rs, Resources res, String familyName, Style fontStyle, float pointSize)
- throws IllegalArgumentException {
+ static public Font create(RenderScript rs, Resources res, String familyName, Style fontStyle, float pointSize) {
String fileName = getFontFileName(familyName, fontStyle);
String fontPath = Environment.getRootDirectory().getAbsolutePath();
fontPath += "/fonts/" + fileName;
diff --git a/graphics/java/android/renderscript/Mesh.java b/graphics/java/android/renderscript/Mesh.java
index 59e3dd9..b77fe7d 100644
--- a/graphics/java/android/renderscript/Mesh.java
+++ b/graphics/java/android/renderscript/Mesh.java
@@ -23,10 +23,29 @@
/**
* @hide
+ * Mesh class is a container for geometric data displayed in
+ * renderscript.
+ *
+ * Internally, mesh is a collection of allocations that
+ * represent vertex data (positions, normals, texture
+ * coordinates) and index data such as triangles and lines.
+ *
+ * Vertex data could either be interlieved within one
+ * allocation, provided separately as multiple allocation
+ * objects or done as a combination of the above. When a
+ * vertex channel name matches an input in the vertex program,
+ * renderscript will automatically connect the two together.
+ *
+ * Parts of the mesh could be rendered with either explicit
+ * index sets or primitive types.
*
**/
public class Mesh extends BaseObj {
+ /**
+ * Describes the way mesh vertex data is interpreted when rendering
+ *
+ **/
public enum Primitive {
POINT (0),
LINE (1),
@@ -49,25 +68,50 @@
super(id, rs);
}
+ /**
+ * @return number of allocations containing vertex data
+ *
+ **/
public int getVertexAllocationCount() {
if(mVertexBuffers == null) {
return 0;
}
return mVertexBuffers.length;
}
+ /**
+ * @param slot index in the list of allocations to return
+ * @return vertex data allocation at the given index
+ *
+ **/
public Allocation getVertexAllocation(int slot) {
return mVertexBuffers[slot];
}
+ /**
+ * @return number of primitives or index sets in the mesh
+ *
+ **/
public int getPrimitiveCount() {
if(mIndexBuffers == null) {
return 0;
}
return mIndexBuffers.length;
}
+
+ /**
+ * @param slot locaton within the list of index set allocation
+ * @return allocation containing primtive index data or null if
+ * the index data is not specified explicitly
+ *
+ **/
public Allocation getIndexSetAllocation(int slot) {
return mIndexBuffers[slot];
}
+ /**
+ * @param slot locaiton within the list of index set primitives
+ * @return index set primitive type
+ *
+ **/
public Primitive getPrimitive(int slot) {
return mPrimitives[slot];
}
@@ -105,6 +149,12 @@
}
}
+ /**
+ * Mesh builder object. It starts empty and requires the user to
+ * add the types necessary to create vertex and index
+ * allocations
+ *
+ */
public static class Builder {
RenderScript mRS;
int mUsage;
@@ -121,6 +171,13 @@
Entry[] mVertexTypes;
Vector mIndexTypes;
+ /**
+ * Creates builder object
+ * @param rs
+ * @param usage specifies how the mesh allocations are to be
+ * handled, whether they need to be uploaded to a
+ * buffer on the gpu, maintain a cpu copy, etc
+ */
public Builder(RenderScript rs, int usage) {
mRS = rs;
mUsage = usage;
@@ -129,14 +186,29 @@
mIndexTypes = new Vector();
}
+ /**
+ * @return internal index of the last vertex buffer type added to
+ * builder
+ **/
public int getCurrentVertexTypeIndex() {
return mVertexTypeCount - 1;
}
+ /**
+ * @return internal index of the last index set added to the
+ * builder
+ **/
public int getCurrentIndexSetIndex() {
return mIndexTypes.size() - 1;
}
+ /**
+ * Adds a vertex data type to the builder object
+ *
+ * @param r type of the vertex data allocation to be created
+ *
+ * @return this
+ **/
public Builder addVertexType(Type t) throws IllegalStateException {
if (mVertexTypeCount >= mVertexTypes.length) {
throw new IllegalStateException("Max vertex types exceeded.");
@@ -149,6 +221,14 @@
return this;
}
+ /**
+ * Adds a vertex data type to the builder object
+ *
+ * @param e element describing the vertex data layout
+ * @param size number of elements in the buffer
+ *
+ * @return this
+ **/
public Builder addVertexType(Element e, int size) throws IllegalStateException {
if (mVertexTypeCount >= mVertexTypes.length) {
throw new IllegalStateException("Max vertex types exceeded.");
@@ -162,6 +242,14 @@
return this;
}
+ /**
+ * Adds an index set data type to the builder object
+ *
+ * @param t type of the index set data, could be null
+ * @param p primitive type
+ *
+ * @return this
+ **/
public Builder addIndexSetType(Type t, Primitive p) {
Entry indexType = new Entry();
indexType.t = t;
@@ -172,6 +260,13 @@
return this;
}
+ /**
+ * Adds an index set primitive type to the builder object
+ *
+ * @param p primitive type
+ *
+ * @return this
+ **/
public Builder addIndexSetType(Primitive p) {
Entry indexType = new Entry();
indexType.t = null;
@@ -182,6 +277,15 @@
return this;
}
+ /**
+ * Adds an index set data type to the builder object
+ *
+ * @param e element describing the index set data layout
+ * @param size number of elements in the buffer
+ * @param p primitive type
+ *
+ * @return this
+ **/
public Builder addIndexSetType(Element e, int size, Primitive p) {
Entry indexType = new Entry();
indexType.t = null;
@@ -237,6 +341,10 @@
return newMesh;
}
+ /**
+ * Create a Mesh object from the current state of the builder
+ *
+ **/
public Mesh create() {
mRS.validate();
Mesh sm = internalCreate(mRS, this);
@@ -244,6 +352,12 @@
}
}
+ /**
+ * Mesh builder object. It starts empty and requires the user to
+ * add all the vertex and index allocations that comprise the
+ * mesh
+ *
+ */
public static class AllocationBuilder {
RenderScript mRS;
@@ -264,14 +378,30 @@
mIndexTypes = new Vector();
}
+ /**
+ * @return internal index of the last vertex buffer type added to
+ * builder
+ **/
public int getCurrentVertexTypeIndex() {
return mVertexTypeCount - 1;
}
+ /**
+ * @return internal index of the last index set added to the
+ * builder
+ **/
public int getCurrentIndexSetIndex() {
return mIndexTypes.size() - 1;
}
+ /**
+ * Adds an allocation containing vertex buffer data to the
+ * builder
+ *
+ * @param a vertex data allocation
+ *
+ * @return this
+ **/
public AllocationBuilder addVertexAllocation(Allocation a) throws IllegalStateException {
if (mVertexTypeCount >= mVertexTypes.length) {
throw new IllegalStateException("Max vertex types exceeded.");
@@ -283,6 +413,15 @@
return this;
}
+ /**
+ * Adds an allocation containing index buffer data and index type
+ * to the builder
+ *
+ * @param a index set data allocation, could be null
+ * @param p index set primitive type
+ *
+ * @return this
+ **/
public AllocationBuilder addIndexSetAllocation(Allocation a, Primitive p) {
Entry indexType = new Entry();
indexType.a = a;
@@ -291,6 +430,13 @@
return this;
}
+ /**
+ * Adds an index set type to the builder
+ *
+ * @param p index set primitive type
+ *
+ * @return this
+ **/
public AllocationBuilder addIndexSetType(Primitive p) {
Entry indexType = new Entry();
indexType.a = null;
@@ -325,6 +471,10 @@
return newMesh;
}
+ /**
+ * Create a Mesh object from the current state of the builder
+ *
+ **/
public Mesh create() {
mRS.validate();
Mesh sm = internalCreate(mRS, this);
@@ -332,7 +482,11 @@
}
}
-
+ /**
+ * Builder that allows creation of a mesh object point by point
+ * and triangle by triangle
+ *
+ **/
public static class TriangleMeshBuilder {
float mVtxData[];
int mVtxCount;
@@ -358,6 +512,15 @@
public static final int NORMAL = 0x0002;
public static final int TEXTURE_0 = 0x0100;
+ /**
+ * @param rs
+ * @param vtxSize specifies whether the vertex is a float2 or
+ * float3
+ * @param flags bitfield that is a combination of COLOR, NORMAL,
+ * and TEXTURE_0 that specifies what vertex data
+ * channels are present in the mesh
+ *
+ **/
public TriangleMeshBuilder(RenderScript rs, int vtxSize, int flags) {
mRS = rs;
mVtxCount = 0;
@@ -401,6 +564,15 @@
}
}
+ /**
+ * Adds a float2 vertex to the mesh
+ *
+ * @param x position x
+ * @param y position y
+ *
+ * @return this
+ *
+ **/
public TriangleMeshBuilder addVertex(float x, float y) {
if (mVtxSize != 2) {
throw new IllegalStateException("add mistmatch with declared components.");
@@ -412,6 +584,16 @@
return this;
}
+ /**
+ * Adds a float3 vertex to the mesh
+ *
+ * @param x position x
+ * @param y position y
+ * @param z position z
+ *
+ * @return this
+ *
+ **/
public TriangleMeshBuilder addVertex(float x, float y, float z) {
if (mVtxSize != 3) {
throw new IllegalStateException("add mistmatch with declared components.");
@@ -424,6 +606,14 @@
return this;
}
+ /**
+ * Sets the texture coordinate for the last added vertex
+ *
+ * @param s texture coordinate s
+ * @param t texture coordinate t
+ *
+ * @return this
+ **/
public TriangleMeshBuilder setTexture(float s, float t) {
if ((mFlags & TEXTURE_0) == 0) {
throw new IllegalStateException("add mistmatch with declared components.");
@@ -433,6 +623,15 @@
return this;
}
+ /**
+ * Sets the normal vector for the last added vertex
+ *
+ * @param x normal vector x
+ * @param y normal vector y
+ * @param z normal vector z
+ *
+ * @return this
+ **/
public TriangleMeshBuilder setNormal(float x, float y, float z) {
if ((mFlags & NORMAL) == 0) {
throw new IllegalStateException("add mistmatch with declared components.");
@@ -443,6 +642,16 @@
return this;
}
+ /**
+ * Sets the color for the last added vertex
+ *
+ * @param r red component
+ * @param g green component
+ * @param b blue component
+ * @param a alpha component
+ *
+ * @return this
+ **/
public TriangleMeshBuilder setColor(float r, float g, float b, float a) {
if ((mFlags & COLOR) == 0) {
throw new IllegalStateException("add mistmatch with declared components.");
@@ -454,6 +663,15 @@
return this;
}
+ /**
+ * Adds a new triangle to the mesh builder
+ *
+ * @param idx1 index of the first vertex in the triangle
+ * @param idx2 index of the second vertex in the triangle
+ * @param idx3 index of the third vertex in the triangle
+ *
+ * @return this
+ **/
public TriangleMeshBuilder addTriangle(int idx1, int idx2, int idx3) {
if((idx1 >= mVtxCount) || (idx1 < 0) ||
(idx2 >= mVtxCount) || (idx2 < 0) ||
@@ -471,6 +689,20 @@
return this;
}
+ /**
+ * Creates the mesh object from the current state of the builder
+ *
+ * @param uploadToBufferObject specifies whether the vertex data
+ * is to be uploaded into the buffer
+ * object indicating that it's likely
+ * not going to be modified and
+ * rendered many times.
+ * Alternatively, it indicates the
+ * mesh data will be updated
+ * frequently and remain in script
+ * accessible memory
+ *
+ **/
public Mesh create(boolean uploadToBufferObject) {
Element.Builder b = new Element.Builder(mRS);
int floatCount = mVtxSize;
diff --git a/graphics/java/android/renderscript/Program.java b/graphics/java/android/renderscript/Program.java
index b07ae7d..fdd138c 100644
--- a/graphics/java/android/renderscript/Program.java
+++ b/graphics/java/android/renderscript/Program.java
@@ -28,6 +28,9 @@
/**
*
+ * Program is a base class for all the objects that modify
+ * various stages of the graphics pipeline
+ *
**/
public class Program extends BaseObj {
public static final int MAX_INPUT = 8;
@@ -35,6 +38,12 @@
public static final int MAX_CONSTANT = 8;
public static final int MAX_TEXTURE = 8;
+ /**
+ *
+ * TextureType specifies what textures are attached to Program
+ * objects
+ *
+ **/
public enum TextureType {
TEXTURE_2D (0),
TEXTURE_CUBE (1);
@@ -68,6 +77,14 @@
super(id, rs);
}
+ /**
+ * Binds a constant buffer to be used as uniform inputs to the
+ * program
+ *
+ * @param a allocation containing uniform data
+ * @param slot index within the program's list of constant
+ * buffer allocations
+ */
public void bindConstants(Allocation a, int slot) {
if (slot < 0 || slot >= mConstants.length) {
throw new IllegalArgumentException("Slot ID out of range.");
@@ -80,6 +97,13 @@
mRS.nProgramBindConstants(getID(), slot, id);
}
+ /**
+ * Binds a texture to be used in the program
+ *
+ * @param va allocation containing texture data
+ * @param slot index within the program's list of textures
+ *
+ */
public void bindTexture(Allocation va, int slot)
throws IllegalArgumentException {
mRS.validate();
@@ -95,6 +119,15 @@
mRS.nProgramBindTexture(getID(), slot, id);
}
+ /**
+ * Binds an object that describes how a texture at the
+ * corresponding location is sampled
+ *
+ * @param vs sampler for a corresponding texture
+ * @param slot index within the program's list of textures to
+ * use the sampler on
+ *
+ */
public void bindSampler(Sampler vs, int slot)
throws IllegalArgumentException {
mRS.validate();
@@ -133,11 +166,25 @@
mTextureTypes = new TextureType[MAX_TEXTURE];
}
+ /**
+ * Sets the GLSL shader code to be used in the program
+ *
+ * @param s GLSL shader string
+ * @return self
+ */
public BaseProgramBuilder setShader(String s) {
mShader = s;
return this;
}
+ /**
+ * Sets the GLSL shader code to be used in the program
+ *
+ * @param resources application resources
+ * @param resourceID id of the file containing GLSL shader code
+ *
+ * @return self
+ */
public BaseProgramBuilder setShader(Resources resources, int resourceID) {
byte[] str;
int strLength;
@@ -176,14 +223,29 @@
return this;
}
+ /**
+ * Queries the index of the last added constant buffer type
+ *
+ */
public int getCurrentConstantIndex() {
return mConstantCount - 1;
}
+ /**
+ * Queries the index of the last added texture type
+ *
+ */
public int getCurrentTextureIndex() {
return mTextureCount - 1;
}
+ /**
+ * Adds constant (uniform) inputs to the program
+ *
+ * @param t Type that describes the layout of the Allocation
+ * object to be used as constant inputs to the Program
+ * @return self
+ */
public BaseProgramBuilder addConstant(Type t) throws IllegalStateException {
// Should check for consistant and non-conflicting names...
if(mConstantCount >= MAX_CONSTANT) {
@@ -197,6 +259,13 @@
return this;
}
+ /**
+ * Adds a texture input to the Program
+ *
+ * @param texType describes that the texture to append it (2D,
+ * Cubemap, etc.)
+ * @return self
+ */
public BaseProgramBuilder addTexture(TextureType texType) throws IllegalArgumentException {
if(mTextureCount >= MAX_TEXTURE) {
throw new IllegalArgumentException("Max texture count exceeded.");
diff --git a/graphics/java/android/renderscript/ProgramFragment.java b/graphics/java/android/renderscript/ProgramFragment.java
index 7f12661..14c0c01 100644
--- a/graphics/java/android/renderscript/ProgramFragment.java
+++ b/graphics/java/android/renderscript/ProgramFragment.java
@@ -22,6 +22,9 @@
/**
+ * ProgramFragment, also know as a fragment shader, describes a
+ * stage in the graphics pipeline responsible for manipulating
+ * pixel data in a user-defined way.
*
**/
public class ProgramFragment extends Program {
@@ -30,10 +33,20 @@
}
public static class Builder extends BaseProgramBuilder {
+ /**
+ * Create a builder object.
+ *
+ * @param rs
+ */
public Builder(RenderScript rs) {
super(rs);
}
+ /**
+ * Creates ProgramFragment from the current state of the builder
+ *
+ * @return ProgramFragment
+ */
public ProgramFragment create() {
mRS.validate();
int[] tmp = new int[(mInputCount + mOutputCount + mConstantCount + mTextureCount) * 2];
diff --git a/graphics/java/android/renderscript/ProgramFragmentFixedFunction.java b/graphics/java/android/renderscript/ProgramFragmentFixedFunction.java
index f0040c6..663bc9f 100644
--- a/graphics/java/android/renderscript/ProgramFragmentFixedFunction.java
+++ b/graphics/java/android/renderscript/ProgramFragmentFixedFunction.java
@@ -22,6 +22,13 @@
/**
+ * ProgramFragmentFixedFunction is a helper class that provides
+ * a way to make a simple fragment shader without writing any
+ * GLSL code.
+ *
+ * This class allows for display of constant color, interpolated
+ * color from vertex shader, or combinations of the above
+ * blended with results of up to two texture lookups.
*
**/
public class ProgramFragmentFixedFunction extends ProgramFragment {
@@ -34,6 +41,12 @@
super(rs);
}
+ /**
+ * Creates ProgramFragmentFixedFunction from the current state
+ * of the builder
+ *
+ * @return ProgramFragmentFixedFunction
+ */
public ProgramFragmentFixedFunction create() {
mRS.validate();
int[] tmp = new int[(mInputCount + mOutputCount + mConstantCount + mTextureCount) * 2];
@@ -71,6 +84,11 @@
String mShader;
RenderScript mRS;
+ /**
+ * EnvMode describes how textures are combined with the existing
+ * color in the fixed function fragment shader
+ *
+ **/
public enum EnvMode {
REPLACE (1),
MODULATE (2),
@@ -82,6 +100,11 @@
}
}
+ /**
+ * Format describes the pixel format of textures in the fixed
+ * function fragment shader and how they are sampled
+ *
+ **/
public enum Format {
ALPHA (1),
LUMINANCE_ALPHA (2),
@@ -168,12 +191,30 @@
mShader += "}\n";
}
+ /**
+ * Creates a builder for fixed function fragment program
+ *
+ * @param rs
+ */
public Builder(RenderScript rs) {
mRS = rs;
mSlots = new Slot[MAX_TEXTURE];
mPointSpriteEnable = false;
}
+ /**
+ * Adds a texture to be fetched as part of the fixed function
+ * fragment program
+ *
+ * @param env specifies how the texture is combined with the
+ * current color
+ * @param fmt specifies the format of the texture and how its
+ * components will be used to combine with the
+ * current color
+ * @param slot index of the texture to apply the operations on
+ *
+ * @return this
+ */
public Builder setTexture(EnvMode env, Format fmt, int slot)
throws IllegalArgumentException {
if((slot < 0) || (slot >= MAX_TEXTURE)) {
@@ -183,16 +224,34 @@
return this;
}
+ /**
+ * Specifies whether the texture coordinate passed from the
+ * vertex program is replaced with an openGL internal point
+ * sprite texture coordinate
+ *
+ **/
public Builder setPointSpriteTexCoordinateReplacement(boolean enable) {
mPointSpriteEnable = enable;
return this;
}
+ /**
+ * Specifies whether the varying color passed from the vertex
+ * program or the constant color set on the fragment program is
+ * used in the final color calculation in the fixed function
+ * fragment shader
+ *
+ **/
public Builder setVaryingColor(boolean enable) {
mVaryingColorEnable = enable;
return this;
}
+ /**
+ * Creates the fixed function fragment program from the current
+ * state of the builder.
+ *
+ */
public ProgramFragmentFixedFunction create() {
InternalBuilder sb = new InternalBuilder(mRS);
mNumTextures = 0;
diff --git a/graphics/java/android/renderscript/ProgramVertex.java b/graphics/java/android/renderscript/ProgramVertex.java
index 13800ff..7ba8b82 100644
--- a/graphics/java/android/renderscript/ProgramVertex.java
+++ b/graphics/java/android/renderscript/ProgramVertex.java
@@ -23,6 +23,9 @@
/**
+ * ProgramVertex, also know as a vertex shader, describes a
+ * stage in the graphics pipeline responsible for manipulating
+ * geometric data in a user-defined way.
*
**/
public class ProgramVertex extends Program {
@@ -31,11 +34,31 @@
super(id, rs);
}
+ /**
+ * Builder class for creating ProgramVertex objects.
+ * The builder starts empty and the user must minimally provide
+ * the GLSL shader code, and the varying inputs. Constant, or
+ * uniform parameters to the shader may optionally be provided as
+ * well.
+ *
+ **/
public static class Builder extends BaseProgramBuilder {
+ /**
+ * Create a builder object.
+ *
+ * @param rs
+ */
public Builder(RenderScript rs) {
super(rs);
}
+ /**
+ * Add varying inputs to the program
+ *
+ * @param e element describing the layout of the varying input
+ * structure
+ * @return self
+ */
public Builder addInput(Element e) throws IllegalStateException {
// Should check for consistant and non-conflicting names...
if(mInputCount >= MAX_INPUT) {
@@ -48,6 +71,11 @@
return this;
}
+ /**
+ * Creates ProgramVertex from the current state of the builder
+ *
+ * @return ProgramVertex
+ */
public ProgramVertex create() {
mRS.validate();
int[] tmp = new int[(mInputCount + mOutputCount + mConstantCount + mTextureCount) * 2];
diff --git a/graphics/java/android/renderscript/ProgramVertexFixedFunction.java b/graphics/java/android/renderscript/ProgramVertexFixedFunction.java
index 1b69efe..b9537c7 100644
--- a/graphics/java/android/renderscript/ProgramVertexFixedFunction.java
+++ b/graphics/java/android/renderscript/ProgramVertexFixedFunction.java
@@ -23,6 +23,9 @@
/**
+ * ProgramVertexFixedFunction is a helper class that provides a
+ * simple way to create a fixed function emulation vertex shader
+ * without writing any GLSL code.
*
**/
public class ProgramVertexFixedFunction extends ProgramVertex {
@@ -31,6 +34,12 @@
super(id, rs);
}
+ /**
+ * Binds the constant buffer containing fixed function emulation
+ * matrices
+ *
+ * @param va allocation containing fixed function matrices
+ */
public void bindConstants(Constants va) {
mRS.validate();
bindConstants(va.getAllocation(), 0);
@@ -53,6 +62,12 @@
return this;
}
+ /**
+ * Creates ProgramVertexFixedFunction from the current state of
+ * the builder
+ *
+ * @return ProgramVertexFixedFunction
+ */
public ProgramVertexFixedFunction create() {
mRS.validate();
int[] tmp = new int[(mInputCount + mOutputCount + mConstantCount + mTextureCount) * 2];
@@ -87,10 +102,20 @@
String mShader;
RenderScript mRS;
+ /**
+ * Creates a builder for fixed function vertex program
+ *
+ * @param rs
+ */
public Builder(RenderScript rs) {
mRS = rs;
}
+ /**
+ * Specifies whether texture matrix calculations are to be added
+ * to the shader
+ *
+ */
public Builder setTextureMatrixEnable(boolean enable) {
mTextureMatrixEnable = enable;
return this;
@@ -126,6 +151,12 @@
mShader += "}\n";
}
+ /**
+ * Creates ProgramVertexFixedFunction from the current state of
+ * the builder
+ *
+ * @return Fixed function emulation ProgramVertex
+ */
public ProgramVertexFixedFunction create() {
buildShaderString();
@@ -144,6 +175,11 @@
}
}
+ /**
+ * Helper class to store modelview, projection and texture
+ * matrices for ProgramVertexFixedFunction
+ *
+ */
public static class Constants {
static final int MODELVIEW_OFFSET = 0;
static final int PROJECTION_OFFSET = 16;
@@ -159,6 +195,11 @@
}
private FieldPacker mIOBuffer;
+ /**
+ * Creates buffer to store fixed function emulation matrices
+ *
+ * @param rs
+ **/
public Constants(RenderScript rs) {
Type constInputType = ProgramVertexFixedFunction.Builder.getConstantInputType(rs);
mAlloc = Allocation.createTyped(rs, constInputType);
@@ -173,6 +214,11 @@
setTexture(new Matrix4f());
}
+ /**
+ * Forces deallocation of memory backing the contant matrices.
+ * Normally, this is unnecessary and will be garbage collected
+ *
+ */
public void destroy() {
mAlloc.destroy();
mAlloc = null;
@@ -186,16 +232,34 @@
mAlloc.copyFrom(mIOBuffer.getData());
}
+ /**
+ * Sets the modelview matrix in the fixed function matrix buffer
+ *
+ * @param m modelview matrix
+ */
public void setModelview(Matrix4f m) {
mModel.load(m);
addToBuffer(MODELVIEW_OFFSET*4, m);
}
+ /**
+ * Sets the projection matrix in the fixed function matrix buffer
+ *
+ * @param m projection matrix
+ */
public void setProjection(Matrix4f m) {
mProjection.load(m);
addToBuffer(PROJECTION_OFFSET*4, m);
}
+ /**
+ * Sets the texture matrix in the fixed function matrix buffer.
+ * Texture matrix must be enabled in the
+ * ProgramVertexFixedFunction builder for the shader to utilize
+ * it.
+ *
+ * @param m modelview matrix
+ */
public void setTexture(Matrix4f m) {
mTexture.load(m);
addToBuffer(TEXTURE_OFFSET*4, m);
diff --git a/graphics/java/android/renderscript/RenderScript.java b/graphics/java/android/renderscript/RenderScript.java
index 6a52810..4c9ad56 100644
--- a/graphics/java/android/renderscript/RenderScript.java
+++ b/graphics/java/android/renderscript/RenderScript.java
@@ -19,6 +19,7 @@
import java.lang.reflect.Field;
import android.content.Context;
+import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Config;
@@ -59,7 +60,8 @@
_nInit();
sInitialized = true;
} catch (UnsatisfiedLinkError e) {
- Log.d(LOG_TAG, "RenderScript JNI library not found!");
+ Log.e(LOG_TAG, "Error loading RS jni library: " + e);
+ throw new RSRuntimeException("Error loading RS jni library: " + e);
}
}
@@ -249,6 +251,14 @@
rsnAllocationElementData1D(mContext, id, xoff, mip, compIdx, d, sizeBytes);
}
+ native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, byte[] d, int sizeBytes);
+ synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, byte[] d, int sizeBytes) {
+ rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
+ }
+ native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, short[] d, int sizeBytes);
+ synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, short[] d, int sizeBytes) {
+ rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
+ }
native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, int w, int h, int[] d, int sizeBytes);
synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, int[] d, int sizeBytes) {
rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
@@ -257,7 +267,19 @@
synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, int w, int h, float[] d, int sizeBytes) {
rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, w, h, d, sizeBytes);
}
+ native void rsnAllocationData2D(int con, int id, int xoff, int yoff, int mip, int face, Bitmap b);
+ synchronized void nAllocationData2D(int id, int xoff, int yoff, int mip, int face, Bitmap b) {
+ rsnAllocationData2D(mContext, id, xoff, yoff, mip, face, b);
+ }
+ native void rsnAllocationRead(int con, int id, byte[] d);
+ synchronized void nAllocationRead(int id, byte[] d) {
+ rsnAllocationRead(mContext, id, d);
+ }
+ native void rsnAllocationRead(int con, int id, short[] d);
+ synchronized void nAllocationRead(int id, short[] d) {
+ rsnAllocationRead(mContext, id, d);
+ }
native void rsnAllocationRead(int con, int id, int[] d);
synchronized void nAllocationRead(int id, int[] d) {
rsnAllocationRead(mContext, id, d);
@@ -284,6 +306,14 @@
synchronized int nFileA3DCreateFromAssetStream(int assetStream) {
return rsnFileA3DCreateFromAssetStream(mContext, assetStream);
}
+ native int rsnFileA3DCreateFromFile(int con, String path);
+ synchronized int nFileA3DCreateFromFile(String path) {
+ return rsnFileA3DCreateFromFile(mContext, path);
+ }
+ native int rsnFileA3DCreateFromAsset(int con, AssetManager mgr, String path);
+ synchronized int nFileA3DCreateFromAsset(AssetManager mgr, String path) {
+ return rsnFileA3DCreateFromAsset(mContext, mgr, path);
+ }
native int rsnFileA3DGetNumIndexEntries(int con, int fileA3D);
synchronized int nFileA3DGetNumIndexEntries(int fileA3D) {
return rsnFileA3DGetNumIndexEntries(mContext, fileA3D);
@@ -301,6 +331,14 @@
synchronized int nFontCreateFromFile(String fileName, float size, int dpi) {
return rsnFontCreateFromFile(mContext, fileName, size, dpi);
}
+ native int rsnFontCreateFromAssetStream(int con, String name, float size, int dpi, int assetStream);
+ synchronized int nFontCreateFromAssetStream(String name, float size, int dpi, int assetStream) {
+ return rsnFontCreateFromAssetStream(mContext, name, size, dpi, assetStream);
+ }
+ native int rsnFontCreateFromAsset(int con, AssetManager mgr, String path, float size, int dpi);
+ synchronized int nFontCreateFromAsset(AssetManager mgr, String path, float size, int dpi) {
+ return rsnFontCreateFromAsset(mContext, mgr, path, size, dpi);
+ }
native void rsnScriptBindAllocation(int con, int script, int alloc, int slot);
diff --git a/graphics/java/android/renderscript/Script.java b/graphics/java/android/renderscript/Script.java
index ddf41cb..b3ad20a 100644
--- a/graphics/java/android/renderscript/Script.java
+++ b/graphics/java/android/renderscript/Script.java
@@ -20,32 +20,25 @@
*
**/
public class Script extends BaseObj {
- public static final int MAX_SLOT = 16;
-
- boolean mIsRoot;
- Type[] mTypes;
- boolean[] mWritable;
- Invokable[] mInvokables;
-
- public static class Invokable {
- RenderScript mRS;
- Script mScript;
- int mSlot;
- String mName;
-
- Invokable() {
- mSlot = -1;
- }
-
- public void execute() {
- mRS.nScriptInvoke(mScript.getID(), mSlot);
- }
- }
-
+ /**
+ * @hide
+ *
+ * Only intended for use by generated reflected code.
+ *
+ * @param slot
+ */
protected void invoke(int slot) {
mRS.nScriptInvoke(getID(), slot);
}
+ /**
+ * @hide
+ *
+ * Only intended for use by generated reflected code.
+ *
+ * @param slot
+ * @param v
+ */
protected void invoke(int slot, FieldPacker v) {
if (v != null) {
mRS.nScriptInvokeV(getID(), slot, v.getData());
@@ -59,6 +52,15 @@
super(id, rs);
}
+
+ /**
+ * @hide
+ *
+ * Only intended for use by generated reflected code.
+ *
+ * @param va
+ * @param slot
+ */
public void bindAllocation(Allocation va, int slot) {
mRS.validate();
if (va != null) {
@@ -68,30 +70,86 @@
}
}
+ /**
+ * @hide
+ *
+ * Only intended for use by generated reflected code.
+ *
+ * @param index
+ * @param v
+ */
public void setVar(int index, float v) {
mRS.nScriptSetVarF(getID(), index, v);
}
+ /**
+ * @hide
+ *
+ * Only intended for use by generated reflected code.
+ *
+ * @param index
+ * @param v
+ */
public void setVar(int index, double v) {
mRS.nScriptSetVarD(getID(), index, v);
}
+ /**
+ * @hide
+ *
+ * Only intended for use by generated reflected code.
+ *
+ * @param index
+ * @param v
+ */
public void setVar(int index, int v) {
mRS.nScriptSetVarI(getID(), index, v);
}
+ /**
+ * @hide
+ *
+ * Only intended for use by generated reflected code.
+ *
+ * @param index
+ * @param v
+ */
public void setVar(int index, long v) {
mRS.nScriptSetVarJ(getID(), index, v);
}
+ /**
+ * @hide
+ *
+ * Only intended for use by generated reflected code.
+ *
+ * @param index
+ * @param v
+ */
public void setVar(int index, boolean v) {
mRS.nScriptSetVarI(getID(), index, v ? 1 : 0);
}
+ /**
+ * @hide
+ *
+ * Only intended for use by generated reflected code.
+ *
+ * @param index
+ * @param o
+ */
public void setVar(int index, BaseObj o) {
mRS.nScriptSetVarObj(getID(), index, (o == null) ? 0 : o.getID());
}
+ /**
+ * @hide
+ *
+ * Only intended for use by generated reflected code.
+ *
+ * @param index
+ * @param v
+ */
public void setVar(int index, FieldPacker v) {
mRS.nScriptSetVarV(getID(), index, v.getData());
}
diff --git a/graphics/java/android/renderscript/ScriptC.java b/graphics/java/android/renderscript/ScriptC.java
index 984edd3..14e4ab5 100644
--- a/graphics/java/android/renderscript/ScriptC.java
+++ b/graphics/java/android/renderscript/ScriptC.java
@@ -35,10 +35,28 @@
public class ScriptC extends Script {
private static final String TAG = "ScriptC";
+ /**
+ * @hide
+ *
+ * Only intended for use by the generated derived classes.
+ *
+ * @param id
+ * @param rs
+ */
protected ScriptC(int id, RenderScript rs) {
super(id, rs);
}
+ /**
+ * @hide
+ *
+ * Only intended for use by the generated derived classes.
+ *
+ *
+ * @param rs
+ * @param resources
+ * @param resourceID
+ */
protected ScriptC(RenderScript rs, Resources resources, int resourceID) {
super(0, rs);
int id = internalCreate(rs, resources, resourceID);
diff --git a/graphics/jni/android_renderscript_RenderScript.cpp b/graphics/jni/android_renderscript_RenderScript.cpp
index fe22269..1817a1b 100644
--- a/graphics/jni/android_renderscript_RenderScript.cpp
+++ b/graphics/jni/android_renderscript_RenderScript.cpp
@@ -32,12 +32,14 @@
#include <images/SkImageDecoder.h>
#include <utils/Asset.h>
+#include <utils/AssetManager.h>
#include <utils/ResourceTypes.h>
#include "jni.h"
#include "JNIHelp.h"
#include "android_runtime/AndroidRuntime.h"
#include "android_runtime/android_view_Surface.h"
+#include "android_runtime/android_util_AssetManager.h"
#include <RenderScript.h>
#include <RenderScriptEnv.h>
@@ -47,6 +49,27 @@
using namespace android;
+class AutoJavaStringToUTF8 {
+public:
+ AutoJavaStringToUTF8(JNIEnv* env, jstring str) : fEnv(env), fJStr(str)
+ {
+ fCStr = env->GetStringUTFChars(str, NULL);
+ fLength = env->GetStringUTFLength(str);
+ }
+ ~AutoJavaStringToUTF8()
+ {
+ fEnv->ReleaseStringUTFChars(fJStr, fCStr);
+ }
+ const char* c_str() const { return fCStr; }
+ jsize length() const { return fLength; }
+
+private:
+ JNIEnv* fEnv;
+ jstring fJStr;
+ const char* fCStr;
+ jsize fLength;
+};
+
// ---------------------------------------------------------------------------
static void doThrow(JNIEnv* env, const char* exc, const char* msg = NULL)
@@ -572,7 +595,34 @@
Asset* asset = reinterpret_cast<Asset*>(native_asset);
- jint id = (jint)rsaFileA3DCreateFromAssetStream(con, asset->getBuffer(false), asset->getLength());
+ jint id = (jint)rsaFileA3DCreateFromMemory(con, asset->getBuffer(false), asset->getLength());
+ return id;
+}
+
+static int
+nFileA3DCreateFromAsset(JNIEnv *_env, jobject _this, RsContext con, jobject _assetMgr, jstring _path)
+{
+ AssetManager* mgr = assetManagerForJavaObject(_env, _assetMgr);
+ if (mgr == NULL) {
+ return 0;
+ }
+
+ AutoJavaStringToUTF8 str(_env, _path);
+ Asset* asset = mgr->open(str.c_str(), Asset::ACCESS_BUFFER);
+ if (asset == NULL) {
+ return 0;
+ }
+
+ jint id = (jint)rsaFileA3DCreateFromAsset(con, asset);
+ return id;
+}
+
+static int
+nFileA3DCreateFromFile(JNIEnv *_env, jobject _this, RsContext con, jstring fileName)
+{
+ AutoJavaStringToUTF8 fileNameUTF(_env, fileName);
+ jint id = (jint)rsaFileA3DCreateFromFile(con, fileNameUTF.c_str());
+
return id;
}
@@ -611,11 +661,45 @@
// -----------------------------------
static int
-nFontCreateFromFile(JNIEnv *_env, jobject _this, RsContext con, jstring fileName, jfloat fontSize, jint dpi)
+nFontCreateFromFile(JNIEnv *_env, jobject _this, RsContext con,
+ jstring fileName, jfloat fontSize, jint dpi)
{
- const char* fileNameUTF = _env->GetStringUTFChars(fileName, NULL);
+ AutoJavaStringToUTF8 fileNameUTF(_env, fileName);
+ jint id = (jint)rsFontCreateFromFile(con, fileNameUTF.c_str(), fontSize, dpi);
- jint id = (jint)rsFontCreateFromFile(con, fileNameUTF, fontSize, dpi);
+ return id;
+}
+
+static int
+nFontCreateFromAssetStream(JNIEnv *_env, jobject _this, RsContext con,
+ jstring name, jfloat fontSize, jint dpi, jint native_asset)
+{
+ Asset* asset = reinterpret_cast<Asset*>(native_asset);
+ AutoJavaStringToUTF8 nameUTF(_env, name);
+
+ jint id = (jint)rsFontCreateFromMemory(con, nameUTF.c_str(), fontSize, dpi,
+ asset->getBuffer(false), asset->getLength());
+ return id;
+}
+
+static int
+nFontCreateFromAsset(JNIEnv *_env, jobject _this, RsContext con, jobject _assetMgr, jstring _path,
+ jfloat fontSize, jint dpi)
+{
+ AssetManager* mgr = assetManagerForJavaObject(_env, _assetMgr);
+ if (mgr == NULL) {
+ return 0;
+ }
+
+ AutoJavaStringToUTF8 str(_env, _path);
+ Asset* asset = mgr->open(str.c_str(), Asset::ACCESS_BUFFER);
+ if (asset == NULL) {
+ return 0;
+ }
+
+ jint id = (jint)rsFontCreateFromMemory(con, str.c_str(), fontSize, dpi,
+ asset->getBuffer(false), asset->getLength());
+ delete asset;
return id;
}
@@ -764,13 +848,10 @@
nScriptCCreate(JNIEnv *_env, jobject _this, RsContext con, jstring packageName, jstring resName, jstring cacheDir)
{
LOG_API("nScriptCCreate, con(%p)", con);
- const char* packageNameUTF = _env->GetStringUTFChars(packageName, NULL);
- const char* resNameUTF = _env->GetStringUTFChars(resName, NULL);
- const char* cacheDirUTF = _env->GetStringUTFChars(cacheDir, NULL);
- jint i = (jint)rsScriptCCreate(con, packageNameUTF, resNameUTF, cacheDirUTF);
- _env->ReleaseStringUTFChars(packageName, packageNameUTF);
- _env->ReleaseStringUTFChars(resName, resNameUTF);
- _env->ReleaseStringUTFChars(cacheDir, cacheDirUTF);
+ AutoJavaStringToUTF8 packageNameUTF(_env, packageName);
+ AutoJavaStringToUTF8 resNameUTF(_env, resName);
+ AutoJavaStringToUTF8 cacheDirUTF(_env, cacheDir);
+ jint i = (jint)rsScriptCCreate(con, packageNameUTF.c_str(), resNameUTF.c_str(), cacheDirUTF.c_str());
return i;
}
@@ -853,15 +934,13 @@
static jint
nProgramFragmentCreate(JNIEnv *_env, jobject _this, RsContext con, jstring shader, jintArray params)
{
- const char* shaderUTF = _env->GetStringUTFChars(shader, NULL);
- jint shaderLen = _env->GetStringUTFLength(shader);
+ AutoJavaStringToUTF8 shaderUTF(_env, shader);
jint *paramPtr = _env->GetIntArrayElements(params, NULL);
jint paramLen = _env->GetArrayLength(params);
LOG_API("nProgramFragmentCreate, con(%p), shaderLen(%i), paramLen(%i)", con, shaderLen, paramLen);
- jint ret = (jint)rsProgramFragmentCreate(con, shaderUTF, shaderLen, (uint32_t *)paramPtr, paramLen);
- _env->ReleaseStringUTFChars(shader, shaderUTF);
+ jint ret = (jint)rsProgramFragmentCreate(con, shaderUTF.c_str(), shaderUTF.length(), (uint32_t *)paramPtr, paramLen);
_env->ReleaseIntArrayElements(params, paramPtr, JNI_ABORT);
return ret;
}
@@ -872,15 +951,13 @@
static jint
nProgramVertexCreate(JNIEnv *_env, jobject _this, RsContext con, jstring shader, jintArray params)
{
- const char* shaderUTF = _env->GetStringUTFChars(shader, NULL);
- jint shaderLen = _env->GetStringUTFLength(shader);
+ AutoJavaStringToUTF8 shaderUTF(_env, shader);
jint *paramPtr = _env->GetIntArrayElements(params, NULL);
jint paramLen = _env->GetArrayLength(params);
LOG_API("nProgramVertexCreate, con(%p), shaderLen(%i), paramLen(%i)", con, shaderLen, paramLen);
- jint ret = (jint)rsProgramVertexCreate(con, shaderUTF, shaderLen, (uint32_t *)paramPtr, paramLen);
- _env->ReleaseStringUTFChars(shader, shaderUTF);
+ jint ret = (jint)rsProgramVertexCreate(con, shaderUTF.c_str(), shaderUTF.length(), (uint32_t *)paramPtr, paramLen);
_env->ReleaseIntArrayElements(params, paramPtr, JNI_ABORT);
return ret;
}
@@ -1095,12 +1172,16 @@
{"rsnGetName", "(II)Ljava/lang/String;", (void*)nGetName },
{"rsnObjDestroy", "(II)V", (void*)nObjDestroy },
+{"rsnFileA3DCreateFromFile", "(ILjava/lang/String;)I", (void*)nFileA3DCreateFromFile },
{"rsnFileA3DCreateFromAssetStream", "(II)I", (void*)nFileA3DCreateFromAssetStream },
+{"rsnFileA3DCreateFromAsset", "(ILandroid/content/res/AssetManager;Ljava/lang/String;)I", (void*)nFileA3DCreateFromAsset },
{"rsnFileA3DGetNumIndexEntries", "(II)I", (void*)nFileA3DGetNumIndexEntries },
{"rsnFileA3DGetIndexEntries", "(III[I[Ljava/lang/String;)V", (void*)nFileA3DGetIndexEntries },
{"rsnFileA3DGetEntryByIndex", "(III)I", (void*)nFileA3DGetEntryByIndex },
{"rsnFontCreateFromFile", "(ILjava/lang/String;FI)I", (void*)nFontCreateFromFile },
+{"rsnFontCreateFromAssetStream", "(ILjava/lang/String;FII)I", (void*)nFontCreateFromAssetStream },
+{"rsnFontCreateFromAsset", "(ILandroid/content/res/AssetManager;Ljava/lang/String;FI)I", (void*)nFontCreateFromAsset },
{"rsnElementCreate", "(IIIZI)I", (void*)nElementCreate },
{"rsnElementCreate2", "(I[I[Ljava/lang/String;[I)I", (void*)nElementCreate2 },
diff --git a/include/camera/Camera.h b/include/camera/Camera.h
index c95f31e..e5f7e62 100644
--- a/include/camera/Camera.h
+++ b/include/camera/Camera.h
@@ -19,6 +19,7 @@
#include <utils/Timers.h>
#include <camera/ICameraClient.h>
+#include <gui/ISurfaceTexture.h>
namespace android {
@@ -175,6 +176,9 @@
// pass the buffered Surface to the camera service
status_t setPreviewDisplay(const sp<Surface>& surface);
+ // pass the buffered ISurfaceTexture to the camera service
+ status_t setPreviewTexture(const sp<ISurfaceTexture>& surfaceTexture);
+
// start preview mode, must call setPreviewDisplay first
status_t startPreview();
diff --git a/include/camera/ICamera.h b/include/camera/ICamera.h
index b69e075..b2310a6 100644
--- a/include/camera/ICamera.h
+++ b/include/camera/ICamera.h
@@ -24,6 +24,7 @@
#include <binder/IMemory.h>
#include <utils/String8.h>
#include <camera/Camera.h>
+#include <gui/ISurfaceTexture.h>
namespace android {
@@ -48,6 +49,10 @@
// pass the buffered Surface to the camera service
virtual status_t setPreviewDisplay(const sp<Surface>& surface) = 0;
+ // pass the buffered ISurfaceTexture to the camera service
+ virtual status_t setPreviewTexture(
+ const sp<ISurfaceTexture>& surfaceTexture) = 0;
+
// set the preview callback flag to affect how the received frames from
// preview are handled.
virtual void setPreviewCallbackFlag(int flag) = 0;
diff --git a/include/gui/ISurfaceTexture.h b/include/gui/ISurfaceTexture.h
new file mode 100644
index 0000000..77d37f1
--- /dev/null
+++ b/include/gui/ISurfaceTexture.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2010 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_GUI_ISURFACETEXTURE_H
+#define ANDROID_GUI_ISURFACETEXTURE_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+
+#include <binder/IInterface.h>
+
+#include <ui/GraphicBuffer.h>
+#include <ui/Rect.h>
+
+namespace android {
+// ----------------------------------------------------------------------------
+
+class ISurfaceTexture : public IInterface
+{
+public:
+ DECLARE_META_INTERFACE(SurfaceTexture);
+
+ // requestBuffer requests a new buffer for the given index. The server (i.e.
+ // the ISurfaceTexture implementation) assigns the newly created buffer to
+ // the given slot index, and the client is expected to mirror the
+ // slot->buffer mapping so that it's not necessary to transfer a
+ // GraphicBuffer for every dequeue operation.
+ virtual sp<GraphicBuffer> requestBuffer(int slot, uint32_t w, uint32_t h,
+ uint32_t format, uint32_t usage) = 0;
+
+ // setBufferCount sets the number of buffer slots available. Calling this
+ // will also cause all buffer slots to be emptied. The caller should empty
+ // its mirrored copy of the buffer slots when calling this method.
+ virtual status_t setBufferCount(int bufferCount) = 0;
+
+ // dequeueBuffer requests a new buffer slot for the client to use. Ownership
+ // of the slot is transfered to the client, meaning that the server will not
+ // use the contents of the buffer associated with that slot. The slot index
+ // returned may or may not contain a buffer. If the slot is empty the client
+ // should call requestBuffer to assign a new buffer to that slot. The client
+ // is expected to either call cancelBuffer on the dequeued slot or to fill
+ // in the contents of its associated buffer contents and call queueBuffer.
+ virtual status_t dequeueBuffer(int *slot) = 0;
+
+ // queueBuffer indicates that the client has finished filling in the
+ // contents of the buffer associated with slot and transfers ownership of
+ // that slot back to the server. It is not valid to call queueBuffer on a
+ // slot that is not owned by the client or one for which a buffer associated
+ // via requestBuffer.
+ virtual status_t queueBuffer(int slot) = 0;
+
+ // cancelBuffer indicates that the client does not wish to fill in the
+ // buffer associated with slot and transfers ownership of the slot back to
+ // the server.
+ virtual void cancelBuffer(int slot) = 0;
+
+ virtual status_t setCrop(const Rect& reg) = 0;
+ virtual status_t setTransform(uint32_t transform) = 0;
+};
+
+// ----------------------------------------------------------------------------
+
+class BnSurfaceTexture : public BnInterface<ISurfaceTexture>
+{
+public:
+ virtual status_t onTransact( uint32_t code,
+ const Parcel& data,
+ Parcel* reply,
+ uint32_t flags = 0);
+};
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_GUI_ISURFACETEXTURE_H
diff --git a/include/gui/SurfaceTexture.h b/include/gui/SurfaceTexture.h
new file mode 100644
index 0000000..cbc15d8
--- /dev/null
+++ b/include/gui/SurfaceTexture.h
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2010 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_GUI_SURFACETEXTURE_H
+#define ANDROID_GUI_SURFACETEXTURE_H
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES2/gl2.h>
+
+#include <gui/ISurfaceTexture.h>
+
+#include <ui/GraphicBuffer.h>
+
+#include <utils/threads.h>
+
+#define ANDROID_GRAPHICS_SURFACETEXTURE_JNI_ID "mSurfaceTexture"
+
+namespace android {
+// ----------------------------------------------------------------------------
+
+class SurfaceTexture : public BnSurfaceTexture {
+public:
+ enum { MIN_BUFFER_SLOTS = 3 };
+ enum { NUM_BUFFER_SLOTS = 32 };
+
+ // tex indicates the name OpenGL texture to which images are to be streamed.
+ // This texture name cannot be changed once the SurfaceTexture is created.
+ SurfaceTexture(GLuint tex);
+
+ virtual ~SurfaceTexture();
+
+ // setBufferCount updates the number of available buffer slots. After
+ // calling this all buffer slots are both unallocated and owned by the
+ // SurfaceTexture object (i.e. they are not owned by the client).
+ virtual status_t setBufferCount(int bufferCount);
+
+ virtual sp<GraphicBuffer> requestBuffer(int buf, uint32_t w, uint32_t h,
+ uint32_t format, uint32_t usage);
+
+ // dequeueBuffer gets the next buffer slot index for the client to use. If a
+ // buffer slot is available then that slot index is written to the location
+ // pointed to by the buf argument and a status of OK is returned. If no
+ // slot is available then a status of -EBUSY is returned and buf is
+ // unmodified.
+ virtual status_t dequeueBuffer(int *buf);
+
+ virtual status_t queueBuffer(int buf);
+ virtual void cancelBuffer(int buf);
+ virtual status_t setCrop(const Rect& reg);
+ virtual status_t setTransform(uint32_t transform);
+
+ // updateTexImage sets the image contents of the target texture to that of
+ // the most recently queued buffer.
+ //
+ // This call may only be made while the OpenGL ES context to which the
+ // target texture belongs is bound to the calling thread.
+ status_t updateTexImage();
+
+private:
+
+ // freeAllBuffers frees the resources (both GraphicBuffer and EGLImage) for
+ // all slots.
+ void freeAllBuffers();
+
+ // createImage creates a new EGLImage from a GraphicBuffer.
+ EGLImageKHR createImage(EGLDisplay dpy,
+ const sp<GraphicBuffer>& graphicBuffer);
+
+ enum { INVALID_BUFFER_SLOT = -1 };
+
+ struct BufferSlot {
+ // mGraphicBuffer points to the buffer allocated for this slot or is NULL
+ // if no buffer has been allocated.
+ sp<GraphicBuffer> mGraphicBuffer;
+
+ // mEglImage is the EGLImage created from mGraphicBuffer.
+ EGLImageKHR mEglImage;
+
+ // mEglDisplay is the EGLDisplay used to create mEglImage.
+ EGLDisplay mEglDisplay;
+
+ // mOwnedByClient indicates whether the slot is currently accessible to a
+ // client and should not be used by the SurfaceTexture object. It gets
+ // set to true when dequeueBuffer returns the slot and is reset to false
+ // when the client calls either queueBuffer or cancelBuffer on the slot.
+ bool mOwnedByClient;
+ };
+
+ // mSlots is the array of buffer slots that must be mirrored on the client
+ // side. This allows buffer ownership to be transferred between the client
+ // and server without sending a GraphicBuffer over binder. The entire array
+ // is initialized to NULL at construction time, and buffers are allocated
+ // for a slot when requestBuffer is called with that slot's index.
+ BufferSlot mSlots[NUM_BUFFER_SLOTS];
+
+ // mBufferCount is the number of buffer slots that the client and server
+ // must maintain. It defaults to MIN_BUFFER_SLOTS and can be changed by
+ // calling setBufferCount.
+ int mBufferCount;
+
+ // mCurrentTexture is the buffer slot index of the buffer that is currently
+ // bound to the OpenGL texture. It is initialized to INVALID_BUFFER_SLOT,
+ // indicating that no buffer slot is currently bound to the texture. Note,
+ // however, that a value of INVALID_BUFFER_SLOT does not necessarily mean
+ // that no buffer is bound to the texture. A call to setBufferCount will
+ // reset mCurrentTexture to INVALID_BUFFER_SLOT.
+ int mCurrentTexture;
+
+ // mLastQueued is the buffer slot index of the most recently enqueued buffer.
+ // At construction time it is initialized to INVALID_BUFFER_SLOT, and is
+ // updated each time queueBuffer is called.
+ int mLastQueued;
+
+ // mTexName is the name of the OpenGL texture to which streamed images will
+ // be bound when updateTexImage is called. It is set at construction time
+ // changed with a call to setTexName.
+ const GLuint mTexName;
+
+ // mMutex is the mutex used to prevent concurrent access to the member
+ // variables of SurfaceTexture objects. It must be locked whenever the
+ // member variables are accessed.
+ Mutex mMutex;
+};
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+
+#endif // ANDROID_GUI_SURFACETEXTURE_H
diff --git a/include/gui/SurfaceTextureClient.h b/include/gui/SurfaceTextureClient.h
new file mode 100644
index 0000000..dd1d490
--- /dev/null
+++ b/include/gui/SurfaceTextureClient.h
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2010 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_GUI_SURFACETEXTURECLIENT_H
+#define ANDROID_GUI_SURFACETEXTURECLIENT_H
+
+#include <gui/ISurfaceTexture.h>
+#include <gui/SurfaceTexture.h>
+
+#include <ui/egl/android_natives.h>
+
+#include <utils/RefBase.h>
+#include <utils/threads.h>
+
+namespace android {
+
+class SurfaceTextureClient
+ : public EGLNativeBase<ANativeWindow, SurfaceTextureClient, RefBase>
+{
+public:
+ SurfaceTextureClient(const sp<ISurfaceTexture>& surfaceTexture);
+
+private:
+
+ // can't be copied
+ SurfaceTextureClient& operator = (const SurfaceTextureClient& rhs);
+ SurfaceTextureClient(const SurfaceTextureClient& rhs);
+
+ // ANativeWindow hooks
+ static int setSwapInterval(ANativeWindow* window, int interval);
+ static int dequeueBuffer(ANativeWindow* window, android_native_buffer_t** buffer);
+ static int cancelBuffer(ANativeWindow* window, android_native_buffer_t* buffer);
+ static int lockBuffer(ANativeWindow* window, android_native_buffer_t* buffer);
+ static int queueBuffer(ANativeWindow* window, android_native_buffer_t* buffer);
+ static int query(ANativeWindow* window, int what, int* value);
+ static int perform(ANativeWindow* window, int operation, ...);
+
+ int setSwapInterval(int interval);
+ int dequeueBuffer(android_native_buffer_t** buffer);
+ int lockBuffer(android_native_buffer_t* buffer);
+ int queueBuffer(android_native_buffer_t* buffer);
+ int cancelBuffer(android_native_buffer_t* buffer);
+ int query(int what, int* value);
+ int perform(int operation, va_list args);
+
+ int dispatchSetUsage(va_list args);
+ int dispatchConnect(va_list args);
+ int dispatchDisconnect(va_list args);
+ int dispatchSetCrop(va_list args);
+ int dispatchSetBufferCount(va_list args);
+ int dispatchSetBuffersGeometry(va_list args);
+ int dispatchSetBuffersTransform(va_list args);
+
+ int connect(int api);
+ int disconnect(int api);
+ int setUsage(uint32_t reqUsage);
+ int setCrop(Rect const* rect);
+ int setBufferCount(int bufferCount);
+ int setBuffersGeometry(int w, int h, int format);
+ int setBuffersTransform(int transform);
+
+ void freeAllBuffers();
+
+ enum { MIN_BUFFER_SLOTS = SurfaceTexture::MIN_BUFFER_SLOTS };
+ enum { NUM_BUFFER_SLOTS = SurfaceTexture::NUM_BUFFER_SLOTS };
+ enum { DEFAULT_FORMAT = PIXEL_FORMAT_RGBA_8888 };
+
+ // mSurfaceTexture is the interface to the surface texture server. All
+ // operations on the surface texture client ultimately translate into
+ // interactions with the server using this interface.
+ sp<ISurfaceTexture> mSurfaceTexture;
+
+ // mSlots stores the buffers that have been allocated for each buffer slot.
+ // It is initialized to null pointers, and gets filled in with the result of
+ // ISurfaceTexture::requestBuffer when the client dequeues a buffer from a
+ // slot that has not yet been used. The buffer allocated to a slot will also
+ // be replaced if the requested buffer usage or geometry differs from that
+ // of the buffer allocated to a slot.
+ sp<GraphicBuffer> mSlots[NUM_BUFFER_SLOTS];
+
+ // mReqWidth is the buffer width that will be requested at the next dequeue
+ // operation. It is initialized to 1.
+ uint32_t mReqWidth;
+
+ // mReqHeight is the buffer height that will be requested at the next deuque
+ // operation. It is initialized to 1.
+ uint32_t mReqHeight;
+
+ // mReqFormat is the buffer pixel format that will be requested at the next
+ // deuque operation. It is initialized to PIXEL_FORMAT_RGBA_8888.
+ uint32_t mReqFormat;
+
+ // mReqUsage is the set of buffer usage flags that will be requested
+ // at the next deuque operation. It is initialized to 0.
+ uint32_t mReqUsage;
+
+ // mMutex is the mutex used to prevent concurrent access to the member
+ // variables of SurfaceTexture objects. It must be locked whenever the
+ // member variables are accessed.
+ Mutex mMutex;
+};
+
+}; // namespace android
+
+#endif // ANDROID_GUI_SURFACETEXTURECLIENT_H
diff --git a/include/media/mediametadataretriever.h b/include/media/mediametadataretriever.h
index ed54b37..03dd52d 100644
--- a/include/media/mediametadataretriever.h
+++ b/include/media/mediametadataretriever.h
@@ -56,6 +56,7 @@
METADATA_KEY_MIMETYPE = 22,
METADATA_KEY_DISC_NUMBER = 23,
METADATA_KEY_ALBUMARTIST = 24,
+ METADATA_KEY_COMPILATION = 25,
// Add more here...
};
diff --git a/include/media/stagefright/ACodec.h b/include/media/stagefright/ACodec.h
index b3815c4..4599d70 100644
--- a/include/media/stagefright/ACodec.h
+++ b/include/media/stagefright/ACodec.h
@@ -101,6 +101,8 @@
List<sp<AMessage> > mDeferredQueue;
+ bool mSentFormat;
+
status_t allocateBuffersOnPort(OMX_U32 portIndex);
status_t freeBuffersOnPort(OMX_U32 portIndex);
status_t freeBuffer(OMX_U32 portIndex, size_t i);
@@ -145,6 +147,8 @@
void deferMessage(const sp<AMessage> &msg);
void processDeferredMessages();
+ void sendFormatChange();
+
DISALLOW_EVIL_CONSTRUCTORS(ACodec);
};
diff --git a/include/media/stagefright/ColorConverter.h b/include/media/stagefright/ColorConverter.h
index 2b61f58..2ae8a5b 100644
--- a/include/media/stagefright/ColorConverter.h
+++ b/include/media/stagefright/ColorConverter.h
@@ -21,6 +21,7 @@
#include <sys/types.h>
#include <stdint.h>
+#include <utils/Errors.h>
#include <OMX_Video.h>
@@ -32,7 +33,7 @@
bool isValid() const;
- void convert(
+ status_t convert(
const void *srcBits,
size_t srcWidth, size_t srcHeight,
size_t srcCropLeft, size_t srcCropTop,
@@ -63,16 +64,16 @@
uint8_t *initClip();
- void convertCbYCrY(
+ status_t convertCbYCrY(
const BitmapParams &src, const BitmapParams &dst);
- void convertYUV420Planar(
+ status_t convertYUV420Planar(
const BitmapParams &src, const BitmapParams &dst);
- void convertQCOMYUV420SemiPlanar(
+ status_t convertQCOMYUV420SemiPlanar(
const BitmapParams &src, const BitmapParams &dst);
- void convertYUV420SemiPlanar(
+ status_t convertYUV420SemiPlanar(
const BitmapParams &src, const BitmapParams &dst);
ColorConverter(const ColorConverter &);
diff --git a/include/media/stagefright/MetaData.h b/include/media/stagefright/MetaData.h
index 5f33739..5170a2c 100644
--- a/include/media/stagefright/MetaData.h
+++ b/include/media/stagefright/MetaData.h
@@ -80,6 +80,7 @@
kKeyDiscNumber = 'dnum', // cstring
kKeyDate = 'date', // cstring
kKeyWriter = 'writ', // cstring
+ kKeyCompilation = 'cpil', // cstring
kKeyTimeScale = 'tmsl', // int32_t
// video profile and level
diff --git a/include/media/stagefright/OMXCodec.h b/include/media/stagefright/OMXCodec.h
index bba5b53..f8daa4f 100644
--- a/include/media/stagefright/OMXCodec.h
+++ b/include/media/stagefright/OMXCodec.h
@@ -70,8 +70,6 @@
virtual status_t pause();
- void on_message(const omx_message &msg);
-
// from MediaBufferObserver
virtual void signalBufferReturned(MediaBuffer *buffer);
@@ -79,6 +77,13 @@
virtual ~OMXCodec();
private:
+
+ // Make sure mLock is accessible to OMXCodecObserver
+ friend class OMXCodecObserver;
+
+ // Call this with mLock hold
+ void on_message(const omx_message &msg);
+
enum State {
DEAD,
LOADED,
diff --git a/include/media/stagefright/foundation/AMessage.h b/include/media/stagefright/foundation/AMessage.h
index 91ec60c..72dc730 100644
--- a/include/media/stagefright/foundation/AMessage.h
+++ b/include/media/stagefright/foundation/AMessage.h
@@ -52,6 +52,10 @@
void setObject(const char *name, const sp<RefBase> &obj);
void setMessage(const char *name, const sp<AMessage> &obj);
+ void setRect(
+ const char *name,
+ int32_t left, int32_t top, int32_t right, int32_t bottom);
+
bool findInt32(const char *name, int32_t *value) const;
bool findInt64(const char *name, int64_t *value) const;
bool findSize(const char *name, size_t *value) const;
@@ -62,6 +66,10 @@
bool findObject(const char *name, sp<RefBase> *obj) const;
bool findMessage(const char *name, sp<AMessage> *obj) const;
+ bool findRect(
+ const char *name,
+ int32_t *left, int32_t *top, int32_t *right, int32_t *bottom) const;
+
void post(int64_t delayUs = 0);
// Performs a deep-copy of "this", contained messages are in turn "dup'ed".
@@ -85,11 +93,16 @@
kTypeString,
kTypeObject,
kTypeMessage,
+ kTypeRect,
};
uint32_t mWhat;
ALooper::handler_id mTarget;
+ struct Rect {
+ int32_t mLeft, mTop, mRight, mBottom;
+ };
+
struct Item {
union {
int32_t int32Value;
@@ -100,6 +113,7 @@
void *ptrValue;
RefBase *refValue;
AString *stringValue;
+ Rect rectValue;
} u;
const char *mName;
Type mType;
diff --git a/include/surfaceflinger/ISurfaceComposer.h b/include/surfaceflinger/ISurfaceComposer.h
index 693fbfb..1bab7d7 100644
--- a/include/surfaceflinger/ISurfaceComposer.h
+++ b/include/surfaceflinger/ISurfaceComposer.h
@@ -131,6 +131,13 @@
* This is an ASYNCHRONOUS call.
*/
virtual void signal() const = 0;
+
+ /* Create a new GraphicBuffer for the client to use. SurfaceFlinger will
+ * not maintain a reference to the GraphicBuffer, so the underlying native
+ * handle will be freed once the client references are released.
+ */
+ virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
+ PixelFormat format, uint32_t usage) const = 0;
};
// ----------------------------------------------------------------------------
@@ -144,6 +151,7 @@
BOOT_FINISHED = IBinder::FIRST_CALL_TRANSACTION,
CREATE_CONNECTION,
CREATE_CLIENT_CONNECTION,
+ CREATE_GRAPHIC_BUFFER,
GET_CBLK,
OPEN_GLOBAL_TRANSACTION,
CLOSE_GLOBAL_TRANSACTION,
diff --git a/include/ui/GraphicBuffer.h b/include/ui/GraphicBuffer.h
index aa65d93..8b256f4 100644
--- a/include/ui/GraphicBuffer.h
+++ b/include/ui/GraphicBuffer.h
@@ -121,6 +121,7 @@
friend class Surface;
friend class BpSurface;
friend class BnSurface;
+ friend class SurfaceTextureClient;
friend class LightRefBase<GraphicBuffer>;
GraphicBuffer(const GraphicBuffer& rhs);
GraphicBuffer& operator = (const GraphicBuffer& rhs);
diff --git a/libs/camera/Android.mk b/libs/camera/Android.mk
index 03ff229..2f16923 100644
--- a/libs/camera/Android.mk
+++ b/libs/camera/Android.mk
@@ -14,7 +14,8 @@
libbinder \
libhardware \
libsurfaceflinger_client \
- libui
+ libui \
+ libgui
LOCAL_MODULE:= libcamera_client
diff --git a/libs/camera/Camera.cpp b/libs/camera/Camera.cpp
index ab626ad..907f119 100644
--- a/libs/camera/Camera.cpp
+++ b/libs/camera/Camera.cpp
@@ -182,6 +182,20 @@
}
}
+// pass the buffered ISurfaceTexture to the camera service
+status_t Camera::setPreviewTexture(const sp<ISurfaceTexture>& surfaceTexture)
+{
+ LOGV("setPreviewTexture(%p)", surfaceTexture.get());
+ sp <ICamera> c = mCamera;
+ if (c == 0) return NO_INIT;
+ if (surfaceTexture != 0) {
+ return c->setPreviewTexture(surfaceTexture);
+ } else {
+ LOGD("app passed NULL surface");
+ return c->setPreviewTexture(0);
+ }
+}
+
// start preview mode
status_t Camera::startPreview()
{
diff --git a/libs/camera/ICamera.cpp b/libs/camera/ICamera.cpp
index 7ba8d12..0881d65 100644
--- a/libs/camera/ICamera.cpp
+++ b/libs/camera/ICamera.cpp
@@ -28,6 +28,7 @@
enum {
DISCONNECT = IBinder::FIRST_CALL_TRANSACTION,
SET_PREVIEW_DISPLAY,
+ SET_PREVIEW_TEXTURE,
SET_PREVIEW_CALLBACK_FLAG,
START_PREVIEW,
STOP_PREVIEW,
@@ -78,6 +79,18 @@
return reply.readInt32();
}
+ // pass the buffered SurfaceTexture to the camera service
+ status_t setPreviewTexture(const sp<ISurfaceTexture>& surfaceTexture)
+ {
+ LOGV("setPreviewTexture");
+ Parcel data, reply;
+ data.writeInterfaceToken(ICamera::getInterfaceDescriptor());
+ sp<IBinder> b(surfaceTexture->asBinder());
+ data.writeStrongBinder(b);
+ remote()->transact(SET_PREVIEW_TEXTURE, data, &reply);
+ return reply.readInt32();
+ }
+
// set the preview callback flag to affect how the received frames from
// preview are handled. See Camera.h for details.
void setPreviewCallbackFlag(int flag)
@@ -296,6 +309,13 @@
reply->writeInt32(setPreviewDisplay(surface));
return NO_ERROR;
} break;
+ case SET_PREVIEW_TEXTURE: {
+ LOGV("SET_PREVIEW_TEXTURE");
+ CHECK_INTERFACE(ICamera, data, reply);
+ sp<ISurfaceTexture> st = interface_cast<ISurfaceTexture>(data.readStrongBinder());
+ reply->writeInt32(setPreviewTexture(st));
+ return NO_ERROR;
+ } break;
case SET_PREVIEW_CALLBACK_FLAG: {
LOGV("SET_PREVIEW_CALLBACK_TYPE");
CHECK_INTERFACE(ICamera, data, reply);
diff --git a/libs/gui/Android.mk b/libs/gui/Android.mk
index 249558a..d1a6af1 100644
--- a/libs/gui/Android.mk
+++ b/libs/gui/Android.mk
@@ -4,17 +4,25 @@
LOCAL_SRC_FILES:= \
ISensorEventConnection.cpp \
ISensorServer.cpp \
+ ISurfaceTexture.cpp \
Sensor.cpp \
SensorChannel.cpp \
SensorEventQueue.cpp \
- SensorManager.cpp
+ SensorManager.cpp \
+ SurfaceTexture.cpp \
+ SurfaceTextureClient.cpp
LOCAL_SHARED_LIBRARIES := \
libcutils \
libutils \
libbinder \
libhardware \
- libhardware_legacy
+ libhardware_legacy \
+ libui \
+ libEGL \
+ libGLESv2 \
+ libsurfaceflinger_client
+
LOCAL_MODULE:= libgui
diff --git a/libs/gui/ISurfaceTexture.cpp b/libs/gui/ISurfaceTexture.cpp
new file mode 100644
index 0000000..90bca3c
--- /dev/null
+++ b/libs/gui/ISurfaceTexture.cpp
@@ -0,0 +1,204 @@
+/*
+ * Copyright (C) 2010 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 <stdint.h>
+#include <sys/types.h>
+
+#include <utils/Errors.h>
+#include <utils/RefBase.h>
+#include <utils/Vector.h>
+#include <utils/Timers.h>
+
+#include <binder/Parcel.h>
+#include <binder/IInterface.h>
+
+#include <gui/ISurfaceTexture.h>
+
+namespace android {
+// ----------------------------------------------------------------------------
+
+enum {
+ REQUEST_BUFFER = IBinder::FIRST_CALL_TRANSACTION,
+ SET_BUFFER_COUNT,
+ DEQUEUE_BUFFER,
+ QUEUE_BUFFER,
+ CANCEL_BUFFER,
+ SET_CROP,
+ SET_TRANSFORM,
+};
+
+
+class BpSurfaceTexture : public BpInterface<ISurfaceTexture>
+{
+public:
+ BpSurfaceTexture(const sp<IBinder>& impl)
+ : BpInterface<ISurfaceTexture>(impl)
+ {
+ }
+
+ virtual sp<GraphicBuffer> requestBuffer(int bufferIdx,
+ uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
+ Parcel data, reply;
+ data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
+ data.writeInt32(bufferIdx);
+ data.writeInt32(w);
+ data.writeInt32(h);
+ data.writeInt32(format);
+ data.writeInt32(usage);
+ remote()->transact(REQUEST_BUFFER, data, &reply);
+ sp<GraphicBuffer> buffer;
+ bool nonNull = reply.readInt32();
+ if (nonNull) {
+ buffer = new GraphicBuffer();
+ reply.read(*buffer);
+ }
+ return buffer;
+ }
+
+ virtual status_t setBufferCount(int bufferCount)
+ {
+ Parcel data, reply;
+ data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
+ data.writeInt32(bufferCount);
+ remote()->transact(SET_BUFFER_COUNT, data, &reply);
+ status_t err = reply.readInt32();
+ return err;
+ }
+
+ virtual status_t dequeueBuffer(int *buf) {
+ Parcel data, reply;
+ data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
+ remote()->transact(DEQUEUE_BUFFER, data, &reply);
+ *buf = reply.readInt32();
+ int result = reply.readInt32();
+ return result;
+ }
+
+ virtual status_t queueBuffer(int buf) {
+ Parcel data, reply;
+ data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
+ data.writeInt32(buf);
+ remote()->transact(QUEUE_BUFFER, data, &reply);
+ status_t result = reply.readInt32();
+ return result;
+ }
+
+ virtual void cancelBuffer(int buf) {
+ Parcel data, reply;
+ data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
+ data.writeInt32(buf);
+ remote()->transact(CANCEL_BUFFER, data, &reply);
+ }
+
+ virtual status_t setCrop(const Rect& reg) {
+ Parcel data, reply;
+ data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
+ data.writeFloat(reg.left);
+ data.writeFloat(reg.top);
+ data.writeFloat(reg.right);
+ data.writeFloat(reg.bottom);
+ remote()->transact(SET_CROP, data, &reply);
+ status_t result = reply.readInt32();
+ return result;
+ }
+
+ virtual status_t setTransform(uint32_t transform) {
+ Parcel data, reply;
+ data.writeInterfaceToken(ISurfaceTexture::getInterfaceDescriptor());
+ data.writeInt32(transform);
+ remote()->transact(SET_TRANSFORM, data, &reply);
+ status_t result = reply.readInt32();
+ return result;
+ }
+};
+
+IMPLEMENT_META_INTERFACE(SurfaceTexture, "android.gui.SurfaceTexture");
+
+// ----------------------------------------------------------------------
+
+status_t BnSurfaceTexture::onTransact(
+ uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
+{
+ switch(code) {
+ case REQUEST_BUFFER: {
+ CHECK_INTERFACE(ISurfaceTexture, data, reply);
+ int bufferIdx = data.readInt32();
+ uint32_t w = data.readInt32();
+ uint32_t h = data.readInt32();
+ uint32_t format = data.readInt32();
+ uint32_t usage = data.readInt32();
+ sp<GraphicBuffer> buffer(requestBuffer(bufferIdx, w, h, format,
+ usage));
+ reply->writeInt32(buffer != 0);
+ if (buffer != 0) {
+ reply->write(*buffer);
+ }
+ return NO_ERROR;
+ } break;
+ case SET_BUFFER_COUNT: {
+ CHECK_INTERFACE(ISurfaceTexture, data, reply);
+ int bufferCount = data.readInt32();
+ int result = setBufferCount(bufferCount);
+ reply->writeInt32(result);
+ return NO_ERROR;
+ } break;
+ case DEQUEUE_BUFFER: {
+ CHECK_INTERFACE(ISurfaceTexture, data, reply);
+ int buf;
+ int result = dequeueBuffer(&buf);
+ reply->writeInt32(buf);
+ reply->writeInt32(result);
+ return NO_ERROR;
+ } break;
+ case QUEUE_BUFFER: {
+ CHECK_INTERFACE(ISurfaceTexture, data, reply);
+ int buf = data.readInt32();
+ status_t result = queueBuffer(buf);
+ reply->writeInt32(result);
+ return NO_ERROR;
+ } break;
+ case CANCEL_BUFFER: {
+ CHECK_INTERFACE(ISurfaceTexture, data, reply);
+ int buf = data.readInt32();
+ cancelBuffer(buf);
+ return NO_ERROR;
+ } break;
+ case SET_CROP: {
+ Rect reg;
+ CHECK_INTERFACE(ISurfaceTexture, data, reply);
+ reg.left = data.readFloat();
+ reg.top = data.readFloat();
+ reg.right = data.readFloat();
+ reg.bottom = data.readFloat();
+ status_t result = setCrop(reg);
+ reply->writeInt32(result);
+ return NO_ERROR;
+ } break;
+ case SET_TRANSFORM: {
+ Rect reg;
+ CHECK_INTERFACE(ISurfaceTexture, data, reply);
+ uint32_t transform = data.readInt32();
+ status_t result = setTransform(transform);
+ reply->writeInt32(result);
+ return NO_ERROR;
+ } break;
+ }
+ return BBinder::onTransact(code, data, reply, flags);
+}
+
+// ----------------------------------------------------------------------------
+
+}; // namespace android
diff --git a/libs/gui/SurfaceTexture.cpp b/libs/gui/SurfaceTexture.cpp
new file mode 100644
index 0000000..11a48d9
--- /dev/null
+++ b/libs/gui/SurfaceTexture.cpp
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2010 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 "SurfaceTexture"
+//#define LOG_NDEBUG 0
+
+#define GL_GLEXT_PROTOTYPES
+#define EGL_EGLEXT_PROTOTYPES
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+#include <gui/SurfaceTexture.h>
+
+#include <surfaceflinger/ISurfaceComposer.h>
+#include <surfaceflinger/SurfaceComposerClient.h>
+
+#include <utils/Log.h>
+
+namespace android {
+
+SurfaceTexture::SurfaceTexture(GLuint tex) :
+ mBufferCount(MIN_BUFFER_SLOTS), mCurrentTexture(INVALID_BUFFER_SLOT),
+ mLastQueued(INVALID_BUFFER_SLOT), mTexName(tex) {
+ LOGV("SurfaceTexture::SurfaceTexture");
+ for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
+ mSlots[i].mEglImage = EGL_NO_IMAGE_KHR;
+ mSlots[i].mEglDisplay = EGL_NO_DISPLAY;
+ mSlots[i].mOwnedByClient = false;
+ }
+}
+
+SurfaceTexture::~SurfaceTexture() {
+ LOGV("SurfaceTexture::~SurfaceTexture");
+ freeAllBuffers();
+}
+
+status_t SurfaceTexture::setBufferCount(int bufferCount) {
+ LOGV("SurfaceTexture::setBufferCount");
+ Mutex::Autolock lock(mMutex);
+ freeAllBuffers();
+ mBufferCount = bufferCount;
+ mCurrentTexture = INVALID_BUFFER_SLOT;
+ mLastQueued = INVALID_BUFFER_SLOT;
+ return OK;
+}
+
+sp<GraphicBuffer> SurfaceTexture::requestBuffer(int buf,
+ uint32_t w, uint32_t h, uint32_t format, uint32_t usage) {
+ LOGV("SurfaceTexture::requestBuffer");
+ Mutex::Autolock lock(mMutex);
+ if (buf < 0 || mBufferCount <= buf) {
+ LOGE("requestBuffer: slot index out of range [0, %d]: %d",
+ mBufferCount, buf);
+ return 0;
+ }
+ usage |= GraphicBuffer::USAGE_HW_TEXTURE;
+ sp<ISurfaceComposer> composer(ComposerService::getComposerService());
+ sp<GraphicBuffer> graphicBuffer(composer->createGraphicBuffer(w, h,
+ format, usage));
+ if (graphicBuffer == 0) {
+ LOGE("requestBuffer: SurfaceComposer::createGraphicBuffer failed");
+ } else {
+ mSlots[buf].mGraphicBuffer = graphicBuffer;
+ if (mSlots[buf].mEglImage != EGL_NO_IMAGE_KHR) {
+ eglDestroyImageKHR(mSlots[buf].mEglDisplay, mSlots[buf].mEglImage);
+ mSlots[buf].mEglImage = EGL_NO_IMAGE_KHR;
+ mSlots[buf].mEglDisplay = EGL_NO_DISPLAY;
+ }
+ }
+ return graphicBuffer;
+}
+
+status_t SurfaceTexture::dequeueBuffer(int *buf) {
+ LOGV("SurfaceTexture::dequeueBuffer");
+ Mutex::Autolock lock(mMutex);
+ int found = INVALID_BUFFER_SLOT;
+ for (int i = 0; i < mBufferCount; i++) {
+ if (!mSlots[i].mOwnedByClient && i != mCurrentTexture) {
+ mSlots[i].mOwnedByClient = true;
+ found = i;
+ break;
+ }
+ }
+ if (found == INVALID_BUFFER_SLOT) {
+ return -EBUSY;
+ }
+ *buf = found;
+ return OK;
+}
+
+status_t SurfaceTexture::queueBuffer(int buf) {
+ LOGV("SurfaceTexture::queueBuffer");
+ Mutex::Autolock lock(mMutex);
+ if (buf < 0 || mBufferCount <= buf) {
+ LOGE("queueBuffer: slot index out of range [0, %d]: %d",
+ mBufferCount, buf);
+ return -EINVAL;
+ } else if (!mSlots[buf].mOwnedByClient) {
+ LOGE("queueBuffer: slot %d is not owned by the client", buf);
+ return -EINVAL;
+ } else if (mSlots[buf].mGraphicBuffer == 0) {
+ LOGE("queueBuffer: slot %d was enqueued without requesting a buffer",
+ buf);
+ return -EINVAL;
+ }
+ mSlots[buf].mOwnedByClient = false;
+ mLastQueued = buf;
+ return OK;
+}
+
+void SurfaceTexture::cancelBuffer(int buf) {
+ LOGV("SurfaceTexture::cancelBuffer");
+ Mutex::Autolock lock(mMutex);
+ if (buf < 0 || mBufferCount <= buf) {
+ LOGE("cancelBuffer: slot index out of range [0, %d]: %d", mBufferCount,
+ buf);
+ return;
+ } else if (!mSlots[buf].mOwnedByClient) {
+ LOGE("cancelBuffer: slot %d is not owned by the client", buf);
+ return;
+ }
+ mSlots[buf].mOwnedByClient = false;
+}
+
+status_t SurfaceTexture::setCrop(const Rect& reg) {
+ LOGV("SurfaceTexture::setCrop");
+ Mutex::Autolock lock(mMutex);
+ // XXX: How should we handle crops?
+ return OK;
+}
+
+status_t SurfaceTexture::setTransform(uint32_t transform) {
+ LOGV("SurfaceTexture::setTransform");
+ Mutex::Autolock lock(mMutex);
+ // XXX: How should we handle transforms?
+ return OK;
+}
+
+status_t SurfaceTexture::updateTexImage() {
+ LOGV("SurfaceTexture::updateTexImage");
+ Mutex::Autolock lock(mMutex);
+
+ // We always bind the texture even if we don't update its contents.
+ glBindTexture(GL_TEXTURE_EXTERNAL_OES, mTexName);
+
+ // Initially both mCurrentTexture and mLastQueued are INVALID_BUFFER_SLOT,
+ // so this check will fail until a buffer gets queued.
+ if (mCurrentTexture != mLastQueued) {
+ // XXX: Figure out the right target.
+ mCurrentTexture = mLastQueued;
+ EGLImageKHR image = mSlots[mCurrentTexture].mEglImage;
+ if (image == EGL_NO_IMAGE_KHR) {
+ EGLDisplay dpy = eglGetCurrentDisplay();
+ sp<GraphicBuffer> graphicBuffer = mSlots[mCurrentTexture].mGraphicBuffer;
+ image = createImage(dpy, graphicBuffer);
+ mSlots[mCurrentTexture].mEglImage = image;
+ mSlots[mCurrentTexture].mEglDisplay = dpy;
+ }
+ glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, (GLeglImageOES)image);
+ GLint error = glGetError();
+ if (error != GL_NO_ERROR) {
+ LOGE("error binding external texture image %p (slot %d): %#04x",
+ image, mCurrentTexture, error);
+ return -EINVAL;
+ }
+ }
+ return OK;
+}
+
+void SurfaceTexture::freeAllBuffers() {
+ for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
+ mSlots[i].mGraphicBuffer = 0;
+ mSlots[i].mOwnedByClient = false;
+ if (mSlots[i].mEglImage != EGL_NO_IMAGE_KHR) {
+ eglDestroyImageKHR(mSlots[i].mEglDisplay, mSlots[i].mEglImage);
+ mSlots[i].mEglImage = EGL_NO_IMAGE_KHR;
+ mSlots[i].mEglDisplay = EGL_NO_DISPLAY;
+ }
+ }
+}
+
+EGLImageKHR SurfaceTexture::createImage(EGLDisplay dpy,
+ const sp<GraphicBuffer>& graphicBuffer) {
+ EGLClientBuffer cbuf = (EGLClientBuffer)graphicBuffer->getNativeBuffer();
+ EGLint attrs[] = {
+ EGL_IMAGE_PRESERVED_KHR, EGL_TRUE,
+ EGL_NONE,
+ };
+ EGLImageKHR image = eglCreateImageKHR(dpy, EGL_NO_CONTEXT,
+ EGL_NATIVE_BUFFER_ANDROID, cbuf, attrs);
+ EGLint error = eglGetError();
+ if (error != EGL_SUCCESS) {
+ LOGE("error creating EGLImage: %#x", error);
+ } else if (image == EGL_NO_IMAGE_KHR) {
+ LOGE("no error reported, but no image was returned by "
+ "eglCreateImageKHR");
+ }
+ return image;
+}
+
+}; // namespace android
diff --git a/libs/gui/SurfaceTextureClient.cpp b/libs/gui/SurfaceTextureClient.cpp
new file mode 100644
index 0000000..8a59144
--- /dev/null
+++ b/libs/gui/SurfaceTextureClient.cpp
@@ -0,0 +1,285 @@
+/*
+ * Copyright (C) 2010 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 "SurfaceTextureClient"
+
+#include <gui/SurfaceTextureClient.h>
+
+#include <utils/Log.h>
+
+namespace android {
+
+SurfaceTextureClient::SurfaceTextureClient(
+ const sp<ISurfaceTexture>& surfaceTexture):
+ mSurfaceTexture(surfaceTexture), mReqWidth(1), mReqHeight(1),
+ mReqFormat(DEFAULT_FORMAT), mReqUsage(0), mMutex() {
+ // Initialize the ANativeWindow function pointers.
+ ANativeWindow::setSwapInterval = setSwapInterval;
+ ANativeWindow::dequeueBuffer = dequeueBuffer;
+ ANativeWindow::cancelBuffer = cancelBuffer;
+ ANativeWindow::lockBuffer = lockBuffer;
+ ANativeWindow::queueBuffer = queueBuffer;
+ ANativeWindow::query = query;
+ ANativeWindow::perform = perform;
+}
+
+int SurfaceTextureClient::setSwapInterval(ANativeWindow* window, int interval) {
+ SurfaceTextureClient* c = getSelf(window);
+ return c->setSwapInterval(interval);
+}
+
+int SurfaceTextureClient::dequeueBuffer(ANativeWindow* window,
+ android_native_buffer_t** buffer) {
+ SurfaceTextureClient* c = getSelf(window);
+ return c->dequeueBuffer(buffer);
+}
+
+int SurfaceTextureClient::cancelBuffer(ANativeWindow* window,
+ android_native_buffer_t* buffer) {
+ SurfaceTextureClient* c = getSelf(window);
+ return c->cancelBuffer(buffer);
+}
+
+int SurfaceTextureClient::lockBuffer(ANativeWindow* window,
+ android_native_buffer_t* buffer) {
+ SurfaceTextureClient* c = getSelf(window);
+ return c->lockBuffer(buffer);
+}
+
+int SurfaceTextureClient::queueBuffer(ANativeWindow* window,
+ android_native_buffer_t* buffer) {
+ SurfaceTextureClient* c = getSelf(window);
+ return c->queueBuffer(buffer);
+}
+
+int SurfaceTextureClient::query(ANativeWindow* window, int what, int* value) {
+ SurfaceTextureClient* c = getSelf(window);
+ return c->query(what, value);
+}
+
+int SurfaceTextureClient::perform(ANativeWindow* window, int operation, ...) {
+ va_list args;
+ va_start(args, operation);
+ SurfaceTextureClient* c = getSelf(window);
+ return c->perform(operation, args);
+}
+
+int SurfaceTextureClient::setSwapInterval(int interval) {
+ return INVALID_OPERATION;
+}
+
+int SurfaceTextureClient::dequeueBuffer(android_native_buffer_t** buffer) {
+ Mutex::Autolock lock(mMutex);
+ int buf = -1;
+ status_t err = mSurfaceTexture->dequeueBuffer(&buf);
+ if (err < 0) {
+ return err;
+ }
+ sp<GraphicBuffer>& gbuf(mSlots[buf]);
+ if (gbuf == 0 || gbuf->getWidth() != mReqWidth ||
+ gbuf->getHeight() != mReqHeight ||
+ uint32_t(gbuf->getPixelFormat()) != mReqFormat ||
+ (gbuf->getUsage() & mReqUsage) != mReqUsage) {
+ gbuf = mSurfaceTexture->requestBuffer(buf, mReqWidth, mReqHeight,
+ mReqFormat, mReqUsage);
+ if (gbuf == 0) {
+ return NO_MEMORY;
+ }
+ }
+ *buffer = gbuf.get();
+ return OK;
+}
+
+int SurfaceTextureClient::cancelBuffer(android_native_buffer_t* buffer) {
+ Mutex::Autolock lock(mMutex);
+ for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
+ if (mSlots[i].get() == buffer) {
+ mSurfaceTexture->cancelBuffer(i);
+ return OK;
+ }
+ }
+ return BAD_VALUE;
+}
+
+int SurfaceTextureClient::lockBuffer(android_native_buffer_t* buffer) {
+ Mutex::Autolock lock(mMutex);
+ return OK;
+}
+
+int SurfaceTextureClient::queueBuffer(android_native_buffer_t* buffer) {
+ Mutex::Autolock lock(mMutex);
+ for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
+ if (mSlots[i].get() == GraphicBuffer::getSelf(buffer)) {
+ return mSurfaceTexture->queueBuffer(i);
+ }
+ }
+ LOGE("queueBuffer: unknown buffer queued");
+ return BAD_VALUE;
+}
+
+int SurfaceTextureClient::query(int what, int* value) {
+ Mutex::Autolock lock(mMutex);
+ // XXX: Implement this!
+ return INVALID_OPERATION;
+}
+
+int SurfaceTextureClient::perform(int operation, va_list args)
+{
+ int res = NO_ERROR;
+ switch (operation) {
+ case NATIVE_WINDOW_CONNECT:
+ res = dispatchConnect(args);
+ break;
+ case NATIVE_WINDOW_DISCONNECT:
+ res = dispatchDisconnect(args);
+ break;
+ case NATIVE_WINDOW_SET_USAGE:
+ res = dispatchSetUsage(args);
+ break;
+ case NATIVE_WINDOW_SET_CROP:
+ res = dispatchSetCrop(args);
+ break;
+ case NATIVE_WINDOW_SET_BUFFER_COUNT:
+ res = dispatchSetBufferCount(args);
+ break;
+ case NATIVE_WINDOW_SET_BUFFERS_GEOMETRY:
+ res = dispatchSetBuffersGeometry(args);
+ break;
+ case NATIVE_WINDOW_SET_BUFFERS_TRANSFORM:
+ res = dispatchSetBuffersTransform(args);
+ break;
+ default:
+ res = NAME_NOT_FOUND;
+ break;
+ }
+ return res;
+}
+
+int SurfaceTextureClient::dispatchConnect(va_list args) {
+ int api = va_arg(args, int);
+ return connect(api);
+}
+
+int SurfaceTextureClient::dispatchDisconnect(va_list args) {
+ int api = va_arg(args, int);
+ return disconnect(api);
+}
+
+int SurfaceTextureClient::dispatchSetUsage(va_list args) {
+ int usage = va_arg(args, int);
+ return setUsage(usage);
+}
+
+int SurfaceTextureClient::dispatchSetCrop(va_list args) {
+ android_native_rect_t const* rect = va_arg(args, android_native_rect_t*);
+ return setCrop(reinterpret_cast<Rect const*>(rect));
+}
+
+int SurfaceTextureClient::dispatchSetBufferCount(va_list args) {
+ size_t bufferCount = va_arg(args, size_t);
+ return setBufferCount(bufferCount);
+}
+
+int SurfaceTextureClient::dispatchSetBuffersGeometry(va_list args) {
+ int w = va_arg(args, int);
+ int h = va_arg(args, int);
+ int f = va_arg(args, int);
+ return setBuffersGeometry(w, h, f);
+}
+
+int SurfaceTextureClient::dispatchSetBuffersTransform(va_list args) {
+ int transform = va_arg(args, int);
+ return setBuffersTransform(transform);
+}
+
+int SurfaceTextureClient::connect(int api) {
+ // XXX: Implement this!
+ return INVALID_OPERATION;
+}
+
+int SurfaceTextureClient::disconnect(int api) {
+ // XXX: Implement this!
+ return INVALID_OPERATION;
+}
+
+int SurfaceTextureClient::setUsage(uint32_t reqUsage)
+{
+ Mutex::Autolock lock(mMutex);
+ mReqUsage = reqUsage;
+ return OK;
+}
+
+int SurfaceTextureClient::setCrop(Rect const* rect)
+{
+ Mutex::Autolock lock(mMutex);
+
+ // empty/invalid rects are not allowed
+ if (rect->isEmpty())
+ return BAD_VALUE;
+
+ status_t err = mSurfaceTexture->setCrop(*rect);
+ LOGE_IF(err, "ISurfaceTexture::setCrop(...) returned %s",
+ strerror(-err));
+
+ return err;
+}
+
+int SurfaceTextureClient::setBufferCount(int bufferCount)
+{
+ Mutex::Autolock lock(mMutex);
+
+ status_t err = mSurfaceTexture->setBufferCount(bufferCount);
+ LOGE_IF(err, "ISurfaceTexture::setBufferCount(%d) returned %s",
+ bufferCount, strerror(-err));
+
+ if (err == NO_ERROR) {
+ freeAllBuffers();
+ }
+
+ return err;
+}
+
+int SurfaceTextureClient::setBuffersGeometry(int w, int h, int format)
+{
+ Mutex::Autolock lock(mMutex);
+
+ if (w<0 || h<0 || format<0)
+ return BAD_VALUE;
+
+ if ((w && !h) || (!w && h))
+ return BAD_VALUE;
+
+ mReqWidth = w;
+ mReqHeight = h;
+ mReqFormat = format;
+
+ return NO_ERROR;
+}
+
+int SurfaceTextureClient::setBuffersTransform(int transform)
+{
+ Mutex::Autolock lock(mMutex);
+ status_t err = mSurfaceTexture->setTransform(transform);
+ return err;
+}
+
+void SurfaceTextureClient::freeAllBuffers() {
+ for (int i = 0; i < NUM_BUFFER_SLOTS; i++) {
+ mSlots[i] = 0;
+ }
+}
+
+}; // namespace android
diff --git a/libs/hwui/Caches.cpp b/libs/hwui/Caches.cpp
index 40dd117..406d09f 100644
--- a/libs/hwui/Caches.cpp
+++ b/libs/hwui/Caches.cpp
@@ -53,6 +53,10 @@
mDebugLevel = readDebugLevel();
LOGD("Enabling debug mode %d", mDebugLevel);
+
+#if RENDER_LAYERS_AS_REGIONS
+ LOGD("Layers will be composited as regions");
+#endif
}
Caches::~Caches() {
diff --git a/libs/hwui/DisplayListRenderer.cpp b/libs/hwui/DisplayListRenderer.cpp
index 77d628a..afb82bf 100644
--- a/libs/hwui/DisplayListRenderer.cpp
+++ b/libs/hwui/DisplayListRenderer.cpp
@@ -82,6 +82,43 @@
///////////////////////////////////////////////////////////////////////////////
DisplayList::DisplayList(const DisplayListRenderer& recorder) {
+ initFromDisplayListRenderer(recorder);
+}
+
+DisplayList::~DisplayList() {
+ sk_free((void*) mReader.base());
+
+ Caches& caches = Caches::getInstance();
+
+ for (size_t i = 0; i < mBitmapResources.size(); i++) {
+ caches.resourceCache.decrementRefcount(mBitmapResources.itemAt(i));
+ }
+ mBitmapResources.clear();
+
+ for (size_t i = 0; i < mShaderResources.size(); i++) {
+ caches.resourceCache.decrementRefcount(mShaderResources.itemAt(i));
+ }
+ mShaderResources.clear();
+
+ for (size_t i = 0; i < mPaints.size(); i++) {
+ delete mPaints.itemAt(i);
+ }
+ mPaints.clear();
+
+ for (size_t i = 0; i < mMatrices.size(); i++) {
+ delete mMatrices.itemAt(i);
+ }
+ mMatrices.clear();
+
+ if (mPathHeap) {
+ for (int i = 0; i < mPathHeap->count(); i++) {
+ caches.pathCache.removeDeferred(&(*mPathHeap)[i]);
+ }
+ mPathHeap->safeUnref();
+ }
+}
+
+void DisplayList::initFromDisplayListRenderer(const DisplayListRenderer& recorder) {
const SkWriter32& writer = recorder.writeStream();
init();
@@ -132,39 +169,6 @@
}
}
-DisplayList::~DisplayList() {
- sk_free((void*) mReader.base());
-
- Caches& caches = Caches::getInstance();
-
- for (size_t i = 0; i < mBitmapResources.size(); i++) {
- caches.resourceCache.decrementRefcount(mBitmapResources.itemAt(i));
- }
- mBitmapResources.clear();
-
- for (size_t i = 0; i < mShaderResources.size(); i++) {
- caches.resourceCache.decrementRefcount(mShaderResources.itemAt(i));
- }
- mShaderResources.clear();
-
- for (size_t i = 0; i < mPaints.size(); i++) {
- delete mPaints.itemAt(i);
- }
- mPaints.clear();
-
- for (size_t i = 0; i < mMatrices.size(); i++) {
- delete mMatrices.itemAt(i);
- }
- mMatrices.clear();
-
- if (mPathHeap) {
- for (int i = 0; i < mPathHeap->count(); i++) {
- caches.pathCache.removeDeferred(&(*mPathHeap)[i]);
- }
- mPathHeap->safeUnref();
- }
-}
-
void DisplayList::init() {
mPathHeap = NULL;
}
@@ -327,6 +331,7 @@
DisplayListRenderer::DisplayListRenderer():
mHeap(HEAP_BLOCK_SIZE), mWriter(MIN_WRITER_SIZE) {
mPathHeap = NULL;
+ mDisplayList = NULL;
}
DisplayListRenderer::~DisplayListRenderer() {
@@ -367,6 +372,15 @@
// Operations
///////////////////////////////////////////////////////////////////////////////
+DisplayList* DisplayListRenderer::getDisplayList() {
+ if (mDisplayList == NULL) {
+ mDisplayList = new DisplayList(*this);
+ } else {
+ mDisplayList->initFromDisplayListRenderer(*this);
+ }
+ return mDisplayList;
+}
+
void DisplayListRenderer::setViewport(int width, int height) {
mOrthoMatrix.loadOrtho(0, width, height, 0, -1, 1);
diff --git a/libs/hwui/DisplayListRenderer.h b/libs/hwui/DisplayListRenderer.h
index b608381..fedb174 100644
--- a/libs/hwui/DisplayListRenderer.h
+++ b/libs/hwui/DisplayListRenderer.h
@@ -110,6 +110,8 @@
SetupShadow
};
+ void initFromDisplayListRenderer(const DisplayListRenderer& recorder);
+
void replay(OpenGLRenderer& renderer);
private:
@@ -216,6 +218,8 @@
DisplayListRenderer();
~DisplayListRenderer();
+ DisplayList* getDisplayList();
+
void setViewport(int width, int height);
void prepare(bool opaque);
@@ -266,10 +270,6 @@
void reset();
- DisplayList* getDisplayList() const {
- return new DisplayList(*this);
- }
-
const SkWriter32& writeStream() const {
return mWriter;
}
@@ -422,6 +422,8 @@
SkRefCntRecorder mRCRecorder;
SkRefCntRecorder mTFRecorder;
+ DisplayList *mDisplayList;
+
friend class DisplayList;
}; // class DisplayListRenderer
diff --git a/libs/hwui/Layer.h b/libs/hwui/Layer.h
index a780183..7d54d3b 100644
--- a/libs/hwui/Layer.h
+++ b/libs/hwui/Layer.h
@@ -26,6 +26,7 @@
#include <SkXfermode.h>
#include "Rect.h"
+#include "SkiaColorFilter.h"
namespace android {
namespace uirenderer {
@@ -93,6 +94,11 @@
* have been drawn.
*/
Region region;
+
+ /**
+ * Color filter used to draw this layer. Optional.
+ */
+ SkiaColorFilter* colorFilter;
}; // struct Layer
}; // namespace uirenderer
diff --git a/libs/hwui/LayerCache.cpp b/libs/hwui/LayerCache.cpp
index 9ce0359..ec186a4 100644
--- a/libs/hwui/LayerCache.cpp
+++ b/libs/hwui/LayerCache.cpp
@@ -102,6 +102,7 @@
layer->blend = true;
layer->empty = true;
layer->fbo = 0;
+ layer->colorFilter = NULL;
glGenTextures(1, &layer->texture);
glBindTexture(GL_TEXTURE_2D, layer->texture);
diff --git a/libs/hwui/OpenGLRenderer.cpp b/libs/hwui/OpenGLRenderer.cpp
index eec8d8c..99bb6f0 100644
--- a/libs/hwui/OpenGLRenderer.cpp
+++ b/libs/hwui/OpenGLRenderer.cpp
@@ -162,6 +162,11 @@
GLenum status = GL_NO_ERROR;
while ((status = glGetError()) != GL_NO_ERROR) {
LOGD("GL error from OpenGLRenderer: 0x%x", status);
+ switch (status) {
+ case GL_OUT_OF_MEMORY:
+ LOGE(" OpenGLRenderer is out of memory!");
+ break;
+ }
}
#endif
#if DEBUG_MEMORY_USAGE
@@ -406,6 +411,7 @@
layer->layer.set(bounds);
layer->texCoords.set(0.0f, bounds.getHeight() / float(layer->height),
bounds.getWidth() / float(layer->width), 0.0f);
+ layer->colorFilter = mColorFilter;
// Save the layer in the snapshot
snapshot->flags |= Snapshot::kFlagIsLayer;
@@ -459,7 +465,6 @@
snapshot->flags |= Snapshot::kFlagIsFboLayer;
snapshot->fbo = layer->fbo;
snapshot->resetTransform(-bounds.left, -bounds.top, 0.0f);
- //snapshot->resetClip(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
snapshot->resetClip(clip.left, clip.top, clip.right, clip.bottom);
snapshot->viewport.set(0.0f, 0.0f, bounds.getWidth(), bounds.getHeight());
snapshot->height = bounds.getHeight();
@@ -544,7 +549,13 @@
// drawing only the dirty region
if (fboLayer) {
dirtyLayer(rect.left, rect.top, rect.right, rect.bottom, *previous->transform);
+ if (layer->colorFilter) {
+ setupColorFilter(layer->colorFilter);
+ }
composeLayerRegion(layer, rect);
+ if (layer->colorFilter) {
+ resetColorFilter();
+ }
} else {
dirtyLayer(rect.left, rect.top, rect.right, rect.bottom);
composeLayerRect(layer, rect, true);
@@ -593,43 +604,23 @@
size_t count;
const android::Rect* rects = layer->region.getArray(&count);
- setupDraw();
-
- ProgramDescription description;
- description.hasTexture = true;
-
const float alpha = layer->alpha / 255.0f;
- const bool setColor = description.setColor(alpha, alpha, alpha, alpha);
- chooseBlending(layer->blend || layer->alpha < 255, layer->mode, description, false);
-
- useProgram(mCaches.programCache.get(description));
-
- // Texture
- bindTexture(layer->texture);
- glUniform1i(mCaches.currentProgram->getUniform("sampler"), 0);
-
- // Always premultiplied
- if (setColor) {
- mCaches.currentProgram->setColor(alpha, alpha, alpha, alpha);
- }
-
- // Mesh
- int texCoordsSlot = mCaches.currentProgram->getAttrib("texCoords");
- glEnableVertexAttribArray(texCoordsSlot);
-
- mModelView.loadIdentity();
- mCaches.currentProgram->set(mOrthoMatrix, mModelView, *mSnapshot->transform);
-
const float texX = 1.0f / float(layer->width);
const float texY = 1.0f / float(layer->height);
TextureVertex* mesh = mCaches.getRegionMesh();
GLsizei numQuads = 0;
- glVertexAttribPointer(mCaches.currentProgram->position, 2, GL_FLOAT, GL_FALSE,
- gMeshStride, &mesh[0].position[0]);
- glVertexAttribPointer(texCoordsSlot, 2, GL_FLOAT, GL_FALSE,
- gMeshStride, &mesh[0].texture[0]);
+ setupDraw();
+ setupDrawWithTexture();
+ setupDrawColor(alpha, alpha, alpha, alpha);
+ setupDrawBlending(layer->blend || layer->alpha < 255, layer->mode, false);
+ setupDrawProgram();
+ setupDrawDirtyRegionsDisabled();
+ setupDrawPureColorUniforms();
+ setupDrawTexture(layer->texture);
+ setupDrawModelViewIdentity();
+ setupDrawMesh(&mesh[0].position[0], &mesh[0].texture[0]);
for (size_t i = 0; i < count; i++) {
const android::Rect* r = &rects[i];
@@ -659,7 +650,7 @@
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
- glDisableVertexAttribArray(texCoordsSlot);
+ finishDrawTexture();
#if DEBUG_LAYERS_AS_REGIONS
uint32_t colors[] = {
@@ -1175,7 +1166,6 @@
}
void OpenGLRenderer::drawLines(float* points, int count, SkPaint* paint) {
- // TODO: Should do quickReject for each line
if (mSnapshot->isIgnored()) return;
const bool isAA = paint->isAntiAlias();
@@ -1189,6 +1179,7 @@
getAlphaAndMode(paint, &alpha, &mode);
int verticesCount = count >> 2;
+ int generatedVerticesCount = 0;
if (!isHairLine) {
// TODO: AA needs more vertices
verticesCount *= 6;
@@ -1235,31 +1226,55 @@
vec2 p3 = b + n;
vec2 p4 = b - n;
- // Draw the line as 2 triangles, could be optimized
- // by using only 4 vertices and the correct indices
- // Also we should probably used non textured vertices
- // when line AA is disabled to save on bandwidth
- TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
- TextureVertex::set(vertex++, p2.x, p2.y, 0.0f, 0.0f);
- TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
- TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
- TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
- TextureVertex::set(vertex++, p4.x, p4.y, 0.0f, 0.0f);
+ const float left = fmin(p1.x, fmin(p2.x, fmin(p3.x, p4.x)));
+ const float right = fmax(p1.x, fmax(p2.x, fmax(p3.x, p4.x)));
+ const float top = fmin(p1.y, fmin(p2.y, fmin(p3.y, p4.y)));
+ const float bottom = fmax(p1.y, fmax(p2.y, fmax(p3.y, p4.y)));
- // TODO: Mark the dirty regions when RENDER_LAYERS_AS_REGIONS is set
+ if (!quickReject(left, top, right, bottom)) {
+ // Draw the line as 2 triangles, could be optimized
+ // by using only 4 vertices and the correct indices
+ // Also we should probably used non textured vertices
+ // when line AA is disabled to save on bandwidth
+ TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
+ TextureVertex::set(vertex++, p2.x, p2.y, 0.0f, 0.0f);
+ TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
+ TextureVertex::set(vertex++, p1.x, p1.y, 0.0f, 0.0f);
+ TextureVertex::set(vertex++, p3.x, p3.y, 0.0f, 0.0f);
+ TextureVertex::set(vertex++, p4.x, p4.y, 0.0f, 0.0f);
+
+ generatedVerticesCount += 6;
+
+ dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
+ }
}
- // GL_LINE does not give the result we want to match Skia
- glDrawArrays(GL_TRIANGLES, 0, verticesCount);
+ if (generatedVerticesCount > 0) {
+ // GL_LINE does not give the result we want to match Skia
+ glDrawArrays(GL_TRIANGLES, 0, generatedVerticesCount);
+ }
} else {
// TODO: Handle the AA case
for (int i = 0; i < count; i += 4) {
- TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
- TextureVertex::set(vertex++, points[i + 2], points[i + 3], 0.0f, 0.0f);
+ const float left = fmin(points[i], points[i + 1]);
+ const float right = fmax(points[i], points[i + 1]);
+ const float top = fmin(points[i + 2], points[i + 3]);
+ const float bottom = fmax(points[i + 2], points[i + 3]);
+
+ if (!quickReject(left, top, right, bottom)) {
+ TextureVertex::set(vertex++, points[i], points[i + 1], 0.0f, 0.0f);
+ TextureVertex::set(vertex++, points[i + 2], points[i + 3], 0.0f, 0.0f);
+
+ generatedVerticesCount += 2;
+
+ dirtyLayer(left, top, right, bottom, *mSnapshot->transform);
+ }
}
- glLineWidth(1.0f);
- glDrawArrays(GL_LINES, 0, verticesCount);
+ if (generatedVerticesCount > 0) {
+ glLineWidth(1.0f);
+ glDrawArrays(GL_LINES, 0, generatedVerticesCount);
+ }
}
}
diff --git a/libs/hwui/PathCache.cpp b/libs/hwui/PathCache.cpp
index 8740a64..3184598 100644
--- a/libs/hwui/PathCache.cpp
+++ b/libs/hwui/PathCache.cpp
@@ -197,10 +197,16 @@
bitmap.eraseColor(0);
SkPaint pathPaint(*paint);
- if (!pathPaint.getXfermode()) {
- SkXfermode* mode = SkXfermode::Create(SkXfermode::kSrc_Mode);
- pathPaint.setXfermode(mode)->safeUnref();
- }
+
+ // Make sure the paint is opaque, color, alpha, filter, etc.
+ // will be applied later when compositing the alpha8 texture
+ pathPaint.setColor(0xff000000);
+ pathPaint.setAlpha(255);
+ pathPaint.setColorFilter(NULL);
+ pathPaint.setMaskFilter(NULL);
+ pathPaint.setShader(NULL);
+ SkXfermode* mode = SkXfermode::Create(SkXfermode::kSrc_Mode);
+ pathPaint.setXfermode(mode)->safeUnref();
SkCanvas canvas(bitmap);
canvas.translate(-bounds.fLeft + offset, -bounds.fTop + offset);
diff --git a/libs/hwui/Properties.h b/libs/hwui/Properties.h
index c474936..6a0d7ea 100644
--- a/libs/hwui/Properties.h
+++ b/libs/hwui/Properties.h
@@ -26,7 +26,7 @@
*/
// If turned on, layers drawn inside FBOs are optimized with regions
-#define RENDER_LAYERS_AS_REGIONS 0
+#define RENDER_LAYERS_AS_REGIONS 1
/**
* Debug level for app developers.
diff --git a/libs/rs/RenderScript.h b/libs/rs/RenderScript.h
index 87758e5..f160ef1 100644
--- a/libs/rs/RenderScript.h
+++ b/libs/rs/RenderScript.h
@@ -334,7 +334,9 @@
// A3D loading and object update code.
// Should only be called at object creation, not thread safe
RsObjectBase rsaFileA3DGetEntryByIndex(RsContext, uint32_t idx, RsFile);
-RsFile rsaFileA3DCreateFromAssetStream(RsContext, const void *data, uint32_t len);
+RsFile rsaFileA3DCreateFromMemory(RsContext, const void *data, uint32_t len);
+RsFile rsaFileA3DCreateFromAsset(RsContext, void *asset);
+RsFile rsaFileA3DCreateFromFile(RsContext, const char *path);
void rsaFileA3DGetNumIndexEntries(RsContext, int32_t *numEntries, RsFile);
void rsaFileA3DGetIndexEntries(RsContext, RsFileIndexEntry *fileEntries,uint32_t numEntries, RsFile);
void rsaGetName(RsContext, void * obj, const char **name);
diff --git a/libs/rs/java/Samples/res/drawable/cubemap_test.png b/libs/rs/java/Samples/res/drawable/cubemap_test.png
index 75ad0a4..baf35d0 100644
--- a/libs/rs/java/Samples/res/drawable/cubemap_test.png
+++ b/libs/rs/java/Samples/res/drawable/cubemap_test.png
Binary files differ
diff --git a/libs/rs/java/Samples/src/com/android/samples/RsBenchRS.java b/libs/rs/java/Samples/src/com/android/samples/RsBenchRS.java
index 5430a13..1afcee3 100644
--- a/libs/rs/java/Samples/src/com/android/samples/RsBenchRS.java
+++ b/libs/rs/java/Samples/src/com/android/samples/RsBenchRS.java
@@ -22,7 +22,6 @@
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.renderscript.*;
-import android.renderscript.Allocation.CubemapLayout;
import android.renderscript.Allocation.MipmapControl;
import android.renderscript.Program.TextureType;
import android.renderscript.ProgramStore.DepthFunc;
@@ -318,8 +317,7 @@
mTexTransparent = loadTextureARGB(R.drawable.leaf);
mTexChecker = loadTextureRGB(R.drawable.checker);
Bitmap b = BitmapFactory.decodeResource(mRes, R.drawable.cubemap_test);
- mTexCube = Allocation.createCubemapFromBitmap(mRS, b,
- Allocation.CubemapLayout.VERTICAL_FACE_LIST);
+ mTexCube = Allocation.createCubemapFromBitmap(mRS, b);
mScript.set_gTexTorus(mTexTorus);
mScript.set_gTexOpaque(mTexOpaque);
diff --git a/libs/rs/java/Samples/src/com/android/samples/RsRenderStatesRS.java b/libs/rs/java/Samples/src/com/android/samples/RsRenderStatesRS.java
index cac105a..87840a7 100644
--- a/libs/rs/java/Samples/src/com/android/samples/RsRenderStatesRS.java
+++ b/libs/rs/java/Samples/src/com/android/samples/RsRenderStatesRS.java
@@ -22,7 +22,6 @@
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.renderscript.*;
-import android.renderscript.Allocation.CubemapLayout;
import android.renderscript.Font.Style;
import android.renderscript.Program.TextureType;
import android.renderscript.ProgramStore.DepthFunc;
@@ -308,8 +307,7 @@
mTexTransparent = loadTextureARGB(R.drawable.leaf);
mTexChecker = loadTextureRGB(R.drawable.checker);
Bitmap b = BitmapFactory.decodeResource(mRes, R.drawable.cubemap_test);
- mTexCube = Allocation.createCubemapFromBitmap(mRS, b,
- Allocation.CubemapLayout.VERTICAL_FACE_LIST);
+ mTexCube = Allocation.createCubemapFromBitmap(mRS, b);
mScript.set_gTexTorus(mTexTorus);
mScript.set_gTexOpaque(mTexOpaque);
diff --git a/libs/rs/java/tests/src/com/android/rs/test/RSTestCore.java b/libs/rs/java/tests/src/com/android/rs/test/RSTestCore.java
index a50321e..fc3a065 100644
--- a/libs/rs/java/tests/src/com/android/rs/test/RSTestCore.java
+++ b/libs/rs/java/tests/src/com/android/rs/test/RSTestCore.java
@@ -66,6 +66,7 @@
unitTests.add(new UT_primitives(this, mRes, mCtx));
unitTests.add(new UT_rsdebug(this, mRes, mCtx));
+ unitTests.add(new UT_rstime(this, mRes, mCtx));
unitTests.add(new UT_rstypes(this, mRes, mCtx));
unitTests.add(new UT_fp_mad(this, mRes, mCtx));
/*
diff --git a/libs/rs/java/tests/src/com/android/rs/test/UT_rstime.java b/libs/rs/java/tests/src/com/android/rs/test/UT_rstime.java
new file mode 100644
index 0000000..f302e1a
--- /dev/null
+++ b/libs/rs/java/tests/src/com/android/rs/test/UT_rstime.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2010 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.rs.test;
+
+import android.content.Context;
+import android.content.res.Resources;
+import android.renderscript.*;
+
+public class UT_rstime extends UnitTest {
+ private Resources mRes;
+
+ protected UT_rstime(RSTestCore rstc, Resources res, Context ctx) {
+ super(rstc, "rsTime", ctx);
+ mRes = res;
+ }
+
+ public void run() {
+ RenderScript pRS = RenderScript.create(mCtx);
+ ScriptC_rstime s = new ScriptC_rstime(pRS, mRes, R.raw.rstime);
+ pRS.setMessageHandler(mRsMessage);
+ s.invoke_test_rstime(0, 0);
+ pRS.finish();
+ waitForMessage();
+ pRS.destroy();
+ }
+}
diff --git a/libs/rs/java/tests/src/com/android/rs/test/rstime.rs b/libs/rs/java/tests/src/com/android/rs/test/rstime.rs
new file mode 100644
index 0000000..5e3e078
--- /dev/null
+++ b/libs/rs/java/tests/src/com/android/rs/test/rstime.rs
@@ -0,0 +1,52 @@
+#include "shared.rsh"
+
+static bool basic_test(uint32_t index) {
+ bool failed = false;
+
+ rs_time_t curTime = rsTime(0);
+ rs_tm tm;
+ rsDebug("curTime", curTime);
+
+ rsLocaltime(&tm, &curTime);
+
+ rsDebug("tm.tm_sec", tm.tm_sec);
+ rsDebug("tm.tm_min", tm.tm_min);
+ rsDebug("tm.tm_hour", tm.tm_hour);
+ rsDebug("tm.tm_mday", tm.tm_mday);
+ rsDebug("tm.tm_mon", tm.tm_mon);
+ rsDebug("tm.tm_year", tm.tm_year);
+ rsDebug("tm.tm_wday", tm.tm_wday);
+ rsDebug("tm.tm_yday", tm.tm_yday);
+ rsDebug("tm.tm_isdst", tm.tm_isdst);
+
+ // Test a specific time (only valid for PST localtime)
+ curTime = 1294438893;
+ rsLocaltime(&tm, &curTime);
+
+ _RS_ASSERT(tm.tm_sec == 33);
+ _RS_ASSERT(tm.tm_min == 21);
+ _RS_ASSERT(tm.tm_hour == 14);
+ _RS_ASSERT(tm.tm_mday == 7);
+ _RS_ASSERT(tm.tm_mon == 0);
+ _RS_ASSERT(tm.tm_year == 111);
+ _RS_ASSERT(tm.tm_wday == 5);
+ _RS_ASSERT(tm.tm_yday == 6);
+ _RS_ASSERT(tm.tm_isdst == 0);
+
+ return failed;
+}
+
+void test_rstime(uint32_t index, int test_num) {
+ bool failed = false;
+ failed |= basic_test(index);
+
+ if (failed) {
+ rsSendToClientBlocking(RS_MSG_TEST_FAILED);
+ rsDebug("rstime_test FAILED", -1);
+ }
+ else {
+ rsSendToClientBlocking(RS_MSG_TEST_PASSED);
+ rsDebug("rstime_test PASSED", 0);
+ }
+}
+
diff --git a/libs/rs/rs.spec b/libs/rs/rs.spec
index 3483a5d..33ac2f0 100644
--- a/libs/rs/rs.spec
+++ b/libs/rs/rs.spec
@@ -346,12 +346,6 @@
ret RsProgramVertex
}
-FileOpen {
- ret RsFile
- param const char *name
- param size_t len
- }
-
FontCreateFromFile {
param const char *name
param float fontSize
@@ -359,6 +353,15 @@
ret RsFont
}
+FontCreateFromMemory {
+ param const char *name
+ param float fontSize
+ param uint32_t dpi
+ param const void *data
+ param uint32_t dataLen
+ ret RsFont
+ }
+
MeshCreate {
ret RsMesh
param uint32_t vtxCount
diff --git a/libs/rs/rsAllocation.cpp b/libs/rs/rsAllocation.cpp
index 3608e43..673ade2 100644
--- a/libs/rs/rsAllocation.cpp
+++ b/libs/rs/rsAllocation.cpp
@@ -831,16 +831,21 @@
return NULL;
}
+ uint32_t faceSize = t->getDimX();
+ uint32_t strideBytes = faceSize * 6 * t->getElementSizeBytes();
+ uint32_t copySize = faceSize * t->getElementSizeBytes();
+
uint8_t *sourcePtr = (uint8_t*)data;
for (uint32_t face = 0; face < 6; face ++) {
Adapter2D faceAdapter(rsc, texAlloc);
faceAdapter.setFace(face);
- size_t cpySize = t->getDimX() * t->getDimX() * t->getElementSizeBytes();
- memcpy(faceAdapter.getElement(0, 0), sourcePtr, cpySize);
+ for (uint32_t dI = 0; dI < faceSize; dI ++) {
+ memcpy(faceAdapter.getElement(0, dI), sourcePtr + strideBytes * dI, copySize);
+ }
// Move the data pointer to the next cube face
- sourcePtr += cpySize;
+ sourcePtr += copySize;
if (mips == RS_ALLOCATION_MIPMAP_FULL) {
Adapter2D adapt(rsc, texAlloc);
diff --git a/libs/rs/rsContext.cpp b/libs/rs/rsContext.cpp
index c437d72..c5ee7ee 100644
--- a/libs/rs/rsContext.cpp
+++ b/libs/rs/rsContext.cpp
@@ -44,6 +44,7 @@
uint32_t Context::gThreadTLSKeyCount = 0;
uint32_t Context::gGLContextCount = 0;
pthread_mutex_t Context::gInitMutex = PTHREAD_MUTEX_INITIALIZER;
+pthread_mutex_t Context::gLibMutex = PTHREAD_MUTEX_INITIALIZER;
static void checkEglError(const char* op, EGLBoolean returnVal = EGL_TRUE) {
if (returnVal != EGL_TRUE) {
@@ -539,6 +540,7 @@
}
ObjectBase::zeroAllUserRef(this);
LOGV("destroyWorkerThreadResources 2");
+ mExit = true;
}
void * Context::helperThreadProc(void *vrsc) {
@@ -713,6 +715,9 @@
Context::~Context() {
LOGV("Context::~Context");
+
+ mIO.mToCore.flush();
+ rsAssert(mExit);
mExit = true;
mPaused = false;
void *res;
diff --git a/libs/rs/rsContext.h b/libs/rs/rsContext.h
index 3c402c4..df275bc 100644
--- a/libs/rs/rsContext.h
+++ b/libs/rs/rsContext.h
@@ -75,6 +75,8 @@
static uint32_t gThreadTLSKeyCount;
static uint32_t gGLContextCount;
static pthread_mutex_t gInitMutex;
+ // Library mutex (for providing thread-safe calls from the runtime)
+ static pthread_mutex_t gLibMutex;
struct ScriptTLSStruct {
Context * mContext;
diff --git a/libs/rs/rsFileA3D.cpp b/libs/rs/rsFileA3D.cpp
index 0c8692d..d34ddd6 100644
--- a/libs/rs/rsFileA3D.cpp
+++ b/libs/rs/rsFileA3D.cpp
@@ -35,6 +35,7 @@
mData = NULL;
mWriteStream = NULL;
mReadStream = NULL;
+ mAsset = NULL;
mMajorVersion = 0;
mMinorVersion = 1;
@@ -57,6 +58,9 @@
if (mAlloc) {
free(mAlloc);
}
+ if (mAsset) {
+ delete mAsset;
+ }
}
void FileA3D::parseHeader(IStream *headerStream) {
@@ -83,6 +87,11 @@
}
}
+bool FileA3D::load(Asset *asset) {
+ mAsset = asset;
+ return load(asset->getBuffer(false), asset->getLength());
+}
+
bool FileA3D::load(const void *data, size_t length) {
const uint8_t *localData = (const uint8_t *)data;
@@ -357,26 +366,6 @@
mWriteStream->align(4);
}
-namespace android {
-namespace renderscript {
-
-RsFile rsi_FileOpen(Context *rsc, char const *path, unsigned int len) {
- FileA3D *fa3d = new FileA3D(rsc);
-
- FILE *f = fopen("/sdcard/test.a3d", "rb");
- if (f) {
- fa3d->load(f);
- fclose(f);
- fa3d->incUserRef();
- return fa3d;
- }
- delete fa3d;
- return NULL;
-}
-
-}
-}
-
RsObjectBase rsaFileA3DGetEntryByIndex(RsContext con, uint32_t index, RsFile file) {
FileA3D *fa3d = static_cast<FileA3D *>(file);
if (!fa3d) {
@@ -422,7 +411,7 @@
}
}
-RsFile rsaFileA3DCreateFromAssetStream(RsContext con, const void *data, uint32_t len) {
+RsFile rsaFileA3DCreateFromMemory(RsContext con, const void *data, uint32_t len) {
if (data == NULL) {
LOGE("File load failed. Asset stream is NULL");
return NULL;
@@ -435,3 +424,35 @@
fa3d->load(data, len);
return fa3d;
}
+
+RsFile rsaFileA3DCreateFromAsset(RsContext con, void *_asset) {
+ Context *rsc = static_cast<Context *>(con);
+ Asset *asset = static_cast<Asset *>(_asset);
+ FileA3D *fa3d = new FileA3D(rsc);
+ fa3d->incUserRef();
+
+ fa3d->load(asset);
+ return fa3d;
+}
+
+RsFile rsaFileA3DCreateFromFile(RsContext con, const char *path) {
+ if (path == NULL) {
+ LOGE("File load failed. Path is NULL");
+ return NULL;
+ }
+
+ Context *rsc = static_cast<Context *>(con);
+ FileA3D *fa3d = NULL;
+
+ FILE *f = fopen(path, "rb");
+ if (f) {
+ fa3d = new FileA3D(rsc);
+ fa3d->incUserRef();
+ fa3d->load(f);
+ fclose(f);
+ } else {
+ LOGE("Could not open file %s", path);
+ }
+
+ return fa3d;
+}
diff --git a/libs/rs/rsFileA3D.h b/libs/rs/rsFileA3D.h
index 3ece4c9..056b5af 100644
--- a/libs/rs/rsFileA3D.h
+++ b/libs/rs/rsFileA3D.h
@@ -21,6 +21,7 @@
#include "rsMesh.h"
#include <utils/String8.h>
+#include <utils/Asset.h>
#include "rsStream.h"
#include <stdio.h>
@@ -59,6 +60,7 @@
};
bool load(FILE *f);
+ bool load(Asset *asset);
bool load(const void *data, size_t length);
size_t getNumIndexEntries() const;
@@ -83,6 +85,7 @@
const uint8_t * mData;
void * mAlloc;
uint64_t mDataSize;
+ Asset *mAsset;
OStream *mWriteStream;
Vector<A3DIndexEntry*> mWriteIndex;
diff --git a/libs/rs/rsFont.cpp b/libs/rs/rsFont.cpp
index 3dcf743..8571c32 100644
--- a/libs/rs/rsFont.cpp
+++ b/libs/rs/rsFont.cpp
@@ -40,13 +40,19 @@
mFace = NULL;
}
-bool Font::init(const char *name, float fontSize, uint32_t dpi) {
+bool Font::init(const char *name, float fontSize, uint32_t dpi, const void *data, uint32_t dataLen) {
if (mInitialized) {
LOGE("Reinitialization of fonts not supported");
return false;
}
- FT_Error error = FT_New_Face(mRSC->mStateFont.getLib(), name, 0, &mFace);
+ FT_Error error = 0;
+ if (data != NULL && dataLen > 0) {
+ error = FT_New_Memory_Face(mRSC->mStateFont.getLib(), (const FT_Byte*)data, dataLen, 0, &mFace);
+ } else {
+ error = FT_New_Face(mRSC->mStateFont.getLib(), name, 0, &mFace);
+ }
+
if (error) {
LOGE("Unable to initialize font %s", name);
return false;
@@ -127,7 +133,8 @@
int32_t width = (int32_t) glyph->mBitmapWidth;
int32_t height = (int32_t) glyph->mBitmapHeight;
- if (bounds->bottom > nPenY) {
+ // 0, 0 is top left, so bottom is a positive number
+ if (bounds->bottom < nPenY) {
bounds->bottom = nPenY;
}
if (bounds->left > nPenX) {
@@ -136,8 +143,8 @@
if (bounds->right < nPenX + width) {
bounds->right = nPenX + width;
}
- if (bounds->top < nPenY + height) {
- bounds->top = nPenY + height;
+ if (bounds->top > nPenY - height) {
+ bounds->top = nPenY - height;
}
}
@@ -155,7 +162,7 @@
return;
}
// Reset min and max of the bounding box to something large
- bounds->set(1e6, -1e6, -1e6, 1e6);
+ bounds->set(1e6, -1e6, 1e6, -1e6);
}
int32_t penX = x, penY = y;
@@ -273,7 +280,8 @@
return newGlyph;
}
-Font * Font::create(Context *rsc, const char *name, float fontSize, uint32_t dpi) {
+Font * Font::create(Context *rsc, const char *name, float fontSize, uint32_t dpi,
+ const void *data, uint32_t dataLen) {
rsc->mStateFont.checkInit();
Vector<Font*> &activeFonts = rsc->mStateFont.mActiveFonts;
@@ -285,7 +293,7 @@
}
Font *newFont = new Font(rsc);
- bool isInitialized = newFont->init(name, fontSize, dpi);
+ bool isInitialized = newFont->init(name, fontSize, dpi, data, dataLen);
if (isInitialized) {
activeFonts.push(newFont);
rsc->mStateFont.precacheLatin(newFont);
@@ -743,6 +751,8 @@
void FontState::measureText(const char *text, uint32_t len, Font::Rect *bounds) {
renderText(text, len, 0, 0, 0, -1, Font::MEASURE, bounds);
+ bounds->bottom = - bounds->bottom;
+ bounds->top = - bounds->top;
}
void FontState::setFontColor(float r, float g, float b, float a) {
@@ -811,5 +821,13 @@
return newFont;
}
+RsFont rsi_FontCreateFromMemory(Context *rsc, char const *name, float fontSize, uint32_t dpi, const void *data, uint32_t dataLen) {
+ Font *newFont = Font::create(rsc, name, fontSize, dpi, data, dataLen);
+ if (newFont) {
+ newFont->incUserRef();
+ }
+ return newFont;
+}
+
} // renderscript
} // android
diff --git a/libs/rs/rsFont.h b/libs/rs/rsFont.h
index c24c9f1..00d77c8 100644
--- a/libs/rs/rsFont.h
+++ b/libs/rs/rsFont.h
@@ -73,7 +73,8 @@
return RS_A3D_CLASS_ID_UNKNOWN;
}
- static Font * create(Context *rsc, const char *name, float fontSize, uint32_t dpi);
+ static Font * create(Context *rsc, const char *name, float fontSize, uint32_t dpi,
+ const void *data = NULL, uint32_t dataLen = 0);
protected:
@@ -116,7 +117,7 @@
uint32_t mDpi;
Font(Context *rsc);
- bool init(const char *name, float fontSize, uint32_t dpi);
+ bool init(const char *name, float fontSize, uint32_t dpi, const void *data = NULL, uint32_t dataLen = 0);
FT_Face mFace;
bool mInitialized;
diff --git a/libs/rs/rsScriptC.cpp b/libs/rs/rsScriptC.cpp
index ef06033..5dd976a 100644
--- a/libs/rs/rsScriptC.cpp
+++ b/libs/rs/rsScriptC.cpp
@@ -410,40 +410,38 @@
void ScriptCState::runCompiler(Context *rsc,
ScriptC *s,
- long modWhen,
- long crc32,
const char *resName,
const char *cacheDir) {
{
s->mBccScript = bccCreateScript();
+
s->mEnviroment.mIsThreadable = true;
+
bccRegisterSymbolCallback(s->mBccScript, symbolLookup, s);
- // bccReadBC() reads in the BitCode, if no cache file corresponding to
- // the resName is found. Otherwise, bccReadBC() returns a negative value
- // and the "else" branch will be taken.
+
if (bccReadBC(s->mBccScript,
s->mEnviroment.mScriptText,
s->mEnviroment.mScriptTextLength,
- modWhen,
- crc32,
- resName,
- cacheDir) >= 0) {
- //bccLinkBC(s->mBccScript, rs_runtime_lib_bc, rs_runtime_lib_bc_size);
- bccCompileBC(s->mBccScript);
- } else {
- // bccReadBC returns a neagative value: Didn't read any script,
- // So, use cached binary instead
- if (bccLoadBinary(s->mBccScript)) { // LoadBinary fails ==> Recompile
- bccReadBC(s->mBccScript,
- s->mEnviroment.mScriptText,
- s->mEnviroment.mScriptTextLength,
- modWhen,
- crc32,
- resName,
- cacheDir);
- bccCompileBC(s->mBccScript);
- }
+ /*deprecated*/ 0, /*deprecated*/ 0,
+ resName, cacheDir) != 0) {
+ LOGE("bcc: FAILS to read bitcode");
+ // Handle Fatal Error
}
+
+#if 0
+ if (bccLinkBC(s->mBccScript,
+ rs_runtime_lib_bc,
+ rs_runtime_lib_bc_size) != 0) {
+ LOGE("bcc: FAILS to link bitcode");
+ // Handle Fatal Error
+ }
+#endif
+
+ if (bccPrepareExecutable(s->mBccScript) != 0) {
+ LOGE("bcc: FAILS to prepare executable");
+ // Handle Fatal Error
+ }
+
bccGetScriptLabel(s->mBccScript, "root", (BCCvoid**) &s->mProgram.mRoot);
bccGetScriptLabel(s->mBccScript, "init", (BCCvoid**) &s->mProgram.mInit);
}
@@ -535,7 +533,8 @@
} else {
- // Deal with an error.
+ LOGE("bcc: FAILS to prepare executable");
+ // Handle Fatal Error
}
}
@@ -559,7 +558,7 @@
RsScript rsi_ScriptCCreate(Context *rsc,
- const char *packageName,
+ const char *packageName /* deprecated */,
const char *resName,
const char *cacheDir)
{
@@ -569,34 +568,7 @@
ss->mScript.clear();
s->incUserRef();
- // Open the apk and return the ZipArchive:
- // int dexZipOpenArchive(const char* fileName, ZipArchive* pArchive)
- ZipArchive archive;
- long modWhen;
- long crc32;
- if (!dexZipOpenArchive(packageName, &archive)) { // Success
- ZipEntry entry = dexZipFindEntry(&archive, resName);
-
- int method;
- size_t uncompLen;
- size_t compLen;
- off_t offset;
- if (!dexZipGetEntryInfo(&archive,
- entry,
- &method,
- &uncompLen,
- &compLen,
- &offset,
- &modWhen,
- &crc32)) {
- } else {
- LOGI("Coudn't get entry info for the bitcode in an apk");
- }
- } else {
- LOGI("Couldn't open the archive and read the bitcode");
- }
-
- ss->runCompiler(rsc, s.get(), modWhen, crc32, resName, cacheDir);
+ ss->runCompiler(rsc, s.get(), resName, cacheDir);
ss->clear(rsc);
return s.get();
}
diff --git a/libs/rs/rsScriptC.h b/libs/rs/rsScriptC.h
index ce9358e..cd68546 100644
--- a/libs/rs/rsScriptC.h
+++ b/libs/rs/rsScriptC.h
@@ -83,7 +83,7 @@
void init(Context *rsc);
void clear(Context *rsc);
- void runCompiler(Context *rsc, ScriptC *s, long modWhen, long crc32, const char *resName, const char *cacheDir);
+ void runCompiler(Context *rsc, ScriptC *s, const char *resName, const char *cacheDir);
struct SymbolTable_t {
const char * mName;
diff --git a/libs/rs/rsScriptC_Lib.cpp b/libs/rs/rsScriptC_Lib.cpp
index f61b983..0b21669 100644
--- a/libs/rs/rsScriptC_Lib.cpp
+++ b/libs/rs/rsScriptC_Lib.cpp
@@ -100,70 +100,24 @@
// Time routines
//////////////////////////////////////////////////////////////////////////////
-static int32_t SC_second() {
+static time_t SC_time(time_t *timer) {
GET_TLS();
-
- time_t rawtime;
- time(&rawtime);
-
- struct tm *timeinfo;
- timeinfo = localtime(&rawtime);
- return timeinfo->tm_sec;
+ return time(timer);
}
-static int32_t SC_minute() {
+static tm* SC_localtime(tm *local, time_t *timer) {
GET_TLS();
+ if (!local) {
+ return NULL;
+ }
- time_t rawtime;
- time(&rawtime);
-
- struct tm *timeinfo;
- timeinfo = localtime(&rawtime);
- return timeinfo->tm_min;
-}
-
-static int32_t SC_hour() {
- GET_TLS();
-
- time_t rawtime;
- time(&rawtime);
-
- struct tm *timeinfo;
- timeinfo = localtime(&rawtime);
- return timeinfo->tm_hour;
-}
-
-static int32_t SC_day() {
- GET_TLS();
-
- time_t rawtime;
- time(&rawtime);
-
- struct tm *timeinfo;
- timeinfo = localtime(&rawtime);
- return timeinfo->tm_mday;
-}
-
-static int32_t SC_month() {
- GET_TLS();
-
- time_t rawtime;
- time(&rawtime);
-
- struct tm *timeinfo;
- timeinfo = localtime(&rawtime);
- return timeinfo->tm_mon;
-}
-
-static int32_t SC_year() {
- GET_TLS();
-
- time_t rawtime;
- time(&rawtime);
-
- struct tm *timeinfo;
- timeinfo = localtime(&rawtime);
- return timeinfo->tm_year;
+ // The native localtime function is not thread-safe, so we
+ // have to apply locking for proper behavior in RenderScript.
+ pthread_mutex_lock(&rsc->gLibMutex);
+ tm *tmp = localtime(timer);
+ memcpy(local, tmp, sizeof(*tmp));
+ pthread_mutex_unlock(&rsc->gLibMutex);
+ return local;
}
static int64_t SC_uptimeMillis() {
@@ -498,12 +452,8 @@
{ "_Z6rsFracf", (void *)&SC_frac, true },
// time
- { "_Z8rsSecondv", (void *)&SC_second, true },
- { "_Z8rsMinutev", (void *)&SC_minute, true },
- { "_Z6rsHourv", (void *)&SC_hour, true },
- { "_Z5rsDayv", (void *)&SC_day, true },
- { "_Z7rsMonthv", (void *)&SC_month, true },
- { "_Z6rsYearv", (void *)&SC_year, true },
+ { "_Z6rsTimePi", (void *)&SC_time, true },
+ { "_Z11rsLocaltimeP5rs_tmPKi", (void *)&SC_localtime, true },
{ "_Z14rsUptimeMillisv", (void*)&SC_uptimeMillis, true },
{ "_Z13rsUptimeNanosv", (void*)&SC_uptimeNanos, true },
{ "_Z7rsGetDtv", (void*)&SC_getDt, false },
diff --git a/libs/rs/scriptc/rs_math.rsh b/libs/rs/scriptc/rs_math.rsh
index d059997..a74c0e0 100644
--- a/libs/rs/scriptc/rs_math.rsh
+++ b/libs/rs/scriptc/rs_math.rsh
@@ -118,32 +118,6 @@
extern float __attribute__((overloadable))
rsFrac(float);
-// time
-extern int32_t __attribute__((overloadable))
- rsSecond(void);
-extern int32_t __attribute__((overloadable))
- rsMinute(void);
-extern int32_t __attribute__((overloadable))
- rsHour(void);
-extern int32_t __attribute__((overloadable))
- rsDay(void);
-extern int32_t __attribute__((overloadable))
- rsMonth(void);
-extern int32_t __attribute__((overloadable))
- rsYear(void);
-
-// Return the current system clock in milliseconds
-extern int64_t __attribute__((overloadable))
- rsUptimeMillis(void);
-
-// Return the current system clock in nanoseconds
-extern int64_t __attribute__((overloadable))
- rsUptimeNanos(void);
-
-// Return the time in seconds since function was last called in this script.
-extern float __attribute__((overloadable))
- rsGetDt(void);
-
// Send a message back to the client. Will not block and returns true
// if the message was sendable and false if the fifo was full.
// A message ID is required. Data payload is optional.
diff --git a/libs/rs/scriptc/rs_time.rsh b/libs/rs/scriptc/rs_time.rsh
new file mode 100644
index 0000000..f1abed63
--- /dev/null
+++ b/libs/rs/scriptc/rs_time.rsh
@@ -0,0 +1,36 @@
+#ifndef __RS_TIME_RSH__
+#define __RS_TIME_RSH__
+
+typedef int rs_time_t;
+
+typedef struct {
+ int tm_sec;
+ int tm_min;
+ int tm_hour;
+ int tm_mday;
+ int tm_mon;
+ int tm_year;
+ int tm_wday;
+ int tm_yday;
+ int tm_isdst;
+} rs_tm;
+
+extern rs_time_t __attribute__((overloadable))
+ rsTime(rs_time_t *timer);
+
+extern rs_tm * __attribute__((overloadable))
+ rsLocaltime(rs_tm *local, const rs_time_t *timer);
+
+// Return the current system clock in milliseconds
+extern int64_t __attribute__((overloadable))
+ rsUptimeMillis(void);
+
+// Return the current system clock in nanoseconds
+extern int64_t __attribute__((overloadable))
+ rsUptimeNanos(void);
+
+// Return the time in seconds since function was last called in this script.
+extern float __attribute__((overloadable))
+ rsGetDt(void);
+
+#endif
diff --git a/libs/surfaceflinger_client/ISurfaceComposer.cpp b/libs/surfaceflinger_client/ISurfaceComposer.cpp
index b8a7a79..a42b49d 100644
--- a/libs/surfaceflinger_client/ISurfaceComposer.cpp
+++ b/libs/surfaceflinger_client/ISurfaceComposer.cpp
@@ -26,6 +26,7 @@
#include <binder/IServiceManager.h>
#include <ui/DisplayInfo.h>
+#include <ui/GraphicBuffer.h>
#include <surfaceflinger/ISurfaceComposer.h>
@@ -169,6 +170,25 @@
data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
remote()->transact(BnSurfaceComposer::SIGNAL, data, &reply, IBinder::FLAG_ONEWAY);
}
+
+ virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
+ PixelFormat format, uint32_t usage) const {
+ Parcel data, reply;
+ data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
+ data.writeInt32(w);
+ data.writeInt32(h);
+ data.writeInt32(format);
+ data.writeInt32(usage);
+ remote()->transact(BnSurfaceComposer::CREATE_GRAPHIC_BUFFER, data,
+ &reply);
+ sp<GraphicBuffer> graphicBuffer;
+ bool nonNull = (bool)reply.readInt32();
+ if (nonNull) {
+ graphicBuffer = new GraphicBuffer();
+ reply.read(*graphicBuffer);
+ }
+ return graphicBuffer;
+ }
};
IMPLEMENT_META_INTERFACE(SurfaceComposer, "android.ui.ISurfaceComposer");
@@ -247,6 +267,18 @@
reply->writeInt32(f);
reply->writeInt32(res);
} break;
+ case CREATE_GRAPHIC_BUFFER: {
+ CHECK_INTERFACE(ISurfaceComposer, data, reply);
+ uint32_t w = data.readInt32();
+ uint32_t h = data.readInt32();
+ PixelFormat format = data.readInt32();
+ uint32_t usage = data.readInt32();
+ sp<GraphicBuffer> result(createGraphicBuffer(w, h, format, usage));
+ reply->writeInt32(result != 0);
+ if (result != 0) {
+ reply->write(*result);
+ }
+ } break;
case TURN_ELECTRON_BEAM_OFF: {
CHECK_INTERFACE(ISurfaceComposer, data, reply);
int32_t mode = data.readInt32();
diff --git a/media/java/android/media/AudioService.java b/media/java/android/media/AudioService.java
index 97fcf27..6a79384 100644
--- a/media/java/android/media/AudioService.java
+++ b/media/java/android/media/AudioService.java
@@ -275,6 +275,15 @@
// in call audio)
private static final int SCO_STATE_ACTIVE_EXTERNAL = 2;
+ // true if boot sequence has been completed
+ private boolean mBootCompleted;
+ // listener for SoundPool sample load completion indication
+ private SoundPoolCallback mSoundPoolCallBack;
+ // thread for SoundPool listener
+ private SoundPoolListenerThread mSoundPoolListenerThread;
+ // message looper for SoundPool listener
+ private Looper mSoundPoolLooper = null;
+
///////////////////////////////////////////////////////////////////////////
// Construction
///////////////////////////////////////////////////////////////////////////
@@ -308,7 +317,6 @@
setRingerModeInt(getRingerMode(), false);
AudioSystem.setErrorCallback(mAudioSystemCallback);
- loadSoundEffects();
mBluetoothHeadsetDevice = null;
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
@@ -868,12 +876,42 @@
* This method must be called at when sound effects are enabled
*/
public boolean loadSoundEffects() {
+ int status;
+
synchronized (mSoundEffectsLock) {
+ if (!mBootCompleted) {
+ Log.w(TAG, "loadSoundEffects() called before boot complete");
+ return false;
+ }
+
if (mSoundPool != null) {
return true;
}
mSoundPool = new SoundPool(NUM_SOUNDPOOL_CHANNELS, AudioSystem.STREAM_SYSTEM, 0);
if (mSoundPool == null) {
+ Log.w(TAG, "loadSoundEffects() could not allocate sound pool");
+ return false;
+ }
+
+ try {
+ mSoundPoolCallBack = null;
+ mSoundPoolListenerThread = new SoundPoolListenerThread();
+ mSoundPoolListenerThread.start();
+ // Wait for mSoundPoolCallBack to be set by the other thread
+ mSoundEffectsLock.wait();
+ } catch (InterruptedException e) {
+ Log.w(TAG, "Interrupted while waiting sound pool listener thread.");
+ }
+
+ if (mSoundPoolCallBack == null) {
+ Log.w(TAG, "loadSoundEffects() could not create SoundPool listener or thread");
+ if (mSoundPoolLooper != null) {
+ mSoundPoolLooper.quit();
+ mSoundPoolLooper = null;
+ }
+ mSoundPoolListenerThread = null;
+ mSoundPool.release();
+ mSoundPool = null;
return false;
}
/*
@@ -891,26 +929,49 @@
* If load succeeds, value in SOUND_EFFECT_FILES_MAP[effect][1] is > 0:
* this indicates we have a valid sample loaded for this effect.
*/
+
for (int effect = 0; effect < AudioManager.NUM_SOUND_EFFECTS; effect++) {
// Do not load sample if this effect uses the MediaPlayer
if (SOUND_EFFECT_FILES_MAP[effect][1] == 0) {
continue;
}
if (poolId[SOUND_EFFECT_FILES_MAP[effect][0]] == -1) {
- String filePath = Environment.getRootDirectory() + SOUND_EFFECTS_PATH + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]];
+ String filePath = Environment.getRootDirectory()
+ + SOUND_EFFECTS_PATH
+ + SOUND_EFFECT_FILES[SOUND_EFFECT_FILES_MAP[effect][0]];
int sampleId = mSoundPool.load(filePath, 0);
SOUND_EFFECT_FILES_MAP[effect][1] = sampleId;
poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = sampleId;
if (sampleId <= 0) {
Log.w(TAG, "Soundpool could not load file: "+filePath);
}
+ mSoundPoolCallBack.setLastSample(sampleId);
} else {
SOUND_EFFECT_FILES_MAP[effect][1] = poolId[SOUND_EFFECT_FILES_MAP[effect][0]];
}
}
+ // wait for all samples to be loaded
+ try {
+ mSoundEffectsLock.wait();
+ status = mSoundPoolCallBack.status();
+ } catch (java.lang.InterruptedException e) {
+ status = -1;
+ }
+ if (mSoundPoolLooper != null) {
+ mSoundPoolLooper.quit();
+ mSoundPoolLooper = null;
+ }
+ mSoundPoolListenerThread = null;
+ if (status != 0) {
+ Log.w(TAG,
+ "loadSoundEffects(), Error "
+ + mSoundPoolCallBack.status()
+ + " while loading samples");
+ mSoundPool.release();
+ mSoundPool = null;
+ }
}
-
- return true;
+ return (status == 0);
}
/**
@@ -923,6 +984,9 @@
if (mSoundPool == null) {
return;
}
+
+ mAudioHandler.removeMessages(MSG_PLAY_SOUND_EFFECT);
+
int[] poolId = new int[SOUND_EFFECT_FILES.length];
for (int fileIdx = 0; fileIdx < SOUND_EFFECT_FILES.length; fileIdx++) {
poolId[fileIdx] = 0;
@@ -938,10 +1002,60 @@
poolId[SOUND_EFFECT_FILES_MAP[effect][0]] = -1;
}
}
+ mSoundPool.release();
mSoundPool = null;
}
}
+ class SoundPoolListenerThread extends Thread {
+ public SoundPoolListenerThread() {
+ super("SoundPoolListenerThread");
+ }
+
+ @Override
+ public void run() {
+
+ Looper.prepare();
+ mSoundPoolLooper = Looper.myLooper();
+
+ synchronized (mSoundEffectsLock) {
+ if (mSoundPool != null) {
+ mSoundPoolCallBack = new SoundPoolCallback();
+ mSoundPool.setOnLoadCompleteListener(mSoundPoolCallBack);
+ }
+ mSoundEffectsLock.notify();
+ }
+ Looper.loop();
+ }
+ }
+
+ private final class SoundPoolCallback implements
+ android.media.SoundPool.OnLoadCompleteListener {
+
+ int mStatus;
+ int mLastSample;
+
+ public int status() {
+ return mStatus;
+ }
+
+ public void setLastSample(int sample) {
+ mLastSample = sample;
+ }
+
+ public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
+ synchronized (mSoundEffectsLock) {
+ if (status != 0) {
+ mStatus = status;
+ }
+ if (sampleId == mLastSample) {
+ Log.e(TAG, "onLoadComplete last sample loaded");
+ mSoundEffectsLock.notify();
+ }
+ }
+ }
+ }
+
/** @see AudioManager#reloadAudioSettings() */
public void reloadAudioSettings() {
// restore ringer mode, ringer mode affected streams, mute affected streams and vibrate settings
@@ -2130,6 +2244,8 @@
mContext.sendStickyBroadcast(newIntent);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
+ mBootCompleted = true;
+ loadSoundEffects();
Intent newIntent = new Intent(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED);
newIntent.putExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
AudioManager.SCO_AUDIO_STATE_DISCONNECTED);
diff --git a/media/java/android/media/MediaMetadataRetriever.java b/media/java/android/media/MediaMetadataRetriever.java
index 6209dc0..b99f7ed 100644
--- a/media/java/android/media/MediaMetadataRetriever.java
+++ b/media/java/android/media/MediaMetadataRetriever.java
@@ -345,5 +345,6 @@
public static final int METADATA_KEY_MIMETYPE = 22;
public static final int METADATA_KEY_DISCNUMBER = 23;
public static final int METADATA_KEY_ALBUMARTIST = 24;
+ public static final int METADATA_KEY_COMPILATION = 25;
// Add more here...
}
diff --git a/media/java/android/media/MediaPlayer.java b/media/java/android/media/MediaPlayer.java
index 01134f2..f61ac0f 100644
--- a/media/java/android/media/MediaPlayer.java
+++ b/media/java/android/media/MediaPlayer.java
@@ -1300,9 +1300,9 @@
return;
case MEDIA_INFO:
- // For PV specific code values (msg.arg2) look in
- // opencore/pvmi/pvmf/include/pvmf_return_codes.h
- Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
+ if (msg.arg1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) {
+ Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
+ }
if (mOnInfoListener != null) {
mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
}
diff --git a/media/java/android/media/SoundPool.java b/media/java/android/media/SoundPool.java
index 18ce5c1..5e9c018 100644
--- a/media/java/android/media/SoundPool.java
+++ b/media/java/android/media/SoundPool.java
@@ -141,17 +141,6 @@
throw new RuntimeException("Native setup failed");
}
mLock = new Object();
-
- // setup message handler
- Looper looper;
- if ((looper = Looper.myLooper()) != null) {
- mEventHandler = new EventHandler(this, looper);
- } else if ((looper = Looper.getMainLooper()) != null) {
- mEventHandler = new EventHandler(this, looper);
- } else {
- mEventHandler = null;
- }
-
}
/**
@@ -427,6 +416,19 @@
public void setOnLoadCompleteListener(OnLoadCompleteListener listener)
{
synchronized(mLock) {
+ if (listener != null) {
+ // setup message handler
+ Looper looper;
+ if ((looper = Looper.myLooper()) != null) {
+ mEventHandler = new EventHandler(this, looper);
+ } else if ((looper = Looper.getMainLooper()) != null) {
+ mEventHandler = new EventHandler(this, looper);
+ } else {
+ mEventHandler = null;
+ }
+ } else {
+ mEventHandler = null;
+ }
mOnLoadCompleteListener = listener;
}
}
diff --git a/media/jni/soundpool/SoundPool.cpp b/media/jni/soundpool/SoundPool.cpp
index fef880b..1e2d6ce 100644
--- a/media/jni/soundpool/SoundPool.cpp
+++ b/media/jni/soundpool/SoundPool.cpp
@@ -81,10 +81,10 @@
quit();
Mutex::Autolock lock(&mLock);
+
mChannels.clear();
if (mChannelPool)
delete [] mChannelPool;
-
// clean up samples
LOGV("clear samples");
mSamples.clear();
@@ -96,8 +96,19 @@
void SoundPool::addToRestartList(SoundChannel* channel)
{
Mutex::Autolock lock(&mRestartLock);
- mRestart.push_back(channel);
- mCondition.signal();
+ if (!mQuit) {
+ mRestart.push_back(channel);
+ mCondition.signal();
+ }
+}
+
+void SoundPool::addToStopList(SoundChannel* channel)
+{
+ Mutex::Autolock lock(&mRestartLock);
+ if (!mQuit) {
+ mStop.push_back(channel);
+ mCondition.signal();
+ }
}
int SoundPool::beginThread(void* arg)
@@ -114,17 +125,38 @@
LOGV("awake");
if (mQuit) break;
+ while (!mStop.empty()) {
+ SoundChannel* channel;
+ LOGV("Getting channel from stop list");
+ List<SoundChannel* >::iterator iter = mStop.begin();
+ channel = *iter;
+ mStop.erase(iter);
+ mRestartLock.unlock();
+ if (channel != 0) {
+ Mutex::Autolock lock(&mLock);
+ channel->stop();
+ }
+ mRestartLock.lock();
+ if (mQuit) break;
+ }
+
while (!mRestart.empty()) {
SoundChannel* channel;
LOGV("Getting channel from list");
List<SoundChannel*>::iterator iter = mRestart.begin();
channel = *iter;
mRestart.erase(iter);
- if (channel) channel->nextEvent();
+ mRestartLock.unlock();
+ if (channel != 0) {
+ Mutex::Autolock lock(&mLock);
+ channel->nextEvent();
+ }
+ mRestartLock.lock();
if (mQuit) break;
}
}
+ mStop.clear();
mRestart.clear();
mCondition.signal();
mRestartLock.unlock();
@@ -208,43 +240,43 @@
int SoundPool::play(int sampleID, float leftVolume, float rightVolume,
int priority, int loop, float rate)
{
- LOGV("sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
+ LOGV("play sampleID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
sampleID, leftVolume, rightVolume, priority, loop, rate);
sp<Sample> sample;
SoundChannel* channel;
int channelID;
- // scope for lock
- {
- Mutex::Autolock lock(&mLock);
+ Mutex::Autolock lock(&mLock);
- // is sample ready?
- sample = findSample(sampleID);
- if ((sample == 0) || (sample->state() != Sample::READY)) {
- LOGW(" sample %d not READY", sampleID);
- return 0;
- }
-
- dump();
-
- // allocate a channel
- channel = allocateChannel(priority);
-
- // no channel allocated - return 0
- if (!channel) {
- LOGV("No channel allocated");
- return 0;
- }
-
- channelID = ++mNextChannelID;
+ if (mQuit) {
+ return 0;
+ }
+ // is sample ready?
+ sample = findSample(sampleID);
+ if ((sample == 0) || (sample->state() != Sample::READY)) {
+ LOGW(" sample %d not READY", sampleID);
+ return 0;
}
- LOGV("channel state = %d", channel->state());
+ dump();
+
+ // allocate a channel
+ channel = allocateChannel_l(priority);
+
+ // no channel allocated - return 0
+ if (!channel) {
+ LOGV("No channel allocated");
+ return 0;
+ }
+
+ channelID = ++mNextChannelID;
+
+ LOGV("play channel %p state = %d", channel, channel->state());
channel->play(sample, channelID, leftVolume, rightVolume, priority, loop, rate);
return channelID;
}
-SoundChannel* SoundPool::allocateChannel(int priority)
+SoundChannel* SoundPool::allocateChannel_l(int priority)
{
List<SoundChannel*>::iterator iter;
SoundChannel* channel = NULL;
@@ -273,7 +305,7 @@
}
// move a channel from its current position to the front of the list
-void SoundPool::moveToFront(SoundChannel* channel)
+void SoundPool::moveToFront_l(SoundChannel* channel)
{
for (List<SoundChannel*>::iterator iter = mChannels.begin(); iter != mChannels.end(); ++iter) {
if (*iter == channel) {
@@ -378,10 +410,9 @@
}
// call with lock held
-void SoundPool::done(SoundChannel* channel)
+void SoundPool::done_l(SoundChannel* channel)
{
- LOGV("done(%d)", channel->channelID());
-
+ LOGV("done_l(%d)", channel->channelID());
// if "stolen", play next event
if (channel->nextChannelID() != 0) {
LOGV("add to restart list");
@@ -391,7 +422,7 @@
// return to idle state
else {
LOGV("move to front");
- moveToFront(channel);
+ moveToFront_l(channel);
}
}
@@ -511,81 +542,88 @@
mSoundPool = soundPool;
}
+// call with sound pool lock held
void SoundChannel::play(const sp<Sample>& sample, int nextChannelID, float leftVolume,
float rightVolume, int priority, int loop, float rate)
{
AudioTrack* oldTrack;
+ AudioTrack* newTrack;
+ status_t status;
- LOGV("play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f, priority=%d, loop=%d, rate=%f",
- this, sample->sampleID(), nextChannelID, leftVolume, rightVolume, priority, loop, rate);
+ { // scope for the lock
+ Mutex::Autolock lock(&mLock);
- // if not idle, this voice is being stolen
- if (mState != IDLE) {
- LOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
- mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
- stop();
- return;
- }
+ LOGV("SoundChannel::play %p: sampleID=%d, channelID=%d, leftVolume=%f, rightVolume=%f,"
+ " priority=%d, loop=%d, rate=%f",
+ this, sample->sampleID(), nextChannelID, leftVolume, rightVolume,
+ priority, loop, rate);
- // initialize track
- int afFrameCount;
- int afSampleRate;
- int streamType = mSoundPool->streamType();
- if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
- afFrameCount = kDefaultFrameCount;
- }
- if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
- afSampleRate = kDefaultSampleRate;
- }
- int numChannels = sample->numChannels();
- uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
- uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
- uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
- uint32_t frameCount = 0;
+ // if not idle, this voice is being stolen
+ if (mState != IDLE) {
+ LOGV("channel %d stolen - event queued for channel %d", channelID(), nextChannelID);
+ mNextEvent.set(sample, nextChannelID, leftVolume, rightVolume, priority, loop, rate);
+ stop_l();
+ return;
+ }
- if (loop) {
- frameCount = sample->size()/numChannels/((sample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
- }
+ // initialize track
+ int afFrameCount;
+ int afSampleRate;
+ int streamType = mSoundPool->streamType();
+ if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
+ afFrameCount = kDefaultFrameCount;
+ }
+ if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
+ afSampleRate = kDefaultSampleRate;
+ }
+ int numChannels = sample->numChannels();
+ uint32_t sampleRate = uint32_t(float(sample->sampleRate()) * rate + 0.5);
+ uint32_t totalFrames = (kDefaultBufferCount * afFrameCount * sampleRate) / afSampleRate;
+ uint32_t bufferFrames = (totalFrames + (kDefaultBufferCount - 1)) / kDefaultBufferCount;
+ uint32_t frameCount = 0;
+
+ if (loop) {
+ frameCount = sample->size()/numChannels/
+ ((sample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
+ }
#ifndef USE_SHARED_MEM_BUFFER
- // Ensure minimum audio buffer size in case of short looped sample
- if(frameCount < totalFrames) {
- frameCount = totalFrames;
- }
+ // Ensure minimum audio buffer size in case of short looped sample
+ if(frameCount < totalFrames) {
+ frameCount = totalFrames;
+ }
#endif
- AudioTrack* newTrack;
+ // mToggle toggles each time a track is started on a given channel.
+ // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
+ // as callback user data. This enables the detection of callbacks received from the old
+ // audio track while the new one is being started and avoids processing them with
+ // wrong audio audio buffer size (mAudioBufferSize)
+ unsigned long toggle = mToggle ^ 1;
+ void *userData = (void *)((unsigned long)this | toggle);
+ uint32_t channels = (numChannels == 2) ?
+ AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO;
- // mToggle toggles each time a track is started on a given channel.
- // The toggle is concatenated with the SoundChannel address and passed to AudioTrack
- // as callback user data. This enables the detection of callbacks received from the old
- // audio track while the new one is being started and avoids processing them with
- // wrong audio audio buffer size (mAudioBufferSize)
- unsigned long toggle = mToggle ^ 1;
- void *userData = (void *)((unsigned long)this | toggle);
- uint32_t channels = (numChannels == 2) ? AudioSystem::CHANNEL_OUT_STEREO : AudioSystem::CHANNEL_OUT_MONO;
-
+ // do not create a new audio track if current track is compatible with sample parameters
#ifdef USE_SHARED_MEM_BUFFER
- newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
- channels, sample->getIMemory(), 0, callback, userData);
+ newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
+ channels, sample->getIMemory(), 0, callback, userData);
#else
- newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
- channels, frameCount, 0, callback, userData, bufferFrames);
+ newTrack = new AudioTrack(streamType, sampleRate, sample->format(),
+ channels, frameCount, 0, callback, userData, bufferFrames);
#endif
- if (newTrack->initCheck() != NO_ERROR) {
- LOGE("Error creating AudioTrack");
- delete newTrack;
- return;
- }
- LOGV("setVolume %p", newTrack);
- newTrack->setVolume(leftVolume, rightVolume);
- newTrack->setLoop(0, frameCount, loop);
+ oldTrack = mAudioTrack;
+ status = newTrack->initCheck();
+ if (status != NO_ERROR) {
+ LOGE("Error creating AudioTrack");
+ goto exit;
+ }
+ LOGV("setVolume %p", newTrack);
+ newTrack->setVolume(leftVolume, rightVolume);
+ newTrack->setLoop(0, frameCount, loop);
- {
- Mutex::Autolock lock(&mLock);
// From now on, AudioTrack callbacks recevieved with previous toggle value will be ignored.
mToggle = toggle;
- oldTrack = mAudioTrack;
mAudioTrack = newTrack;
mPos = 0;
mSample = sample;
@@ -602,8 +640,13 @@
mAudioBufferSize = newTrack->frameCount()*newTrack->frameSize();
}
+exit:
LOGV("delete oldTrack %p", oldTrack);
delete oldTrack;
+ if (status != NO_ERROR) {
+ delete newTrack;
+ mAudioTrack = NULL;
+ }
}
void SoundChannel::nextEvent()
@@ -639,29 +682,44 @@
void SoundChannel::callback(int event, void* user, void *info)
{
- unsigned long toggle = (unsigned long)user & 1;
SoundChannel* channel = static_cast<SoundChannel*>((void *)((unsigned long)user & ~1));
- if (channel->mToggle != toggle) {
- LOGV("callback with wrong toggle");
- return;
- }
- channel->process(event, info);
+ channel->process(event, info, (unsigned long)user & 1);
}
-void SoundChannel::process(int event, void *info)
+void SoundChannel::process(int event, void *info, unsigned long toggle)
{
//LOGV("process(%d)", mChannelID);
+
+ Mutex::Autolock lock(&mLock);
+
+ AudioTrack::Buffer* b = NULL;
+ if (event == AudioTrack::EVENT_MORE_DATA) {
+ b = static_cast<AudioTrack::Buffer *>(info);
+ }
+
+ if (mToggle != toggle) {
+ LOGV("process wrong toggle %p channel %d", this, mChannelID);
+ if (b != NULL) {
+ b->size = 0;
+ }
+ return;
+ }
+
sp<Sample> sample = mSample;
// LOGV("SoundChannel::process event %d", event);
if (event == AudioTrack::EVENT_MORE_DATA) {
- AudioTrack::Buffer* b = static_cast<AudioTrack::Buffer *>(info);
// check for stop state
if (b->size == 0) return;
+ if (mState == IDLE) {
+ b->size = 0;
+ return;
+ }
+
if (sample != 0) {
// fill buffer
uint8_t* q = (uint8_t*) b->i8;
@@ -674,14 +732,14 @@
count = b->size;
}
memcpy(q, p, count);
- LOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size, count);
+// LOGV("fill: q=%p, p=%p, mPos=%u, b->size=%u, count=%d", q, p, mPos, b->size, count);
} else if (mPos < mAudioBufferSize) {
count = mAudioBufferSize - mPos;
if (count > b->size) {
count = b->size;
}
memset(q, 0, count);
- LOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
+// LOGV("fill extra: q=%p, mPos=%u, b->size=%u, count=%d", q, mPos, b->size, count);
}
mPos += count;
@@ -689,16 +747,16 @@
//LOGV("buffer=%p, [0]=%d", b->i16, b->i16[0]);
}
} else if (event == AudioTrack::EVENT_UNDERRUN) {
- LOGV("stopping track");
- stop();
+ LOGV("process %p channel %d EVENT_UNDERRUN", this, mChannelID);
+ mSoundPool->addToStopList(this);
} else if (event == AudioTrack::EVENT_LOOP_END) {
- LOGV("End loop: %d", *(int *)info);
+ LOGV("End loop %p channel %d count %d", this, mChannelID, *(int *)info);
}
}
// call with lock held
-void SoundChannel::stop_l()
+bool SoundChannel::doStop_l()
{
if (mState != IDLE) {
setVolume_l(0, 0);
@@ -707,16 +765,31 @@
mSample.clear();
mState = IDLE;
mPriority = IDLE_PRIORITY;
+ return true;
+ }
+ return false;
+}
+
+// call with lock held and sound pool lock held
+void SoundChannel::stop_l()
+{
+ if (doStop_l()) {
+ mSoundPool->done_l(this);
}
}
+// call with sound pool lock held
void SoundChannel::stop()
{
+ bool stopped;
{
Mutex::Autolock lock(&mLock);
- stop_l();
+ stopped = doStop_l();
}
- mSoundPool->done(this);
+
+ if (stopped) {
+ mSoundPool->done_l(this);
+ }
}
//FIXME: Pause is a little broken right now
@@ -791,21 +864,24 @@
{
Mutex::Autolock lock(&mLock);
if (mAudioTrack != 0 && mSample.get() != 0) {
- mAudioTrack->setLoop(0, mSample->size()/mNumChannels/((mSample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t)), loop);
+ uint32_t loopEnd = mSample->size()/mNumChannels/
+ ((mSample->format() == AudioSystem::PCM_16_BIT) ? sizeof(int16_t) : sizeof(uint8_t));
+ mAudioTrack->setLoop(0, loopEnd, loop);
mLoop = loop;
}
}
SoundChannel::~SoundChannel()
{
- LOGV("SoundChannel destructor");
- if (mAudioTrack) {
- LOGV("stop track");
- mAudioTrack->stop();
- delete mAudioTrack;
+ LOGV("SoundChannel destructor %p", this);
+ {
+ Mutex::Autolock lock(&mLock);
+ clearNextEvent();
+ doStop_l();
}
- clearNextEvent();
- mSample.clear();
+ // do not call AudioTrack destructor with mLock held as it will wait for the AudioTrack
+ // callback thread to exit which may need to execute process() and acquire the mLock.
+ delete mAudioTrack;
}
void SoundChannel::dump()
@@ -817,7 +893,7 @@
void SoundEvent::set(const sp<Sample>& sample, int channelID, float leftVolume,
float rightVolume, int priority, int loop, float rate)
{
- mSample =sample;
+ mSample = sample;
mChannelID = channelID;
mLeftVolume = leftVolume;
mRightVolume = rightVolume;
diff --git a/media/jni/soundpool/SoundPool.h b/media/jni/soundpool/SoundPool.h
index 1b0fd38..6010aac 100644
--- a/media/jni/soundpool/SoundPool.h
+++ b/media/jni/soundpool/SoundPool.h
@@ -142,7 +142,8 @@
private:
static void callback(int event, void* user, void *info);
- void process(int event, void *info);
+ void process(int event, void *info, unsigned long toggle);
+ bool doStop_l();
SoundPool* mSoundPool;
AudioTrack* mAudioTrack;
@@ -184,7 +185,7 @@
void sampleLoaded(int sampleID);
// called from AudioTrack thread
- void done(SoundChannel* channel);
+ void done_l(SoundChannel* channel);
// callback function
void setCallback(SoundPoolCallback* callback, void* user);
@@ -197,13 +198,14 @@
sp<Sample> findSample(int sampleID) { return mSamples.valueFor(sampleID); }
SoundChannel* findChannel (int channelID);
SoundChannel* findNextChannel (int channelID);
- SoundChannel* allocateChannel(int priority);
- void moveToFront(SoundChannel* channel);
+ SoundChannel* allocateChannel_l(int priority);
+ void moveToFront_l(SoundChannel* channel);
void notify(SoundPoolEvent event);
void dump();
// restart thread
void addToRestartList(SoundChannel* channel);
+ void addToStopList(SoundChannel* channel);
static int beginThread(void* arg);
int run();
void quit();
@@ -215,6 +217,7 @@
SoundChannel* mChannelPool;
List<SoundChannel*> mChannels;
List<SoundChannel*> mRestart;
+ List<SoundChannel*> mStop;
DefaultKeyedVector< int, sp<Sample> > mSamples;
int mMaxChannels;
int mStreamType;
diff --git a/media/jni/soundpool/SoundPoolThread.h b/media/jni/soundpool/SoundPoolThread.h
index bbd35e0..d388388 100644
--- a/media/jni/soundpool/SoundPoolThread.h
+++ b/media/jni/soundpool/SoundPoolThread.h
@@ -31,10 +31,8 @@
SoundPoolMsg() : mMessageType(INVALID), mData(0) {}
SoundPoolMsg(MessageType MessageType, int data) :
mMessageType(MessageType), mData(data) {}
- uint8_t mMessageType;
- uint8_t mData;
- uint8_t mData2;
- uint8_t mData3;
+ uint16_t mMessageType;
+ uint16_t mData;
};
/*
diff --git a/media/libmedia/mediaplayer.cpp b/media/libmedia/mediaplayer.cpp
index a098d69..87c8fe4 100644
--- a/media/libmedia/mediaplayer.cpp
+++ b/media/libmedia/mediaplayer.cpp
@@ -607,7 +607,9 @@
case MEDIA_INFO:
// ext1: Media framework error code.
// ext2: Implementation dependant error code.
- LOGW("info/warning (%d, %d)", ext1, ext2);
+ if (ext1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) {
+ LOGW("info/warning (%d, %d)", ext1, ext2);
+ }
break;
case MEDIA_SEEK_COMPLETE:
LOGV("Received seek complete");
diff --git a/media/libmediaplayerservice/MediaPlayerService.cpp b/media/libmediaplayerservice/MediaPlayerService.cpp
index 97c541a..439e4ce 100644
--- a/media/libmediaplayerservice/MediaPlayerService.cpp
+++ b/media/libmediaplayerservice/MediaPlayerService.cpp
@@ -733,8 +733,8 @@
}
char value[PROPERTY_VALUE_MAX];
- if (property_get("media.httplive.enable-nuplayer", value, NULL)
- && (!strcasecmp(value, "true") || !strcmp(value, "1"))) {
+ if (!property_get("media.httplive.disable-nuplayer", value, NULL)
+ || (strcasecmp(value, "true") && strcmp(value, "1"))) {
if (!strncasecmp("http://", url, 7)) {
size_t len = strlen(url);
if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
diff --git a/media/libmediaplayerservice/nuplayer/DecoderWrapper.cpp b/media/libmediaplayerservice/nuplayer/DecoderWrapper.cpp
index 4d4cd8d..802d1fb 100644
--- a/media/libmediaplayerservice/nuplayer/DecoderWrapper.cpp
+++ b/media/libmediaplayerservice/nuplayer/DecoderWrapper.cpp
@@ -309,6 +309,18 @@
realNotify->setInt32("width", width);
realNotify->setInt32("height", height);
+
+ int32_t cropLeft, cropTop, cropRight, cropBottom;
+ if (!meta->findRect(
+ kKeyCropRect,
+ &cropLeft, &cropTop, &cropRight, &cropBottom)) {
+ cropLeft = 0;
+ cropTop = 0;
+ cropRight = width - 1;
+ cropBottom = height - 1;
+ }
+
+ realNotify->setRect("crop", cropLeft, cropTop, cropRight, cropBottom);
}
notify->post();
diff --git a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
index e1b371e..7f534c0 100644
--- a/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
+++ b/media/libmediaplayerservice/nuplayer/NuPlayer.cpp
@@ -271,22 +271,43 @@
finishFlushIfPossible();
} else if (what == ACodec::kWhatOutputFormatChanged) {
- CHECK(audio);
+ if (audio) {
+ int32_t numChannels;
+ CHECK(codecRequest->findInt32("channel-count", &numChannels));
- int32_t numChannels;
- CHECK(codecRequest->findInt32("channel-count", &numChannels));
+ int32_t sampleRate;
+ CHECK(codecRequest->findInt32("sample-rate", &sampleRate));
- int32_t sampleRate;
- CHECK(codecRequest->findInt32("sample-rate", &sampleRate));
+ LOGV("Audio output format changed to %d Hz, %d channels",
+ sampleRate, numChannels);
- LOGV("Audio output format changed to %d Hz, %d channels",
- sampleRate, numChannels);
+ mAudioSink->close();
+ CHECK_EQ(mAudioSink->open(sampleRate, numChannels), (status_t)OK);
+ mAudioSink->start();
- mAudioSink->close();
- CHECK_EQ(mAudioSink->open(sampleRate, numChannels), (status_t)OK);
- mAudioSink->start();
+ mRenderer->signalAudioSinkChanged();
+ } else {
+ // video
- mRenderer->signalAudioSinkChanged();
+ int32_t width, height;
+ CHECK(codecRequest->findInt32("width", &width));
+ CHECK(codecRequest->findInt32("height", &height));
+
+ int32_t cropLeft, cropTop, cropRight, cropBottom;
+ CHECK(codecRequest->findRect(
+ "crop",
+ &cropLeft, &cropTop, &cropRight, &cropBottom));
+
+ LOGV("Video output format changed to %d x %d "
+ "(crop: %d, %d, %d, %d)",
+ width, height,
+ cropLeft, cropTop, cropRight, cropBottom);
+
+ notifyListener(
+ MEDIA_SET_VIDEO_SIZE,
+ cropRight - cropLeft + 1,
+ cropBottom - cropTop + 1);
+ }
} else if (what == ACodec::kWhatShutdownCompleted) {
LOGV("%s shutdown completed", audio ? "audio" : "video");
if (audio) {
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index 39e0c51..dfb4e00 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -299,7 +299,8 @@
////////////////////////////////////////////////////////////////////////////////
ACodec::ACodec()
- : mNode(NULL) {
+ : mNode(NULL),
+ mSentFormat(false) {
mUninitializedState = new UninitializedState(this);
mLoadedToIdleState = new LoadedToIdleState(this);
mIdleToExecutingState = new IdleToExecutingState(this);
@@ -980,6 +981,103 @@
}
}
+void ACodec::sendFormatChange() {
+ sp<AMessage> notify = mNotify->dup();
+ notify->setInt32("what", kWhatOutputFormatChanged);
+
+ OMX_PARAM_PORTDEFINITIONTYPE def;
+ InitOMXParams(&def);
+ def.nPortIndex = kPortIndexOutput;
+
+ CHECK_EQ(mOMX->getParameter(
+ mNode, OMX_IndexParamPortDefinition, &def, sizeof(def)),
+ (status_t)OK);
+
+ CHECK_EQ((int)def.eDir, (int)OMX_DirOutput);
+
+ switch (def.eDomain) {
+ case OMX_PortDomainVideo:
+ {
+ OMX_VIDEO_PORTDEFINITIONTYPE *videoDef = &def.format.video;
+
+ notify->setString("mime", MEDIA_MIMETYPE_VIDEO_RAW);
+ notify->setInt32("width", videoDef->nFrameWidth);
+ notify->setInt32("height", videoDef->nFrameHeight);
+
+ OMX_CONFIG_RECTTYPE rect;
+ InitOMXParams(&rect);
+ rect.nPortIndex = kPortIndexOutput;
+
+ if (mOMX->getConfig(
+ mNode, OMX_IndexConfigCommonOutputCrop,
+ &rect, sizeof(rect)) != OK) {
+ rect.nLeft = 0;
+ rect.nTop = 0;
+ rect.nWidth = videoDef->nFrameWidth;
+ rect.nHeight = videoDef->nFrameHeight;
+ }
+
+ CHECK_GE(rect.nLeft, 0);
+ CHECK_GE(rect.nTop, 0);
+ CHECK_GE(rect.nWidth, 0u);
+ CHECK_GE(rect.nHeight, 0u);
+ CHECK_LE(rect.nLeft + rect.nWidth - 1, videoDef->nFrameWidth);
+ CHECK_LE(rect.nTop + rect.nHeight - 1, videoDef->nFrameHeight);
+
+ notify->setRect(
+ "crop",
+ rect.nLeft,
+ rect.nTop,
+ rect.nLeft + rect.nWidth - 1,
+ rect.nTop + rect.nHeight - 1);
+
+ if (mNativeWindow != NULL) {
+ android_native_rect_t crop;
+ crop.left = rect.nLeft;
+ crop.top = rect.nTop;
+ crop.right = rect.nLeft + rect.nWidth - 1;
+ crop.bottom = rect.nTop + rect.nHeight - 1;
+
+ CHECK_EQ(0, native_window_set_crop(
+ mNativeWindow.get(), &crop));
+ }
+ break;
+ }
+
+ case OMX_PortDomainAudio:
+ {
+ OMX_AUDIO_PORTDEFINITIONTYPE *audioDef = &def.format.audio;
+ CHECK_EQ((int)audioDef->eEncoding, (int)OMX_AUDIO_CodingPCM);
+
+ OMX_AUDIO_PARAM_PCMMODETYPE params;
+ InitOMXParams(¶ms);
+ params.nPortIndex = kPortIndexOutput;
+
+ CHECK_EQ(mOMX->getParameter(
+ mNode, OMX_IndexParamAudioPcm,
+ ¶ms, sizeof(params)),
+ (status_t)OK);
+
+ CHECK(params.nChannels == 1 || params.bInterleaved);
+ CHECK_EQ(params.nBitPerSample, 16u);
+ CHECK_EQ((int)params.eNumData, (int)OMX_NumericalDataSigned);
+ CHECK_EQ((int)params.ePCMMode, (int)OMX_AUDIO_PCMModeLinear);
+
+ notify->setString("mime", MEDIA_MIMETYPE_AUDIO_RAW);
+ notify->setInt32("channel-count", params.nChannels);
+ notify->setInt32("sample-rate", params.nSamplingRate);
+ break;
+ }
+
+ default:
+ TRESPASS();
+ }
+
+ notify->post();
+
+ mSentFormat = true;
+}
+
////////////////////////////////////////////////////////////////////////////////
ACodec::BaseState::BaseState(ACodec *codec, const sp<AState> &parentState)
@@ -1305,6 +1403,10 @@
info->mStatus = BufferInfo::OWNED_BY_COMPONENT;
}
} else {
+ if (!mCodec->mSentFormat) {
+ mCodec->sendFormatChange();
+ }
+
if (mCodec->mNativeWindow == NULL) {
info->mData->setRange(rangeOffset, rangeLength);
}
@@ -1717,7 +1819,7 @@
{
CHECK_EQ(data1, (OMX_U32)kPortIndexOutput);
- if (data2 == OMX_IndexParamPortDefinition) {
+ if (data2 == 0 || data2 == OMX_IndexParamPortDefinition) {
CHECK_EQ(mCodec->mOMX->sendCommand(
mCodec->mNode,
OMX_CommandPortDisable, kPortIndexOutput),
@@ -1729,6 +1831,8 @@
}
mCodec->changeState(mCodec->mOutputPortSettingsChangedState);
+ } else if (data2 == OMX_IndexConfigCommonOutputCrop) {
+ mCodec->mSentFormat = false;
} else {
LOGV("[%s] OMX_EventPortSettingsChanged 0x%08lx",
mCodec->mComponentName.c_str(), data2);
@@ -1816,6 +1920,8 @@
} else if (data1 == (OMX_U32)OMX_CommandPortEnable) {
CHECK_EQ(data2, (OMX_U32)kPortIndexOutput);
+ mCodec->mSentFormat = false;
+
LOGV("[%s] Output port now reenabled.",
mCodec->mComponentName.c_str());
@@ -1869,6 +1975,8 @@
void ACodec::ExecutingToIdleState::stateEntered() {
LOGV("[%s] Now Executing->Idle", mCodec->mComponentName.c_str());
+
+ mCodec->mSentFormat = false;
}
bool ACodec::ExecutingToIdleState::onOMXEvent(
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index b350daf..4cfe28e 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -52,6 +52,7 @@
#include "include/LiveSession.h"
#define USE_SURFACE_ALLOC 1
+#define FRAME_DROP_FREQ 7
namespace android {
@@ -178,6 +179,8 @@
mStreamDoneEventPending = false;
mBufferingEvent = new AwesomeEvent(this, &AwesomePlayer::onBufferingUpdate);
mBufferingEventPending = false;
+ mVideoLagEvent = new AwesomeEvent(this, &AwesomePlayer::onVideoLagUpdate);
+ mVideoEventPending = false;
mCheckAudioStatusEvent = new AwesomeEvent(
this, &AwesomePlayer::onCheckAudioStatus);
@@ -204,6 +207,8 @@
mStreamDoneEventPending = false;
mQueue.cancelEvent(mCheckAudioStatusEvent->eventID());
mAudioStatusEventPending = false;
+ mQueue.cancelEvent(mVideoLagEvent->eventID());
+ mVideoLagEventPending = false;
if (!keepBufferingGoing) {
mQueue.cancelEvent(mBufferingEvent->eventID());
@@ -529,6 +534,28 @@
}
}
+void AwesomePlayer::onVideoLagUpdate() {
+ Mutex::Autolock autoLock(mLock);
+ if (!mVideoLagEventPending) {
+ return;
+ }
+ mVideoLagEventPending = false;
+
+ int64_t audioTimeUs = mAudioPlayer->getMediaTimeUs();
+ int64_t videoLateByUs = audioTimeUs - mVideoTimeUs;
+
+ if (videoLateByUs > 300000ll) {
+ LOGV("video late by %lld ms.", videoLateByUs / 1000ll);
+
+ notifyListener_l(
+ MEDIA_INFO,
+ MEDIA_INFO_VIDEO_TRACK_LAGGING,
+ videoLateByUs / 1000ll);
+ }
+
+ postVideoLagEvent_l();
+}
+
void AwesomePlayer::onBufferingUpdate() {
Mutex::Autolock autoLock(mLock);
if (!mBufferingEventPending) {
@@ -787,6 +814,10 @@
if (mVideoSource != NULL) {
// Kick off video playback
postVideoEvent_l();
+
+ if (mAudioSource != NULL && mVideoSource != NULL) {
+ postVideoLagEvent_l();
+ }
}
if (deferredAudioSeek) {
@@ -1255,7 +1286,7 @@
if (mFlags & FIRST_FRAME) {
mFlags &= ~FIRST_FRAME;
-
+ mSinceLastDropped = 0;
mTimeSourceDeltaUs = ts->getRealTimeUs() - timeUs;
}
@@ -1283,12 +1314,16 @@
if (latenessUs > 40000) {
// We're more than 40ms late.
LOGV("we're late by %lld us (%.2f secs)", latenessUs, latenessUs / 1E6);
+ if ( mSinceLastDropped > FRAME_DROP_FREQ)
+ {
+ LOGV("we're late by %lld us (%.2f secs) dropping one after %d frames", latenessUs, latenessUs / 1E6, mSinceLastDropped);
+ mSinceLastDropped = 0;
+ mVideoBuffer->release();
+ mVideoBuffer = NULL;
- mVideoBuffer->release();
- mVideoBuffer = NULL;
-
- postVideoEvent_l();
- return;
+ postVideoEvent_l();
+ return;
+ }
}
if (latenessUs < -10000) {
@@ -1305,6 +1340,7 @@
}
if (mVideoRenderer != NULL) {
+ mSinceLastDropped++;
mVideoRenderer->render(mVideoBuffer);
}
@@ -1341,6 +1377,14 @@
mQueue.postEventWithDelay(mBufferingEvent, 1000000ll);
}
+void AwesomePlayer::postVideoLagEvent_l() {
+ if (mVideoLagEventPending) {
+ return;
+ }
+ mVideoLagEventPending = true;
+ mQueue.postEventWithDelay(mVideoLagEvent, 1000000ll);
+}
+
void AwesomePlayer::postCheckAudioStatusEvent_l() {
if (mAudioStatusEventPending) {
return;
diff --git a/media/libstagefright/CameraSourceTimeLapse.cpp b/media/libstagefright/CameraSourceTimeLapse.cpp
index 9677838..31b6ec9 100644
--- a/media/libstagefright/CameraSourceTimeLapse.cpp
+++ b/media/libstagefright/CameraSourceTimeLapse.cpp
@@ -347,7 +347,8 @@
}
void CameraSourceTimeLapse::releaseRecordingFrame(const sp<IMemory>& frame) {
- if (!mUseStillCameraForTimeLapse) {
+ if (!mUseStillCameraForTimeLapse &&
+ mCamera != NULL) {
mCamera->releaseRecordingFrame(frame);
}
}
diff --git a/media/libstagefright/MP3Extractor.cpp b/media/libstagefright/MP3Extractor.cpp
index 9610f90..0bb3a86 100644
--- a/media/libstagefright/MP3Extractor.cpp
+++ b/media/libstagefright/MP3Extractor.cpp
@@ -614,6 +614,7 @@
{ kKeyAuthor, "TXT", "TEXT" },
{ kKeyCDTrackNumber, "TRK", "TRCK" },
{ kKeyDiscNumber, "TPA", "TPOS" },
+ { kKeyCompilation, "TCP", "TCMP" },
};
static const size_t kNumMapEntries = sizeof(kMap) / sizeof(kMap[0]);
diff --git a/media/libstagefright/MPEG4Extractor.cpp b/media/libstagefright/MPEG4Extractor.cpp
index dfc9b5a..bafa243 100644
--- a/media/libstagefright/MPEG4Extractor.cpp
+++ b/media/libstagefright/MPEG4Extractor.cpp
@@ -1392,6 +1392,17 @@
metadataKey = kKeyGenre;
break;
}
+ case FOURCC('c', 'p', 'i', 'l'):
+ {
+ if (size == 9 && flags == 21) {
+ char tmp[16];
+ sprintf(tmp, "%d",
+ (int)buffer[size - 1]);
+
+ mFileMetaData->setCString(kKeyCompilation, tmp);
+ }
+ break;
+ }
case FOURCC('t', 'r', 'k', 'n'):
{
if (size == 16 && flags == 0) {
diff --git a/media/libstagefright/NuCachedSource2.cpp b/media/libstagefright/NuCachedSource2.cpp
index 110fb03..cdf4270 100644
--- a/media/libstagefright/NuCachedSource2.cpp
+++ b/media/libstagefright/NuCachedSource2.cpp
@@ -348,7 +348,7 @@
ssize_t NuCachedSource2::readAt(off64_t offset, void *data, size_t size) {
Mutex::Autolock autoSerializer(mSerializer);
- LOGV("readAt offset %ld, size %d", offset, size);
+ LOGV("readAt offset %lld, size %d", offset, size);
Mutex::Autolock autoLock(mLock);
@@ -408,7 +408,7 @@
}
ssize_t NuCachedSource2::readInternal(off64_t offset, void *data, size_t size) {
- LOGV("readInternal offset %ld size %d", offset, size);
+ LOGV("readInternal offset %lld size %d", offset, size);
Mutex::Autolock autoLock(mLock);
diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp
index f63774a..e516cb4 100644
--- a/media/libstagefright/OMXCodec.cpp
+++ b/media/libstagefright/OMXCodec.cpp
@@ -235,7 +235,9 @@
sp<OMXCodec> codec = mTarget.promote();
if (codec.get() != NULL) {
+ Mutex::Autolock autoLock(codec->mLock);
codec->on_message(msg);
+ codec.clear();
}
}
@@ -1506,7 +1508,7 @@
OMXCodec::~OMXCodec() {
mSource.clear();
- CHECK(mState == LOADED || mState == ERROR);
+ CHECK(mState == LOADED || mState == ERROR || mState == LOADED_TO_IDLE);
status_t err = mOMX->freeNode(mNode);
CHECK_EQ(err, (status_t)OK);
@@ -1845,8 +1847,6 @@
}
void OMXCodec::on_message(const omx_message &msg) {
- Mutex::Autolock autoLock(mLock);
-
switch (msg.type) {
case omx_message::EVENT:
{
@@ -3923,6 +3923,8 @@
if (!mIsEncoder) {
OMX_CONFIG_RECTTYPE rect;
+ InitOMXParams(&rect);
+ rect.nPortIndex = kPortIndexOutput;
status_t err =
mOMX->getConfig(
mNode, OMX_IndexConfigCommonOutputCrop,
diff --git a/media/libstagefright/OggExtractor.cpp b/media/libstagefright/OggExtractor.cpp
index 4b8a014..cf622af 100644
--- a/media/libstagefright/OggExtractor.cpp
+++ b/media/libstagefright/OggExtractor.cpp
@@ -660,6 +660,9 @@
} kMap[] = {
{ "TITLE", kKeyTitle },
{ "ARTIST", kKeyArtist },
+ { "ALBUMARTIST", kKeyAlbumArtist },
+ { "ALBUM ARTIST", kKeyAlbumArtist },
+ { "COMPILATION", kKeyCompilation },
{ "ALBUM", kKeyAlbum },
{ "COMPOSER", kKeyComposer },
{ "GENRE", kKeyGenre },
diff --git a/media/libstagefright/StagefrightMediaScanner.cpp b/media/libstagefright/StagefrightMediaScanner.cpp
index 86e0e73..5d15246 100644
--- a/media/libstagefright/StagefrightMediaScanner.cpp
+++ b/media/libstagefright/StagefrightMediaScanner.cpp
@@ -156,6 +156,7 @@
{ "year", METADATA_KEY_YEAR },
{ "duration", METADATA_KEY_DURATION },
{ "writer", METADATA_KEY_WRITER },
+ { "compilation", METADATA_KEY_COMPILATION },
};
static const size_t kNumEntries = sizeof(kKeyMap) / sizeof(kKeyMap[0]);
diff --git a/media/libstagefright/StagefrightMetadataRetriever.cpp b/media/libstagefright/StagefrightMetadataRetriever.cpp
index 6331a63..4f483ac 100644
--- a/media/libstagefright/StagefrightMetadataRetriever.cpp
+++ b/media/libstagefright/StagefrightMetadataRetriever.cpp
@@ -238,7 +238,7 @@
(OMX_COLOR_FORMATTYPE)srcFormat, OMX_COLOR_Format16bitRGB565);
CHECK(converter.isValid());
- converter.convert(
+ err = converter.convert(
(const uint8_t *)buffer->data() + buffer->range_offset(),
width, height,
crop_left, crop_top, crop_right, crop_bottom,
@@ -252,6 +252,13 @@
decoder->stop();
+ if (err != OK) {
+ LOGE("Colorconverter failed to convert frame.");
+
+ delete frame;
+ frame = NULL;
+ }
+
return frame;
}
@@ -387,6 +394,7 @@
{ kKeyTitle, METADATA_KEY_TITLE },
{ kKeyYear, METADATA_KEY_YEAR },
{ kKeyWriter, METADATA_KEY_WRITER },
+ { kKeyCompilation, METADATA_KEY_COMPILATION },
};
static const size_t kNumMapEntries = sizeof(kMap) / sizeof(kMap[0]);
diff --git a/media/libstagefright/codecs/m4v_h263/dec/M4vH263Decoder.cpp b/media/libstagefright/codecs/m4v_h263/dec/M4vH263Decoder.cpp
index 0f08f6e..38778fb 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/M4vH263Decoder.cpp
+++ b/media/libstagefright/codecs/m4v_h263/dec/M4vH263Decoder.cpp
@@ -132,7 +132,10 @@
}
MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle);
- CHECK_EQ(mode, actualMode);
+ if (mode != actualMode) {
+ PVCleanUpVideoDecoder(mHandle);
+ return UNKNOWN_ERROR;
+ }
PVSetPostProcType((VideoDecControls *) mHandle, 0);
diff --git a/media/libstagefright/colorconversion/ColorConverter.cpp b/media/libstagefright/colorconversion/ColorConverter.cpp
index 600f040..d518c97 100644
--- a/media/libstagefright/colorconversion/ColorConverter.cpp
+++ b/media/libstagefright/colorconversion/ColorConverter.cpp
@@ -16,6 +16,7 @@
#include <media/stagefright/ColorConverter.h>
#include <media/stagefright/MediaDebug.h>
+#include <media/stagefright/MediaErrors.h>
namespace android {
@@ -72,7 +73,7 @@
return mCropBottom - mCropTop + 1;
}
-void ColorConverter::convert(
+status_t ColorConverter::convert(
const void *srcBits,
size_t srcWidth, size_t srcHeight,
size_t srcCropLeft, size_t srcCropTop,
@@ -81,7 +82,9 @@
size_t dstWidth, size_t dstHeight,
size_t dstCropLeft, size_t dstCropTop,
size_t dstCropRight, size_t dstCropBottom) {
- CHECK_EQ(mDstFormat, OMX_COLOR_Format16bitRGB565);
+ if (mDstFormat != OMX_COLOR_Format16bitRGB565) {
+ return ERROR_UNSUPPORTED;
+ }
BitmapParams src(
const_cast<void *>(srcBits),
@@ -93,21 +96,23 @@
dstWidth, dstHeight,
dstCropLeft, dstCropTop, dstCropRight, dstCropBottom);
+ status_t err;
+
switch (mSrcFormat) {
case OMX_COLOR_FormatYUV420Planar:
- convertYUV420Planar(src, dst);
+ err = convertYUV420Planar(src, dst);
break;
case OMX_COLOR_FormatCbYCrY:
- convertCbYCrY(src, dst);
+ err = convertCbYCrY(src, dst);
break;
case OMX_QCOM_COLOR_FormatYVU420SemiPlanar:
- convertQCOMYUV420SemiPlanar(src, dst);
+ err = convertQCOMYUV420SemiPlanar(src, dst);
break;
case OMX_COLOR_FormatYUV420SemiPlanar:
- convertYUV420SemiPlanar(src, dst);
+ err = convertYUV420SemiPlanar(src, dst);
break;
default:
@@ -116,17 +121,21 @@
break;
}
}
+
+ return err;
}
-void ColorConverter::convertCbYCrY(
+status_t ColorConverter::convertCbYCrY(
const BitmapParams &src, const BitmapParams &dst) {
// XXX Untested
uint8_t *kAdjustedClip = initClip();
- CHECK((src.mCropLeft & 1) == 0);
- CHECK_EQ(src.cropWidth(), dst.cropWidth());
- CHECK_EQ(src.cropHeight(), dst.cropHeight());
+ if (!((src.mCropLeft & 1) == 0
+ && src.cropWidth() == dst.cropWidth()
+ && src.cropHeight() == dst.cropHeight())) {
+ return ERROR_UNSUPPORTED;
+ }
uint32_t *dst_ptr = (uint32_t *)dst.mBits
+ (dst.mCropTop * dst.mWidth + dst.mCropLeft) / 2;
@@ -172,16 +181,20 @@
src_ptr += src.mWidth * 2;
dst_ptr += dst.mWidth / 2;
}
+
+ return OK;
}
-void ColorConverter::convertYUV420Planar(
+status_t ColorConverter::convertYUV420Planar(
const BitmapParams &src, const BitmapParams &dst) {
- uint8_t *kAdjustedClip = initClip();
+ if (!((dst.mWidth & 3) == 0
+ && (src.mCropLeft & 1) == 0
+ && src.cropWidth() == dst.cropWidth()
+ && src.cropHeight() == dst.cropHeight())) {
+ return ERROR_UNSUPPORTED;
+ }
- CHECK((dst.mWidth & 3) == 0);
- CHECK((src.mCropLeft & 1) == 0);
- CHECK_EQ(src.cropWidth(), dst.cropWidth());
- CHECK_EQ(src.cropHeight(), dst.cropHeight());
+ uint8_t *kAdjustedClip = initClip();
uint32_t *dst_ptr = (uint32_t *)dst.mBits
+ (dst.mCropTop * dst.mWidth + dst.mCropLeft) / 2;
@@ -259,16 +272,20 @@
dst_ptr += dst.mWidth / 2;
}
+
+ return OK;
}
-void ColorConverter::convertQCOMYUV420SemiPlanar(
+status_t ColorConverter::convertQCOMYUV420SemiPlanar(
const BitmapParams &src, const BitmapParams &dst) {
uint8_t *kAdjustedClip = initClip();
- CHECK((dst.mWidth & 3) == 0);
- CHECK((src.mCropLeft & 1) == 0);
- CHECK_EQ(src.cropWidth(), dst.cropWidth());
- CHECK_EQ(src.cropHeight(), dst.cropHeight());
+ if (!((dst.mWidth & 3) == 0
+ && (src.mCropLeft & 1) == 0
+ && src.cropWidth() == dst.cropWidth()
+ && src.cropHeight() == dst.cropHeight())) {
+ return ERROR_UNSUPPORTED;
+ }
uint32_t *dst_ptr = (uint32_t *)dst.mBits
+ (dst.mCropTop * dst.mWidth + dst.mCropLeft) / 2;
@@ -324,18 +341,22 @@
dst_ptr += dst.mWidth / 2;
}
+
+ return OK;
}
-void ColorConverter::convertYUV420SemiPlanar(
+status_t ColorConverter::convertYUV420SemiPlanar(
const BitmapParams &src, const BitmapParams &dst) {
// XXX Untested
uint8_t *kAdjustedClip = initClip();
- CHECK((dst.mWidth & 3) == 0);
- CHECK((src.mCropLeft & 1) == 0);
- CHECK_EQ(src.cropWidth(), dst.cropWidth());
- CHECK_EQ(src.cropHeight(), dst.cropHeight());
+ if (!((dst.mWidth & 3) == 0
+ && (src.mCropLeft & 1) == 0
+ && src.cropWidth() == dst.cropWidth()
+ && src.cropHeight() == dst.cropHeight())) {
+ return ERROR_UNSUPPORTED;
+ }
uint32_t *dst_ptr = (uint32_t *)dst.mBits
+ (dst.mCropTop * dst.mWidth + dst.mCropLeft) / 2;
@@ -391,6 +412,8 @@
dst_ptr += dst.mWidth / 2;
}
+
+ return OK;
}
uint8_t *ColorConverter::initClip() {
diff --git a/media/libstagefright/foundation/AMessage.cpp b/media/libstagefright/foundation/AMessage.cpp
index 0e40acc..b592c3f 100644
--- a/media/libstagefright/foundation/AMessage.cpp
+++ b/media/libstagefright/foundation/AMessage.cpp
@@ -171,6 +171,18 @@
item->u.refValue = obj.get();
}
+void AMessage::setRect(
+ const char *name,
+ int32_t left, int32_t top, int32_t right, int32_t bottom) {
+ Item *item = allocateItem(name);
+ item->mType = kTypeRect;
+
+ item->u.rectValue.mLeft = left;
+ item->u.rectValue.mTop = top;
+ item->u.rectValue.mRight = right;
+ item->u.rectValue.mBottom = bottom;
+}
+
bool AMessage::findString(const char *name, AString *value) const {
const Item *item = findItem(name, kTypeString);
if (item) {
@@ -198,6 +210,22 @@
return false;
}
+bool AMessage::findRect(
+ const char *name,
+ int32_t *left, int32_t *top, int32_t *right, int32_t *bottom) const {
+ const Item *item = findItem(name, kTypeRect);
+ if (item == NULL) {
+ return false;
+ }
+
+ *left = item->u.rectValue.mLeft;
+ *top = item->u.rectValue.mTop;
+ *right = item->u.rectValue.mRight;
+ *bottom = item->u.rectValue.mBottom;
+
+ return true;
+}
+
void AMessage::post(int64_t delayUs) {
extern ALooperRoster gLooperRoster;
diff --git a/media/libstagefright/httplive/LiveSession.cpp b/media/libstagefright/httplive/LiveSession.cpp
index 6fd0171..5979be6 100644
--- a/media/libstagefright/httplive/LiveSession.cpp
+++ b/media/libstagefright/httplive/LiveSession.cpp
@@ -158,8 +158,8 @@
mBandwidthItems.sort(SortByBandwidth);
char value[PROPERTY_VALUE_MAX];
- if (!property_get("media.httplive.enable-nuplayer", value, NULL)
- || (strcasecmp(value, "true") && strcmp(value, "1"))) {
+ if (property_get("media.httplive.disable-nuplayer", value, NULL)
+ && (!strcasecmp(value, "true") || !strcmp(value, "1"))) {
// The "legacy" player cannot deal with audio format changes,
// some streams use different audio encoding parameters for
// their lowest bandwidth stream.
@@ -229,7 +229,7 @@
bufferRemaining);
if (n < 0) {
- return err;
+ return n;
}
if (n == 0) {
@@ -340,6 +340,7 @@
void LiveSession::onDownloadNext() {
size_t bandwidthIndex = getBandwidthIndex();
+rinse_repeat:
int64_t nowUs = ALooper::GetNowUs();
if (mLastPlaylistFetchTimeUs < 0
@@ -437,6 +438,18 @@
if (mSeqNumber < firstSeqNumberInPlaylist
|| mSeqNumber > lastSeqNumberInPlaylist) {
+ if (mSeqNumber < firstSeqNumberInPlaylist
+ && mPrevBandwidthIndex != (ssize_t)bandwidthIndex) {
+ // Go back to the previous bandwidth.
+
+ LOGI("new bandwidth does not have the sequence number "
+ "we're looking for, switching back to previous bandwidth");
+
+ mLastPlaylistFetchTimeUs = -1;
+ bandwidthIndex = mPrevBandwidthIndex;
+ goto rinse_repeat;
+ }
+
if (!mPlaylist->isComplete()
&& mSeqNumber > lastSeqNumberInPlaylist
&& mNumRetries < kMaxNumRetries) {
diff --git a/media/libstagefright/include/AwesomePlayer.h b/media/libstagefright/include/AwesomePlayer.h
index 0c67432..130ad82 100644
--- a/media/libstagefright/include/AwesomePlayer.h
+++ b/media/libstagefright/include/AwesomePlayer.h
@@ -151,6 +151,7 @@
uint32_t mFlags;
uint32_t mExtractorFlags;
+ uint32_t mSinceLastDropped;
int64_t mTimeSourceDeltaUs;
int64_t mVideoTimeUs;
@@ -172,6 +173,8 @@
bool mBufferingEventPending;
sp<TimedEventQueue::Event> mCheckAudioStatusEvent;
bool mAudioStatusEventPending;
+ sp<TimedEventQueue::Event> mVideoLagEvent;
+ bool mVideoLagEventPending;
sp<TimedEventQueue::Event> mAsyncPrepareEvent;
Condition mPreparedCondition;
@@ -183,6 +186,7 @@
void postBufferingEvent_l();
void postStreamDoneEvent_l(status_t status);
void postCheckAudioStatusEvent_l();
+ void postVideoLagEvent_l();
status_t play_l();
MediaBuffer *mVideoBuffer;
@@ -232,6 +236,7 @@
void onPrepareAsyncEvent();
void abortPrepare(status_t err);
void finishAsyncPrepare_l();
+ void onVideoLagUpdate();
bool getCachedDuration_l(int64_t *durationUs, bool *eos);
diff --git a/media/libstagefright/include/NuCachedSource2.h b/media/libstagefright/include/NuCachedSource2.h
index 78719c1..aa320fc 100644
--- a/media/libstagefright/include/NuCachedSource2.h
+++ b/media/libstagefright/include/NuCachedSource2.h
@@ -55,8 +55,8 @@
enum {
kPageSize = 65536,
- kHighWaterThreshold = 5 * 1024 * 1024,
- kLowWaterThreshold = 1024 * 1024,
+ kHighWaterThreshold = 20 * 1024 * 1024,
+ kLowWaterThreshold = 4 * 1024 * 1024,
// Read data after a 15 sec timeout whether we're actively
// fetching or not.
diff --git a/media/libstagefright/matroska/MatroskaExtractor.cpp b/media/libstagefright/matroska/MatroskaExtractor.cpp
index e0ac49f..eca9ed6 100644
--- a/media/libstagefright/matroska/MatroskaExtractor.cpp
+++ b/media/libstagefright/matroska/MatroskaExtractor.cpp
@@ -118,6 +118,9 @@
virtual status_t read(
MediaBuffer **buffer, const ReadOptions *options);
+protected:
+ virtual ~MatroskaSource();
+
private:
enum Type {
AVC,
@@ -131,8 +134,13 @@
BlockIterator mBlockIter;
size_t mNALSizeLen; // for type AVC
+ List<MediaBuffer *> mPendingFrames;
+
status_t advance();
+ status_t readBlock();
+ void clearPendingFrames();
+
MatroskaSource(const MatroskaSource &);
MatroskaSource &operator=(const MatroskaSource &);
};
@@ -168,6 +176,10 @@
}
}
+MatroskaSource::~MatroskaSource() {
+ clearPendingFrames();
+}
+
status_t MatroskaSource::start(MetaData *params) {
mBlockIter.reset();
@@ -175,6 +187,8 @@
}
status_t MatroskaSource::stop() {
+ clearPendingFrames();
+
return OK;
}
@@ -256,6 +270,214 @@
return ptr[0] << 16 | ptr[1] << 8 | ptr[2];
}
+static size_t clz(uint8_t x) {
+ size_t numLeadingZeroes = 0;
+
+ while (!(x & 0x80)) {
+ ++numLeadingZeroes;
+ x = x << 1;
+ }
+
+ return numLeadingZeroes;
+}
+
+void MatroskaSource::clearPendingFrames() {
+ while (!mPendingFrames.empty()) {
+ MediaBuffer *frame = *mPendingFrames.begin();
+ mPendingFrames.erase(mPendingFrames.begin());
+
+ frame->release();
+ frame = NULL;
+ }
+}
+
+#define BAIL(err) \
+ do { \
+ if (bigbuf) { \
+ bigbuf->release(); \
+ bigbuf = NULL; \
+ } \
+ \
+ return err; \
+ } while (0)
+
+status_t MatroskaSource::readBlock() {
+ CHECK(mPendingFrames.empty());
+
+ if (mBlockIter.eos()) {
+ return ERROR_END_OF_STREAM;
+ }
+
+ const mkvparser::Block *block = mBlockIter.block();
+
+ size_t size = block->GetSize();
+ int64_t timeUs = mBlockIter.blockTimeUs();
+ int32_t isSync = block->IsKey();
+
+ MediaBuffer *bigbuf = new MediaBuffer(size);
+
+ long res = block->Read(
+ mExtractor->mReader, (unsigned char *)bigbuf->data());
+
+ if (res != 0) {
+ bigbuf->release();
+ bigbuf = NULL;
+
+ return ERROR_END_OF_STREAM;
+ }
+
+ mBlockIter.advance();
+
+ bigbuf->meta_data()->setInt64(kKeyTime, timeUs);
+ bigbuf->meta_data()->setInt32(kKeyIsSyncFrame, isSync);
+
+ unsigned lacing = (block->Flags() >> 1) & 3;
+
+ if (lacing == 0) {
+ mPendingFrames.push_back(bigbuf);
+ return OK;
+ }
+
+ LOGV("lacing = %u, size = %d", lacing, size);
+
+ const uint8_t *data = (const uint8_t *)bigbuf->data();
+ // hexdump(data, size);
+
+ if (size == 0) {
+ BAIL(ERROR_MALFORMED);
+ }
+
+ unsigned numFrames = (unsigned)data[0] + 1;
+ ++data;
+ --size;
+
+ Vector<uint64_t> frameSizes;
+
+ switch (lacing) {
+ case 1: // Xiph
+ {
+ for (size_t i = 0; i < numFrames - 1; ++i) {
+ size_t frameSize = 0;
+ uint8_t byte;
+ do {
+ if (size == 0) {
+ BAIL(ERROR_MALFORMED);
+ }
+ byte = data[0];
+ ++data;
+ --size;
+
+ frameSize += byte;
+ } while (byte == 0xff);
+
+ frameSizes.push(frameSize);
+ }
+
+ break;
+ }
+
+ case 2: // fixed-size
+ {
+ if ((size % numFrames) != 0) {
+ BAIL(ERROR_MALFORMED);
+ }
+
+ size_t frameSize = size / numFrames;
+ for (size_t i = 0; i < numFrames - 1; ++i) {
+ frameSizes.push(frameSize);
+ }
+
+ break;
+ }
+
+ case 3: // EBML
+ {
+ uint64_t lastFrameSize = 0;
+ for (size_t i = 0; i < numFrames - 1; ++i) {
+ uint8_t byte;
+
+ if (size == 0) {
+ BAIL(ERROR_MALFORMED);
+ }
+ byte = data[0];
+ ++data;
+ --size;
+
+ size_t numLeadingZeroes = clz(byte);
+
+ uint64_t frameSize = byte & ~(0x80 >> numLeadingZeroes);
+ for (size_t j = 0; j < numLeadingZeroes; ++j) {
+ if (size == 0) {
+ BAIL(ERROR_MALFORMED);
+ }
+
+ frameSize = frameSize << 8;
+ frameSize |= data[0];
+ ++data;
+ --size;
+ }
+
+ if (i == 0) {
+ frameSizes.push(frameSize);
+ } else {
+ size_t shift =
+ 7 - numLeadingZeroes + 8 * numLeadingZeroes;
+
+ int64_t delta =
+ (int64_t)frameSize - (1ll << (shift - 1)) + 1;
+
+ frameSize = lastFrameSize + delta;
+
+ frameSizes.push(frameSize);
+ }
+
+ lastFrameSize = frameSize;
+ }
+ break;
+ }
+
+ default:
+ TRESPASS();
+ }
+
+#if 0
+ AString out;
+ for (size_t i = 0; i < frameSizes.size(); ++i) {
+ if (i > 0) {
+ out.append(", ");
+ }
+ out.append(StringPrintf("%llu", frameSizes.itemAt(i)));
+ }
+ LOGV("sizes = [%s]", out.c_str());
+#endif
+
+ for (size_t i = 0; i < frameSizes.size(); ++i) {
+ uint64_t frameSize = frameSizes.itemAt(i);
+
+ if (size < frameSize) {
+ BAIL(ERROR_MALFORMED);
+ }
+
+ MediaBuffer *mbuf = new MediaBuffer(frameSize);
+ mbuf->meta_data()->setInt64(kKeyTime, timeUs);
+ mbuf->meta_data()->setInt32(kKeyIsSyncFrame, isSync);
+ memcpy(mbuf->data(), data, frameSize);
+ mPendingFrames.push_back(mbuf);
+
+ data += frameSize;
+ size -= frameSize;
+ }
+
+ size_t offset = bigbuf->range_length() - size;
+ bigbuf->set_range(offset, size);
+
+ mPendingFrames.push_back(bigbuf);
+
+ return OK;
+}
+
+#undef BAIL
+
status_t MatroskaSource::read(
MediaBuffer **out, const ReadOptions *options) {
*out = NULL;
@@ -263,17 +485,38 @@
int64_t seekTimeUs;
ReadOptions::SeekMode mode;
if (options && options->getSeekTo(&seekTimeUs, &mode)) {
+ clearPendingFrames();
mBlockIter.seek(seekTimeUs);
}
again:
- if (mBlockIter.eos()) {
- return ERROR_END_OF_STREAM;
+ while (mPendingFrames.empty()) {
+ status_t err = readBlock();
+
+ if (err != OK) {
+ clearPendingFrames();
+
+ return err;
+ }
}
- const mkvparser::Block *block = mBlockIter.block();
- size_t size = block->GetSize();
- int64_t timeUs = mBlockIter.blockTimeUs();
+ MediaBuffer *frame = *mPendingFrames.begin();
+ mPendingFrames.erase(mPendingFrames.begin());
+
+ size_t size = frame->range_length();
+
+ if (mType != AVC) {
+ *out = frame;
+
+ return OK;
+ }
+
+ if (size < mNALSizeLen) {
+ frame->release();
+ frame = NULL;
+
+ return ERROR_MALFORMED;
+ }
// In the case of AVC content, each NAL unit is prefixed by
// mNALSizeLen bytes of length. We want to prefix the data with
@@ -283,73 +526,54 @@
static const size_t kPadding = 3;
MediaBuffer *buffer = new MediaBuffer(size + kPadding);
+
+ int64_t timeUs;
+ CHECK(frame->meta_data()->findInt64(kKeyTime, &timeUs));
+ int32_t isSync;
+ CHECK(frame->meta_data()->findInt32(kKeyIsSyncFrame, &isSync));
+
buffer->meta_data()->setInt64(kKeyTime, timeUs);
- buffer->meta_data()->setInt32(kKeyIsSyncFrame, block->IsKey());
+ buffer->meta_data()->setInt32(kKeyIsSyncFrame, isSync);
- long res = block->Read(
- mExtractor->mReader, (unsigned char *)buffer->data() + kPadding);
-
- if (res != 0) {
- return ERROR_END_OF_STREAM;
- }
+ memcpy((uint8_t *)buffer->data() + kPadding,
+ (const uint8_t *)frame->data() + frame->range_offset(),
+ size);
buffer->set_range(kPadding, size);
- if (mType == AVC) {
- CHECK_GE(size, mNALSizeLen);
+ frame->release();
+ frame = NULL;
- uint8_t *data = (uint8_t *)buffer->data();
+ uint8_t *data = (uint8_t *)buffer->data();
- size_t NALsize;
- switch (mNALSizeLen) {
- case 1: NALsize = data[kPadding]; break;
- case 2: NALsize = U16_AT(&data[kPadding]); break;
- case 3: NALsize = U24_AT(&data[kPadding]); break;
- case 4: NALsize = U32_AT(&data[kPadding]); break;
- default:
- TRESPASS();
- }
-
- CHECK_GE(size, NALsize + mNALSizeLen);
- if (size > NALsize + mNALSizeLen) {
- LOGW("discarding %d bytes of data.", size - NALsize - mNALSizeLen);
- }
-
- // actual data starts at &data[kPadding + mNALSizeLen]
-
- memcpy(&data[mNALSizeLen - 1], "\x00\x00\x00\x01", 4);
- buffer->set_range(mNALSizeLen - 1, NALsize + 4);
- } else if (mType == AAC) {
- // There's strange junk at the beginning...
-
- const uint8_t *data = (const uint8_t *)buffer->data() + kPadding;
-
- // hexdump(data, size);
-
- size_t offset = 0;
- while (offset < size && data[offset] != 0x21) {
- ++offset;
- }
-
- if (size == offset) {
- buffer->release();
-
- mBlockIter.advance();
- goto again;
- }
-
- buffer->set_range(kPadding + offset, size - offset);
+ size_t NALsize;
+ switch (mNALSizeLen) {
+ case 1: NALsize = data[kPadding]; break;
+ case 2: NALsize = U16_AT(&data[kPadding]); break;
+ case 3: NALsize = U24_AT(&data[kPadding]); break;
+ case 4: NALsize = U32_AT(&data[kPadding]); break;
+ default:
+ TRESPASS();
}
+ if (size < NALsize + mNALSizeLen) {
+ buffer->release();
+ buffer = NULL;
+
+ return ERROR_MALFORMED;
+ }
+
+ if (size > NALsize + mNALSizeLen) {
+ LOGW("discarding %d bytes of data.", size - NALsize - mNALSizeLen);
+ }
+
+ // actual data starts at &data[kPadding + mNALSizeLen]
+
+ memcpy(&data[mNALSizeLen - 1], "\x00\x00\x00\x01", 4);
+ buffer->set_range(mNALSizeLen - 1, NALsize + 4);
+
*out = buffer;
-#if 0
- hexdump((const uint8_t *)buffer->data() + buffer->range_offset(),
- buffer->range_length());
-#endif
-
- mBlockIter.advance();
-
return OK;
}
diff --git a/media/libstagefright/matroska/mkvparser.cpp b/media/libstagefright/matroska/mkvparser.cpp
index 455b1d6..7448d96 100644
--- a/media/libstagefright/matroska/mkvparser.cpp
+++ b/media/libstagefright/matroska/mkvparser.cpp
@@ -4474,6 +4474,9 @@
return ((m_flags & static_cast<unsigned char>(1 << 7)) != 0);
}
+unsigned char Block::Flags() const {
+ return m_flags;
+}
void Block::SetKey(bool bKey)
{
diff --git a/media/libstagefright/matroska/mkvparser.hpp b/media/libstagefright/matroska/mkvparser.hpp
index c46d349..f7d8948 100644
--- a/media/libstagefright/matroska/mkvparser.hpp
+++ b/media/libstagefright/matroska/mkvparser.hpp
@@ -80,6 +80,8 @@
bool IsKey() const;
void SetKey(bool);
+ unsigned char Flags() const;
+
long long GetOffset() const;
long GetSize() const;
long Read(IMkvReader*, unsigned char*) const;
diff --git a/media/libstagefright/omx/OMX.cpp b/media/libstagefright/omx/OMX.cpp
index 4e9920b..3638f41 100644
--- a/media/libstagefright/omx/OMX.cpp
+++ b/media/libstagefright/omx/OMX.cpp
@@ -86,6 +86,9 @@
mQueueChanged.signal();
}
+ // Don't call join on myself
+ CHECK(mThread != pthread_self());
+
void *dummy;
pthread_join(mThread, &dummy);
}
@@ -246,9 +249,12 @@
status_t err = instance->freeNode(mMaster);
- index = mDispatchers.indexOfKey(node);
- CHECK(index >= 0);
- mDispatchers.removeItemsAt(index);
+ {
+ Mutex::Autolock autoLock(mLock);
+ index = mDispatchers.indexOfKey(node);
+ CHECK(index >= 0);
+ mDispatchers.removeItemsAt(index);
+ }
return err;
}
diff --git a/opengl/tests/hwc/Android.mk b/opengl/tests/hwc/Android.mk
index 743dbf1..6312970 100644
--- a/opengl/tests/hwc/Android.mk
+++ b/opengl/tests/hwc/Android.mk
@@ -1,7 +1,40 @@
+# Copyright (C) 2010 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.
+
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
-LOCAL_SRC_FILES:= hwc_stress.cpp
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE:= libhwcTest
+LOCAL_SRC_FILES:= hwcTestLib.cpp
+LOCAL_C_INCLUDES += system/extras/tests/include \
+ bionic \
+ bionic/libstdc++/include \
+ external/stlport/stlport \
+ frameworks/base/opengl/tests \
+ frameworks/base/opengl/tests/include \
+
+LOCAL_CFLAGS := -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+
+LOCAL_SHARED_LIBRARIES += libcutils libutils libstlport
+LOCAL_STATIC_LIBRARIES += libglTest
+LOCAL_PRELINK_MODULE := false
+
+include $(BUILD_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES:= hwcStress.cpp
LOCAL_SHARED_LIBRARIES := \
libcutils \
@@ -12,12 +45,18 @@
LOCAL_STATIC_LIBRARIES := \
libtestUtil \
+ libglTest \
+ libhwcTest \
LOCAL_C_INCLUDES += \
system/extras/tests/include \
hardware/libhardware/include \
+ frameworks/base/opengl/tests \
+ frameworks/base/opengl/tests/include \
-LOCAL_MODULE:= hwc_stress
+LOCAL_CFLAGS := -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+
+LOCAL_MODULE:= hwcStress
LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativestresstest
LOCAL_MODULE_TAGS := tests
@@ -25,3 +64,93 @@
LOCAL_CFLAGS := -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
include $(BUILD_NATIVE_TEST)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES:= hwcRects.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+ libcutils \
+ libEGL \
+ libGLESv2 \
+ libui \
+ libhardware \
+
+LOCAL_STATIC_LIBRARIES := \
+ libtestUtil \
+ libglTest \
+ libhwcTest \
+
+LOCAL_C_INCLUDES += \
+ system/extras/tests/include \
+ hardware/libhardware/include \
+ frameworks/base/opengl/tests \
+ frameworks/base/opengl/tests/include \
+
+LOCAL_MODULE:= hwcRects
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativeutil
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_CFLAGS := -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+
+include $(BUILD_NATIVE_TEST)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES:= hwcColorEquiv.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+ libcutils \
+ libEGL \
+ libGLESv2 \
+ libui \
+ libhardware \
+
+LOCAL_STATIC_LIBRARIES := \
+ libtestUtil \
+ libglTest \
+ libhwcTest \
+
+LOCAL_C_INCLUDES += \
+ system/extras/tests/include \
+ hardware/libhardware/include \
+ frameworks/base/opengl/tests \
+ frameworks/base/opengl/tests/include \
+
+LOCAL_MODULE:= hwcColorEquiv
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativeutil
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_CFLAGS := -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+
+include $(BUILD_NATIVE_TEST)
+
+include $(CLEAR_VARS)
+LOCAL_SRC_FILES:= hwcCommit.cpp
+
+LOCAL_SHARED_LIBRARIES := \
+ libcutils \
+ libEGL \
+ libGLESv2 \
+ libui \
+ libhardware \
+
+LOCAL_STATIC_LIBRARIES := \
+ libtestUtil \
+ libglTest \
+ libhwcTest \
+
+LOCAL_C_INCLUDES += \
+ system/extras/tests/include \
+ hardware/libhardware/include \
+ frameworks/base/opengl/tests \
+ frameworks/base/opengl/tests/include \
+
+LOCAL_MODULE:= hwcCommit
+LOCAL_MODULE_PATH := $(TARGET_OUT_DATA)/nativebenchmark
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_CFLAGS := -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+
+include $(BUILD_NATIVE_TEST)
diff --git a/opengl/tests/hwc/hwcColorEquiv.cpp b/opengl/tests/hwc/hwcColorEquiv.cpp
new file mode 100644
index 0000000..1d03948
--- /dev/null
+++ b/opengl/tests/hwc/hwcColorEquiv.cpp
@@ -0,0 +1,438 @@
+/*
+ * Copyright (C) 2011 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.
+ *
+ */
+
+/*
+ * Hardware Composer Color Equivalence
+ *
+ * Synopsis
+ * hwc_colorequiv [options] eFmt
+ *
+ * options:
+ -v - verbose
+ * -s <0.##, 0.##, 0.##> - Start color (default: <0.0, 0.0, 0.0>
+ * -e <0.##, 0.##, 0.##> - Ending color (default: <1.0, 1.0, 1.0>
+ * -r fmt - reference graphic format
+ * -D #.## - End of test delay
+ *
+ * graphic formats:
+ * RGBA8888 (reference frame default)
+ * RGBX8888
+ * RGB888
+ * RGB565
+ * BGRA8888
+ * RGBA5551
+ * RGBA4444
+ * YV12
+ *
+ * Description
+ * Renders a horizontal blend in two frames. The first frame is rendered
+ * in the upper third of the display and is called the reference frame.
+ * The second frame is displayed in the middle third and is called the
+ * equivalence frame. The primary purpose of this utility is to verify
+ * that the colors produced in the reference and equivalence frames are
+ * the same. The colors are the same when the colors are the same
+ * vertically between the reference and equivalence frames.
+ *
+ * By default the reference frame is rendered through the use of the
+ * RGBA8888 graphic format. The -r option can be used to specify a
+ * non-default reference frame graphic format. The graphic format of
+ * the equivalence frame is determined by a single required positional
+ * parameter. Intentionally there is no default for the graphic format
+ * of the equivalence frame.
+ *
+ * The horizontal blend in the reference frame is produced from a linear
+ * interpolation from a start color (default: <0.0, 0.0, 0.0> on the left
+ * side to an end color (default <1.0, 1.0, 1.0> on the right side. Where
+ * possible the equivalence frame is rendered with the equivalent color
+ * from the reference frame. A color of black is used in the equivalence
+ * frame for cases where an equivalent color does not exist.
+ */
+
+#include <algorithm>
+#include <assert.h>
+#include <cerrno>
+#include <cmath>
+#include <cstdlib>
+#include <ctime>
+#include <libgen.h>
+#include <sched.h>
+#include <sstream>
+#include <stdint.h>
+#include <string.h>
+#include <unistd.h>
+#include <vector>
+
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+#include <ui/FramebufferNativeWindow.h>
+#include <ui/GraphicBuffer.h>
+#include <ui/EGLUtils.h>
+
+#define LOG_TAG "hwcColorEquivTest"
+#include <utils/Log.h>
+#include <testUtil.h>
+
+#include <hardware/hwcomposer.h>
+
+#include "hwcTestLib.h"
+
+using namespace std;
+using namespace android;
+
+// Defaults for command-line options
+const bool defaultVerbose = false;
+const ColorFract defaultStartColor(0.0, 0.0, 0.0);
+const ColorFract defaultEndColor(1.0, 1.0, 1.0);
+const char *defaultRefFormat = "RGBA8888";
+const float defaultEndDelay = 2.0; // Default delay after rendering graphics
+
+// Defines
+#define MAXSTR 100
+#define MAXCMD 200
+#define BITSPERBYTE 8 // TODO: Obtain from <values.h>, once
+ // it has been added
+
+#define CMD_STOP_FRAMEWORK "stop 2>&1"
+#define CMD_START_FRAMEWORK "start 2>&1"
+
+// Macros
+#define NUMA(a) (sizeof(a) / sizeof(a [0])) // Num elements in an array
+#define MEMCLR(addr, size) do { \
+ memset((addr), 0, (size)); \
+ } while (0)
+
+// Globals
+static const int texUsage = GraphicBuffer::USAGE_HW_TEXTURE |
+ GraphicBuffer::USAGE_SW_WRITE_RARELY;
+static hwc_composer_device_t *hwcDevice;
+static EGLDisplay dpy;
+static EGLSurface surface;
+static EGLint width, height;
+
+// Functions prototypes
+void init(void);
+void printSyntax(const char *cmd);
+
+// Command-line option settings
+static bool verbose = defaultVerbose;
+static ColorFract startRefColor = defaultStartColor;
+static ColorFract endRefColor = defaultEndColor;
+static float endDelay = defaultEndDelay;
+static const struct hwcTestGraphicFormat *refFormat
+ = hwcTestGraphicFormatLookup(defaultRefFormat);
+static const struct hwcTestGraphicFormat *equivFormat;
+
+/*
+ * Main
+ *
+ * Performs the following high-level sequence of operations:
+ *
+ * 1. Command-line parsing
+ *
+ * 2. Stop framework
+ *
+ * 3. Initialization
+ *
+ * 4. Create Hardware Composer description of reference and equivalence frames
+ *
+ * 5. Have Hardware Composer render the reference and equivalence frames
+ *
+ * 6. Delay for amount of time given by endDelay
+ *
+ * 7. Start framework
+ */
+int
+main(int argc, char *argv[])
+{
+ int rv, opt;
+ bool error;
+ char *chptr;
+ unsigned int pass;
+ char cmd[MAXCMD];
+ string str;
+
+ testSetLogCatTag(LOG_TAG);
+
+ assert(refFormat != NULL);
+
+ testSetLogCatTag(LOG_TAG);
+
+ // Parse command line arguments
+ while ((opt = getopt(argc, argv, "vs:e:r:D:?h")) != -1) {
+ switch (opt) {
+ case 'D': // End of test delay
+ // Delay between completion of final pass and restart
+ // of framework
+ endDelay = strtod(optarg, &chptr);
+ if ((*chptr != '\0') || (endDelay < 0.0)) {
+ testPrintE("Invalid command-line specified end of test delay "
+ "of: %s", optarg);
+ exit(1);
+ }
+ break;
+
+ case 's': // Starting reference color
+ str = optarg;
+ while (optind < argc) {
+ if (*argv[optind] == '-') { break; }
+ char endChar = (str.length() > 1) ? str[str.length() - 1] : 0;
+ if ((endChar == '>') || (endChar == ']')) { break; }
+ str += " " + string(argv[optind++]);
+ }
+ {
+ istringstream in(str);
+ startRefColor = hwcTestParseColor(in, error);
+ // Any parse error or characters not used by parser
+ if (error
+ || (((unsigned int) in.tellg() != in.str().length())
+ && (in.tellg() != (streampos) -1))) {
+ testPrintE("Invalid command-line specified start "
+ "reference color of: %s", str.c_str());
+ exit(2);
+ }
+ }
+ break;
+
+ case 'e': // Ending reference color
+ str = optarg;
+ while (optind < argc) {
+ if (*argv[optind] == '-') { break; }
+ char endChar = (str.length() > 1) ? str[str.length() - 1] : 0;
+ if ((endChar == '>') || (endChar == ']')) { break; }
+ str += " " + string(argv[optind++]);
+ }
+ {
+ istringstream in(str);
+ endRefColor = hwcTestParseColor(in, error);
+ // Any parse error or characters not used by parser
+ if (error
+ || (((unsigned int) in.tellg() != in.str().length())
+ && (in.tellg() != (streampos) -1))) {
+ testPrintE("Invalid command-line specified end "
+ "reference color of: %s", str.c_str());
+ exit(3);
+ }
+ }
+ break;
+
+ case 'r': // Reference graphic format
+ refFormat = hwcTestGraphicFormatLookup(optarg);
+ if (refFormat == NULL) {
+ testPrintE("Unkown command-line specified reference graphic "
+ "format of: %s", optarg);
+ printSyntax(basename(argv[0]));
+ exit(4);
+ }
+ break;
+
+ case 'v': // Verbose
+ verbose = true;
+ break;
+
+ case 'h': // Help
+ case '?':
+ default:
+ printSyntax(basename(argv[0]));
+ exit(((optopt == 0) || (optopt == '?')) ? 0 : 5);
+ }
+ }
+
+ // Expect a single positional parameter, which specifies the
+ // equivalence graphic format.
+ if (argc != (optind + 1)) {
+ testPrintE("Expected a single command-line postional parameter");
+ printSyntax(basename(argv[0]));
+ exit(6);
+ }
+ equivFormat = hwcTestGraphicFormatLookup(argv[optind]);
+ if (equivFormat == NULL) {
+ testPrintE("Unkown command-line specified equivalence graphic "
+ "format of: %s", argv[optind]);
+ printSyntax(basename(argv[0]));
+ exit(7);
+ }
+
+ testPrintI("refFormat: %u %s", refFormat->format, refFormat->desc);
+ testPrintI("equivFormat: %u %s", equivFormat->format, equivFormat->desc);
+ testPrintI("startRefColor: %s", ((string) startRefColor).c_str());
+ testPrintI("endRefColor: %s", ((string) endRefColor).c_str());
+ testPrintI("endDelay: %f", endDelay);
+
+ // Stop framework
+ rv = snprintf(cmd, sizeof(cmd), "%s", CMD_STOP_FRAMEWORK);
+ if (rv >= (signed) sizeof(cmd) - 1) {
+ testPrintE("Command too long for: %s", CMD_STOP_FRAMEWORK);
+ exit(8);
+ }
+ testExecCmd(cmd);
+ testDelay(1.0); // TODO - needs means to query whether asynchronous stop
+ // framework operation has completed. For now, just wait
+ // a long time.
+
+ init();
+
+ // Use the upper third of the display for the reference frame and
+ // the middle third for the equivalence frame.
+ unsigned int refHeight = height / 3;
+ unsigned int refPosY = 0; // Reference frame Y position
+ unsigned int refPosX = 0; // Reference frame X position
+ unsigned int refWidth = width - refPosX;
+ if ((refWidth & refFormat->wMod) != 0) {
+ refWidth += refFormat->wMod - (refWidth % refFormat->wMod);
+ }
+ unsigned int equivHeight = height / 3;
+ unsigned int equivPosY = refHeight; // Equivalence frame Y position
+ unsigned int equivPosX = 0; // Equivalence frame X position
+ unsigned int equivWidth = width - equivPosX;
+ if ((equivWidth & equivFormat->wMod) != 0) {
+ equivWidth += equivFormat->wMod - (equivWidth % equivFormat->wMod);
+ }
+
+ // Create reference and equivalence graphic buffers
+ const unsigned int numFrames = 2;
+ sp<GraphicBuffer> refFrame;
+ refFrame = new GraphicBuffer(refWidth, refHeight,
+ refFormat->format, texUsage);
+ if ((rv = refFrame->initCheck()) != NO_ERROR) {
+ testPrintE("refFrame initCheck failed, rv: %i", rv);
+ testPrintE(" width %u height: %u format: %u %s", refWidth, refHeight,
+ refFormat->format,
+ hwcTestGraphicFormat2str(refFormat->format));
+ exit(9);
+ }
+ testPrintI("refFrame width: %u height: %u format: %u %s",
+ refWidth, refHeight, refFormat->format,
+ hwcTestGraphicFormat2str(refFormat->format));
+
+ sp<GraphicBuffer> equivFrame;
+ equivFrame = new GraphicBuffer(equivWidth, equivHeight,
+ equivFormat->format, texUsage);
+ if ((rv = refFrame->initCheck()) != NO_ERROR) {
+ testPrintE("refFrame initCheck failed, rv: %i", rv);
+ testPrintE(" width %u height: %u format: %u %s", refWidth, refHeight,
+ refFormat->format,
+ hwcTestGraphicFormat2str(refFormat->format));
+ exit(10);
+ }
+ testPrintI("equivFrame width: %u height: %u format: %u %s",
+ equivWidth, equivHeight, equivFormat->format,
+ hwcTestGraphicFormat2str(equivFormat->format));
+
+ // Fill the frames with a horizontal blend
+ hwcTestFillColorHBlend(refFrame.get(), refFormat->format,
+ startRefColor, endRefColor);
+ hwcTestFillColorHBlend(equivFrame.get(), refFormat->format,
+ startRefColor, endRefColor);
+
+ hwc_layer_list_t *list;
+ size_t size = sizeof(hwc_layer_list) + numFrames * sizeof(hwc_layer_t);
+ if ((list = (hwc_layer_list_t *) calloc(1, size)) == NULL) {
+ testPrintE("Allocate list failed");
+ exit(11);
+ }
+ list->flags = HWC_GEOMETRY_CHANGED;
+ list->numHwLayers = numFrames;
+
+ hwc_layer_t *layer = &list->hwLayers[0];
+ layer->handle = refFrame->handle;
+ layer->blending = HWC_BLENDING_NONE;
+ layer->sourceCrop.left = 0;
+ layer->sourceCrop.top = 0;
+ layer->sourceCrop.right = width;
+ layer->sourceCrop.bottom = refHeight;
+ layer->displayFrame.left = 0;
+ layer->displayFrame.top = 0;
+ layer->displayFrame.right = width;
+ layer->displayFrame.bottom = refHeight;
+ layer->visibleRegionScreen.numRects = 1;
+ layer->visibleRegionScreen.rects = &layer->displayFrame;
+
+ layer++;
+ layer->handle = equivFrame->handle;
+ layer->blending = HWC_BLENDING_NONE;
+ layer->sourceCrop.left = 0;
+ layer->sourceCrop.top = 0;
+ layer->sourceCrop.right = width;
+ layer->sourceCrop.bottom = equivHeight;
+ layer->displayFrame.left = 0;
+ layer->displayFrame.top = refHeight;
+ layer->displayFrame.right = width;
+ layer->displayFrame.bottom = layer->displayFrame.top + equivHeight;
+ layer->visibleRegionScreen.numRects = 1;
+ layer->visibleRegionScreen.rects = &layer->displayFrame;
+
+ // Perform prepare operation
+ if (verbose) { testPrintI("Prepare:"); hwcTestDisplayList(list); }
+ hwcDevice->prepare(hwcDevice, list);
+ if (verbose) {
+ testPrintI("Post Prepare:");
+ hwcTestDisplayListPrepareModifiable(list);
+ }
+
+ // Turn off the geometry changed flag
+ list->flags &= ~HWC_GEOMETRY_CHANGED;
+
+ if (verbose) {hwcTestDisplayListHandles(list); }
+ hwcDevice->set(hwcDevice, dpy, surface, list);
+
+ testDelay(endDelay);
+
+ // Start framework
+ rv = snprintf(cmd, sizeof(cmd), "%s", CMD_START_FRAMEWORK);
+ if (rv >= (signed) sizeof(cmd) - 1) {
+ testPrintE("Command too long for: %s", CMD_START_FRAMEWORK);
+ exit(12);
+ }
+ testExecCmd(cmd);
+
+ return 0;
+}
+
+void init(void)
+{
+ // Seed pseudo random number generator
+ // Seeding causes fill horizontal blend to fill the pad area with
+ // a deterministic set of values.
+ srand48(0);
+
+ hwcTestInitDisplay(verbose, &dpy, &surface, &width, &height);
+
+ hwcTestOpenHwc(&hwcDevice);
+}
+
+void printSyntax(const char *cmd)
+{
+ testPrintE(" %s [options] graphicFormat", cmd);
+ testPrintE(" options:");
+ testPrintE(" -s <0.##, 0.##, 0.##> - Starting reference color");
+ testPrintE(" -e <0.##, 0.##, 0.##> - Ending reference color");
+ testPrintE(" -r format - Reference graphic format");
+ testPrintE(" -D #.## - End of test delay");
+ testPrintE(" -v Verbose");
+ testPrintE("");
+ testPrintE(" graphic formats:");
+ for (unsigned int n1 = 0; n1 < NUMA(hwcTestGraphicFormat); n1++) {
+ testPrintE(" %s", hwcTestGraphicFormat[n1].desc);
+ }
+}
diff --git a/opengl/tests/hwc/hwcCommit.cpp b/opengl/tests/hwc/hwcCommit.cpp
new file mode 100644
index 0000000..66ccdae
--- /dev/null
+++ b/opengl/tests/hwc/hwcCommit.cpp
@@ -0,0 +1,1562 @@
+/*
+ * Copyright (C) 2011 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.
+ *
+ */
+
+/*
+ * Hardware Composer Commit Points
+ *
+ * Synopsis
+ * hwcCommit [options] graphicFormat ...
+ * options:
+ * -s [width, height] - Starting dimension
+ * -v - Verbose
+ *
+ * graphic formats:
+ * RGBA8888 (reference frame default)
+ * RGBX8888
+ * RGB888
+ * RGB565
+ * BGRA8888
+ * RGBA5551
+ * RGBA4444
+ * YV12
+ *
+ * Description
+ * The Hardware Composer (HWC) Commit test is a benchmark that
+ * discovers the points at which the HWC will commit to rendering an
+ * overlay(s). Before rendering a set of overlays, the HWC is shown
+ * the list through a prepare call. During the prepare call the HWC
+ * is able to examine the list and specify which overlays it is able
+ * to handle. The overlays that it can't handle are typically composited
+ * by a higher level (e.g. Surface Flinger) and then the original list
+ * plus a composit of what HWC passed on are provided back to the HWC
+ * for rendering.
+ *
+ * Once an implementation of the HWC has been shipped, a regression would
+ * likely occur if a latter implementation started passing on conditions
+ * that it used to commit to. The primary purpose of this benchmark
+ * is the automated discovery of the commit points, where an implementation
+ * is on the edge between committing and not committing. These are commonly
+ * referred to as commit points. Between implementations changes to the
+ * commit points are allowed, as long as they improve what the HWC commits
+ * to. Once an implementation of the HWC is shipped, the commit points are
+ * not allowed to regress in future implementations.
+ *
+ * This benchmark takes a sampling and then adjusts until it finds a
+ * commit point. It doesn't exhaustively check all possible conditions,
+ * which do to the number of combinations would be impossible. Instead
+ * it starts its search from a starting dimension, that can be changed
+ * via the -s option. The search is also bounded by a set of search
+ * limits, that are hard-coded into a structure of constants named
+ * searchLimits. Results that happen to reach a searchLimit are prefixed
+ * with >=, so that it is known that the value could possibly be larger.
+ *
+ * Measurements are made for each of the graphic formats specified as
+ * positional parameters on the command-line. If no graphic formats
+ * are specified on the command line, then by default measurements are
+ * made and reported for each of the known graphic format.
+ */
+
+#include <algorithm>
+#include <assert.h>
+#include <cerrno>
+#include <cmath>
+#include <cstdlib>
+#include <ctime>
+#include <iomanip>
+#include <istream>
+#include <libgen.h>
+#include <list>
+#include <sched.h>
+#include <sstream>
+#include <stdint.h>
+#include <string.h>
+#include <unistd.h>
+#include <vector>
+
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+#include <ui/FramebufferNativeWindow.h>
+#include <ui/GraphicBuffer.h>
+#include <ui/EGLUtils.h>
+
+#define LOG_TAG "hwcCommitTest"
+#include <utils/Log.h>
+#include <testUtil.h>
+
+#include <hardware/hwcomposer.h>
+
+#include <glTestLib.h>
+#include <hwc/hwcTestLib.h>
+
+using namespace std;
+using namespace android;
+
+// Defaults
+const HwcTestDim defaultStartDim = HwcTestDim(100, 100);
+const bool defaultVerbose = false;
+
+const uint32_t defaultFormat = HAL_PIXEL_FORMAT_RGBA_8888;
+const int32_t defaultTransform = 0;
+const uint32_t defaultBlend = HWC_BLENDING_NONE;
+const ColorFract defaultColor(0.5, 0.5, 0.5);
+const float defaultAlpha = 1.0; // Opaque
+const HwcTestDim defaultSourceDim(1, 1);
+const struct hwc_rect defaultSourceCrop = {0, 0, 1, 1};
+const struct hwc_rect defaultDisplayFrame = {0, 0, 100, 100};
+
+// Global Constants
+const uint32_t printFieldWidth = 2;
+const struct searchLimits {
+ uint32_t numOverlays;
+ HwcTestDim sourceCrop;
+} searchLimits = {
+ 10,
+ HwcTestDim(3000, 2000),
+};
+const struct transformType {
+ const char *desc;
+ uint32_t id;
+} transformType[] = {
+ {"fliph", HWC_TRANSFORM_FLIP_H},
+ {"flipv", HWC_TRANSFORM_FLIP_V},
+ {"rot90", HWC_TRANSFORM_ROT_90},
+ {"rot180", HWC_TRANSFORM_ROT_180},
+ {"rot270", HWC_TRANSFORM_ROT_270},
+};
+const struct blendType {
+ const char *desc;
+ uint32_t id;
+} blendType[] = {
+ {"none", HWC_BLENDING_NONE},
+ {"premult", HWC_BLENDING_PREMULT},
+ {"coverage", HWC_BLENDING_COVERAGE},
+};
+
+// Defines
+#define MAXCMD 200
+#define CMD_STOP_FRAMEWORK "stop 2>&1"
+#define CMD_START_FRAMEWORK "start 2>&1"
+
+// Macros
+#define NUMA(a) (sizeof(a) / sizeof(a [0])) // Num elements in an array
+
+// Local types
+class Rectangle {
+public:
+ Rectangle(uint32_t graphicFormat = defaultFormat,
+ HwcTestDim dfDim = HwcTestDim(1, 1),
+ HwcTestDim sDim = HwcTestDim(1, 1));
+ void setSourceDim(HwcTestDim dim);
+
+ uint32_t format;
+ uint32_t transform;
+ int32_t blend;
+ ColorFract color;
+ float alpha;
+ HwcTestDim sourceDim;
+ struct hwc_rect sourceCrop;
+ struct hwc_rect displayFrame;
+};
+
+class Range {
+public:
+ Range(void) : _l(0), _u(0) {}
+ Range(uint32_t lower, uint32_t upper) : _l(lower), _u(upper) {}
+ uint32_t lower(void) { return _l; }
+ uint32_t upper(void) { return _u; }
+
+ operator string();
+
+private:
+ uint32_t _l; // lower
+ uint32_t _u; // upper
+};
+
+Range::operator string()
+{
+ ostringstream out;
+
+ out << '[' << _l << ", " << _u << ']';
+
+ return out.str();
+}
+
+class Rational {
+public:
+ Rational(void) : _n(0), _d(1) {}
+ Rational(uint32_t n, uint32_t d) : _n(n), _d(d) {}
+ uint32_t numerator(void) { return _n; }
+ uint32_t denominator(void) { return _d; }
+ void setNumerator(uint32_t numerator) { _n = numerator; }
+
+ bool operator==(const Rational& other) const;
+ bool operator!=(const Rational& other) const { return !(*this == other); }
+ bool operator<(const Rational& other) const;
+ bool operator>(const Rational& other) const {
+ return (!(*this == other) && !(*this < other));
+ }
+ static void double2Rational(double f, Range nRange, Range dRange,
+ Rational& lower, Rational& upper);
+
+ operator string() const;
+ operator double() const { return (double) _n / (double) _d; }
+
+
+private:
+ uint32_t _n;
+ uint32_t _d;
+};
+
+// Globals
+static const int texUsage = GraphicBuffer::USAGE_HW_TEXTURE |
+ GraphicBuffer::USAGE_SW_WRITE_RARELY;
+static hwc_composer_device_t *hwcDevice;
+static EGLDisplay dpy;
+static EGLSurface surface;
+static EGLint width, height;
+static size_t maxHeadingLen;
+static vector<string> formats;
+
+// Measurements
+struct meas {
+ uint32_t format;
+ uint32_t startDimOverlays;
+ uint32_t maxNonOverlapping;
+ uint32_t maxOverlapping;
+ list<uint32_t> transforms;
+ list<uint32_t> blends;
+ struct displayFrame {
+ uint32_t minWidth;
+ uint32_t minHeight;
+ HwcTestDim minDim;
+ uint32_t maxWidth;
+ uint32_t maxHeight;
+ HwcTestDim maxDim;
+ } df;
+ struct sourceCrop {
+ uint32_t minWidth;
+ uint32_t minHeight;
+ HwcTestDim minDim;
+ uint32_t maxWidth;
+ uint32_t maxHeight;
+ HwcTestDim maxDim;
+ Rational hScale;
+ HwcTestDim hScaleBestDf;
+ HwcTestDim hScaleBestSc;
+ Rational vScale;
+ HwcTestDim vScaleBestDf;
+ HwcTestDim vScaleBestSc;
+ } sc;
+ vector<uint32_t> overlapBlendNone;
+ vector<uint32_t> overlapBlendPremult;
+ vector<uint32_t> overlapBlendCoverage;
+};
+vector<meas> measurements;
+
+// Function prototypes
+uint32_t numOverlays(list<Rectangle>& rectList);
+uint32_t maxOverlays(uint32_t format, bool allowOverlap);
+list<uint32_t> supportedTransforms(uint32_t format);
+list<uint32_t> supportedBlends(uint32_t format);
+uint32_t dfMinWidth(uint32_t format);
+uint32_t dfMinHeight(uint32_t format);
+uint32_t dfMaxWidth(uint32_t format);
+uint32_t dfMaxHeight(uint32_t format);
+HwcTestDim dfMinDim(uint32_t format);
+HwcTestDim dfMaxDim(uint32_t format);
+uint32_t scMinWidth(uint32_t format, const HwcTestDim& dfDim);
+uint32_t scMinHeight(uint32_t format, const HwcTestDim& dfDim);
+uint32_t scMaxWidth(uint32_t format, const HwcTestDim& dfDim);
+uint32_t scMaxHeight(uint32_t format, const HwcTestDim& dfDim);
+HwcTestDim scMinDim(uint32_t format, const HwcTestDim& dfDim);
+HwcTestDim scMaxDim(uint32_t format, const HwcTestDim& dfDim);
+Rational scHScale(uint32_t format,
+ const HwcTestDim& dfMin, const HwcTestDim& dfMax,
+ const HwcTestDim& scMin, const HwcTestDim& scMax,
+ HwcTestDim& outBestDf, HwcTestDim& outBestSc);
+Rational scVScale(uint32_t format,
+ const HwcTestDim& dfMin, const HwcTestDim& dfMax,
+ const HwcTestDim& scMin, const HwcTestDim& scMax,
+ HwcTestDim& outBestDf, HwcTestDim& outBestSc);
+uint32_t numOverlapping(uint32_t backgroundFormat, uint32_t foregroundFormat,
+ uint32_t backgroundBlend, uint32_t foregroundBlend);
+string transformList2str(const list<uint32_t>& transformList);
+string blendList2str(const list<uint32_t>& blendList);
+void init(void);
+void printFormatHeadings(size_t indent);
+void printOverlapLine(size_t indent, const string formatStr,
+ const vector<uint32_t>& results);
+void printSyntax(const char *cmd);
+
+// Command-line option settings
+static bool verbose = defaultVerbose;
+static HwcTestDim startDim = defaultStartDim;
+
+/*
+ * Main
+ *
+ * Performs the following high-level sequence of operations:
+ *
+ * 1. Command-line parsing
+ *
+ * 2. Form a list of command-line specified graphic formats. If
+ * no formats are specified, then form a list of all known formats.
+ *
+ * 3. Stop framework
+ * Only one user at a time is allowed to use the HWC. Surface
+ * Flinger uses the HWC and is part of the framework. Need to
+ * stop the framework so that Surface Flinger will stop using
+ * the HWC.
+ *
+ * 4. Initialization
+ *
+ * 5. For each graphic format in the previously formed list perform
+ * measurements on that format and report the results.
+ *
+ * 6. Start framework
+ */
+int
+main(int argc, char *argv[])
+{
+ int rv, opt;
+ char *chptr;
+ bool error;
+ string str;
+ char cmd[MAXCMD];
+ list<Rectangle> rectList;
+
+ testSetLogCatTag(LOG_TAG);
+
+ // Parse command line arguments
+ while ((opt = getopt(argc, argv, "s:v?h")) != -1) {
+ switch (opt) {
+
+ case 's': // Start Dimension
+ // Use arguments until next starts with a dash
+ // or current ends with a > or ]
+ str = optarg;
+ while (optind < argc) {
+ if (*argv[optind] == '-') { break; }
+ char endChar = (str.length() > 1) ? str[str.length() - 1] : 0;
+ if ((endChar == '>') || (endChar == ']')) { break; }
+ str += " " + string(argv[optind++]);
+ }
+ {
+ istringstream in(str);
+ startDim = hwcTestParseDim(in, error);
+ // Any parse error or characters not used by parser
+ if (error
+ || (((unsigned int) in.tellg() != in.str().length())
+ && (in.tellg() != (streampos) -1))) {
+ testPrintE("Invalid command-line specified start "
+ "dimension of: %s", str.c_str());
+ exit(8);
+ }
+ }
+ break;
+
+ case 'v': // Verbose
+ verbose = true;
+ break;
+
+ case 'h': // Help
+ case '?':
+ default:
+ printSyntax(basename(argv[0]));
+ exit(((optopt == 0) || (optopt == '?')) ? 0 : 11);
+ }
+ }
+
+ // Positional parameters
+ // Positional parameters provide the names of graphic formats that
+ // measurements are to be made on. Measurements are made on all
+ // known graphic formats when no positional parameters are provided.
+ if (optind == argc) {
+ // No command-line specified graphic formats
+ // Add all graphic formats to the list of formats to be measured
+ for (unsigned int n1 = 0; n1 < NUMA(hwcTestGraphicFormat); n1++) {
+ formats.push_back(hwcTestGraphicFormat[n1].desc);
+ }
+ } else {
+ // Add names of command-line specified graphic formats to the
+ // list of formats to be tested
+ for (; argv[optind] != NULL; optind++) {
+ formats.push_back(argv[optind]);
+ }
+ }
+
+ // Determine length of longest specified graphic format.
+ // This value is used for output formating
+ for (vector<string>::iterator it = formats.begin();
+ it != formats.end(); ++it) {
+ maxHeadingLen = max(maxHeadingLen, it->length());
+ }
+
+ // Stop framework
+ rv = snprintf(cmd, sizeof(cmd), "%s", CMD_STOP_FRAMEWORK);
+ if (rv >= (signed) sizeof(cmd) - 1) {
+ testPrintE("Command too long for: %s", CMD_STOP_FRAMEWORK);
+ exit(14);
+ }
+ testExecCmd(cmd);
+ testDelay(1.0); // TODO - needs means to query whether asynchronous stop
+ // framework operation has completed. For now, just wait
+ // a long time.
+
+ testPrintI("startDim: %s", ((string) startDim).c_str());
+
+ init();
+
+ // For each of the graphic formats
+ for (vector<string>::iterator itFormat = formats.begin();
+ itFormat != formats.end(); ++itFormat) {
+
+ // Locate hwcTestLib structure that describes this format
+ const struct hwcTestGraphicFormat *format;
+ format = hwcTestGraphicFormatLookup((*itFormat).c_str());
+ if (format == NULL) {
+ testPrintE("Unknown graphic format of: %s", (*itFormat).c_str());
+ exit(1);
+ }
+
+ // Display format header
+ testPrintI("format: %s", format->desc);
+
+ // Create area to hold the measurements
+ struct meas meas;
+ struct meas *measPtr;
+ meas.format = format->format;
+ measurements.push_back(meas);
+ measPtr = &measurements[measurements.size() - 1];
+
+ // Start dimension num overlays
+ Rectangle rect(format->format, startDim);
+ rectList.clear();
+ rectList.push_back(rect);
+ measPtr->startDimOverlays = numOverlays(rectList);
+ testPrintI(" startDimOverlays: %u", measPtr->startDimOverlays);
+
+ // Skip the rest of the measurements, when the start dimension
+ // doesn't produce an overlay
+ if (measPtr->startDimOverlays == 0) { continue; }
+
+ // Max Overlays
+ measPtr->maxNonOverlapping = maxOverlays(format->format, false);
+ testPrintI(" max nonOverlapping overlays: %s%u",
+ (measPtr->maxNonOverlapping == searchLimits.numOverlays)
+ ? ">= " : "",
+ measPtr->maxNonOverlapping);
+ measPtr->maxOverlapping = maxOverlays(format->format, true);
+ testPrintI(" max Overlapping overlays: %s%u",
+ (measPtr->maxOverlapping == searchLimits.numOverlays)
+ ? ">= " : "",
+ measPtr->maxOverlapping);
+
+ // Transforms and blends
+ measPtr->transforms = supportedTransforms(format->format);
+ testPrintI(" transforms: %s",
+ transformList2str(measPtr->transforms).c_str());
+ measPtr->blends = supportedBlends(format->format);
+ testPrintI(" blends: %s",
+ blendList2str(measPtr->blends).c_str());
+
+ // Display frame measurements
+ measPtr->df.minWidth = dfMinWidth(format->format);
+ testPrintI(" dfMinWidth: %u", measPtr->df.minWidth);
+
+ measPtr->df.minHeight = dfMinHeight(format->format);
+ testPrintI(" dfMinHeight: %u", measPtr->df.minHeight);
+
+ measPtr->df.maxWidth = dfMaxWidth(format->format);
+ testPrintI(" dfMaxWidth: %u", measPtr->df.maxWidth);
+
+ measPtr->df.maxHeight = dfMaxHeight(format->format);
+ testPrintI(" dfMaxHeight: %u", measPtr->df.maxHeight);
+
+ measPtr->df.minDim = dfMinDim(format->format);
+ testPrintI(" dfMinDim: %s", ((string) measPtr->df.minDim).c_str());
+
+ measPtr->df.maxDim = dfMaxDim(format->format);
+ testPrintI(" dfMaxDim: %s", ((string) measPtr->df.maxDim).c_str());
+
+ // Source crop measurements
+ measPtr->sc.minWidth = scMinWidth(format->format, measPtr->df.minDim);
+ testPrintI(" scMinWidth: %u", measPtr->sc.minWidth);
+
+ measPtr->sc.minHeight = scMinHeight(format->format, measPtr->df.minDim);
+ testPrintI(" scMinHeight: %u", measPtr->sc.minHeight);
+
+ measPtr->sc.maxWidth = scMaxWidth(format->format, measPtr->df.maxDim);
+ testPrintI(" scMaxWidth: %s%u", (measPtr->sc.maxWidth
+ == searchLimits.sourceCrop.width()) ? ">= " : "",
+ measPtr->sc.maxWidth);
+
+ measPtr->sc.maxHeight = scMaxHeight(format->format, measPtr->df.maxDim);
+ testPrintI(" scMaxHeight: %s%u", (measPtr->sc.maxHeight
+ == searchLimits.sourceCrop.height()) ? ">= " : "",
+ measPtr->sc.maxHeight);
+
+ measPtr->sc.minDim = scMinDim(format->format, measPtr->df.minDim);
+ testPrintI(" scMinDim: %s", ((string) measPtr->sc.minDim).c_str());
+
+ measPtr->sc.maxDim = scMaxDim(format->format, measPtr->df.maxDim);
+ testPrintI(" scMaxDim: %s%s", ((measPtr->sc.maxDim.width()
+ >= searchLimits.sourceCrop.width())
+ || (measPtr->sc.maxDim.width() >=
+ searchLimits.sourceCrop.height())) ? ">= " : "",
+ ((string) measPtr->sc.maxDim).c_str());
+
+ measPtr->sc.hScale = scHScale(format->format,
+ measPtr->df.minDim, measPtr->df.maxDim,
+ measPtr->sc.minDim, measPtr->sc.maxDim,
+ measPtr->sc.hScaleBestDf,
+ measPtr->sc.hScaleBestSc);
+ testPrintI(" scHScale: %s%f",
+ (measPtr->sc.hScale
+ >= Rational(searchLimits.sourceCrop.width(),
+ measPtr->df.minDim.width())) ? ">= " : "",
+ (double) measPtr->sc.hScale);
+ testPrintI(" HScale Best Display Frame: %s",
+ ((string) measPtr->sc.hScaleBestDf).c_str());
+ testPrintI(" HScale Best Source Crop: %s",
+ ((string) measPtr->sc.hScaleBestSc).c_str());
+
+ measPtr->sc.vScale = scVScale(format->format,
+ measPtr->df.minDim, measPtr->df.maxDim,
+ measPtr->sc.minDim, measPtr->sc.maxDim,
+ measPtr->sc.vScaleBestDf,
+ measPtr->sc.vScaleBestSc);
+ testPrintI(" scVScale: %s%f",
+ (measPtr->sc.vScale
+ >= Rational(searchLimits.sourceCrop.height(),
+ measPtr->df.minDim.height())) ? ">= " : "",
+ (double) measPtr->sc.vScale);
+ testPrintI(" VScale Best Display Frame: %s",
+ ((string) measPtr->sc.vScaleBestDf).c_str());
+ testPrintI(" VScale Best Source Crop: %s",
+ ((string) measPtr->sc.vScaleBestSc).c_str());
+
+ // Overlap two graphic formats and different blends
+ // Results displayed after all overlap measurments with
+ // current format in the foreground
+ // TODO: make measurments with background blend other than
+ // none. All of these measurements are done with a
+ // background blend of HWC_BLENDING_NONE, with the
+ // blend type of the foregound being varied.
+ uint32_t foregroundFormat = format->format;
+ for (vector<string>::iterator it = formats.begin();
+ it != formats.end(); ++it) {
+ uint32_t num;
+
+ const struct hwcTestGraphicFormat *backgroundFormatPtr
+ = hwcTestGraphicFormatLookup((*it).c_str());
+ uint32_t backgroundFormat = backgroundFormatPtr->format;
+
+ num = numOverlapping(backgroundFormat, foregroundFormat,
+ HWC_BLENDING_NONE, HWC_BLENDING_NONE);
+ measPtr->overlapBlendNone.push_back(num);
+
+ num = numOverlapping(backgroundFormat, foregroundFormat,
+ HWC_BLENDING_NONE, HWC_BLENDING_PREMULT);
+ measPtr->overlapBlendPremult.push_back(num);
+
+ num = numOverlapping(backgroundFormat, foregroundFormat,
+ HWC_BLENDING_NONE, HWC_BLENDING_COVERAGE);
+ measPtr->overlapBlendCoverage.push_back(num);
+ }
+
+ }
+
+ // Display overlap results
+ size_t indent = 2;
+ testPrintI("overlapping blend: none");
+ printFormatHeadings(indent);
+ for (vector<string>::iterator it = formats.begin();
+ it != formats.end(); ++it) {
+ printOverlapLine(indent, *it, measurements[it
+ - formats.begin()].overlapBlendNone);
+ }
+ testPrintI("");
+
+ testPrintI("overlapping blend: premult");
+ printFormatHeadings(indent);
+ for (vector<string>::iterator it = formats.begin();
+ it != formats.end(); ++it) {
+ printOverlapLine(indent, *it, measurements[it
+ - formats.begin()].overlapBlendPremult);
+ }
+ testPrintI("");
+
+ testPrintI("overlapping blend: coverage");
+ printFormatHeadings(indent);
+ for (vector<string>::iterator it = formats.begin();
+ it != formats.end(); ++it) {
+ printOverlapLine(indent, *it, measurements[it
+ - formats.begin()].overlapBlendCoverage);
+ }
+ testPrintI("");
+
+ // Start framework
+ rv = snprintf(cmd, sizeof(cmd), "%s", CMD_START_FRAMEWORK);
+ if (rv >= (signed) sizeof(cmd) - 1) {
+ testPrintE("Command too long for: %s", CMD_START_FRAMEWORK);
+ exit(21);
+ }
+ testExecCmd(cmd);
+
+ return 0;
+}
+
+// Determine the maximum number of overlays that are all of the same format
+// that the HWC will commit to. If allowOverlap is true, then the rectangles
+// are laid out on a diagonal starting from the upper left corner. With
+// each rectangle adjust one pixel to the right and one pixel down.
+// When allowOverlap is false, the rectangles are tiled in column major
+// order. Note, column major ordering is used so that the initial rectangles
+// are all on different horizontal scan rows. It is common that hardware
+// has limits on the number of objects it can handle on any single row.
+uint32_t maxOverlays(uint32_t format, bool allowOverlap)
+{
+ unsigned int max = 0;
+
+ for (unsigned int numRects = 1; numRects <= searchLimits.numOverlays;
+ numRects++) {
+ list<Rectangle> rectList;
+
+ for (unsigned int x = 0;
+ (x + startDim.width()) < (unsigned int) width;
+ x += (allowOverlap) ? 1 : startDim.width()) {
+ for (unsigned int y = 0;
+ (y + startDim.height()) < (unsigned int) height;
+ y += (allowOverlap) ? 1 : startDim.height()) {
+ Rectangle rect(format, startDim, startDim);
+ rect.displayFrame.left = x;
+ rect.displayFrame.top = y;
+ rect.displayFrame.right = x + startDim.width();
+ rect.displayFrame.bottom = y + startDim.height();
+
+ rectList.push_back(rect);
+
+ if (rectList.size() >= numRects) { break; }
+ }
+ if (rectList.size() >= numRects) { break; }
+ }
+
+ uint32_t num = numOverlays(rectList);
+ if (num > max) { max = num; }
+ }
+
+ return max;
+}
+
+// Measures what transforms (i.e. flip horizontal, rotate 180) are
+// supported by the specified format
+list<uint32_t> supportedTransforms(uint32_t format)
+{
+ list<uint32_t> rv;
+ list<Rectangle> rectList;
+ Rectangle rect(format, startDim);
+
+ // For each of the transform types
+ for (unsigned int idx = 0; idx < NUMA(transformType); idx++) {
+ unsigned int id = transformType[idx].id;
+
+ rect.transform = id;
+ rectList.clear();
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+
+ if (num == 1) {
+ rv.push_back(id);
+ }
+ }
+
+ return rv;
+}
+
+// Determines which types of blends (i.e. none, premult, coverage) are
+// supported by the specified format
+list<uint32_t> supportedBlends(uint32_t format)
+{
+ list<uint32_t> rv;
+ list<Rectangle> rectList;
+ Rectangle rect(format, startDim);
+
+ // For each of the blend types
+ for (unsigned int idx = 0; idx < NUMA(blendType); idx++) {
+ unsigned int id = blendType[idx].id;
+
+ rect.blend = id;
+ rectList.clear();
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+
+ if (num == 1) {
+ rv.push_back(id);
+ }
+ }
+
+ return rv;
+}
+
+// Determines the minimum width of any display frame of the given format
+// that the HWC will commit to.
+uint32_t dfMinWidth(uint32_t format)
+{
+ uint32_t w;
+ list<Rectangle> rectList;
+
+ for (w = 1; w <= startDim.width(); w++) {
+ HwcTestDim dim(w, startDim.height());
+ Rectangle rect(format, dim);
+ rectList.clear();
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ return w;
+ }
+ }
+ if (w > startDim.width()) {
+ testPrintE("Failed to locate display frame min width");
+ exit(33);
+ }
+
+ return w;
+}
+
+// Display frame minimum height
+uint32_t dfMinHeight(uint32_t format)
+{
+ uint32_t h;
+ list<Rectangle> rectList;
+
+ for (h = 1; h <= startDim.height(); h++) {
+ HwcTestDim dim(startDim.width(), h);
+ Rectangle rect(format, dim);
+ rectList.clear();
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ return h;
+ }
+ }
+ if (h > startDim.height()) {
+ testPrintE("Failed to locate display frame min height");
+ exit(34);
+ }
+
+ return h;
+}
+
+// Display frame maximum width
+uint32_t dfMaxWidth(uint32_t format)
+{
+ uint32_t w;
+ list<Rectangle> rectList;
+
+ for (w = width; w >= startDim.width(); w--) {
+ HwcTestDim dim(w, startDim.height());
+ Rectangle rect(format, dim);
+ rectList.clear();
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ return w;
+ }
+ }
+ if (w < startDim.width()) {
+ testPrintE("Failed to locate display frame max width");
+ exit(35);
+ }
+
+ return w;
+}
+
+// Display frame maximum height
+uint32_t dfMaxHeight(uint32_t format)
+{
+ uint32_t h;
+
+ for (h = height; h >= startDim.height(); h--) {
+ HwcTestDim dim(startDim.width(), h);
+ Rectangle rect(format, dim);
+ list<Rectangle> rectList;
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ return h;
+ }
+ }
+ if (h < startDim.height()) {
+ testPrintE("Failed to locate display frame max height");
+ exit(36);
+ }
+
+ return h;
+}
+
+// Determine the minimum number of pixels that the HWC will ever commit to.
+// Note, this might be different that dfMinWidth * dfMinHeight, in that this
+// function adjusts both the width and height from the starting dimension.
+HwcTestDim dfMinDim(uint32_t format)
+{
+ uint64_t bestMinPixels = 0;
+ HwcTestDim bestDim;
+ bool bestSet = false; // True when value has been assigned to
+ // bestMinPixels and bestDim
+
+ bool origVerbose = verbose; // Temporarily turn off verbose
+ verbose = false;
+ for (uint32_t w = 1; w <= startDim.width(); w++) {
+ for (uint32_t h = 1; h <= startDim.height(); h++) {
+ if (bestSet && ((w > bestMinPixels) || (h > bestMinPixels))) {
+ break;
+ }
+
+ HwcTestDim dim(w, h);
+ Rectangle rect(format, dim);
+ list<Rectangle> rectList;
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ uint64_t pixels = dim.width() * dim.height();
+ if (!bestSet || (pixels < bestMinPixels)) {
+ bestMinPixels = pixels;
+ bestDim = dim;
+ bestSet = true;
+ }
+ }
+ }
+ }
+ verbose = origVerbose;
+
+ if (!bestSet) {
+ testPrintE("Unable to locate display frame min dimension");
+ exit(20);
+ }
+
+ return bestDim;
+}
+
+// Display frame maximum dimension
+HwcTestDim dfMaxDim(uint32_t format)
+{
+ uint64_t bestMaxPixels = 0;
+ HwcTestDim bestDim;
+ bool bestSet = false; // True when value has been assigned to
+ // bestMaxPixels and bestDim;
+
+ // Potentially increase benchmark performance by first checking
+ // for the common case of supporting a full display frame.
+ HwcTestDim dim(width, height);
+ Rectangle rect(format, dim);
+ list<Rectangle> rectList;
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num == 1) { return dim; }
+
+ // TODO: Use a binary search
+ bool origVerbose = verbose; // Temporarily turn off verbose
+ verbose = false;
+ for (uint32_t w = startDim.width(); w <= (uint32_t) width; w++) {
+ for (uint32_t h = startDim.height(); h <= (uint32_t) height; h++) {
+ if (bestSet && ((w * h) <= bestMaxPixels)) { continue; }
+
+ HwcTestDim dim(w, h);
+ Rectangle rect(format, dim);
+ list<Rectangle> rectList;
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ uint64_t pixels = dim.width() * dim.height();
+ if (!bestSet || (pixels > bestMaxPixels)) {
+ bestMaxPixels = pixels;
+ bestDim = dim;
+ bestSet = true;
+ }
+ }
+ }
+ }
+ verbose = origVerbose;
+
+ if (!bestSet) {
+ testPrintE("Unable to locate display frame max dimension");
+ exit(21);
+ }
+
+ return bestDim;
+}
+
+// Source crop minimum width
+uint32_t scMinWidth(uint32_t format, const HwcTestDim& dfDim)
+{
+ uint32_t w;
+ list<Rectangle> rectList;
+
+ // Source crop frame min width
+ for (w = 1; w <= dfDim.width(); w++) {
+ Rectangle rect(format, dfDim, HwcTestDim(w, dfDim.height()));
+ rectList.clear();
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ return w;
+ }
+ }
+ testPrintE("Failed to locate source crop min width");
+ exit(35);
+}
+
+// Source crop minimum height
+uint32_t scMinHeight(uint32_t format, const HwcTestDim& dfDim)
+{
+ uint32_t h;
+ list<Rectangle> rectList;
+
+ for (h = 1; h <= dfDim.height(); h++) {
+ Rectangle rect(format, dfDim, HwcTestDim(dfDim.width(), h));
+ rectList.clear();
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ return h;
+ }
+ }
+ testPrintE("Failed to locate source crop min height");
+ exit(36);
+}
+
+// Source crop maximum width
+uint32_t scMaxWidth(uint32_t format, const HwcTestDim& dfDim)
+{
+ uint32_t w;
+ list<Rectangle> rectList;
+
+ for (w = searchLimits.sourceCrop.width(); w >= dfDim.width(); w--) {
+ Rectangle rect(format, dfDim, HwcTestDim(w, dfDim.height()));
+ rectList.clear();
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ return w;
+ }
+ }
+ testPrintE("Failed to locate source crop max width");
+ exit(35);
+}
+
+// Source crop maximum height
+uint32_t scMaxHeight(uint32_t format, const HwcTestDim& dfDim)
+{
+ uint32_t h;
+ list<Rectangle> rectList;
+
+ for (h = searchLimits.sourceCrop.height(); h >= dfDim.height(); h--) {
+ Rectangle rect(format, dfDim, HwcTestDim(dfDim.width(), h));
+ rectList.clear();
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ return h;
+ }
+ }
+ testPrintE("Failed to locate source crop max height");
+ exit(36);
+}
+
+// Source crop minimum dimension
+// Discovers the source crop with the least number of pixels that the
+// HWC will commit to. Note, this may be different from scMinWidth
+// * scMinHeight, in that this function searches for a combination of
+// width and height. While the other routines always keep one of the
+// dimensions equal to the corresponding start dimension.
+HwcTestDim scMinDim(uint32_t format, const HwcTestDim& dfDim)
+{
+ uint64_t bestMinPixels = 0;
+ HwcTestDim bestDim;
+ bool bestSet = false; // True when value has been assigned to
+ // bestMinPixels and bestDim
+
+ bool origVerbose = verbose; // Temporarily turn off verbose
+ verbose = false;
+ for (uint32_t w = 1; w <= dfDim.width(); w++) {
+ for (uint32_t h = 1; h <= dfDim.height(); h++) {
+ if (bestSet && ((w > bestMinPixels) || (h > bestMinPixels))) {
+ break;
+ }
+
+ HwcTestDim dim(w, h);
+ Rectangle rect(format, dfDim, HwcTestDim(w, h));
+ list<Rectangle> rectList;
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ uint64_t pixels = dim.width() * dim.height();
+ if (!bestSet || (pixels < bestMinPixels)) {
+ bestMinPixels = pixels;
+ bestDim = dim;
+ bestSet = true;
+ }
+ }
+ }
+ }
+ verbose = origVerbose;
+
+ if (!bestSet) {
+ testPrintE("Unable to locate source crop min dimension");
+ exit(20);
+ }
+
+ return bestDim;
+}
+
+// Source crop maximum dimension
+HwcTestDim scMaxDim(uint32_t format, const HwcTestDim& dfDim)
+{
+ uint64_t bestMaxPixels = 0;
+ HwcTestDim bestDim;
+ bool bestSet = false; // True when value has been assigned to
+ // bestMaxPixels and bestDim;
+
+ // Potentially increase benchmark performance by first checking
+ // for the common case of supporting the maximum checked source size
+ HwcTestDim dim = searchLimits.sourceCrop;
+ Rectangle rect(format, dfDim, searchLimits.sourceCrop);
+ list<Rectangle> rectList;
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num == 1) { return dim; }
+
+ // TODO: Use a binary search
+ bool origVerbose = verbose; // Temporarily turn off verbose
+ verbose = false;
+ for (uint32_t w = dfDim.width();
+ w <= searchLimits.sourceCrop.width(); w++) {
+ for (uint32_t h = dfDim.height();
+ h <= searchLimits.sourceCrop.height(); h++) {
+ if (bestSet && ((w * h) <= bestMaxPixels)) { continue; }
+
+ HwcTestDim dim(w, h);
+ Rectangle rect(format, dfDim, dim);
+ list<Rectangle> rectList;
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+ if (num > 0) {
+ uint64_t pixels = dim.width() * dim.height();
+ if (!bestSet || (pixels > bestMaxPixels)) {
+ bestMaxPixels = pixels;
+ bestDim = dim;
+ bestSet = true;
+ }
+ }
+ }
+ }
+ verbose = origVerbose;
+
+ if (!bestSet) {
+ testPrintE("Unable to locate source crop max dimension");
+ exit(21);
+ }
+
+ return bestDim;
+}
+
+// Source crop horizontal scale
+// Determines the maximum factor by which the source crop can be larger
+// that the display frame. The commit point is discovered through a
+// binary search of rational numbers. The numerator in each of the
+// rational numbers contains the dimension for the source crop, while
+// the denominator specifies the dimension for the display frame. On
+// each pass of the binary search the mid-point between the greatest
+// point committed to (best) and the smallest point in which a commit
+// has failed is calculated. This mid-point is then passed to a function
+// named double2Rational, which determines the closest rational numbers
+// just below and above the mid-point. By default the lower rational
+// number is used for the scale factor on the next pass of the binary
+// search. The upper value is only used when best is already equal
+// to the lower value. This only occurs when the lower value has already
+// been tried.
+Rational scHScale(uint32_t format,
+ const HwcTestDim& dfMin, const HwcTestDim& dfMax,
+ const HwcTestDim& scMin, const HwcTestDim& scMax,
+ HwcTestDim& outBestDf, HwcTestDim& outBestSc)
+{
+ HwcTestDim scDim, dfDim; // Source crop and display frame dimension
+ Rational best(0, 1), minBad; // Current bounds for a binary search
+ // MinGood is set below the lowest
+ // possible scale. The value of minBad,
+ // will be set by the first pass
+ // of the binary search.
+
+ // Perform the passes of the binary search
+ bool firstPass = true;
+ do {
+ // On first pass try the maximum scale within the search limits
+ if (firstPass) {
+ // Try the maximum possible scale, within the search limits
+ scDim = HwcTestDim(searchLimits.sourceCrop.width(), scMin.height());
+ dfDim = dfMin;
+ } else {
+ // Subsequent pass
+ // Halve the difference between best and minBad.
+ Rational lower, upper, selected;
+
+ // Try the closest ratio halfway between minBood and minBad;
+ // TODO: Avoid rounding issue by using Rational type for
+ // midpoint. For now will use double, which should
+ // have more than sufficient resolution.
+ double mid = (double) best
+ + ((double) minBad - (double) best) / 2.0;
+ Rational::double2Rational(mid,
+ Range(scMin.width(), scMax.width()),
+ Range(dfMin.width(), dfMax.width()),
+ lower, upper);
+ if (((lower == best) && (upper == minBad))) {
+ return best;
+ }
+
+ // Use lower value unless its already been tried
+ selected = (lower != best) ? lower : upper;
+
+ // Assign the size of the source crop and display frame
+ // from the selected ratio of source crop to display frame.
+ scDim = HwcTestDim(selected.numerator(), scMin.height());
+ dfDim = HwcTestDim(selected.denominator(), dfMin.height());
+ }
+
+ // See if the HWC will commit to this combination
+ Rectangle rect(format, dfDim, scDim);
+ list<Rectangle> rectList;
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+
+ if (verbose) {
+ testPrintI(" scHscale num: %u scale: %f dfDim: %s scDim: %s",
+ num, (float) Rational(scDim.width(), dfDim.width()),
+ ((string) dfDim).c_str(), ((string) scDim).c_str());
+ }
+ if (num == 1) {
+ // HWC committed to the combination
+ // This is the best scale factor seen so far. Report the
+ // dimensions to the caller, in case nothing better is seen.
+ outBestDf = dfDim;
+ outBestSc = scDim;
+
+ // Success on the first pass means the largest possible scale
+ // is supported, in which case no need to search any further.
+ if (firstPass) { return Rational(scDim.width(), dfDim.width()); }
+
+ // Update the lower bound of the binary search
+ best = Rational(scDim.width(), dfDim.width());
+ } else {
+ // HWC didn't commit to this combination, so update the
+ // upper bound of the binary search.
+ minBad = Rational(scDim.width(), dfDim.width());
+ }
+
+ firstPass = false;
+ } while (best != minBad);
+
+ return best;
+}
+
+// Source crop vertical scale
+// Determines the maximum factor by which the source crop can be larger
+// that the display frame. The commit point is discovered through a
+// binary search of rational numbers. The numerator in each of the
+// rational numbers contains the dimension for the source crop, while
+// the denominator specifies the dimension for the display frame. On
+// each pass of the binary search the mid-point between the greatest
+// point committed to (best) and the smallest point in which a commit
+// has failed is calculated. This mid-point is then passed to a function
+// named double2Rational, which determines the closest rational numbers
+// just below and above the mid-point. By default the lower rational
+// number is used for the scale factor on the next pass of the binary
+// search. The upper value is only used when best is already equal
+// to the lower value. This only occurs when the lower value has already
+// been tried.
+Rational scVScale(uint32_t format,
+ const HwcTestDim& dfMin, const HwcTestDim& dfMax,
+ const HwcTestDim& scMin, const HwcTestDim& scMax,
+ HwcTestDim& outBestDf, HwcTestDim& outBestSc)
+{
+ HwcTestDim scDim, dfDim; // Source crop and display frame dimension
+ Rational best(0, 1), minBad; // Current bounds for a binary search
+ // MinGood is set below the lowest
+ // possible scale. The value of minBad,
+ // will be set by the first pass
+ // of the binary search.
+
+ // Perform the passes of the binary search
+ bool firstPass = true;
+ do {
+ // On first pass try the maximum scale within the search limits
+ if (firstPass) {
+ // Try the maximum possible scale, within the search limits
+ scDim = HwcTestDim(scMin.width(), searchLimits.sourceCrop.height());
+ dfDim = dfMin;
+ } else {
+ // Subsequent pass
+ // Halve the difference between best and minBad.
+ Rational lower, upper, selected;
+
+ // Try the closest ratio halfway between minBood and minBad;
+ // TODO: Avoid rounding issue by using Rational type for
+ // midpoint. For now will use double, which should
+ // have more than sufficient resolution.
+ double mid = (double) best
+ + ((double) minBad - (double) best) / 2.0;
+ Rational::double2Rational(mid,
+ Range(scMin.height(), scMax.height()),
+ Range(dfMin.height(), dfMax.height()),
+ lower, upper);
+ if (((lower == best) && (upper == minBad))) {
+ return best;
+ }
+
+ // Use lower value unless its already been tried
+ selected = (lower != best) ? lower : upper;
+
+ // Assign the size of the source crop and display frame
+ // from the selected ratio of source crop to display frame.
+ scDim = HwcTestDim(scMin.width(), selected.numerator());
+ dfDim = HwcTestDim(dfMin.width(), selected.denominator());
+ }
+
+ // See if the HWC will commit to this combination
+ Rectangle rect(format, dfDim, scDim);
+ list<Rectangle> rectList;
+ rectList.push_back(rect);
+ uint32_t num = numOverlays(rectList);
+
+ if (verbose) {
+ testPrintI(" scHscale num: %u scale: %f dfDim: %s scDim: %s",
+ num, (float) Rational(scDim.height(), dfDim.height()),
+ ((string) dfDim).c_str(), ((string) scDim).c_str());
+ }
+ if (num == 1) {
+ // HWC committed to the combination
+ // This is the best scale factor seen so far. Report the
+ // dimensions to the caller, in case nothing better is seen.
+ outBestDf = dfDim;
+ outBestSc = scDim;
+
+ // Success on the first pass means the largest possible scale
+ // is supported, in which case no need to search any further.
+ if (firstPass) { return Rational(scDim.height(), dfDim.height()); }
+
+ // Update the lower bound of the binary search
+ best = Rational(scDim.height(), dfDim.height());
+ } else {
+ // HWC didn't commit to this combination, so update the
+ // upper bound of the binary search.
+ minBad = Rational(scDim.height(), dfDim.height());
+ }
+
+ firstPass = false;
+ } while (best != minBad);
+
+ return best;
+}
+
+uint32_t numOverlapping(uint32_t backgroundFormat, uint32_t foregroundFormat,
+ uint32_t backgroundBlend, uint32_t foregroundBlend)
+{
+ list<Rectangle> rectList;
+
+ Rectangle background(backgroundFormat, startDim, startDim);
+ background.blend = backgroundBlend;
+ rectList.push_back(background);
+
+ // TODO: Handle cases where startDim is so small that adding 5
+ // causes frames not to overlap.
+ // TODO: Handle cases where startDim is so large that adding 5
+ // cause a portion or all of the foreground displayFrame
+ // to be off the display.
+ Rectangle foreground(foregroundFormat, startDim, startDim);
+ foreground.displayFrame.left += 5;
+ foreground.displayFrame.top += 5;
+ foreground.displayFrame.right += 5;
+ foreground.displayFrame.bottom += 5;
+ background.blend = foregroundBlend;
+ rectList.push_back(foreground);
+
+ uint32_t num = numOverlays(rectList);
+
+ return num;
+}
+
+Rectangle::Rectangle(uint32_t graphicFormat, HwcTestDim dfDim,
+ HwcTestDim sDim) :
+ format(graphicFormat), transform(defaultTransform),
+ blend(defaultBlend), color(defaultColor), alpha(defaultAlpha),
+ sourceCrop(sDim), displayFrame(dfDim)
+{
+ // Set source dimension
+ // Can't use a base initializer, because the setting of format
+ // must be done before setting the sourceDimension.
+ setSourceDim(sDim);
+}
+
+void Rectangle::setSourceDim(HwcTestDim dim)
+{
+ this->sourceDim = dim;
+
+ const struct hwcTestGraphicFormat *attrib;
+ attrib = hwcTestGraphicFormatLookup(this->format);
+ if (attrib != NULL) {
+ if (sourceDim.width() % attrib->wMod) {
+ sourceDim.setWidth(sourceDim.width() + attrib->wMod
+ - (sourceDim.width() % attrib->wMod));
+ }
+ if (sourceDim.height() % attrib->hMod) {
+ sourceDim.setHeight(sourceDim.height() + attrib->hMod
+ - (sourceDim.height() % attrib->hMod));
+ }
+ }
+}
+
+// Rational member functions
+bool Rational::operator==(const Rational& other) const
+{
+ if (((uint64_t) _n * other._d)
+ == ((uint64_t) _d * other._n)) { return true; }
+
+ return false;
+}
+
+bool Rational::operator<(const Rational& other) const
+{
+ if (((uint64_t) _n * other._d)
+ < ((uint64_t) _d * other._n)) { return true; }
+
+ return false;
+}
+
+Rational::operator string() const
+{
+ ostringstream out;
+
+ out << _n << '/' << _d;
+
+ return out.str();
+}
+
+void Rational::double2Rational(double f, Range nRange, Range dRange,
+ Rational& lower, Rational& upper)
+{
+ Rational bestLower(nRange.lower(), dRange.upper());
+ Rational bestUpper(nRange.upper(), dRange.lower());
+
+ // Search for a better solution
+ for (uint32_t d = dRange.lower(); d <= dRange.upper(); d++) {
+ Rational val(d * f, d); // Lower, because double to int cast truncates
+
+ if ((val.numerator() < nRange.lower())
+ || (val.numerator() > nRange.upper())) { continue; }
+
+ if (((double) val > (double) bestLower) && ((double) val <= f)) {
+ bestLower = val;
+ }
+
+ val.setNumerator(val.numerator() + 1);
+ if (val.numerator() > nRange.upper()) { continue; }
+
+ if (((double) val < (double) bestUpper) && ((double) val >= f)) {
+ bestUpper = val;
+ }
+ }
+
+ lower = bestLower;
+ upper = bestUpper;
+}
+
+// Local functions
+
+// Num Overlays
+// Given a list of rectangles, determine how many HWC will commit to render
+uint32_t numOverlays(list<Rectangle>& rectList)
+{
+ hwc_layer_list_t *hwcList;
+ list<sp<GraphicBuffer> > buffers;
+
+ hwcList = hwcTestCreateLayerList(rectList.size());
+ if (hwcList == NULL) {
+ testPrintE("numOverlays create hwcList failed");
+ exit(30);
+ }
+
+ hwc_layer_t *layer = &hwcList->hwLayers[0];
+ for (std::list<Rectangle>::iterator it = rectList.begin();
+ it != rectList.end(); ++it, ++layer) {
+ // Allocate the texture for the source frame
+ // and push it onto the buffers list, so that it
+ // stays in scope until a return from this function.
+ sp<GraphicBuffer> texture;
+ texture = new GraphicBuffer(it->sourceDim.width(),
+ it->sourceDim.height(),
+ it->format, texUsage);
+ buffers.push_back(texture);
+
+ layer->handle = texture->handle;
+ layer->blending = it->blend;
+ layer->transform = it->transform;
+ layer->sourceCrop = it->sourceCrop;
+ layer->displayFrame = it->displayFrame;
+
+ layer->visibleRegionScreen.numRects = 1;
+ layer->visibleRegionScreen.rects = &layer->displayFrame;
+ }
+
+ // Perform prepare operation
+ if (verbose) { testPrintI("Prepare:"); hwcTestDisplayList(hwcList); }
+ hwcDevice->prepare(hwcDevice, hwcList);
+ if (verbose) {
+ testPrintI("Post Prepare:");
+ hwcTestDisplayListPrepareModifiable(hwcList);
+ }
+
+ // Count the number of overlays
+ uint32_t total = 0;
+ for (unsigned int n1 = 0; n1 < hwcList->numHwLayers; n1++) {
+ if (hwcList->hwLayers[n1].compositionType == HWC_OVERLAY) {
+ total++;
+ }
+ }
+
+ // Free the layer list and graphic buffers
+ hwcTestFreeLayerList(hwcList);
+
+ return total;
+}
+
+string transformList2str(const list<uint32_t>& transformList)
+{
+ ostringstream out;
+
+ for (list<uint32_t>::const_iterator it = transformList.begin();
+ it != transformList.end(); ++it) {
+ uint32_t id = *it;
+
+ if (it != transformList.begin()) {
+ out << ", ";
+ }
+ out << id;
+
+ for (unsigned int idx = 0; idx < NUMA(transformType); idx++) {
+ if (id == transformType[idx].id) {
+ out << " (" << transformType[idx].desc << ')';
+ break;
+ }
+ }
+ }
+
+ return out.str();
+}
+
+string blendList2str(const list<uint32_t>& blendList)
+{
+ ostringstream out;
+
+ for (list<uint32_t>::const_iterator it = blendList.begin();
+ it != blendList.end(); ++it) {
+ uint32_t id = *it;
+
+ if (it != blendList.begin()) {
+ out << ", ";
+ }
+ out << id;
+
+ for (unsigned int idx = 0; idx < NUMA(blendType); idx++) {
+ if (id == blendType[idx].id) {
+ out << " (" << blendType[idx].desc << ')';
+ break;
+ }
+ }
+ }
+
+ return out.str();
+}
+
+void init(void)
+{
+ srand48(0);
+
+ hwcTestInitDisplay(verbose, &dpy, &surface, &width, &height);
+
+ hwcTestOpenHwc(&hwcDevice);
+}
+
+void printFormatHeadings(size_t indent)
+{
+ for (size_t row = 0; row <= maxHeadingLen; row++) {
+ ostringstream line;
+ for(vector<string>::iterator it = formats.begin();
+ it != formats.end(); ++it) {
+ if ((maxHeadingLen - row) <= it->length()) {
+ if (row != maxHeadingLen) {
+ char ch = (*it)[it->length() - (maxHeadingLen - row)];
+ line << ' ' << setw(printFieldWidth) << ch;
+ } else {
+ line << ' ' << string(printFieldWidth, '-');
+ }
+ } else {
+ line << ' ' << setw(printFieldWidth) << "";
+ }
+ }
+ testPrintI("%*s%s", indent + maxHeadingLen, "",
+ line.str().c_str());
+ }
+}
+
+void printOverlapLine(size_t indent, const string formatStr,
+ const vector<uint32_t>& results)
+{
+ ostringstream line;
+
+ line << setw(indent + maxHeadingLen - formatStr.length()) << "";
+
+ line << formatStr;
+
+ for (vector<uint32_t>::const_iterator it = results.begin();
+ it != results.end(); ++it) {
+ line << ' ' << setw(printFieldWidth) << *it;
+ }
+
+ testPrintI("%s", line.str().c_str());
+}
+
+void printSyntax(const char *cmd)
+{
+ testPrintE(" %s [options] [graphicFormat] ...",
+ cmd);
+ testPrintE(" options:");
+ testPrintE(" -s [width, height] - start dimension");
+ testPrintE(" -v - Verbose");
+ testPrintE("");
+ testPrintE(" graphic formats:");
+ for (unsigned int n1 = 0; n1 < NUMA(hwcTestGraphicFormat); n1++) {
+ testPrintE(" %s", hwcTestGraphicFormat[n1].desc);
+ }
+}
diff --git a/opengl/tests/hwc/hwcRects.cpp b/opengl/tests/hwc/hwcRects.cpp
new file mode 100644
index 0000000..523e3de
--- /dev/null
+++ b/opengl/tests/hwc/hwcRects.cpp
@@ -0,0 +1,577 @@
+/*
+ * Copyright (C) 2011 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.
+ */
+
+/*
+ * Hardware Composer Rectangles
+ *
+ * Synopsis
+ * hwcRects [options] (graphicFormat displayFrame [attributes],)...
+ * options:
+ * -D #.## - End of test delay
+ * -v - Verbose
+ *
+ * graphic formats:
+ * RGBA8888 (reference frame default)
+ * RGBX8888
+ * RGB888
+ * RGB565
+ * BGRA8888
+ * RGBA5551
+ * RGBA4444
+ * YV12
+ *
+ * displayFrame
+ * [left, top, right, bottom]
+ *
+ * attributes:
+ * transform: none | fliph | flipv | rot90 | rot180 | rot270
+ * blend: none | premult | coverage
+ * color: [0.##, 0.##, 0.##]
+ * alpha: 0.##
+ * sourceDim: [width, height]
+ * sourceCrop: [left, top, right, bottom]
+ *
+ * Example:
+ * # White YV12 rectangle, with overlapping turquoise
+ * # RGBA8888 rectangle at 30%% (alpha: 0.7) transparency
+ * hwcRects -v -D 30.0 \
+ * YV12 [50, 80, 200, 300] transform: none \
+ * color: [1.0, 0.5, 0.5], \
+ * RGBA8888 [100, 150, 300, 400] blend: coverage \
+ * color: [0.251, 0.878, 0.816] alpha: 0.7 \
+ * sourceDim: [50, 60] sourceCrop: [5, 8, 12, 15]
+ *
+ * Description
+ * Constructs a Hardware Composer (HWC) list of frames from
+ * command-line specified parameters. Then sends it to the HWC
+ * be rendered. The intended purpose of this tool is as a means to
+ * reproduce and succinctly specify an observed HWC operation, with
+ * no need to modify/compile a program.
+ *
+ * The command-line syntax consists of a few standard command-line
+ * options and then a description of one or more frames. The frame
+ * descriptions are separated from one another via a comma. The
+ * beginning of a frame description requires the specification
+ * of the graphic format and then the display frame rectangle where
+ * the frame will be displayed. The display frame rectangle is
+ * specified as follows, with the right and bottom coordinates being
+ * exclusive values:
+ *
+ * [left, top, right, bottom]
+ *
+ * After these two required parameters each frame description can
+ * specify 1 or more optional attributes. The name of each optional
+ * attribute is preceded by a colon. The current implementation
+ * then requires white space after the colon and then the value of
+ * the attribute is specified. See the synopsis section above for
+ * a list of attributes and the format of their expected value.
+ */
+
+#include <algorithm>
+#include <assert.h>
+#include <cerrno>
+#include <cmath>
+#include <cstdlib>
+#include <ctime>
+#include <istream>
+#include <libgen.h>
+#include <list>
+#include <sched.h>
+#include <sstream>
+#include <stdint.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+#include <ui/FramebufferNativeWindow.h>
+#include <ui/GraphicBuffer.h>
+#include <ui/EGLUtils.h>
+
+#define LOG_TAG "hwcRectsTest"
+#include <utils/Log.h>
+#include <testUtil.h>
+
+#include <hardware/hwcomposer.h>
+
+#include <glTestLib.h>
+#include <hwc/hwcTestLib.h>
+
+using namespace std;
+using namespace android;
+
+// Defaults
+const bool defaultVerbose = false;
+const float defaultEndDelay = 2.0; // Default delay after rendering graphics
+
+const uint32_t defaultFormat = HAL_PIXEL_FORMAT_RGBA_8888;
+const int32_t defaultTransform = 0;
+const uint32_t defaultBlend = HWC_BLENDING_NONE;
+const ColorFract defaultColor(0.5, 0.5, 0.5);
+const float defaultAlpha = 1.0; // Opaque
+const HwcTestDim defaultSourceDim(1, 1);
+const struct hwc_rect defaultSourceCrop = {0, 0, 1, 1};
+const struct hwc_rect defaultDisplayFrame = {0, 0, 100, 100};
+
+// Defines
+#define MAXCMD 200
+#define CMD_STOP_FRAMEWORK "stop 2>&1"
+#define CMD_START_FRAMEWORK "start 2>&1"
+
+// Macros
+#define NUMA(a) (sizeof(a) / sizeof(a [0])) // Num elements in an array
+
+// Local types
+class Rectangle {
+public:
+ Rectangle() : format(defaultFormat), transform(defaultTransform),
+ blend(defaultBlend), color(defaultColor),
+ alpha(defaultAlpha), sourceDim(defaultSourceDim),
+ sourceCrop(defaultSourceCrop),
+ displayFrame(defaultDisplayFrame) {};
+
+ uint32_t format;
+ uint32_t transform;
+ int32_t blend;
+ ColorFract color;
+ float alpha;
+ HwcTestDim sourceDim;
+ struct hwc_rect sourceCrop;
+ struct hwc_rect displayFrame;
+
+ sp<GraphicBuffer> texture;
+};
+
+// Globals
+list<Rectangle> rectangle;
+static const int texUsage = GraphicBuffer::USAGE_HW_TEXTURE |
+ GraphicBuffer::USAGE_SW_WRITE_RARELY;
+static hwc_composer_device_t *hwcDevice;
+static EGLDisplay dpy;
+static EGLSurface surface;
+static EGLint width, height;
+
+// Function prototypes
+static Rectangle parseRect(string rectStr);
+void init(void);
+void printSyntax(const char *cmd);
+
+// Command-line option settings
+static bool verbose = defaultVerbose;
+static float endDelay = defaultEndDelay;
+
+/*
+ * Main
+ *
+ * Performs the following high-level sequence of operations:
+ *
+ * 1. Parse command-line options
+ *
+ * 2. Stop framework
+ *
+ * 3. Initialization
+ *
+ * 4. Parse frame descriptions
+ *
+ * 5. Create HWC list from frame descriptions
+ *
+ * 6. Have HWC render the list description of the frames
+ *
+ * 7. Delay for amount of time given by endDelay
+ *
+ * 8. Start framework
+ */
+int
+main(int argc, char *argv[])
+{
+ int rv, opt;
+ char *chptr;
+ bool error;
+ string str;
+ char cmd[MAXCMD];
+
+ testSetLogCatTag(LOG_TAG);
+
+ // Parse command line arguments
+ while ((opt = getopt(argc, argv, "D:v?h")) != -1) {
+ switch (opt) {
+ case 'D': // End of test delay
+ endDelay = strtod(optarg, &chptr);
+ if ((*chptr != '\0') || (endDelay < 0.0)) {
+ testPrintE("Invalid command-line specified end of test delay "
+ "of: %s", optarg);
+ exit(1);
+ }
+ break;
+
+ case 'v': // Verbose
+ verbose = true;
+ break;
+
+ case 'h': // Help
+ case '?':
+ default:
+ printSyntax(basename(argv[0]));
+ exit(((optopt == 0) || (optopt == '?')) ? 0 : 2);
+ }
+ }
+
+ // Stop framework
+ rv = snprintf(cmd, sizeof(cmd), "%s", CMD_STOP_FRAMEWORK);
+ if (rv >= (signed) sizeof(cmd) - 1) {
+ testPrintE("Command too long for: %s", CMD_STOP_FRAMEWORK);
+ exit(3);
+ }
+ testExecCmd(cmd);
+ testDelay(1.0); // TODO - needs means to query whether asyncronous stop
+ // framework operation has completed. For now, just wait
+ // a long time.
+
+ init();
+
+ // Parse rectangle descriptions
+ int numOpen = 0; // Current number of unmatched <[
+ string rectDesc(""); // String description of a single rectangle
+ while (optind < argc) {
+ string argNext = string(argv[optind++]);
+
+ if (rectDesc.length()) { rectDesc += ' '; }
+ rectDesc += argNext;
+
+ // Count number of opening <[ and matching >]
+ // At this point not worried about an opening character being
+ // matched by it's corresponding closing character. For example,
+ // "<1.0, 2.0]" is incorrect because the opening < should be matched
+ // with a closing >, instead of the closing ]. Such errors are
+ // detected when the actual value is parsed.
+ for (unsigned int n1 = 0; n1 < argNext.length(); n1++) {
+ switch(argNext[n1]) {
+ case '[':
+ case '<':
+ numOpen++;
+ break;
+
+ case ']':
+ case '>':
+ numOpen--;
+ break;
+ }
+
+ // Error anytime there is more closing then opening characters
+ if (numOpen < 0) {
+ testPrintI("Mismatched number of opening <[ with "
+ "closing >] in: %s", rectDesc.c_str());
+ exit(4);
+ }
+ }
+
+ // Description of a rectangle is complete when all opening
+ // <[ are closed with >] and the string ends with a comma or
+ // there are no more args.
+ if ((numOpen == 0) && rectDesc.length()
+ && ((rectDesc[rectDesc.length() - 1] == ',')
+ || (optind == argc))) {
+ // Remove trailing comma if it is present
+ if (rectDesc[rectDesc.length() - 1] == ',') {
+ rectDesc.erase(rectDesc.length() - 1);
+ }
+
+ // Parse string description of rectangle
+ Rectangle rect = parseRect(rectDesc);
+
+ // Add to the list of rectangles
+ rectangle.push_back(rect);
+
+ // Prepare for description of another rectangle
+ rectDesc = string("");
+ }
+ }
+
+ // Create list of frames
+ hwc_layer_list_t *list;
+ list = hwcTestCreateLayerList(rectangle.size());
+ if (list == NULL) {
+ testPrintE("hwcTestCreateLayerList failed");
+ exit(5);
+ }
+
+ hwc_layer_t *layer = &list->hwLayers[0];
+ for (std::list<Rectangle>::iterator it = rectangle.begin();
+ it != rectangle.end(); ++it, ++layer) {
+ layer->handle = it->texture->handle;
+ layer->blending = it->blend;
+ layer->transform = it->transform;
+ layer->sourceCrop = it->sourceCrop;
+ layer->displayFrame = it->displayFrame;
+
+ layer->visibleRegionScreen.numRects = 1;
+ layer->visibleRegionScreen.rects = &layer->displayFrame;
+ }
+
+ // Perform prepare operation
+ if (verbose) { testPrintI("Prepare:"); hwcTestDisplayList(list); }
+ hwcDevice->prepare(hwcDevice, list);
+ if (verbose) {
+ testPrintI("Post Prepare:");
+ hwcTestDisplayListPrepareModifiable(list);
+ }
+
+ // Turn off the geometry changed flag
+ list->flags &= ~HWC_GEOMETRY_CHANGED;
+
+ // Perform the set operation(s)
+ if (verbose) {testPrintI("Set:"); }
+ if (verbose) { hwcTestDisplayListHandles(list); }
+ hwcDevice->set(hwcDevice, dpy, surface, list);
+
+ testDelay(endDelay);
+
+ // Start framework
+ rv = snprintf(cmd, sizeof(cmd), "%s", CMD_START_FRAMEWORK);
+ if (rv >= (signed) sizeof(cmd) - 1) {
+ testPrintE("Command too long for: %s", CMD_START_FRAMEWORK);
+ exit(6);
+ }
+ testExecCmd(cmd);
+
+ return 0;
+}
+
+// Parse string description of rectangle and add it to list of rectangles
+// to be rendered.
+static Rectangle parseRect(string rectStr)
+{
+ int rv;
+ string str;
+ bool error;
+ istringstream in(rectStr);
+ const struct hwcTestGraphicFormat *format;
+ Rectangle rect;
+ struct hwc_rect hwcRect;
+
+ // Graphic Format
+ in >> str;
+ if (!in) {
+ testPrintE("Error parsing format from: %s", rectStr.c_str());
+ exit(20);
+ }
+ format = hwcTestGraphicFormatLookup(str.c_str());
+ if (format == NULL) {
+ testPrintE("Unknown graphic format in: %s", rectStr.c_str());
+ exit(21);
+ }
+ rect.format = format->format;
+
+ // Display Frame
+ rect.displayFrame = hwcTestParseHwcRect(in, error);
+ if (error) {
+ testPrintE("Invalid display frame in: %s", rectStr.c_str());
+ exit(22);
+ }
+
+ // Set default sourceDim and sourceCrop based on size of display frame.
+ // Default is source size equal to the size of the display frame, with
+ // the source crop being the entire size of the source frame.
+ rect.sourceDim = HwcTestDim(rect.displayFrame.right
+ - rect.displayFrame.left,
+ rect.displayFrame.bottom
+ - rect.displayFrame.top);
+ rect.sourceCrop.left = 0;
+ rect.sourceCrop.top = 0;
+ rect.sourceCrop.right = rect.sourceDim.width();
+ rect.sourceCrop.bottom = rect.sourceDim.height();
+
+ // Optional settings
+ while ((in.tellg() < (streampos) in.str().length())
+ && (in.tellg() != (streampos) -1)) {
+ string attrName;
+
+ in >> attrName;
+ if (in.eof()) { break; }
+ if (!in) {
+ testPrintE("Error reading attribute name in: %s",
+ rectStr.c_str());
+ exit(23);
+ }
+
+ // Transform
+ if (attrName == "transform:") { // Transform
+ string str;
+
+ in >> str;
+ if (str == "none") {
+ rect.transform = 0;
+ } else if (str == "fliph") {
+ rect.transform = HWC_TRANSFORM_FLIP_H;
+ } else if (str == "flipv") {
+ rect.transform = HWC_TRANSFORM_FLIP_V;
+ } else if (str == "rot90") {
+ rect.transform = HWC_TRANSFORM_ROT_90;
+ } else if (str == "rot180") {
+ rect.transform = HWC_TRANSFORM_ROT_180;
+ } else if (str == "rot270") {
+ rect.transform = HWC_TRANSFORM_ROT_270;
+ } else {
+ testPrintE("Unknown transform of \"%s\" in: %s", str.c_str(),
+ rectStr.c_str());
+ exit(24);
+ }
+ } else if (attrName == "blend:") { // Blend
+ string str;
+
+ in >> str;
+ if (str == string("none")) {
+ rect.blend = HWC_BLENDING_NONE;
+ } else if (str == "premult") {
+ rect.blend = HWC_BLENDING_PREMULT;
+ } else if (str == "coverage") {
+ rect.blend = HWC_BLENDING_COVERAGE;
+ } else {
+ testPrintE("Unknown blend of \"%s\" in: %s", str.c_str(),
+ rectStr.c_str());
+ exit(25);
+ }
+ } else if (attrName == "color:") { // Color
+ rect.color = hwcTestParseColor(in, error);
+ if (error) {
+ testPrintE("Error parsing color in: %s", rectStr.c_str());
+ exit(26);
+ }
+ } else if (attrName == "alpha:") { // Alpha
+ in >> rect.alpha;
+ if (!in) {
+ testPrintE("Error parsing value for alpha attribute in: %s",
+ rectStr.c_str());
+ exit(27);
+ }
+ } else if (attrName == "sourceDim:") { // Source Dimension
+ rect.sourceDim = hwcTestParseDim(in, error);
+ if (error) {
+ testPrintE("Error parsing source dimenision in: %s",
+ rectStr.c_str());
+ exit(28);
+ }
+ } else if (attrName == "sourceCrop:") { // Source Crop
+ rect.sourceCrop = hwcTestParseHwcRect(in, error);
+ if (error) {
+ testPrintE("Error parsing source crop in: %s",
+ rectStr.c_str());
+ exit(29);
+ }
+ } else { // Unknown attribute
+ testPrintE("Unknown attribute of \"%s\" in: %s", attrName.c_str(),
+ rectStr.c_str());
+ exit(30);
+ }
+ }
+
+ // Validate
+ if (((uint32_t) rect.sourceCrop.left >= rect.sourceDim.width())
+ || ((uint32_t) rect.sourceCrop.right > rect.sourceDim.width())
+ || ((uint32_t) rect.sourceCrop.top >= rect.sourceDim.height())
+ || ((uint32_t) rect.sourceCrop.bottom > rect.sourceDim.height())) {
+ testPrintE("Invalid source crop in: %s", rectStr.c_str());
+ exit(31);
+ }
+ if ((rect.displayFrame.left >= width)
+ || (rect.displayFrame.right > width)
+ || (rect.displayFrame.top >= height)
+ || (rect.displayFrame.bottom > height)) {
+ testPrintE("Invalid display frame in: %s", rectStr.c_str());
+ exit(32);
+ }
+ if ((rect.alpha < 0.0) || (rect.alpha > 1.0)) {
+ testPrintE("Invalid alpha in: %s", rectStr.c_str());
+ exit(33);
+ }
+
+ // Create source texture
+ rect.texture = new GraphicBuffer(rect.sourceDim.width(),
+ rect.sourceDim.height(),
+ rect.format, texUsage);
+ if ((rv = rect.texture->initCheck()) != NO_ERROR) {
+ testPrintE("source texture initCheck failed, rv: %i", rv);
+ testPrintE(" %s", rectStr.c_str());
+
+ }
+
+ // Fill with uniform color
+ hwcTestFillColor(rect.texture.get(), rect.color, rect.alpha);
+ if (verbose) {
+ testPrintI(" buf: %p handle: %p format: %s width: %u height: %u "
+ "color: %s alpha: %f",
+ rect.texture.get(), rect.texture->handle, format->desc,
+ rect.sourceDim.width(), rect.sourceDim.height(),
+ string(rect.color).c_str(), rect.alpha);
+ }
+
+ return rect;
+}
+
+void init(void)
+{
+ // Seed pseudo random number generator
+ // Needed so that the pad areas of frames are filled with a deterministic
+ // pseudo random value.
+ srand48(0);
+
+ hwcTestInitDisplay(verbose, &dpy, &surface, &width, &height);
+
+ hwcTestOpenHwc(&hwcDevice);
+}
+
+void printSyntax(const char *cmd)
+{
+ testPrintE(" %s [options] (graphicFormat displayFrame [attributes],)...",
+ cmd);
+ testPrintE(" options:");
+ testPrintE(" -D End of test delay");
+ testPrintE(" -v Verbose");
+ testPrintE("");
+ testPrintE(" graphic formats:");
+ for (unsigned int n1 = 0; n1 < NUMA(hwcTestGraphicFormat); n1++) {
+ testPrintE(" %s", hwcTestGraphicFormat[n1].desc);
+ }
+ testPrintE("");
+ testPrintE(" displayFrame");
+ testPrintE(" [left, top, right, bottom]");
+ testPrintE("");
+ testPrintE(" attributes:");
+ testPrintE(" transform: none | fliph | flipv | rot90 | rot180 "
+ " | rot270");
+ testPrintE(" blend: none | premult | coverage");
+ testPrintE(" color: [0.##, 0.##, 0.##]");
+ testPrintE(" alpha: 0.##");
+ testPrintE(" sourceDim: [width, height]");
+ testPrintE(" sourceCrop: [left, top, right, bottom]");
+ testPrintE("");
+ testPrintE(" Example:");
+ testPrintE(" # White YV12 rectangle, with overlapping turquoise ");
+ testPrintE(" # RGBA8888 rectangle at 30%% (alpha: 0.7) transparency");
+ testPrintE(" %s -v -D 30.0 \\", cmd);
+ testPrintE(" YV12 [50, 80, 200, 300] transform: none \\");
+ testPrintE(" color: [1.0, 0.5, 0.5], \\");
+ testPrintE(" RGBA8888 [100, 150, 300, 400] blend: coverage \\");
+ testPrintE(" color: [0.251, 0.878, 0.816] alpha: 0.7 \\");
+ testPrintE(" sourceDim: [50, 60] sourceCrop: [5, 8, 12, 15]");
+}
diff --git a/opengl/tests/hwc/hwcStress.cpp b/opengl/tests/hwc/hwcStress.cpp
new file mode 100644
index 0000000..1cefb4b
--- /dev/null
+++ b/opengl/tests/hwc/hwcStress.cpp
@@ -0,0 +1,645 @@
+/*
+ * Copyright (C) 2010 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.
+ *
+ */
+
+/*
+ * Hardware Composer stress test
+ *
+ * Performs a pseudo-random (prandom) sequence of operations to the
+ * Hardware Composer (HWC), for a specified number of passes or for
+ * a specified period of time. By default the period of time is FLT_MAX,
+ * so that the number of passes will take precedence.
+ *
+ * The passes are grouped together, where (pass / passesPerGroup) specifies
+ * which group a particular pass is in. This causes every passesPerGroup
+ * worth of sequential passes to be within the same group. Computationally
+ * intensive operations are performed just once at the beginning of a group
+ * of passes and then used by all the passes in that group. This is done
+ * so as to increase both the average and peak rate of graphic operations,
+ * by moving computationally intensive operations to the beginning of a group.
+ * In particular, at the start of each group of passes a set of
+ * graphic buffers are created, then used by the first and remaining
+ * passes of that group of passes.
+ *
+ * The per-group initialization of the graphic buffers is performed
+ * by a function called initFrames. This function creates an array
+ * of smart pointers to the graphic buffers, in the form of a vector
+ * of vectors. The array is accessed in row major order, so each
+ * row is a vector of smart pointers. All the pointers of a single
+ * row point to graphic buffers which use the same pixel format and
+ * have the same dimension, although it is likely that each one is
+ * filled with a different color. This is done so that after doing
+ * the first HWC prepare then set call, subsequent set calls can
+ * be made with each of the layer handles changed to a different
+ * graphic buffer within the same row. Since the graphic buffers
+ * in a particular row have the same pixel format and dimension,
+ * additional HWC set calls can be made, without having to perform
+ * an HWC prepare call.
+ *
+ * This test supports the following command-line options:
+ *
+ * -v Verbose
+ * -s num Starting pass
+ * -e num Ending pass
+ * -p num Execute the single pass specified by num
+ * -n num Number of set operations to perform after each prepare operation
+ * -t float Maximum time in seconds to execute the test
+ * -d float Delay in seconds performed after each set operation
+ * -D float Delay in seconds performed after the last pass is executed
+ *
+ * Typically the test is executed for a large range of passes. By default
+ * passes 0 through 99999 (100,000 passes) are executed. Although this test
+ * does not validate the generated image, at times it is useful to reexecute
+ * a particular pass and leave the displayed image on the screen for an
+ * extended period of time. This can be done either by setting the -s
+ * and -e options to the desired pass, along with a large value for -D.
+ * This can also be done via the -p option, again with a large value for
+ * the -D options.
+ *
+ * So far this test only contains code to create graphic buffers with
+ * a continuous solid color. Although this test is unable to validate the
+ * image produced, any image that contains other than rectangles of a solid
+ * color are incorrect. Note that the rectangles may use a transparent
+ * color and have a blending operation that causes the color in overlapping
+ * rectangles to be mixed. In such cases the overlapping portions may have
+ * a different color from the rest of the rectangle.
+ */
+
+#include <algorithm>
+#include <assert.h>
+#include <cerrno>
+#include <cmath>
+#include <cstdlib>
+#include <ctime>
+#include <libgen.h>
+#include <sched.h>
+#include <sstream>
+#include <stdint.h>
+#include <string.h>
+#include <unistd.h>
+#include <vector>
+
+#include <sys/syscall.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+#include <ui/FramebufferNativeWindow.h>
+#include <ui/GraphicBuffer.h>
+#include <ui/EGLUtils.h>
+
+#define LOG_TAG "hwcStressTest"
+#include <utils/Log.h>
+#include <testUtil.h>
+
+#include <hardware/hwcomposer.h>
+
+#include <glTestLib.h>
+#include <hwc/hwcTestLib.h>
+
+using namespace std;
+using namespace android;
+
+const float maxSizeRatio = 1.3; // Graphic buffers can be upto this munch
+ // larger than the default screen size
+const unsigned int passesPerGroup = 10; // A group of passes all use the same
+ // graphic buffers
+
+// Ratios at which rare and frequent conditions should be produced
+const float rareRatio = 0.1;
+const float freqRatio = 0.9;
+
+// Defaults for command-line options
+const bool defaultVerbose = false;
+const unsigned int defaultStartPass = 0;
+const unsigned int defaultEndPass = 99999;
+const unsigned int defaultPerPassNumSet = 10;
+const float defaultPerSetDelay = 0.0; // Default delay after each set
+ // operation. Default delay of
+ // zero used so as to perform the
+ // the set operations as quickly
+ // as possible.
+const float defaultEndDelay = 2.0; // Default delay between completion of
+ // final pass and restart of framework
+const float defaultDuration = FLT_MAX; // A fairly long time, so that
+ // range of passes will have
+ // precedence
+
+// Command-line option settings
+static bool verbose = defaultVerbose;
+static unsigned int startPass = defaultStartPass;
+static unsigned int endPass = defaultEndPass;
+static unsigned int numSet = defaultPerPassNumSet;
+static float perSetDelay = defaultPerSetDelay;
+static float endDelay = defaultEndDelay;
+static float duration = defaultDuration;
+
+// Command-line mutual exclusion detection flags.
+// Corresponding flag set true once an option is used.
+bool eFlag, sFlag, pFlag;
+
+#define MAXSTR 100
+#define MAXCMD 200
+#define BITSPERBYTE 8 // TODO: Obtain from <values.h>, once
+ // it has been added
+
+#define CMD_STOP_FRAMEWORK "stop 2>&1"
+#define CMD_START_FRAMEWORK "start 2>&1"
+
+#define NUMA(a) (sizeof(a) / sizeof(a [0]))
+#define MEMCLR(addr, size) do { \
+ memset((addr), 0, (size)); \
+ } while (0)
+
+// File scope constants
+const unsigned int blendingOps[] = {
+ HWC_BLENDING_NONE,
+ HWC_BLENDING_PREMULT,
+ HWC_BLENDING_COVERAGE,
+};
+const unsigned int layerFlags[] = {
+ HWC_SKIP_LAYER,
+};
+const vector<unsigned int> vecLayerFlags(layerFlags,
+ layerFlags + NUMA(layerFlags));
+
+const unsigned int transformFlags[] = {
+ HWC_TRANSFORM_FLIP_H,
+ HWC_TRANSFORM_FLIP_V,
+ HWC_TRANSFORM_ROT_90,
+ // ROT_180 & ROT_270 intentionally not listed, because they
+ // they are formed from combinations of the flags already listed.
+};
+const vector<unsigned int> vecTransformFlags(transformFlags,
+ transformFlags + NUMA(transformFlags));
+
+// File scope globals
+static const int texUsage = GraphicBuffer::USAGE_HW_TEXTURE |
+ GraphicBuffer::USAGE_SW_WRITE_RARELY;
+static hwc_composer_device_t *hwcDevice;
+static EGLDisplay dpy;
+static EGLSurface surface;
+static EGLint width, height;
+static vector <vector <sp<GraphicBuffer> > > frames;
+
+// File scope prototypes
+void init(void);
+void initFrames(unsigned int seed);
+template <class T> vector<T> vectorRandSelect(const vector<T>& vec, size_t num);
+template <class T> T vectorOr(const vector<T>& vec);
+
+/*
+ * Main
+ *
+ * Performs the following high-level sequence of operations:
+ *
+ * 1. Command-line parsing
+ *
+ * 2. Initialization
+ *
+ * 3. For each pass:
+ *
+ * a. If pass is first pass or in a different group from the
+ * previous pass, initialize the array of graphic buffers.
+ *
+ * b. Create a HWC list with room to specify a prandomly
+ * selected number of layers.
+ *
+ * c. Select a subset of the rows from the graphic buffer array,
+ * such that there is a unique row to be used for each
+ * of the layers in the HWC list.
+ *
+ * d. Prandomly fill in the HWC list with handles
+ * selected from any of the columns of the selected row.
+ *
+ * e. Pass the populated list to the HWC prepare call.
+ *
+ * f. Pass the populated list to the HWC set call.
+ *
+ * g. If additional set calls are to be made, then for each
+ * additional set call, select a new set of handles and
+ * perform the set call.
+ */
+int
+main(int argc, char *argv[])
+{
+ int rv, opt;
+ char *chptr;
+ unsigned int pass;
+ char cmd[MAXCMD];
+ struct timeval startTime, currentTime, delta;
+
+ testSetLogCatTag(LOG_TAG);
+
+ // Parse command line arguments
+ while ((opt = getopt(argc, argv, "vp:d:D:n:s:e:t:?h")) != -1) {
+ switch (opt) {
+ case 'd': // Delay after each set operation
+ perSetDelay = strtod(optarg, &chptr);
+ if ((*chptr != '\0') || (perSetDelay < 0.0)) {
+ testPrintE("Invalid command-line specified per pass delay of: "
+ "%s", optarg);
+ exit(1);
+ }
+ break;
+
+ case 'D': // End of test delay
+ // Delay between completion of final pass and restart
+ // of framework
+ endDelay = strtod(optarg, &chptr);
+ if ((*chptr != '\0') || (endDelay < 0.0)) {
+ testPrintE("Invalid command-line specified end of test delay "
+ "of: %s", optarg);
+ exit(2);
+ }
+ break;
+
+ case 't': // Duration
+ duration = strtod(optarg, &chptr);
+ if ((*chptr != '\0') || (duration < 0.0)) {
+ testPrintE("Invalid command-line specified duration of: %s",
+ optarg);
+ exit(3);
+ }
+ break;
+
+ case 'n': // Num set operations per pass
+ numSet = strtoul(optarg, &chptr, 10);
+ if (*chptr != '\0') {
+ testPrintE("Invalid command-line specified num set per pass "
+ "of: %s", optarg);
+ exit(4);
+ }
+ break;
+
+ case 's': // Starting Pass
+ sFlag = true;
+ if (pFlag) {
+ testPrintE("Invalid combination of command-line options.");
+ testPrintE(" The -p option is mutually exclusive from the");
+ testPrintE(" -s and -e options.");
+ exit(5);
+ }
+ startPass = strtoul(optarg, &chptr, 10);
+ if (*chptr != '\0') {
+ testPrintE("Invalid command-line specified starting pass "
+ "of: %s", optarg);
+ exit(6);
+ }
+ break;
+
+ case 'e': // Ending Pass
+ eFlag = true;
+ if (pFlag) {
+ testPrintE("Invalid combination of command-line options.");
+ testPrintE(" The -p option is mutually exclusive from the");
+ testPrintE(" -s and -e options.");
+ exit(7);
+ }
+ endPass = strtoul(optarg, &chptr, 10);
+ if (*chptr != '\0') {
+ testPrintE("Invalid command-line specified ending pass "
+ "of: %s", optarg);
+ exit(8);
+ }
+ break;
+
+ case 'p': // Run a single specified pass
+ pFlag = true;
+ if (sFlag || eFlag) {
+ testPrintE("Invalid combination of command-line options.");
+ testPrintE(" The -p option is mutually exclusive from the");
+ testPrintE(" -s and -e options.");
+ exit(9);
+ }
+ startPass = endPass = strtoul(optarg, &chptr, 10);
+ if (*chptr != '\0') {
+ testPrintE("Invalid command-line specified pass of: %s",
+ optarg);
+ exit(10);
+ }
+ break;
+
+ case 'v': // Verbose
+ verbose = true;
+ break;
+
+ case 'h': // Help
+ case '?':
+ default:
+ testPrintE(" %s [options]", basename(argv[0]));
+ testPrintE(" options:");
+ testPrintE(" -p Execute specified pass");
+ testPrintE(" -s Starting pass");
+ testPrintE(" -e Ending pass");
+ testPrintE(" -t Duration");
+ testPrintE(" -d Delay after each set operation");
+ testPrintE(" -D End of test delay");
+ testPrintE(" -n Num set operations per pass");
+ testPrintE(" -v Verbose");
+ exit(((optopt == 0) || (optopt == '?')) ? 0 : 11);
+ }
+ }
+ if (endPass < startPass) {
+ testPrintE("Unexpected ending pass before starting pass");
+ testPrintE(" startPass: %u endPass: %u", startPass, endPass);
+ exit(12);
+ }
+ if (argc != optind) {
+ testPrintE("Unexpected command-line postional argument");
+ testPrintE(" %s [-s start_pass] [-e end_pass] [-t duration]",
+ basename(argv[0]));
+ exit(13);
+ }
+ testPrintI("duration: %g", duration);
+ testPrintI("startPass: %u", startPass);
+ testPrintI("endPass: %u", endPass);
+ testPrintI("numSet: %u", numSet);
+
+ // Stop framework
+ rv = snprintf(cmd, sizeof(cmd), "%s", CMD_STOP_FRAMEWORK);
+ if (rv >= (signed) sizeof(cmd) - 1) {
+ testPrintE("Command too long for: %s", CMD_STOP_FRAMEWORK);
+ exit(14);
+ }
+ testExecCmd(cmd);
+ testDelay(1.0); // TODO - need means to query whether asyncronous stop
+ // framework operation has completed. For now, just wait
+ // a long time.
+
+ init();
+
+ // For each pass
+ gettimeofday(&startTime, NULL);
+ for (pass = startPass; pass <= endPass; pass++) {
+ // Stop if duration of work has already been performed
+ gettimeofday(¤tTime, NULL);
+ delta = tvDelta(&startTime, ¤tTime);
+ if (tv2double(&delta) > duration) { break; }
+
+ // Regenerate a new set of test frames when this pass is
+ // either the first pass or is in a different group then
+ // the previous pass. A group of passes are passes that
+ // all have the same quotient when their pass number is
+ // divided by passesPerGroup.
+ if ((pass == startPass)
+ || ((pass / passesPerGroup) != ((pass - 1) / passesPerGroup))) {
+ initFrames(pass / passesPerGroup);
+ }
+
+ testPrintI("==== Starting pass: %u", pass);
+
+ // Cause deterministic sequence of prandom numbers to be
+ // generated for this pass.
+ srand48(pass);
+
+ hwc_layer_list_t *list;
+ list = hwcTestCreateLayerList(testRandMod(frames.size()) + 1);
+ if (list == NULL) {
+ testPrintE("hwcTestCreateLayerList failed");
+ exit(20);
+ }
+
+ // Prandomly select a subset of frames to be used by this pass.
+ vector <vector <sp<GraphicBuffer> > > selectedFrames;
+ selectedFrames = vectorRandSelect(frames, list->numHwLayers);
+
+ // Any transform tends to create a layer that the hardware
+ // composer is unable to support and thus has to leave for
+ // SurfaceFlinger. Place heavy bias on specifying no transforms.
+ bool noTransform = testRandFract() > rareRatio;
+
+ for (unsigned int n1 = 0; n1 < list->numHwLayers; n1++) {
+ unsigned int idx = testRandMod(selectedFrames[n1].size());
+ sp<GraphicBuffer> gBuf = selectedFrames[n1][idx];
+ hwc_layer_t *layer = &list->hwLayers[n1];
+ layer->handle = gBuf->handle;
+
+ layer->blending = blendingOps[testRandMod(NUMA(blendingOps))];
+ layer->flags = (testRandFract() > rareRatio) ? 0
+ : vectorOr(vectorRandSelect(vecLayerFlags,
+ testRandMod(vecLayerFlags.size() + 1)));
+ layer->transform = (noTransform || testRandFract() > rareRatio) ? 0
+ : vectorOr(vectorRandSelect(vecTransformFlags,
+ testRandMod(vecTransformFlags.size() + 1)));
+ layer->sourceCrop.left = testRandMod(gBuf->getWidth());
+ layer->sourceCrop.top = testRandMod(gBuf->getHeight());
+ layer->sourceCrop.right = layer->sourceCrop.left
+ + testRandMod(gBuf->getWidth() - layer->sourceCrop.left) + 1;
+ layer->sourceCrop.bottom = layer->sourceCrop.top
+ + testRandMod(gBuf->getHeight() - layer->sourceCrop.top) + 1;
+ layer->displayFrame.left = testRandMod(width);
+ layer->displayFrame.top = testRandMod(height);
+ layer->displayFrame.right = layer->displayFrame.left
+ + testRandMod(width - layer->displayFrame.left) + 1;
+ layer->displayFrame.bottom = layer->displayFrame.top
+ + testRandMod(height - layer->displayFrame.top) + 1;
+
+ // Increase the frequency that a scale factor of 1.0 from
+ // the sourceCrop to displayFrame occurs. This is the
+ // most common scale factor used by applications and would
+ // be rarely produced by this stress test without this
+ // logic.
+ if (testRandFract() <= freqRatio) {
+ // Only change to scale factor to 1.0 if both the
+ // width and height will fit.
+ int sourceWidth = layer->sourceCrop.right
+ - layer->sourceCrop.left;
+ int sourceHeight = layer->sourceCrop.bottom
+ - layer->sourceCrop.top;
+ if (((layer->displayFrame.left + sourceWidth) <= width)
+ && ((layer->displayFrame.top + sourceHeight) <= height)) {
+ layer->displayFrame.right = layer->displayFrame.left
+ + sourceWidth;
+ layer->displayFrame.bottom = layer->displayFrame.top
+ + sourceHeight;
+ }
+ }
+
+ layer->visibleRegionScreen.numRects = 1;
+ layer->visibleRegionScreen.rects = &layer->displayFrame;
+ }
+
+ // Perform prepare operation
+ if (verbose) { testPrintI("Prepare:"); hwcTestDisplayList(list); }
+ hwcDevice->prepare(hwcDevice, list);
+ if (verbose) {
+ testPrintI("Post Prepare:");
+ hwcTestDisplayListPrepareModifiable(list);
+ }
+
+ // Turn off the geometry changed flag
+ list->flags &= ~HWC_GEOMETRY_CHANGED;
+
+ // Perform the set operation(s)
+ if (verbose) {testPrintI("Set:"); }
+ for (unsigned int n1 = 0; n1 < numSet; n1++) {
+ if (verbose) { hwcTestDisplayListHandles(list); }
+ hwcDevice->set(hwcDevice, dpy, surface, list);
+
+ // Prandomly select a new set of handles
+ for (unsigned int n1 = 0; n1 < list->numHwLayers; n1++) {
+ unsigned int idx = testRandMod(selectedFrames[n1].size());
+ sp<GraphicBuffer> gBuf = selectedFrames[n1][idx];
+ hwc_layer_t *layer = &list->hwLayers[n1];
+ layer->handle = (native_handle_t *) gBuf->handle;
+ }
+
+ testDelay(perSetDelay);
+ }
+
+ hwcTestFreeLayerList(list);
+ testPrintI("==== Completed pass: %u", pass);
+ }
+
+ testDelay(endDelay);
+
+ // Start framework
+ rv = snprintf(cmd, sizeof(cmd), "%s", CMD_START_FRAMEWORK);
+ if (rv >= (signed) sizeof(cmd) - 1) {
+ testPrintE("Command too long for: %s", CMD_START_FRAMEWORK);
+ exit(21);
+ }
+ testExecCmd(cmd);
+
+ testPrintI("Successfully completed %u passes", pass - startPass);
+
+ return 0;
+}
+
+void init(void)
+{
+ srand48(0); // Defensively set pseudo random number generator.
+ // Should not need to set this, because a stress test
+ // sets the seed on each pass. Defensively set it here
+ // so that future code that uses pseudo random numbers
+ // before the first pass will be deterministic.
+
+ hwcTestInitDisplay(verbose, &dpy, &surface, &width, &height);
+
+ hwcTestOpenHwc(&hwcDevice);
+}
+
+/*
+ * Initialize Frames
+ *
+ * Creates an array of graphic buffers, within the global variable
+ * named frames. The graphic buffers are contained within a vector of
+ * vectors. All the graphic buffers in a particular row are of the same
+ * format and dimension. Each graphic buffer is uniformly filled with a
+ * prandomly selected color. It is likely that each buffer, even
+ * in the same row, will be filled with a unique color.
+ */
+void initFrames(unsigned int seed)
+{
+ int rv;
+ const size_t maxRows = 5;
+ const size_t minCols = 2; // Need at least double buffering
+ const size_t maxCols = 4; // One more than triple buffering
+
+ if (verbose) { testPrintI("initFrames seed: %u", seed); }
+ srand48(seed);
+ size_t rows = testRandMod(maxRows) + 1;
+
+ frames.clear();
+ frames.resize(rows);
+
+ for (unsigned int row = 0; row < rows; row++) {
+ // All frames within a row have to have the same format and
+ // dimensions. Width and height need to be >= 1.
+ unsigned int formatIdx = testRandMod(NUMA(hwcTestGraphicFormat));
+ const struct hwcTestGraphicFormat *formatPtr
+ = &hwcTestGraphicFormat[formatIdx];
+ int format = formatPtr->format;
+
+ // Pick width and height, which must be >= 1 and the size
+ // mod the wMod/hMod value must be equal to 0.
+ size_t w = (width * maxSizeRatio) * testRandFract();
+ size_t h = (height * maxSizeRatio) * testRandFract();
+ w = max(1u, w);
+ h = max(1u, h);
+ if ((w % formatPtr->wMod) != 0) {
+ w += formatPtr->wMod - (w % formatPtr->wMod);
+ }
+ if ((h % formatPtr->hMod) != 0) {
+ h += formatPtr->hMod - (h % formatPtr->hMod);
+ }
+ if (verbose) {
+ testPrintI(" frame %u width: %u height: %u format: %u %s",
+ row, w, h, format, hwcTestGraphicFormat2str(format));
+ }
+
+ size_t cols = testRandMod((maxCols + 1) - minCols) + minCols;
+ frames[row].resize(cols);
+ for (unsigned int col = 0; col < cols; col++) {
+ ColorFract color(testRandFract(), testRandFract(), testRandFract());
+ float alpha = testRandFract();
+
+ frames[row][col] = new GraphicBuffer(w, h, format, texUsage);
+ if ((rv = frames[row][col]->initCheck()) != NO_ERROR) {
+ testPrintE("GraphicBuffer initCheck failed, rv: %i", rv);
+ testPrintE(" frame %u width: %u height: %u format: %u %s",
+ row, w, h, format, hwcTestGraphicFormat2str(format));
+ exit(80);
+ }
+
+ hwcTestFillColor(frames[row][col].get(), color, alpha);
+ if (verbose) {
+ testPrintI(" buf: %p handle: %p color: %s alpha: %f",
+ frames[row][col].get(), frames[row][col]->handle,
+ string(color).c_str(), alpha);
+ }
+ }
+ }
+}
+
+/*
+ * Vector Random Select
+ *
+ * Prandomly selects and returns num elements from vec.
+ */
+template <class T>
+vector<T> vectorRandSelect(const vector<T>& vec, size_t num)
+{
+ vector<T> rv = vec;
+
+ while (rv.size() > num) {
+ rv.erase(rv.begin() + testRandMod(rv.size()));
+ }
+
+ return rv;
+}
+
+/*
+ * Vector Or
+ *
+ * Or's togethen the values of each element of vec and returns the result.
+ */
+template <class T>
+T vectorOr(const vector<T>& vec)
+{
+ T rv = 0;
+
+ for (size_t n1 = 0; n1 < vec.size(); n1++) {
+ rv |= vec[n1];
+ }
+
+ return rv;
+}
diff --git a/opengl/tests/hwc/hwcTestLib.cpp b/opengl/tests/hwc/hwcTestLib.cpp
new file mode 100644
index 0000000..925405e
--- /dev/null
+++ b/opengl/tests/hwc/hwcTestLib.cpp
@@ -0,0 +1,1028 @@
+/*
+ * Copyright (C) 2011 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.
+ *
+ */
+
+/*
+ * Hardware Composer Test Library
+ * Utility library functions for use by the Hardware Composer test cases
+ */
+
+#include <sstream>
+#include <string>
+
+#include <arpa/inet.h> // For ntohl() and htonl()
+
+#include <hwc/hwcTestLib.h>
+
+// Defines
+#define NUMA(a) (sizeof(a) / sizeof(a [0]))
+
+// Function Prototypes
+static void printGLString(const char *name, GLenum s);
+static void checkEglError(const char* op, EGLBoolean returnVal = EGL_TRUE);
+static void checkGlError(const char* op);
+static void printEGLConfiguration(EGLDisplay dpy, EGLConfig config);
+
+using namespace std;
+using namespace android;
+
+
+#define BITSPERBYTE 8 // TODO: Obtain from <values.h>, once
+ // it has been added
+
+// Initialize Display
+void hwcTestInitDisplay(bool verbose, EGLDisplay *dpy, EGLSurface *surface,
+ EGLint *width, EGLint *height)
+{
+ static EGLContext context;
+
+ int rv;
+
+ EGLBoolean returnValue;
+ EGLConfig myConfig = {0};
+ EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
+ EGLint sConfigAttribs[] = {
+ EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
+ EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
+ EGL_NONE };
+ EGLint majorVersion, minorVersion;
+
+ checkEglError("<init>");
+ *dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
+ checkEglError("eglGetDisplay");
+ if (*dpy == EGL_NO_DISPLAY) {
+ testPrintE("eglGetDisplay returned EGL_NO_DISPLAY");
+ exit(70);
+ }
+
+ returnValue = eglInitialize(*dpy, &majorVersion, &minorVersion);
+ checkEglError("eglInitialize", returnValue);
+ if (verbose) {
+ testPrintI("EGL version %d.%d", majorVersion, minorVersion);
+ }
+ if (returnValue != EGL_TRUE) {
+ testPrintE("eglInitialize failed");
+ exit(71);
+ }
+
+ EGLNativeWindowType window = android_createDisplaySurface();
+ if (window == NULL) {
+ testPrintE("android_createDisplaySurface failed");
+ exit(72);
+ }
+ returnValue = EGLUtils::selectConfigForNativeWindow(*dpy,
+ sConfigAttribs, window, &myConfig);
+ if (returnValue) {
+ testPrintE("EGLUtils::selectConfigForNativeWindow() returned %d",
+ returnValue);
+ exit(73);
+ }
+ checkEglError("EGLUtils::selectConfigForNativeWindow");
+
+ if (verbose) {
+ testPrintI("Chose this configuration:");
+ printEGLConfiguration(*dpy, myConfig);
+ }
+
+ *surface = eglCreateWindowSurface(*dpy, myConfig, window, NULL);
+ checkEglError("eglCreateWindowSurface");
+ if (*surface == EGL_NO_SURFACE) {
+ testPrintE("gelCreateWindowSurface failed.");
+ exit(74);
+ }
+
+ context = eglCreateContext(*dpy, myConfig, EGL_NO_CONTEXT, contextAttribs);
+ checkEglError("eglCreateContext");
+ if (context == EGL_NO_CONTEXT) {
+ testPrintE("eglCreateContext failed");
+ exit(75);
+ }
+ returnValue = eglMakeCurrent(*dpy, *surface, *surface, context);
+ checkEglError("eglMakeCurrent", returnValue);
+ if (returnValue != EGL_TRUE) {
+ testPrintE("eglMakeCurrent failed");
+ exit(76);
+ }
+ eglQuerySurface(*dpy, *surface, EGL_WIDTH, width);
+ checkEglError("eglQuerySurface");
+ eglQuerySurface(*dpy, *surface, EGL_HEIGHT, height);
+ checkEglError("eglQuerySurface");
+
+ if (verbose) {
+ testPrintI("Window dimensions: %d x %d", *width, *height);
+
+ printGLString("Version", GL_VERSION);
+ printGLString("Vendor", GL_VENDOR);
+ printGLString("Renderer", GL_RENDERER);
+ printGLString("Extensions", GL_EXTENSIONS);
+ }
+}
+
+// Open Hardware Composer Device
+void hwcTestOpenHwc(hwc_composer_device_t **hwcDevicePtr)
+{
+ int rv;
+ hw_module_t const *hwcModule;
+
+ if ((rv = hw_get_module(HWC_HARDWARE_MODULE_ID, &hwcModule)) != 0) {
+ testPrintE("hw_get_module failed, rv: %i", rv);
+ errno = -rv;
+ perror(NULL);
+ exit(77);
+ }
+ if ((rv = hwc_open(hwcModule, hwcDevicePtr)) != 0) {
+ testPrintE("hwc_open failed, rv: %i", rv);
+ errno = -rv;
+ perror(NULL);
+ exit(78);
+ }
+}
+
+// Color fraction class to string conversion
+ColorFract::operator string()
+{
+ ostringstream out;
+
+ out << '[' << this->c1() << ", "
+ << this->c2() << ", "
+ << this->c3() << ']';
+
+ return out.str();
+}
+
+// Dimension class to string conversion
+HwcTestDim::operator string()
+{
+ ostringstream out;
+
+ out << '[' << this->width() << ", "
+ << this->height() << ']';
+
+ return out.str();
+}
+
+// Dimension class to hwc_rect conversion
+HwcTestDim::operator hwc_rect() const
+{
+ hwc_rect rect;
+
+ rect.left = rect.top = 0;
+
+ rect.right = this->_w;
+ rect.bottom = this->_h;
+
+ return rect;
+}
+
+// Hardware Composer rectangle to string conversion
+string hwcTestRect2str(const struct hwc_rect& rect)
+{
+ ostringstream out;
+
+ out << '[';
+ out << rect.left << ", ";
+ out << rect.top << ", ";
+ out << rect.right << ", ";
+ out << rect.bottom;
+ out << ']';
+
+ return out.str();
+}
+
+// Parse HWC rectangle description of form [left, top, right, bottom]
+struct hwc_rect hwcTestParseHwcRect(istringstream& in, bool& error)
+{
+ struct hwc_rect rect;
+ char chStart, ch;
+
+ // Defensively specify that an error occurred. Will clear
+ // error flag if all of parsing succeeds.
+ error = true;
+
+ // First character should be a [ or <
+ in >> chStart;
+ if (!in || ((chStart != '<') && (chStart != '['))) { return rect; }
+
+ // Left
+ in >> rect.left;
+ if (!in) { return rect; }
+ in >> ch;
+ if (!in || (ch != ',')) { return rect; }
+
+ // Top
+ in >> rect.top;
+ if (!in) { return rect; }
+ in >> ch;
+ if (!in || (ch != ',')) { return rect; }
+
+ // Right
+ in >> rect.right;
+ if (!in) { return rect; }
+ in >> ch;
+ if (!in || (ch != ',')) { return rect; }
+
+ // Bottom
+ in >> rect.bottom;
+ if (!in) { return rect; }
+
+ // Closing > or ]
+ in >> ch;
+ if (!in) { return rect; }
+ if (((chStart == '<') && (ch != '>'))
+ || ((chStart == '[') && (ch != ']'))) { return rect; }
+
+ // Validate right and bottom are greater than left and top
+ if ((rect.right <= rect.left) || (rect.bottom <= rect.top)) { return rect; }
+
+ // Made It, clear error indicator
+ error = false;
+
+ return rect;
+}
+
+// Parse dimension of form [width, height]
+HwcTestDim hwcTestParseDim(istringstream& in, bool& error)
+{
+ HwcTestDim dim;
+ char chStart, ch;
+ uint32_t val;
+
+ // Defensively specify that an error occurred. Will clear
+ // error flag if all of parsing succeeds.
+ error = true;
+
+ // First character should be a [ or <
+ in >> chStart;
+ if (!in || ((chStart != '<') && (chStart != '['))) { return dim; }
+
+ // Width
+ in >> val;
+ if (!in) { return dim; }
+ dim.setWidth(val);
+ in >> ch;
+ if (!in || (ch != ',')) { return dim; }
+
+ // Height
+ in >> val;
+ if (!in) { return dim; }
+ dim.setHeight(val);
+
+ // Closing > or ]
+ in >> ch;
+ if (!in) { return dim; }
+ if (((chStart == '<') && (ch != '>'))
+ || ((chStart == '[') && (ch != ']'))) { return dim; }
+
+ // Validate width and height greater than 0
+ if ((dim.width() <= 0) || (dim.height() <= 0)) { return dim; }
+
+ // Made It, clear error indicator
+ error = false;
+ return dim;
+}
+
+// Parse fractional color of form [0.##, 0.##, 0.##]
+// Fractional values can be from 0.0 to 1.0 inclusive. Note, integer
+// values of 0.0 and 1.0, which are non-fractional, are considered valid.
+// They are an exception, all other valid inputs are fractions.
+ColorFract hwcTestParseColor(istringstream& in, bool& error)
+{
+ ColorFract color;
+ char chStart, ch;
+ float c1, c2, c3;
+
+ // Defensively specify that an error occurred. Will clear
+ // error flag if all of parsing succeeds.
+ error = true;
+
+ // First character should be a [ or <
+ in >> chStart;
+ if (!in || ((chStart != '<') && (chStart != '['))) { return color; }
+
+ // 1st Component
+ in >> c1;
+ if (!in) { return color; }
+ if ((c1 < 0.0) || (c1 > 1.0)) { return color; }
+ in >> ch;
+ if (!in || (ch != ',')) { return color; }
+
+ // 2nd Component
+ in >> c2;
+ if (!in) { return color; }
+ if ((c2 < 0.0) || (c2 > 1.0)) { return color; }
+ in >> ch;
+ if (!in || (ch != ',')) { return color; }
+
+ // 3rd Component
+ in >> c3;
+ if (!in) { return color; }
+ if ((c3 < 0.0) || (c3 > 1.0)) { return color; }
+
+ // Closing > or ]
+ in >> ch;
+ if (!in) { return color; }
+ if (((chStart == '<') && (ch != '>'))
+ || ((chStart == '[') && (ch != ']'))) { return color; }
+
+ // Are all the components fractional
+ if ((c1 < 0.0) || (c1 > 1.0)
+ || (c2 < 0.0) || (c2 > 1.0)
+ || (c3 < 0.0) || (c3 > 1.0)) { return color; }
+
+ // Made It, clear error indicator
+ error = false;
+
+ return ColorFract(c1, c2, c3);
+}
+
+// Look up and return pointer to structure with the characteristics
+// of the graphic format named by the desc parameter. Search failure
+// indicated by the return of NULL.
+const struct hwcTestGraphicFormat *hwcTestGraphicFormatLookup(const char *desc)
+{
+ for (unsigned int n1 = 0; n1 < NUMA(hwcTestGraphicFormat); n1++) {
+ if (string(desc) == string(hwcTestGraphicFormat[n1].desc)) {
+ return &hwcTestGraphicFormat[n1];
+ }
+ }
+
+ return NULL;
+}
+
+// Look up and return pointer to structure with the characteristics
+// of the graphic format specified by the id parameter. Search failure
+// indicated by the return of NULL.
+const struct hwcTestGraphicFormat *hwcTestGraphicFormatLookup(uint32_t id)
+{
+ for (unsigned int n1 = 0; n1 < NUMA(hwcTestGraphicFormat); n1++) {
+ if (id == hwcTestGraphicFormat[n1].format) {
+ return &hwcTestGraphicFormat[n1];
+ }
+ }
+
+ return NULL;
+}
+
+
+// Given the integer ID of a graphic format, return a pointer to
+// a string that describes the format.
+const char *hwcTestGraphicFormat2str(uint32_t format)
+{
+ const static char *unknown = "unknown";
+
+ for (unsigned int n1 = 0; n1 < NUMA(hwcTestGraphicFormat); n1++) {
+ if (format == hwcTestGraphicFormat[n1].format) {
+ return hwcTestGraphicFormat[n1].desc;
+ }
+ }
+
+ return unknown;
+}
+
+/*
+ * hwcTestCreateLayerList
+ * Dynamically creates layer list with numLayers worth
+ * of hwLayers entries.
+ */
+hwc_layer_list_t *hwcTestCreateLayerList(size_t numLayers)
+{
+ hwc_layer_list_t *list;
+
+ size_t size = sizeof(hwc_layer_list) + numLayers * sizeof(hwc_layer_t);
+ if ((list = (hwc_layer_list_t *) calloc(1, size)) == NULL) {
+ return NULL;
+ }
+ list->flags = HWC_GEOMETRY_CHANGED;
+ list->numHwLayers = numLayers;
+
+ return list;
+}
+
+/*
+ * hwcTestFreeLayerList
+ * Frees memory previous allocated via hwcTestCreateLayerList().
+ */
+void hwcTestFreeLayerList(hwc_layer_list_t *list)
+{
+ free(list);
+}
+
+// Display the settings of the layer list pointed to by list
+void hwcTestDisplayList(hwc_layer_list_t *list)
+{
+ testPrintI(" flags: %#x%s", list->flags,
+ (list->flags & HWC_GEOMETRY_CHANGED) ? " GEOMETRY_CHANGED" : "");
+ testPrintI(" numHwLayers: %u", list->numHwLayers);
+
+ for (unsigned int layer = 0; layer < list->numHwLayers; layer++) {
+ testPrintI(" layer %u compositionType: %#x%s%s", layer,
+ list->hwLayers[layer].compositionType,
+ (list->hwLayers[layer].compositionType == HWC_FRAMEBUFFER)
+ ? " FRAMEBUFFER" : "",
+ (list->hwLayers[layer].compositionType == HWC_OVERLAY)
+ ? " OVERLAY" : "");
+
+ testPrintI(" hints: %#x",
+ list->hwLayers[layer].hints,
+ (list->hwLayers[layer].hints & HWC_HINT_TRIPLE_BUFFER)
+ ? " TRIPLE_BUFFER" : "",
+ (list->hwLayers[layer].hints & HWC_HINT_CLEAR_FB)
+ ? " CLEAR_FB" : "");
+
+ testPrintI(" flags: %#x%s",
+ list->hwLayers[layer].flags,
+ (list->hwLayers[layer].flags & HWC_SKIP_LAYER)
+ ? " SKIP_LAYER" : "");
+
+ testPrintI(" handle: %p",
+ list->hwLayers[layer].handle);
+
+ // Intentionally skipped display of ROT_180 & ROT_270,
+ // which are formed from combinations of the other flags.
+ testPrintI(" transform: %#x%s%s%s",
+ list->hwLayers[layer].transform,
+ (list->hwLayers[layer].transform & HWC_TRANSFORM_FLIP_H)
+ ? " FLIP_H" : "",
+ (list->hwLayers[layer].transform & HWC_TRANSFORM_FLIP_V)
+ ? " FLIP_V" : "",
+ (list->hwLayers[layer].transform & HWC_TRANSFORM_ROT_90)
+ ? " ROT_90" : "");
+
+ testPrintI(" blending: %#x%s%s%s",
+ list->hwLayers[layer].blending,
+ (list->hwLayers[layer].blending == HWC_BLENDING_NONE)
+ ? " NONE" : "",
+ (list->hwLayers[layer].blending == HWC_BLENDING_PREMULT)
+ ? " PREMULT" : "",
+ (list->hwLayers[layer].blending == HWC_BLENDING_COVERAGE)
+ ? " COVERAGE" : "");
+
+ testPrintI(" sourceCrop: %s",
+ hwcTestRect2str(list->hwLayers[layer].sourceCrop).c_str());
+ testPrintI(" displayFrame: %s",
+ hwcTestRect2str(list->hwLayers[layer].displayFrame).c_str());
+ testPrintI(" scaleFactor: [%f, %f]",
+ (float) (list->hwLayers[layer].sourceCrop.right
+ - list->hwLayers[layer].sourceCrop.left)
+ / (float) (list->hwLayers[layer].displayFrame.right
+ - list->hwLayers[layer].displayFrame.left),
+ (float) (list->hwLayers[layer].sourceCrop.bottom
+ - list->hwLayers[layer].sourceCrop.top)
+ / (float) (list->hwLayers[layer].displayFrame.bottom
+ - list->hwLayers[layer].displayFrame.top));
+ }
+}
+
+/*
+ * Display List Prepare Modifiable
+ *
+ * Displays the portions of a list that are meant to be modified by
+ * a prepare call.
+ */
+void hwcTestDisplayListPrepareModifiable(hwc_layer_list_t *list)
+{
+ uint32_t numOverlays = 0;
+ for (unsigned int layer = 0; layer < list->numHwLayers; layer++) {
+ if (list->hwLayers[layer].compositionType == HWC_OVERLAY) {
+ numOverlays++;
+ }
+ testPrintI(" layer %u compositionType: %#x%s%s", layer,
+ list->hwLayers[layer].compositionType,
+ (list->hwLayers[layer].compositionType == HWC_FRAMEBUFFER)
+ ? " FRAMEBUFFER" : "",
+ (list->hwLayers[layer].compositionType == HWC_OVERLAY)
+ ? " OVERLAY" : "");
+ testPrintI(" hints: %#x%s%s",
+ list->hwLayers[layer].hints,
+ (list->hwLayers[layer].hints & HWC_HINT_TRIPLE_BUFFER)
+ ? " TRIPLE_BUFFER" : "",
+ (list->hwLayers[layer].hints & HWC_HINT_CLEAR_FB)
+ ? " CLEAR_FB" : "");
+ }
+ testPrintI(" numOverlays: %u", numOverlays);
+}
+
+/*
+ * Display List Handles
+ *
+ * Displays the handles of all the graphic buffers in the list.
+ */
+void hwcTestDisplayListHandles(hwc_layer_list_t *list)
+{
+ const unsigned int maxLayersPerLine = 6;
+
+ ostringstream str(" layers:");
+ for (unsigned int layer = 0; layer < list->numHwLayers; layer++) {
+ str << ' ' << list->hwLayers[layer].handle;
+ if (((layer % maxLayersPerLine) == (maxLayersPerLine - 1))
+ && (layer != list->numHwLayers - 1)) {
+ testPrintI("%s", str.str().c_str());
+ str.str(" ");
+ }
+ }
+ testPrintI("%s", str.str().c_str());
+}
+
+// Returns a uint32_t that contains a format specific representation of a
+// single pixel of the given color and alpha values.
+uint32_t hwcTestColor2Pixel(uint32_t format, ColorFract color, float alpha)
+{
+ const struct attrib {
+ uint32_t format;
+ bool hostByteOrder;
+ size_t bytes;
+ size_t c1Offset;
+ size_t c1Size;
+ size_t c2Offset;
+ size_t c2Size;
+ size_t c3Offset;
+ size_t c3Size;
+ size_t aOffset;
+ size_t aSize;
+ } attributes[] = {
+ {HAL_PIXEL_FORMAT_RGBA_8888, false, 4, 0, 8, 8, 8, 16, 8, 24, 8},
+ {HAL_PIXEL_FORMAT_RGBX_8888, false, 4, 0, 8, 8, 8, 16, 8, 0, 0},
+ {HAL_PIXEL_FORMAT_RGB_888, false, 3, 0, 8, 8, 8, 16, 8, 0, 0},
+ {HAL_PIXEL_FORMAT_RGB_565, true, 2, 0, 5, 5, 6, 11, 5, 0, 0},
+ {HAL_PIXEL_FORMAT_BGRA_8888, false, 4, 16, 8, 8, 8, 0, 8, 24, 8},
+ {HAL_PIXEL_FORMAT_RGBA_5551, true , 2, 0, 5, 5, 5, 10, 5, 15, 1},
+ {HAL_PIXEL_FORMAT_RGBA_4444, false, 2, 12, 4, 0, 4, 4, 4, 8, 4},
+ {HAL_PIXEL_FORMAT_YV12, true, 3, 16, 8, 8, 8, 0, 8, 0, 0},
+ };
+
+ const struct attrib *attrib;
+ for (attrib = attributes; attrib < attributes + NUMA(attributes);
+ attrib++) {
+ if (attrib->format == format) { break; }
+ }
+ if (attrib >= attributes + NUMA(attributes)) {
+ testPrintE("colorFract2Pixel unsupported format of: %u", format);
+ exit(80);
+ }
+
+ uint32_t pixel;
+ pixel = htonl((uint32_t) round((((1 << attrib->c1Size) - 1) * color.c1()))
+ << ((sizeof(pixel) * BITSPERBYTE)
+ - (attrib->c1Offset + attrib->c1Size)));
+ pixel |= htonl((uint32_t) round((((1 << attrib->c2Size) - 1) * color.c2()))
+ << ((sizeof(pixel) * BITSPERBYTE)
+ - (attrib->c2Offset + attrib->c2Size)));
+ pixel |= htonl((uint32_t) round((((1 << attrib->c3Size) - 1) * color.c3()))
+ << ((sizeof(pixel) * BITSPERBYTE)
+ - (attrib->c3Offset + attrib->c3Size)));
+ if (attrib->aSize) {
+ pixel |= htonl((uint32_t) round((((1 << attrib->aSize) - 1) * alpha))
+ << ((sizeof(pixel) * BITSPERBYTE)
+ - (attrib->aOffset + attrib->aSize)));
+ }
+ if (attrib->hostByteOrder) {
+ pixel = ntohl(pixel);
+ pixel >>= sizeof(pixel) * BITSPERBYTE - attrib->bytes * BITSPERBYTE;
+ }
+
+ return pixel;
+}
+
+// Sets the pixel at the given x and y coordinates to the color and alpha
+// value given by pixel. The contents of pixel is format specific. It's
+// value should come from a call to hwcTestColor2Pixel().
+void hwcTestSetPixel(GraphicBuffer *gBuf, unsigned char *buf,
+ uint32_t x, uint32_t y, uint32_t pixel)
+{
+
+ const struct attrib {
+ int format;
+ size_t bytes;
+ } attributes[] = {
+ {HAL_PIXEL_FORMAT_RGBA_8888, 4},
+ {HAL_PIXEL_FORMAT_RGBX_8888, 4},
+ {HAL_PIXEL_FORMAT_RGB_888, 3},
+ {HAL_PIXEL_FORMAT_RGB_565, 2},
+ {HAL_PIXEL_FORMAT_BGRA_8888, 4},
+ {HAL_PIXEL_FORMAT_RGBA_5551, 2},
+ {HAL_PIXEL_FORMAT_RGBA_4444, 2},
+ };
+
+ if (gBuf->getPixelFormat() == HAL_PIXEL_FORMAT_YV12) {
+ uint32_t yPlaneOffset, uPlaneOffset, vPlaneOffset;
+ uint32_t yPlaneStride = gBuf->getStride();
+ uint32_t uPlaneStride = ((gBuf->getStride() / 2) + 0xf) & ~0xf;
+ uint32_t vPlaneStride = uPlaneStride;
+ yPlaneOffset = 0;
+ vPlaneOffset = yPlaneOffset + yPlaneStride * gBuf->getHeight();
+ uPlaneOffset = vPlaneOffset
+ + vPlaneStride * (gBuf->getHeight() / 2);
+ *(buf + yPlaneOffset + y * yPlaneStride + x) = pixel & 0xff;
+ *(buf + uPlaneOffset + (y / 2) * uPlaneStride + (x / 2))
+ = (pixel & 0xff00) >> 8;
+ *(buf + vPlaneOffset + (y / 2) * vPlaneStride + (x / 2))
+ = (pixel & 0xff0000) >> 16;
+
+ return;
+ }
+
+ const struct attrib *attrib;
+ for (attrib = attributes; attrib < attributes + NUMA(attributes);
+ attrib++) {
+ if (attrib->format == gBuf->getPixelFormat()) { break; }
+ }
+ if (attrib >= attributes + NUMA(attributes)) {
+ testPrintE("setPixel unsupported format of: %u",
+ gBuf->getPixelFormat());
+ exit(90);
+ }
+
+ memmove(buf + ((gBuf->getStride() * attrib->bytes) * y)
+ + (attrib->bytes * x), &pixel, attrib->bytes);
+}
+
+// Fill a given graphic buffer with a uniform color and alpha
+void hwcTestFillColor(GraphicBuffer *gBuf, ColorFract color, float alpha)
+{
+ unsigned char* buf = NULL;
+ status_t err;
+ uint32_t pixel;
+
+ pixel = hwcTestColor2Pixel(gBuf->getPixelFormat(), color, alpha);
+
+ err = gBuf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&buf));
+ if (err != 0) {
+ testPrintE("hwcTestFillColor lock failed: %d", err);
+ exit(100);
+ }
+
+ for (unsigned int x = 0; x < gBuf->getStride(); x++) {
+ for (unsigned int y = 0; y < gBuf->getHeight(); y++) {
+ uint32_t val = pixel;
+ hwcTestSetPixel(gBuf, buf, x, y, (x < gBuf->getWidth())
+ ? pixel : testRand());
+ }
+ }
+
+ err = gBuf->unlock();
+ if (err != 0) {
+ testPrintE("hwcTestFillColor unlock failed: %d", err);
+ exit(101);
+ }
+}
+
+// Fill the given buffer with a horizontal blend of colors, with the left
+// side color given by startColor and the right side color given by
+// endColor. The startColor and endColor values are specified in the format
+// given by colorFormat, which might be different from the format of the
+// graphic buffer. When different, a color conversion is done when possible
+// to the graphic format of the graphic buffer. A color of black is
+// produced for cases where the conversion is impossible (e.g. out of gamut
+// values).
+void hwcTestFillColorHBlend(GraphicBuffer *gBuf, uint32_t colorFormat,
+ ColorFract startColor, ColorFract endColor)
+{
+ status_t err;
+ unsigned char* buf = NULL;
+ const uint32_t width = gBuf->getWidth();
+ const uint32_t height = gBuf->getHeight();
+ const uint32_t stride = gBuf->getStride();
+
+ err = gBuf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&buf));
+ if (err != 0) {
+ testPrintE("hwcTestFillColorHBlend lock failed: %d", err);
+ exit(110);
+ }
+
+ for (unsigned int x = 0; x < stride; x++) {
+ uint32_t pixel;
+ if (x < width) {
+ ColorFract color(startColor.c1() + (endColor.c1() - startColor.c1())
+ * ((float) x / (float) (width - 1)),
+ startColor.c2() + (endColor.c2() - startColor.c2())
+ * ((float) x / (float) (width - 1)),
+ startColor.c3() + (endColor.c3() - startColor.c3())
+ * ((float) x / (float) (width - 1)));
+
+ // When formats differ, convert colors.
+ // Important to not convert when formats are the same, since
+ // out of gamut colors are always converted to black.
+ if (colorFormat != (uint32_t) gBuf->getPixelFormat()) {
+ hwcTestColorConvert(colorFormat, gBuf->getPixelFormat(), color);
+ }
+ pixel = hwcTestColor2Pixel(gBuf->getPixelFormat(), color, 1.0);
+ } else {
+ // Fill pad with random values
+ pixel = testRand();
+ }
+
+ for (unsigned int y = 0; y < height; y++) {
+ hwcTestSetPixel(gBuf, buf, x, y, pixel);
+ }
+ }
+
+ err = gBuf->unlock();
+ if (err != 0) {
+ testPrintE("hwcTestFillColorHBlend unlock failed: %d", err);
+ exit(111);
+ }
+}
+
+/*
+ * When possible, converts color specified as a full range value in
+ * the fromFormat, into an equivalent full range color in the toFormat.
+ * When conversion is impossible (e.g. out of gamut color) a color
+ * or black in the full range output format is produced. The input
+ * color is given as a fractional color in the parameter named color.
+ * The produced color is written over the same parameter used to
+ * provide the input color.
+ *
+ * Each graphic format has 3 color components and each of these
+ * components has both a full and in gamut range. This function uses
+ * a table that provides the full and in gamut ranges of each of the
+ * supported graphic formats. The full range is given by members named
+ * c[123]Min to c[123]Max, while the in gamut range is given by members
+ * named c[123]Low to c[123]High. In most cases the full and in gamut
+ * ranges are equivalent. This occurs when the c[123]Min == c[123]Low and
+ * c[123]High == c[123]Max.
+ *
+ * The input and produced colors are both specified as a fractional amount
+ * of the full range. The diagram below provides an overview of the
+ * conversion process. The main steps are:
+ *
+ * 1. Produce black if the input color is out of gamut.
+ *
+ * 2. Convert the in gamut color into the fraction of the fromFromat
+ * in gamut range.
+ *
+ * 3. Convert from the fraction of the in gamut from format range to
+ * the fraction of the in gamut to format range. Produce black
+ * if an equivalent color does not exists.
+ *
+ * 4. Covert from the fraction of the in gamut to format to the
+ * fraction of the full range to format.
+ *
+ * From Format To Format
+ * max high high max
+ * ----+ +-----------+
+ * high \ / \ high
+ * ------\-------------+ +-------->
+ * \
+ * \ +--- black --+
+ * \ / \
+ * \ / +-->
+ * low \ / low
+ * -------- ---+-- black --+
+ * min low low min
+ * ^ ^ ^ ^ ^
+ * | | | | |
+ * | | | | +-- fraction of full range
+ * | | | +-- fraction of valid range
+ * | | +-- fromFormat to toFormat color conversion
+ * | +-- fraction of valid range
+ * +-- fraction of full range
+ */
+void hwcTestColorConvert(uint32_t fromFormat, uint32_t toFormat,
+ ColorFract& color)
+{
+ const struct attrib {
+ uint32_t format;
+ bool rgb;
+ bool yuv;
+ int c1Min, c1Low, c1High, c1Max;
+ int c2Min, c2Low, c2High, c2Max;
+ int c3Min, c3Low, c3High, c3Max;
+ } attributes[] = {
+ {HAL_PIXEL_FORMAT_RGBA_8888, true, false,
+ 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255},
+ {HAL_PIXEL_FORMAT_RGBX_8888, true, false,
+ 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255},
+ {HAL_PIXEL_FORMAT_RGB_888, true, false,
+ 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255},
+ {HAL_PIXEL_FORMAT_RGB_565, true, false,
+ 0, 0, 31, 31, 0, 0, 63, 63, 0, 0, 31, 31},
+ {HAL_PIXEL_FORMAT_BGRA_8888, true, false,
+ 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255},
+ {HAL_PIXEL_FORMAT_RGBA_5551, true, false,
+ 0, 0, 31, 31, 0, 0, 31, 31, 0, 0, 31, 31},
+ {HAL_PIXEL_FORMAT_RGBA_4444, true, false,
+ 0, 0, 15, 15, 0, 0, 15, 15, 0, 0, 15, 15},
+ {HAL_PIXEL_FORMAT_YV12, false, true,
+ 0, 16, 235, 255, 0, 16, 240, 255, 0, 16, 240, 255},
+ };
+
+ const struct attrib *fromAttrib;
+ for (fromAttrib = attributes; fromAttrib < attributes + NUMA(attributes);
+ fromAttrib++) {
+ if (fromAttrib->format == fromFormat) { break; }
+ }
+ if (fromAttrib >= attributes + NUMA(attributes)) {
+ testPrintE("hwcTestColorConvert unsupported from format of: %u",
+ fromFormat);
+ exit(120);
+ }
+
+ const struct attrib *toAttrib;
+ for (toAttrib = attributes; toAttrib < attributes + NUMA(attributes);
+ toAttrib++) {
+ if (toAttrib->format == toFormat) { break; }
+ }
+ if (toAttrib >= attributes + NUMA(attributes)) {
+ testPrintE("hwcTestColorConvert unsupported to format of: %u",
+ toFormat);
+ exit(121);
+ }
+
+ // Produce black if any of the from components are outside the
+ // valid color range
+ float c1Val = fromAttrib->c1Min
+ + ((float) (fromAttrib->c1Max - fromAttrib->c1Min) * color.c1());
+ float c2Val = fromAttrib->c2Min
+ + ((float) (fromAttrib->c2Max - fromAttrib->c2Min) * color.c2());
+ float c3Val = fromAttrib->c3Min
+ + ((float) (fromAttrib->c3Max - fromAttrib->c3Min) * color.c3());
+ if ((c1Val < fromAttrib->c1Low) || (c1Val > fromAttrib->c1High)
+ || (c2Val < fromAttrib->c2Low) || (c2Val > fromAttrib->c2High)
+ || (c3Val < fromAttrib->c3Low) || (c3Val > fromAttrib->c3High)) {
+
+ // Return black
+ // Will use representation of black from RGBA8888 graphic format
+ // and recursively convert it to the requested graphic format.
+ color = ColorFract(0.0, 0.0, 0.0);
+ hwcTestColorConvert(HAL_PIXEL_FORMAT_RGBA_8888, toFormat, color);
+ return;
+ }
+
+ // Within from format, convert from fraction of full range
+ // to fraction of valid range
+ color = ColorFract((c1Val - fromAttrib->c1Low)
+ / (fromAttrib->c1High - fromAttrib->c1Low),
+ (c2Val - fromAttrib->c2Low)
+ / (fromAttrib->c2High - fromAttrib->c2Low),
+ (c3Val - fromAttrib->c3Low)
+ / (fromAttrib->c3High - fromAttrib->c3Low));
+
+ // If needed perform RGB to YUV conversion
+ float wr = 0.2126, wg = 0.7152, wb = 0.0722; // ITU709 recommended constants
+ if (fromAttrib->rgb && toAttrib->yuv) {
+ float r = color.c1(), g = color.c2(), b = color.c3();
+ float y = wr * r + wg * g + wb * b;
+ float u = 0.5 * ((b - y) / (1.0 - wb)) + 0.5;
+ float v = 0.5 * ((r - y) / (1.0 - wr)) + 0.5;
+
+ // Produce black if color is outside the YUV gamut
+ if ((y < 0.0) || (y > 1.0)
+ || (u < 0.0) || (u > 1.0)
+ || (v < 0.0) || (v > 1.0)) {
+ y = 0.0;
+ u = v = 0.5;
+ }
+
+ color = ColorFract(y, u, v);
+ }
+
+ // If needed perform YUV to RGB conversion
+ // Equations determined from the ITU709 equations for RGB to YUV
+ // conversion, plus the following algebra:
+ //
+ // u = 0.5 * ((b - y) / (1.0 - wb)) + 0.5
+ // 0.5 * ((b - y) / (1.0 - wb)) = u - 0.5
+ // (b - y) / (1.0 - wb) = 2 * (u - 0.5)
+ // b - y = 2 * (u - 0.5) * (1.0 - wb)
+ // b = 2 * (u - 0.5) * (1.0 - wb) + y
+ //
+ // v = 0.5 * ((r -y) / (1.0 - wr)) + 0.5
+ // 0.5 * ((r - y) / (1.0 - wr)) = v - 0.5
+ // (r - y) / (1.0 - wr) = 2 * (v - 0.5)
+ // r - y = 2 * (v - 0.5) * (1.0 - wr)
+ // r = 2 * (v - 0.5) * (1.0 - wr) + y
+ //
+ // y = wr * r + wg * g + wb * b
+ // wr * r + wg * g + wb * b = y
+ // wg * g = y - wr * r - wb * b
+ // g = (y - wr * r - wb * b) / wg
+ if (fromAttrib->yuv && toAttrib->rgb) {
+ float y = color.c1(), u = color.c2(), v = color.c3();
+ float r = 2.0 * (v - 0.5) * (1.0 - wr) + y;
+ float b = 2.0 * (u - 0.5) * (1.0 - wb) + y;
+ float g = (y - wr * r - wb * b) / wg;
+
+ // Produce black if color is outside the RGB gamut
+ if ((r < 0.0) || (r > 1.0)
+ || (g < 0.0) || (g > 1.0)
+ || (b < 0.0) || (b > 1.0)) {
+ r = g = b = 0.0;
+ }
+
+ color = ColorFract(r, g, b);
+ }
+
+ // Within to format, convert from fraction of valid range
+ // to fraction of full range
+ c1Val = (toAttrib->c1Low
+ + (float) (toAttrib->c1High - toAttrib->c1Low) * color.c1());
+ c2Val = (toAttrib->c1Low
+ + (float) (toAttrib->c2High - toAttrib->c2Low) * color.c2());
+ c3Val = (toAttrib->c1Low
+ + (float) (toAttrib->c3High - toAttrib->c3Low) * color.c3());
+ color = ColorFract((float) (c1Val - toAttrib->c1Min)
+ / (float) (toAttrib->c1Max - toAttrib->c1Min),
+ (float) (c2Val - toAttrib->c2Min)
+ / (float) (toAttrib->c2Max - toAttrib->c2Min),
+ (float) (c3Val - toAttrib->c3Min)
+ / (float) (toAttrib->c3Max - toAttrib->c3Min));
+}
+
+// TODO: Use PrintGLString, CechckGlError, and PrintEGLConfiguration
+// from libglTest
+static void printGLString(const char *name, GLenum s)
+{
+ const char *v = (const char *) glGetString(s);
+
+ if (v == NULL) {
+ testPrintI("GL %s unknown", name);
+ } else {
+ testPrintI("GL %s = %s", name, v);
+ }
+}
+
+static void checkEglError(const char* op, EGLBoolean returnVal)
+{
+ if (returnVal != EGL_TRUE) {
+ testPrintE("%s() returned %d", op, returnVal);
+ }
+
+ for (EGLint error = eglGetError(); error != EGL_SUCCESS; error
+ = eglGetError()) {
+ testPrintE("after %s() eglError %s (0x%x)",
+ op, EGLUtils::strerror(error), error);
+ }
+}
+
+static void checkGlError(const char* op)
+{
+ for (GLint error = glGetError(); error; error
+ = glGetError()) {
+ testPrintE("after %s() glError (0x%x)", op, error);
+ }
+}
+
+static void printEGLConfiguration(EGLDisplay dpy, EGLConfig config)
+{
+
+#define X(VAL) {VAL, #VAL}
+ struct {EGLint attribute; const char* name;} names[] = {
+ X(EGL_BUFFER_SIZE),
+ X(EGL_ALPHA_SIZE),
+ X(EGL_BLUE_SIZE),
+ X(EGL_GREEN_SIZE),
+ X(EGL_RED_SIZE),
+ X(EGL_DEPTH_SIZE),
+ X(EGL_STENCIL_SIZE),
+ X(EGL_CONFIG_CAVEAT),
+ X(EGL_CONFIG_ID),
+ X(EGL_LEVEL),
+ X(EGL_MAX_PBUFFER_HEIGHT),
+ X(EGL_MAX_PBUFFER_PIXELS),
+ X(EGL_MAX_PBUFFER_WIDTH),
+ X(EGL_NATIVE_RENDERABLE),
+ X(EGL_NATIVE_VISUAL_ID),
+ X(EGL_NATIVE_VISUAL_TYPE),
+ X(EGL_SAMPLES),
+ X(EGL_SAMPLE_BUFFERS),
+ X(EGL_SURFACE_TYPE),
+ X(EGL_TRANSPARENT_TYPE),
+ X(EGL_TRANSPARENT_RED_VALUE),
+ X(EGL_TRANSPARENT_GREEN_VALUE),
+ X(EGL_TRANSPARENT_BLUE_VALUE),
+ X(EGL_BIND_TO_TEXTURE_RGB),
+ X(EGL_BIND_TO_TEXTURE_RGBA),
+ X(EGL_MIN_SWAP_INTERVAL),
+ X(EGL_MAX_SWAP_INTERVAL),
+ X(EGL_LUMINANCE_SIZE),
+ X(EGL_ALPHA_MASK_SIZE),
+ X(EGL_COLOR_BUFFER_TYPE),
+ X(EGL_RENDERABLE_TYPE),
+ X(EGL_CONFORMANT),
+ };
+#undef X
+
+ for (size_t j = 0; j < sizeof(names) / sizeof(names[0]); j++) {
+ EGLint value = -1;
+ EGLint returnVal = eglGetConfigAttrib(dpy, config, names[j].attribute,
+ &value);
+ EGLint error = eglGetError();
+ if (returnVal && error == EGL_SUCCESS) {
+ testPrintI(" %s: %d (%#x)", names[j].name, value, value);
+ }
+ }
+ testPrintI("");
+}
diff --git a/opengl/tests/hwc/hwcTestLib.h b/opengl/tests/hwc/hwcTestLib.h
new file mode 100644
index 0000000..99ee608
--- /dev/null
+++ b/opengl/tests/hwc/hwcTestLib.h
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2011 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.
+ *
+ */
+
+/*
+ * Hardware Composer Test Library Header
+ */
+
+#include <sstream>
+#include <string>
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+#include <ui/FramebufferNativeWindow.h>
+#include <ui/GraphicBuffer.h>
+#include <ui/EGLUtils.h>
+
+#include <utils/Log.h>
+#include <testUtil.h>
+
+#include <hardware/hwcomposer.h>
+
+// Characteristics of known graphic formats
+const struct hwcTestGraphicFormat {
+ uint32_t format;
+ const char *desc;
+ uint32_t wMod, hMod; // Width/height mod this value must equal zero
+} hwcTestGraphicFormat[] = {
+ {HAL_PIXEL_FORMAT_RGBA_8888, "RGBA8888", 1, 1},
+ {HAL_PIXEL_FORMAT_RGBX_8888, "RGBX8888", 1, 1},
+ {HAL_PIXEL_FORMAT_RGB_888, "RGB888", 1, 1},
+ {HAL_PIXEL_FORMAT_RGB_565, "RGB565", 1, 1},
+ {HAL_PIXEL_FORMAT_BGRA_8888, "BGRA8888", 1, 1},
+ {HAL_PIXEL_FORMAT_RGBA_5551, "RGBA5551", 1, 1},
+ {HAL_PIXEL_FORMAT_RGBA_4444, "RGBA4444", 1, 1},
+ {HAL_PIXEL_FORMAT_YV12, "YV12", 2, 2},
+};
+
+// Represent RGB color as fraction of color components.
+// Each of the color components are expected in the range [0.0, 1.0]
+class ColorFract {
+ public:
+ ColorFract(): _c1(0.0), _c2(0.0), _c3(0.0) {};
+ ColorFract(float c1, float c2, float c3): _c1(c1), _c2(c2), _c3(c3) {};
+ float c1(void) const { return _c1; }
+ float c2(void) const { return _c2; }
+ float c3(void) const { return _c3; }
+
+ operator std::string();
+
+ private:
+ float _c1;
+ float _c2;
+ float _c3;
+};
+
+// Represent RGB color as fraction of color components.
+// Each of the color components are expected in the range [0.0, 1.0]
+class ColorRGB {
+ public:
+ ColorRGB(): _r(0.0), _g(0.0), _b(0.0) {};
+ ColorRGB(float f): _r(f), _g(f), _b(f) {}; // Gray
+ ColorRGB(float r, float g, float b): _r(r), _g(g), _b(b) {};
+ float r(void) const { return _r; }
+ float g(void) const { return _g; }
+ float b(void) const { return _b; }
+
+ private:
+ float _r;
+ float _g;
+ float _b;
+};
+
+// Dimension - width and height of a rectanguler area
+class HwcTestDim {
+ public:
+ HwcTestDim(): _w(0), _h(0) {};
+ HwcTestDim(uint32_t w, uint32_t h) : _w(w), _h(h) {}
+ uint32_t width(void) const { return _w; }
+ uint32_t height(void) const { return _h; }
+ void setWidth(uint32_t w) { _w = w; }
+ void setHeight(uint32_t h) { _h = h; }
+
+ operator std::string();
+ operator hwc_rect() const;
+
+ private:
+ uint32_t _w;
+ uint32_t _h;
+};
+
+// Function Prototypes
+void hwcTestInitDisplay(bool verbose, EGLDisplay *dpy, EGLSurface *surface,
+ EGLint *width, EGLint *height);
+void hwcTestOpenHwc(hwc_composer_device_t **hwcDevicePtr);
+const struct hwcTestGraphicFormat *hwcTestGraphicFormatLookup(const char *desc);
+const struct hwcTestGraphicFormat *hwcTestGraphicFormatLookup(uint32_t id);
+const char *hwcTestGraphicFormat2str(uint32_t format);
+std::string hwcTestRect2str(const struct hwc_rect& rect);
+
+hwc_layer_list_t *hwcTestCreateLayerList(size_t numLayers);
+void hwcTestFreeLayerList(hwc_layer_list_t *list);
+void hwcTestDisplayList(hwc_layer_list_t *list);
+void hwcTestDisplayListPrepareModifiable(hwc_layer_list_t *list);
+void hwcTestDisplayListHandles(hwc_layer_list_t *list);
+
+uint32_t hwcTestColor2Pixel(uint32_t format, ColorFract color, float alpha);
+void hwcTestColorConvert(uint32_t fromFormat, uint32_t toFormat,
+ ColorFract& color);
+void hwcTestSetPixel(android::GraphicBuffer *gBuf, unsigned char *buf,
+ uint32_t x, uint32_t y, uint32_t pixel);
+void hwcTestFillColor(android::GraphicBuffer *gBuf, ColorFract color,
+ float alpha);
+void hwcTestFillColorHBlend(android::GraphicBuffer *gBuf,
+ uint32_t colorFormat,
+ ColorFract startColor, ColorFract endColor);
+ColorFract hwcTestParseColor(std::istringstream& in, bool& error);
+struct hwc_rect hwcTestParseHwcRect(std::istringstream& in, bool& error);
+HwcTestDim hwcTestParseDim(std::istringstream& in, bool& error);
diff --git a/opengl/tests/hwc/hwc_stress.cpp b/opengl/tests/hwc/hwc_stress.cpp
deleted file mode 100644
index 580eb83..0000000
--- a/opengl/tests/hwc/hwc_stress.cpp
+++ /dev/null
@@ -1,1262 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- *
- */
-
-/*
- * Hardware Composer stress test
- *
- * Performs a pseudo-random (prandom) sequence of operations to the
- * Hardware Composer (HWC), for a specified number of passes or for
- * a specified period of time. By default the period of time is FLT_MAX,
- * so that the number of passes will take precedence.
- *
- * The passes are grouped together, where (pass / passesPerGroup) specifies
- * which group a particular pass is in. This causes every passesPerGroup
- * worth of sequential passes to be within the same group. Computationally
- * intensive operations are performed just once at the beginning of a group
- * of passes and then used by all the passes in that group. This is done
- * so as to increase both the average and peak rate of graphic operations,
- * by moving computationally intensive operations to the beginning of a group.
- * In particular, at the start of each group of passes a set of
- * graphic buffers are created, then used by the first and remaining
- * passes of that group of passes.
- *
- * The per-group initialization of the graphic buffers is performed
- * by a function called initFrames. This function creates an array
- * of smart pointers to the graphic buffers, in the form of a vector
- * of vectors. The array is accessed in row major order, so each
- * row is a vector of smart pointers. All the pointers of a single
- * row point to graphic buffers which use the same pixel format and
- * have the same dimension, although it is likely that each one is
- * filled with a different color. This is done so that after doing
- * the first HWC prepare then set call, subsequent set calls can
- * be made with each of the layer handles changed to a different
- * graphic buffer within the same row. Since the graphic buffers
- * in a particular row have the same pixel format and dimension,
- * additional HWC set calls can be made, without having to perform
- * an HWC prepare call.
- *
- * This test supports the following command-line options:
- *
- * -v Verbose
- * -s num Starting pass
- * -e num Ending pass
- * -p num Execute the single pass specified by num
- * -n num Number of set operations to perform after each prepare operation
- * -t float Maximum time in seconds to execute the test
- * -d float Delay in seconds performed after each set operation
- * -D float Delay in seconds performed after the last pass is executed
- *
- * Typically the test is executed for a large range of passes. By default
- * passes 0 through 99999 (100,000 passes) are executed. Although this test
- * does not validate the generated image, at times it is useful to reexecute
- * a particular pass and leave the displayed image on the screen for an
- * extended period of time. This can be done either by setting the -s
- * and -e options to the desired pass, along with a large value for -D.
- * This can also be done via the -p option, again with a large value for
- * the -D options.
- *
- * So far this test only contains code to create graphic buffers with
- * a continuous solid color. Although this test is unable to validate the
- * image produced, any image that contains other than rectangles of a solid
- * color are incorrect. Note that the rectangles may use a transparent
- * color and have a blending operation that causes the color in overlapping
- * rectangles to be mixed. In such cases the overlapping portions may have
- * a different color from the rest of the rectangle.
- */
-
-#include <algorithm>
-#include <assert.h>
-#include <cerrno>
-#include <cmath>
-#include <cstdlib>
-#include <ctime>
-#include <libgen.h>
-#include <sched.h>
-#include <sstream>
-#include <stdint.h>
-#include <string.h>
-#include <unistd.h>
-#include <vector>
-
-#include <arpa/inet.h> // For ntohl() and htonl()
-
-#include <sys/syscall.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-
-#include <EGL/egl.h>
-#include <EGL/eglext.h>
-#include <GLES2/gl2.h>
-#include <GLES2/gl2ext.h>
-
-#include <ui/FramebufferNativeWindow.h>
-#include <ui/GraphicBuffer.h>
-#include <ui/EGLUtils.h>
-
-#define LOG_TAG "hwcStressTest"
-#include <utils/Log.h>
-#include <testUtil.h>
-
-#include <hardware/hwcomposer.h>
-
-using namespace std;
-using namespace android;
-
-const float maxSizeRatio = 1.3; // Graphic buffers can be upto this munch
- // larger than the default screen size
-const unsigned int passesPerGroup = 10; // A group of passes all use the same
- // graphic buffers
-
-// Ratios at which rare and frequent conditions should be produced
-const float rareRatio = 0.1;
-const float freqRatio = 0.9;
-
-// Defaults for command-line options
-const bool defaultVerbose = false;
-const unsigned int defaultStartPass = 0;
-const unsigned int defaultEndPass = 99999;
-const unsigned int defaultPerPassNumSet = 10;
-const float defaultPerSetDelay = 0.0; // Default delay after each set
- // operation. Default delay of
- // zero used so as to perform the
- // the set operations as quickly
- // as possible.
-const float defaultEndDelay = 2.0; // Default delay between completion of
- // final pass and restart of framework
-const float defaultDuration = FLT_MAX; // A fairly long time, so that
- // range of passes will have
- // precedence
-
-// Command-line option settings
-static bool verbose = defaultVerbose;
-static unsigned int startPass = defaultStartPass;
-static unsigned int endPass = defaultEndPass;
-static unsigned int numSet = defaultPerPassNumSet;
-static float perSetDelay = defaultPerSetDelay;
-static float endDelay = defaultEndDelay;
-static float duration = defaultDuration;
-
-// Command-line mutual exclusion detection flags.
-// Corresponding flag set true once an option is used.
-bool eFlag, sFlag, pFlag;
-
-#define MAXSTR 100
-#define MAXCMD 200
-#define BITSPERBYTE 8 // TODO: Obtain from <values.h>, once
- // it has been added
-
-#define CMD_STOP_FRAMEWORK "stop 2>&1"
-#define CMD_START_FRAMEWORK "start 2>&1"
-
-#define NUMA(a) (sizeof(a) / sizeof(a [0]))
-#define MEMCLR(addr, size) do { \
- memset((addr), 0, (size)); \
- } while (0)
-
-// Represent RGB color as fraction of color components.
-// Each of the color components are expected in the range [0.0, 1.0]
-class RGBColor {
- public:
- RGBColor(): _r(0.0), _g(0.0), _b(0.0) {};
- RGBColor(float f): _r(f), _g(f), _b(f) {}; // Gray
- RGBColor(float r, float g, float b): _r(r), _g(g), _b(b) {};
- float r(void) const { return _r; }
- float g(void) const { return _g; }
- float b(void) const { return _b; }
-
- private:
- float _r;
- float _g;
- float _b;
-};
-
-// Represent YUV color as fraction of color components.
-// Each of the color components are expected in the range [0.0, 1.0]
-class YUVColor {
- public:
- YUVColor(): _y(0.0), _u(0.0), _v(0.0) {};
- YUVColor(float f): _y(f), _u(0.0), _v(0.0) {}; // Gray
- YUVColor(float y, float u, float v): _y(y), _u(u), _v(v) {};
- float y(void) const { return _y; }
- float u(void) const { return _u; }
- float v(void) const { return _v; }
-
- private:
- float _y;
- float _u;
- float _v;
-};
-
-// File scope constants
-static const struct graphicFormat {
- unsigned int format;
- const char *desc;
- unsigned int wMod, hMod; // Width/height mod this value must equal zero
-} graphicFormat[] = {
- {HAL_PIXEL_FORMAT_RGBA_8888, "RGBA8888", 1, 1},
- {HAL_PIXEL_FORMAT_RGBX_8888, "RGBX8888", 1, 1},
- {HAL_PIXEL_FORMAT_RGB_888, "RGB888", 1, 1},
- {HAL_PIXEL_FORMAT_RGB_565, "RGB565", 1, 1},
- {HAL_PIXEL_FORMAT_BGRA_8888, "BGRA8888", 1, 1},
- {HAL_PIXEL_FORMAT_RGBA_5551, "RGBA5551", 1, 1},
- {HAL_PIXEL_FORMAT_RGBA_4444, "RGBA4444", 1, 1},
- {HAL_PIXEL_FORMAT_YV12, "YV12", 2, 2},
-};
-const unsigned int blendingOps[] = {
- HWC_BLENDING_NONE,
- HWC_BLENDING_PREMULT,
- HWC_BLENDING_COVERAGE,
-};
-const unsigned int layerFlags[] = {
- HWC_SKIP_LAYER,
-};
-const vector<unsigned int> vecLayerFlags(layerFlags,
- layerFlags + NUMA(layerFlags));
-
-const unsigned int transformFlags[] = {
- HWC_TRANSFORM_FLIP_H,
- HWC_TRANSFORM_FLIP_V,
- HWC_TRANSFORM_ROT_90,
- // ROT_180 & ROT_270 intentionally not listed, because they
- // they are formed from combinations of the flags already listed.
-};
-const vector<unsigned int> vecTransformFlags(transformFlags,
- transformFlags + NUMA(transformFlags));
-
-// File scope globals
-static const int texUsage = GraphicBuffer::USAGE_HW_TEXTURE |
- GraphicBuffer::USAGE_SW_WRITE_RARELY;
-static hw_module_t const *hwcModule;
-static hwc_composer_device_t *hwcDevice;
-static vector <vector <sp<GraphicBuffer> > > frames;
-static EGLDisplay dpy;
-static EGLContext context;
-static EGLSurface surface;
-static EGLint width, height;
-
-// File scope prototypes
-static void execCmd(const char *cmd);
-static void checkEglError(const char* op, EGLBoolean returnVal = EGL_TRUE);
-static void checkGlError(const char* op);
-static void printEGLConfiguration(EGLDisplay dpy, EGLConfig config);
-static void printGLString(const char *name, GLenum s);
-static hwc_layer_list_t *createLayerList(size_t numLayers);
-static void freeLayerList(hwc_layer_list_t *list);
-static void fillColor(GraphicBuffer *gBuf, RGBColor color, float trans);
-static void fillColor(GraphicBuffer *gBuf, YUVColor color, float trans);
-void init(void);
-void initFrames(unsigned int seed);
-void displayList(hwc_layer_list_t *list);
-void displayListPrepareModifiable(hwc_layer_list_t *list);
-void displayListHandles(hwc_layer_list_t *list);
-const char *graphicFormat2str(unsigned int format);
-template <class T> vector<T> vectorRandSelect(const vector<T>& vec, size_t num);
-template <class T> T vectorOr(const vector<T>& vec);
-
-/*
- * Main
- *
- * Performs the following high-level sequence of operations:
- *
- * 1. Command-line parsing
- *
- * 2. Initialization
- *
- * 3. For each pass:
- *
- * a. If pass is first pass or in a different group from the
- * previous pass, initialize the array of graphic buffers.
- *
- * b. Create a HWC list with room to specify a prandomly
- * selected number of layers.
- *
- * c. Select a subset of the rows from the graphic buffer array,
- * such that there is a unique row to be used for each
- * of the layers in the HWC list.
- *
- * d. Prandomly fill in the HWC list with handles
- * selected from any of the columns of the selected row.
- *
- * e. Pass the populated list to the HWC prepare call.
- *
- * f. Pass the populated list to the HWC set call.
- *
- * g. If additional set calls are to be made, then for each
- * additional set call, select a new set of handles and
- * perform the set call.
- */
-int
-main(int argc, char *argv[])
-{
- int rv, opt;
- char *chptr;
- unsigned int pass;
- char cmd[MAXCMD];
- struct timeval startTime, currentTime, delta;
-
- testSetLogCatTag(LOG_TAG);
-
- // Parse command line arguments
- while ((opt = getopt(argc, argv, "vp:d:D:n:s:e:t:?h")) != -1) {
- switch (opt) {
- case 'd': // Delay after each set operation
- perSetDelay = strtod(optarg, &chptr);
- if ((*chptr != '\0') || (perSetDelay < 0.0)) {
- testPrintE("Invalid command-line specified per pass delay of: "
- "%s", optarg);
- exit(1);
- }
- break;
-
- case 'D': // End of test delay
- // Delay between completion of final pass and restart
- // of framework
- endDelay = strtod(optarg, &chptr);
- if ((*chptr != '\0') || (endDelay < 0.0)) {
- testPrintE("Invalid command-line specified end of test delay "
- "of: %s", optarg);
- exit(2);
- }
- break;
-
- case 't': // Duration
- duration = strtod(optarg, &chptr);
- if ((*chptr != '\0') || (duration < 0.0)) {
- testPrintE("Invalid command-line specified duration of: %s",
- optarg);
- exit(3);
- }
- break;
-
- case 'n': // Num set operations per pass
- numSet = strtoul(optarg, &chptr, 10);
- if (*chptr != '\0') {
- testPrintE("Invalid command-line specified num set per pass "
- "of: %s", optarg);
- exit(4);
- }
- break;
-
- case 's': // Starting Pass
- sFlag = true;
- if (pFlag) {
- testPrintE("Invalid combination of command-line options.");
- testPrintE(" The -p option is mutually exclusive from the");
- testPrintE(" -s and -e options.");
- exit(5);
- }
- startPass = strtoul(optarg, &chptr, 10);
- if (*chptr != '\0') {
- testPrintE("Invalid command-line specified starting pass "
- "of: %s", optarg);
- exit(6);
- }
- break;
-
- case 'e': // Ending Pass
- eFlag = true;
- if (pFlag) {
- testPrintE("Invalid combination of command-line options.");
- testPrintE(" The -p option is mutually exclusive from the");
- testPrintE(" -s and -e options.");
- exit(7);
- }
- endPass = strtoul(optarg, &chptr, 10);
- if (*chptr != '\0') {
- testPrintE("Invalid command-line specified ending pass "
- "of: %s", optarg);
- exit(8);
- }
- break;
-
- case 'p': // Run a single specified pass
- pFlag = true;
- if (sFlag || eFlag) {
- testPrintE("Invalid combination of command-line options.");
- testPrintE(" The -p option is mutually exclusive from the");
- testPrintE(" -s and -e options.");
- exit(9);
- }
- startPass = endPass = strtoul(optarg, &chptr, 10);
- if (*chptr != '\0') {
- testPrintE("Invalid command-line specified pass of: %s",
- optarg);
- exit(10);
- }
- break;
-
- case 'v': // Verbose
- verbose = true;
- break;
-
- case 'h': // Help
- case '?':
- default:
- testPrintE(" %s [options]", basename(argv[0]));
- testPrintE(" options:");
- testPrintE(" -p Execute specified pass");
- testPrintE(" -s Starting pass");
- testPrintE(" -e Ending pass");
- testPrintE(" -t Duration");
- testPrintE(" -d Delay after each set operation");
- testPrintE(" -D End of test delay");
- testPrintE(" -n Num set operations per pass");
- testPrintE(" -v Verbose");
- exit(((optopt == 0) || (optopt == '?')) ? 0 : 11);
- }
- }
- if (endPass < startPass) {
- testPrintE("Unexpected ending pass before starting pass");
- testPrintE(" startPass: %u endPass: %u", startPass, endPass);
- exit(12);
- }
- if (argc != optind) {
- testPrintE("Unexpected command-line postional argument");
- testPrintE(" %s [-s start_pass] [-e end_pass] [-t duration]",
- basename(argv[0]));
- exit(13);
- }
- testPrintI("duration: %g", duration);
- testPrintI("startPass: %u", startPass);
- testPrintI("endPass: %u", endPass);
- testPrintI("numSet: %u", numSet);
-
- // Stop framework
- rv = snprintf(cmd, sizeof(cmd), "%s", CMD_STOP_FRAMEWORK);
- if (rv >= (signed) sizeof(cmd) - 1) {
- testPrintE("Command too long for: %s", CMD_STOP_FRAMEWORK);
- exit(14);
- }
- execCmd(cmd);
- testDelay(1.0); // TODO - needs means to query whether asyncronous stop
- // framework operation has completed. For now, just wait
- // a long time.
-
- init();
-
- // For each pass
- gettimeofday(&startTime, NULL);
- for (pass = startPass; pass <= endPass; pass++) {
- // Stop if duration of work has already been performed
- gettimeofday(¤tTime, NULL);
- delta = tvDelta(&startTime, ¤tTime);
- if (tv2double(&delta) > duration) { break; }
-
- // Regenerate a new set of test frames when this pass is
- // either the first pass or is in a different group then
- // the previous pass. A group of passes are passes that
- // all have the same quotient when their pass number is
- // divided by passesPerGroup.
- if ((pass == startPass)
- || ((pass / passesPerGroup) != ((pass - 1) / passesPerGroup))) {
- initFrames(pass / passesPerGroup);
- }
-
- testPrintI("==== Starting pass: %u", pass);
-
- // Cause deterministic sequence of prandom numbers to be
- // generated for this pass.
- srand48(pass);
-
- hwc_layer_list_t *list;
- list = createLayerList(testRandMod(frames.size()) + 1);
- if (list == NULL) {
- testPrintE("createLayerList failed");
- exit(20);
- }
-
- // Prandomly select a subset of frames to be used by this pass.
- vector <vector <sp<GraphicBuffer> > > selectedFrames;
- selectedFrames = vectorRandSelect(frames, list->numHwLayers);
-
- // Any transform tends to create a layer that the hardware
- // composer is unable to support and thus has to leave for
- // SurfaceFlinger. Place heavy bias on specifying no transforms.
- bool noTransform = testRandFract() > rareRatio;
-
- for (unsigned int n1 = 0; n1 < list->numHwLayers; n1++) {
- unsigned int idx = testRandMod(selectedFrames[n1].size());
- sp<GraphicBuffer> gBuf = selectedFrames[n1][idx];
- hwc_layer_t *layer = &list->hwLayers[n1];
- layer->handle = gBuf->handle;
-
- layer->blending = blendingOps[testRandMod(NUMA(blendingOps))];
- layer->flags = (testRandFract() > rareRatio) ? 0
- : vectorOr(vectorRandSelect(vecLayerFlags,
- testRandMod(vecLayerFlags.size() + 1)));
- layer->transform = (noTransform || testRandFract() > rareRatio) ? 0
- : vectorOr(vectorRandSelect(vecTransformFlags,
- testRandMod(vecTransformFlags.size() + 1)));
- layer->sourceCrop.left = testRandMod(gBuf->getWidth());
- layer->sourceCrop.top = testRandMod(gBuf->getHeight());
- layer->sourceCrop.right = layer->sourceCrop.left
- + testRandMod(gBuf->getWidth() - layer->sourceCrop.left) + 1;
- layer->sourceCrop.bottom = layer->sourceCrop.top
- + testRandMod(gBuf->getHeight() - layer->sourceCrop.top) + 1;
- layer->displayFrame.left = testRandMod(width);
- layer->displayFrame.top = testRandMod(height);
- layer->displayFrame.right = layer->displayFrame.left
- + testRandMod(width - layer->displayFrame.left) + 1;
- layer->displayFrame.bottom = layer->displayFrame.top
- + testRandMod(height - layer->displayFrame.top) + 1;
-
- // Increase the frequency that a scale factor of 1.0 from
- // the sourceCrop to displayFrame occurs. This is the
- // most common scale factor used by applications and would
- // be rarely produced by this stress test without this
- // logic.
- if (testRandFract() <= freqRatio) {
- // Only change to scale factor to 1.0 if both the
- // width and height will fit.
- int sourceWidth = layer->sourceCrop.right
- - layer->sourceCrop.left;
- int sourceHeight = layer->sourceCrop.bottom
- - layer->sourceCrop.top;
- if (((layer->displayFrame.left + sourceWidth) <= width)
- && ((layer->displayFrame.top + sourceHeight) <= height)) {
- layer->displayFrame.right = layer->displayFrame.left
- + sourceWidth;
- layer->displayFrame.bottom = layer->displayFrame.top
- + sourceHeight;
- }
- }
-
- layer->visibleRegionScreen.numRects = 1;
- layer->visibleRegionScreen.rects = &layer->displayFrame;
- }
-
- // Perform prepare operation
- if (verbose) { testPrintI("Prepare:"); displayList(list); }
- hwcDevice->prepare(hwcDevice, list);
- if (verbose) {
- testPrintI("Post Prepare:");
- displayListPrepareModifiable(list);
- }
-
- // Turn off the geometry changed flag
- list->flags &= ~HWC_GEOMETRY_CHANGED;
-
- // Perform the set operation(s)
- if (verbose) {testPrintI("Set:"); }
- for (unsigned int n1 = 0; n1 < numSet; n1++) {
- if (verbose) {displayListHandles(list); }
- hwcDevice->set(hwcDevice, dpy, surface, list);
-
- // Prandomly select a new set of handles
- for (unsigned int n1 = 0; n1 < list->numHwLayers; n1++) {
- unsigned int idx = testRandMod(selectedFrames[n1].size());
- sp<GraphicBuffer> gBuf = selectedFrames[n1][idx];
- hwc_layer_t *layer = &list->hwLayers[n1];
- layer->handle = (native_handle_t *) gBuf->handle;
- }
-
- testDelay(perSetDelay);
- }
-
-
- freeLayerList(list);
- testPrintI("==== Completed pass: %u", pass);
- }
-
- testDelay(endDelay);
-
- // Start framework
- rv = snprintf(cmd, sizeof(cmd), "%s", CMD_START_FRAMEWORK);
- if (rv >= (signed) sizeof(cmd) - 1) {
- testPrintE("Command too long for: %s", CMD_START_FRAMEWORK);
- exit(21);
- }
- execCmd(cmd);
-
- testPrintI("Successfully completed %u passes", pass - startPass);
-
- return 0;
-}
-
-/*
- * Execute Command
- *
- * Executes the command pointed to by cmd. Output from the
- * executed command is captured and sent to LogCat Info. Once
- * the command has finished execution, it's exit status is captured
- * and checked for an exit status of zero. Any other exit status
- * causes diagnostic information to be printed and an immediate
- * testcase failure.
- */
-static void execCmd(const char *cmd)
-{
- FILE *fp;
- int rv;
- int status;
- char str[MAXSTR];
-
- // Display command to be executed
- testPrintI("cmd: %s", cmd);
-
- // Execute the command
- fflush(stdout);
- if ((fp = popen(cmd, "r")) == NULL) {
- testPrintE("execCmd popen failed, errno: %i", errno);
- exit(30);
- }
-
- // Obtain and display each line of output from the executed command
- while (fgets(str, sizeof(str), fp) != NULL) {
- if ((strlen(str) > 1) && (str[strlen(str) - 1] == '\n')) {
- str[strlen(str) - 1] = '\0';
- }
- testPrintI(" out: %s", str);
- }
-
- // Obtain and check return status of executed command.
- // Fail on non-zero exit status
- status = pclose(fp);
- if (!(WIFEXITED(status) && (WEXITSTATUS(status) == 0))) {
- testPrintE("Unexpected command failure");
- testPrintE(" status: %#x", status);
- if (WIFEXITED(status)) {
- testPrintE("WEXITSTATUS: %i", WEXITSTATUS(status));
- }
- if (WIFSIGNALED(status)) {
- testPrintE("WTERMSIG: %i", WTERMSIG(status));
- }
- exit(31);
- }
-}
-
-static void checkEglError(const char* op, EGLBoolean returnVal) {
- if (returnVal != EGL_TRUE) {
- testPrintE("%s() returned %d", op, returnVal);
- }
-
- for (EGLint error = eglGetError(); error != EGL_SUCCESS; error
- = eglGetError()) {
- testPrintE("after %s() eglError %s (0x%x)",
- op, EGLUtils::strerror(error), error);
- }
-}
-
-static void checkGlError(const char* op) {
- for (GLint error = glGetError(); error; error
- = glGetError()) {
- testPrintE("after %s() glError (0x%x)", op, error);
- }
-}
-
-static void printEGLConfiguration(EGLDisplay dpy, EGLConfig config) {
-
-#define X(VAL) {VAL, #VAL}
- struct {EGLint attribute; const char* name;} names[] = {
- X(EGL_BUFFER_SIZE),
- X(EGL_ALPHA_SIZE),
- X(EGL_BLUE_SIZE),
- X(EGL_GREEN_SIZE),
- X(EGL_RED_SIZE),
- X(EGL_DEPTH_SIZE),
- X(EGL_STENCIL_SIZE),
- X(EGL_CONFIG_CAVEAT),
- X(EGL_CONFIG_ID),
- X(EGL_LEVEL),
- X(EGL_MAX_PBUFFER_HEIGHT),
- X(EGL_MAX_PBUFFER_PIXELS),
- X(EGL_MAX_PBUFFER_WIDTH),
- X(EGL_NATIVE_RENDERABLE),
- X(EGL_NATIVE_VISUAL_ID),
- X(EGL_NATIVE_VISUAL_TYPE),
- X(EGL_SAMPLES),
- X(EGL_SAMPLE_BUFFERS),
- X(EGL_SURFACE_TYPE),
- X(EGL_TRANSPARENT_TYPE),
- X(EGL_TRANSPARENT_RED_VALUE),
- X(EGL_TRANSPARENT_GREEN_VALUE),
- X(EGL_TRANSPARENT_BLUE_VALUE),
- X(EGL_BIND_TO_TEXTURE_RGB),
- X(EGL_BIND_TO_TEXTURE_RGBA),
- X(EGL_MIN_SWAP_INTERVAL),
- X(EGL_MAX_SWAP_INTERVAL),
- X(EGL_LUMINANCE_SIZE),
- X(EGL_ALPHA_MASK_SIZE),
- X(EGL_COLOR_BUFFER_TYPE),
- X(EGL_RENDERABLE_TYPE),
- X(EGL_CONFORMANT),
- };
-#undef X
-
- for (size_t j = 0; j < sizeof(names) / sizeof(names[0]); j++) {
- EGLint value = -1;
- EGLint returnVal = eglGetConfigAttrib(dpy, config, names[j].attribute, &value);
- EGLint error = eglGetError();
- if (returnVal && error == EGL_SUCCESS) {
- testPrintI(" %s: %d (%#x)", names[j].name, value, value);
- }
- }
- testPrintI("");
-}
-
-static void printGLString(const char *name, GLenum s)
-{
- const char *v = (const char *) glGetString(s);
-
- if (v == NULL) {
- testPrintI("GL %s unknown", name);
- } else {
- testPrintI("GL %s = %s", name, v);
- }
-}
-
-/*
- * createLayerList
- * dynamically creates layer list with numLayers worth
- * of hwLayers entries.
- */
-static hwc_layer_list_t *createLayerList(size_t numLayers)
-{
- hwc_layer_list_t *list;
-
- size_t size = sizeof(hwc_layer_list) + numLayers * sizeof(hwc_layer_t);
- if ((list = (hwc_layer_list_t *) calloc(1, size)) == NULL) {
- return NULL;
- }
- list->flags = HWC_GEOMETRY_CHANGED;
- list->numHwLayers = numLayers;
-
- return list;
-}
-
-/*
- * freeLayerList
- * Frees memory previous allocated via createLayerList().
- */
-static void freeLayerList(hwc_layer_list_t *list)
-{
- free(list);
-}
-
-static void fillColor(GraphicBuffer *gBuf, RGBColor color, float trans)
-{
- unsigned char* buf = NULL;
- status_t err;
- uint32_t pixel;
-
- // RGB 2 YUV conversion ratios
- const struct rgb2yuvRatios {
- int format;
- float weightRed;
- float weightBlu;
- float weightGrn;
- } rgb2yuvRatios[] = {
- { HAL_PIXEL_FORMAT_YV12, 0.299, 0.114, 0.587 },
- };
-
- const struct rgbAttrib {
- int format;
- bool hostByteOrder;
- size_t bytes;
- size_t rOffset;
- size_t rSize;
- size_t gOffset;
- size_t gSize;
- size_t bOffset;
- size_t bSize;
- size_t aOffset;
- size_t aSize;
- } rgbAttributes[] = {
- {HAL_PIXEL_FORMAT_RGBA_8888, false, 4, 0, 8, 8, 8, 16, 8, 24, 8},
- {HAL_PIXEL_FORMAT_RGBX_8888, false, 4, 0, 8, 8, 8, 16, 8, 0, 0},
- {HAL_PIXEL_FORMAT_RGB_888, false, 3, 0, 8, 8, 8, 16, 8, 0, 0},
- {HAL_PIXEL_FORMAT_RGB_565, true, 2, 0, 5, 5, 6, 11, 5, 0, 0},
- {HAL_PIXEL_FORMAT_BGRA_8888, false, 4, 16, 8, 8, 8, 0, 8, 24, 8},
- {HAL_PIXEL_FORMAT_RGBA_5551, true , 2, 0, 5, 5, 5, 10, 5, 15, 1},
- {HAL_PIXEL_FORMAT_RGBA_4444, false, 2, 12, 4, 0, 4, 4, 4, 8, 4},
- };
-
- // If YUV format, convert color and pass work to YUV color fill
- for (unsigned int n1 = 0; n1 < NUMA(rgb2yuvRatios); n1++) {
- if (gBuf->getPixelFormat() == rgb2yuvRatios[n1].format) {
- float wr = rgb2yuvRatios[n1].weightRed;
- float wb = rgb2yuvRatios[n1].weightBlu;
- float wg = rgb2yuvRatios[n1].weightGrn;
- float y = wr * color.r() + wb * color.b() + wg * color.g();
- float u = 0.5 * ((color.b() - y) / (1 - wb)) + 0.5;
- float v = 0.5 * ((color.r() - y) / (1 - wr)) + 0.5;
- YUVColor yuvColor(y, u, v);
- fillColor(gBuf, yuvColor, trans);
- return;
- }
- }
-
- const struct rgbAttrib *attrib;
- for (attrib = rgbAttributes; attrib < rgbAttributes + NUMA(rgbAttributes);
- attrib++) {
- if (attrib->format == gBuf->getPixelFormat()) { break; }
- }
- if (attrib >= rgbAttributes + NUMA(rgbAttributes)) {
- testPrintE("fillColor rgb unsupported format of: %u",
- gBuf->getPixelFormat());
- exit(50);
- }
-
- pixel = htonl((uint32_t) (((1 << attrib->rSize) - 1) * color.r())
- << ((sizeof(pixel) * BITSPERBYTE)
- - (attrib->rOffset + attrib->rSize)));
- pixel |= htonl((uint32_t) (((1 << attrib->gSize) - 1) * color.g())
- << ((sizeof(pixel) * BITSPERBYTE)
- - (attrib->gOffset + attrib->gSize)));
- pixel |= htonl((uint32_t) (((1 << attrib->bSize) - 1) * color.b())
- << ((sizeof(pixel) * BITSPERBYTE)
- - (attrib->bOffset + attrib->bSize)));
- if (attrib->aSize) {
- pixel |= htonl((uint32_t) (((1 << attrib->aSize) - 1) * trans)
- << ((sizeof(pixel) * BITSPERBYTE)
- - (attrib->aOffset + attrib->aSize)));
- }
- if (attrib->hostByteOrder) {
- pixel = ntohl(pixel);
- pixel >>= sizeof(pixel) * BITSPERBYTE - attrib->bytes * BITSPERBYTE;
- }
-
- err = gBuf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&buf));
- if (err != 0) {
- testPrintE("fillColor rgb lock failed: %d", err);
- exit(51);
- }
-
- for (unsigned int row = 0; row < gBuf->getHeight(); row++) {
- for (unsigned int col = 0; col < gBuf->getWidth(); col++) {
- memmove(buf, &pixel, attrib->bytes);
- buf += attrib->bytes;
- }
- for (unsigned int pad = 0;
- pad < (gBuf->getStride() - gBuf->getWidth()) * attrib->bytes;
- pad++) {
- *buf++ = testRandMod(256);
- }
- }
-
- err = gBuf->unlock();
- if (err != 0) {
- testPrintE("fillColor rgb unlock failed: %d", err);
- exit(52);
- }
-}
-
-static void fillColor(GraphicBuffer *gBuf, YUVColor color, float trans)
-{
- unsigned char* buf = NULL;
- status_t err;
- unsigned int width = gBuf->getWidth();
- unsigned int height = gBuf->getHeight();
-
- const struct yuvAttrib {
- int format;
- bool planar;
- unsigned int uSubSampX;
- unsigned int uSubSampY;
- unsigned int vSubSampX;
- unsigned int vSubSampY;
- } yuvAttributes[] = {
- { HAL_PIXEL_FORMAT_YV12, true, 2, 2, 2, 2},
- };
-
- const struct yuvAttrib *attrib;
- for (attrib = yuvAttributes; attrib < yuvAttributes + NUMA(yuvAttributes);
- attrib++) {
- if (attrib->format == gBuf->getPixelFormat()) { break; }
- }
- if (attrib >= yuvAttributes + NUMA(yuvAttributes)) {
- testPrintE("fillColor yuv unsupported format of: %u",
- gBuf->getPixelFormat());
- exit(60);
- }
-
- assert(attrib->planar == true); // So far, only know how to handle planar
-
- err = gBuf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&buf));
- if (err != 0) {
- testPrintE("fillColor lock failed: %d", err);
- exit(61);
- }
-
- // Fill in Y component
- for (unsigned int row = 0; row < height; row++) {
- for (unsigned int col = 0; col < width; col++) {
- *buf++ = 255 * color.y();
- }
- for (unsigned int pad = 0; pad < gBuf->getStride() - gBuf->getWidth();
- pad++) {
- *buf++ = testRandMod(256);
- }
- }
-
- // Fill in U component
- for (unsigned int row = 0; row < height; row += attrib->uSubSampY) {
- for (unsigned int col = 0; col < width; col += attrib->uSubSampX) {
- *buf++ = 255 * color.u();
- }
- for (unsigned int pad = 0; pad < gBuf->getStride() - gBuf->getWidth();
- pad += attrib->uSubSampX) {
- *buf++ = testRandMod(256);
- }
- }
-
- // Fill in V component
- for (unsigned int row = 0; row < height; row += attrib->vSubSampY) {
- for (unsigned int col = 0; col < width; col += attrib->vSubSampX) {
- *buf++ = 255 * color.v();
- }
- for (unsigned int pad = 0; pad < gBuf->getStride() - gBuf->getWidth();
- pad += attrib->vSubSampX) {
- *buf++ = testRandMod(256);
- }
- }
-
- err = gBuf->unlock();
- if (err != 0) {
- testPrintE("fillColor unlock failed: %d", err);
- exit(62);
- }
-}
-
-void init(void)
-{
- int rv;
-
- EGLBoolean returnValue;
- EGLConfig myConfig = {0};
- EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
- EGLint sConfigAttribs[] = {
- EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
- EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
- EGL_NONE };
- EGLint majorVersion, minorVersion;
-
- checkEglError("<init>");
- dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
- checkEglError("eglGetDisplay");
- if (dpy == EGL_NO_DISPLAY) {
- testPrintE("eglGetDisplay returned EGL_NO_DISPLAY");
- exit(70);
- }
-
- returnValue = eglInitialize(dpy, &majorVersion, &minorVersion);
- checkEglError("eglInitialize", returnValue);
- testPrintI("EGL version %d.%d", majorVersion, minorVersion);
- if (returnValue != EGL_TRUE) {
- testPrintE("eglInitialize failed");
- exit(71);
- }
-
- EGLNativeWindowType window = android_createDisplaySurface();
- if (window == NULL) {
- testPrintE("android_createDisplaySurface failed");
- exit(72);
- }
- returnValue = EGLUtils::selectConfigForNativeWindow(dpy,
- sConfigAttribs, window, &myConfig);
- if (returnValue) {
- testPrintE("EGLUtils::selectConfigForNativeWindow() returned %d",
- returnValue);
- exit(73);
- }
- checkEglError("EGLUtils::selectConfigForNativeWindow");
-
- testPrintI("Chose this configuration:");
- printEGLConfiguration(dpy, myConfig);
-
- surface = eglCreateWindowSurface(dpy, myConfig, window, NULL);
- checkEglError("eglCreateWindowSurface");
- if (surface == EGL_NO_SURFACE) {
- testPrintE("gelCreateWindowSurface failed.");
- exit(74);
- }
-
- context = eglCreateContext(dpy, myConfig, EGL_NO_CONTEXT, contextAttribs);
- checkEglError("eglCreateContext");
- if (context == EGL_NO_CONTEXT) {
- testPrintE("eglCreateContext failed");
- exit(75);
- }
- returnValue = eglMakeCurrent(dpy, surface, surface, context);
- checkEglError("eglMakeCurrent", returnValue);
- if (returnValue != EGL_TRUE) {
- testPrintE("eglMakeCurrent failed");
- exit(76);
- }
- eglQuerySurface(dpy, surface, EGL_WIDTH, &width);
- checkEglError("eglQuerySurface");
- eglQuerySurface(dpy, surface, EGL_HEIGHT, &height);
- checkEglError("eglQuerySurface");
-
- testPrintI("Window dimensions: %d x %d", width, height);
-
- printGLString("Version", GL_VERSION);
- printGLString("Vendor", GL_VENDOR);
- printGLString("Renderer", GL_RENDERER);
- printGLString("Extensions", GL_EXTENSIONS);
-
- if ((rv = hw_get_module(HWC_HARDWARE_MODULE_ID, &hwcModule)) != 0) {
- testPrintE("hw_get_module failed, rv: %i", rv);
- errno = -rv;
- perror(NULL);
- exit(77);
- }
- if ((rv = hwc_open(hwcModule, &hwcDevice)) != 0) {
- testPrintE("hwc_open failed, rv: %i", rv);
- errno = -rv;
- perror(NULL);
- exit(78);
- }
-
- testPrintI("");
-}
-
-/*
- * Initialize Frames
- *
- * Creates an array of graphic buffers, within the global variable
- * named frames. The graphic buffers are contained within a vector of
- * vectors. All the graphic buffers in a particular row are of the same
- * format and dimension. Each graphic buffer is uniformly filled with a
- * prandomly selected color. It is likely that each buffer, even
- * in the same row, will be filled with a unique color.
- */
-void initFrames(unsigned int seed)
-{
- int rv;
- const size_t maxRows = 5;
- const size_t minCols = 2; // Need at least double buffering
- const size_t maxCols = 4; // One more than triple buffering
-
- if (verbose) { testPrintI("initFrames seed: %u", seed); }
- srand48(seed);
- size_t rows = testRandMod(maxRows) + 1;
-
- frames.clear();
- frames.resize(rows);
-
- for (unsigned int row = 0; row < rows; row++) {
- // All frames within a row have to have the same format and
- // dimensions. Width and height need to be >= 1.
- unsigned int formatIdx = testRandMod(NUMA(graphicFormat));
- const struct graphicFormat *formatPtr = &graphicFormat[formatIdx];
- int format = formatPtr->format;
-
- // Pick width and height, which must be >= 1 and the size
- // mod the wMod/hMod value must be equal to 0.
- size_t w = (width * maxSizeRatio) * testRandFract();
- size_t h = (height * maxSizeRatio) * testRandFract();
- w = max(1u, w);
- h = max(1u, h);
- if ((w % formatPtr->wMod) != 0) {
- w += formatPtr->wMod - (w % formatPtr->wMod);
- }
- if ((h % formatPtr->hMod) != 0) {
- h += formatPtr->hMod - (h % formatPtr->hMod);
- }
- if (verbose) {
- testPrintI(" frame %u width: %u height: %u format: %u %s",
- row, w, h, format, graphicFormat2str(format));
- }
-
- size_t cols = testRandMod((maxCols + 1) - minCols) + minCols;
- frames[row].resize(cols);
- for (unsigned int col = 0; col < cols; col++) {
- RGBColor color(testRandFract(), testRandFract(), testRandFract());
- float transp = testRandFract();
-
- frames[row][col] = new GraphicBuffer(w, h, format, texUsage);
- if ((rv = frames[row][col]->initCheck()) != NO_ERROR) {
- testPrintE("GraphicBuffer initCheck failed, rv: %i", rv);
- testPrintE(" frame %u width: %u height: %u format: %u %s",
- row, w, h, format, graphicFormat2str(format));
- exit(80);
- }
-
- fillColor(frames[row][col].get(), color, transp);
- if (verbose) {
- testPrintI(" buf: %p handle: %p color: <%f, %f, %f> "
- "transp: %f",
- frames[row][col].get(), frames[row][col]->handle,
- color.r(), color.g(), color.b(), transp);
- }
- }
- }
-}
-
-void displayList(hwc_layer_list_t *list)
-{
- testPrintI(" flags: %#x%s", list->flags,
- (list->flags & HWC_GEOMETRY_CHANGED) ? " GEOMETRY_CHANGED" : "");
- testPrintI(" numHwLayers: %u", list->numHwLayers);
-
- for (unsigned int layer = 0; layer < list->numHwLayers; layer++) {
- testPrintI(" layer %u compositionType: %#x%s%s", layer,
- list->hwLayers[layer].compositionType,
- (list->hwLayers[layer].compositionType == HWC_FRAMEBUFFER)
- ? " FRAMEBUFFER" : "",
- (list->hwLayers[layer].compositionType == HWC_OVERLAY)
- ? " OVERLAY" : "");
-
- testPrintI(" hints: %#x",
- list->hwLayers[layer].hints,
- (list->hwLayers[layer].hints & HWC_HINT_TRIPLE_BUFFER)
- ? " TRIPLE_BUFFER" : "",
- (list->hwLayers[layer].hints & HWC_HINT_CLEAR_FB)
- ? " CLEAR_FB" : "");
-
- testPrintI(" flags: %#x%s",
- list->hwLayers[layer].flags,
- (list->hwLayers[layer].flags & HWC_SKIP_LAYER)
- ? " SKIP_LAYER" : "");
-
- testPrintI(" handle: %p",
- list->hwLayers[layer].handle);
-
- // Intentionally skipped display of ROT_180 & ROT_270,
- // which are formed from combinations of the other flags.
- testPrintI(" transform: %#x%s%s%s",
- list->hwLayers[layer].transform,
- (list->hwLayers[layer].transform & HWC_TRANSFORM_FLIP_H)
- ? " FLIP_H" : "",
- (list->hwLayers[layer].transform & HWC_TRANSFORM_FLIP_V)
- ? " FLIP_V" : "",
- (list->hwLayers[layer].transform & HWC_TRANSFORM_ROT_90)
- ? " ROT_90" : "");
-
- testPrintI(" blending: %#x",
- list->hwLayers[layer].blending,
- (list->hwLayers[layer].blending == HWC_BLENDING_NONE)
- ? " NONE" : "",
- (list->hwLayers[layer].blending == HWC_BLENDING_PREMULT)
- ? " PREMULT" : "",
- (list->hwLayers[layer].blending == HWC_BLENDING_COVERAGE)
- ? " COVERAGE" : "");
-
- testPrintI(" sourceCrop: [%i, %i, %i, %i]",
- list->hwLayers[layer].sourceCrop.left,
- list->hwLayers[layer].sourceCrop.top,
- list->hwLayers[layer].sourceCrop.right,
- list->hwLayers[layer].sourceCrop.bottom);
-
- testPrintI(" displayFrame: [%i, %i, %i, %i]",
- list->hwLayers[layer].displayFrame.left,
- list->hwLayers[layer].displayFrame.top,
- list->hwLayers[layer].displayFrame.right,
- list->hwLayers[layer].displayFrame.bottom);
- testPrintI(" scaleFactor: [%f %f]",
- (float) (list->hwLayers[layer].displayFrame.right
- - list->hwLayers[layer].displayFrame.left)
- / (float) (list->hwLayers[layer].sourceCrop.right
- - list->hwLayers[layer].sourceCrop.left),
- (float) (list->hwLayers[layer].displayFrame.bottom
- - list->hwLayers[layer].displayFrame.top)
- / (float) (list->hwLayers[layer].sourceCrop.bottom
- - list->hwLayers[layer].sourceCrop.top));
- }
-}
-
-/*
- * Display List Prepare Modifiable
- *
- * Displays the portions of a list that are meant to be modified by
- * a prepare call.
- */
-void displayListPrepareModifiable(hwc_layer_list_t *list)
-{
- for (unsigned int layer = 0; layer < list->numHwLayers; layer++) {
- testPrintI(" layer %u compositionType: %#x%s%s", layer,
- list->hwLayers[layer].compositionType,
- (list->hwLayers[layer].compositionType == HWC_FRAMEBUFFER)
- ? " FRAMEBUFFER" : "",
- (list->hwLayers[layer].compositionType == HWC_OVERLAY)
- ? " OVERLAY" : "");
- testPrintI(" hints: %#x%s%s",
- list->hwLayers[layer].hints,
- (list->hwLayers[layer].hints & HWC_HINT_TRIPLE_BUFFER)
- ? " TRIPLE_BUFFER" : "",
- (list->hwLayers[layer].hints & HWC_HINT_CLEAR_FB)
- ? " CLEAR_FB" : "");
- }
-}
-
-/*
- * Display List Handles
- *
- * Displays the handles of all the graphic buffers in the list.
- */
-void displayListHandles(hwc_layer_list_t *list)
-{
- const unsigned int maxLayersPerLine = 6;
-
- ostringstream str(" layers:");
- for (unsigned int layer = 0; layer < list->numHwLayers; layer++) {
- str << ' ' << list->hwLayers[layer].handle;
- if (((layer % maxLayersPerLine) == (maxLayersPerLine - 1))
- && (layer != list->numHwLayers - 1)) {
- testPrintI("%s", str.str().c_str());
- str.str(" ");
- }
- }
- testPrintI("%s", str.str().c_str());
-}
-
-const char *graphicFormat2str(unsigned int format)
-{
- const static char *unknown = "unknown";
-
- for (unsigned int n1 = 0; n1 < NUMA(graphicFormat); n1++) {
- if (format == graphicFormat[n1].format) {
- return graphicFormat[n1].desc;
- }
- }
-
- return unknown;
-}
-
-/*
- * Vector Random Select
- *
- * Prandomly selects and returns num elements from vec.
- */
-template <class T>
-vector<T> vectorRandSelect(const vector<T>& vec, size_t num)
-{
- vector<T> rv = vec;
-
- while (rv.size() > num) {
- rv.erase(rv.begin() + testRandMod(rv.size()));
- }
-
- return rv;
-}
-
-/*
- * Vector Or
- *
- * Or's togethen the values of each element of vec and returns the result.
- */
-template <class T>
-T vectorOr(const vector<T>& vec)
-{
- T rv = 0;
-
- for (size_t n1 = 0; n1 < vec.size(); n1++) {
- rv |= vec[n1];
- }
-
- return rv;
-}
diff --git a/opengl/tests/include/glTestLib.h b/opengl/tests/include/glTestLib.h
new file mode 100644
index 0000000..06fbf5d
--- /dev/null
+++ b/opengl/tests/include/glTestLib.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2011 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.
+ *
+ */
+
+/*
+ * Graphics Test Library Header
+ */
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+//#include <ui/FramebufferNativeWindow.h>
+//#include <ui/GraphicBuffer.h>
+#include <ui/EGLUtils.h>
+
+void glTestPrintGLString(const char *name, GLenum s);
+void glTestCheckEglError(const char* op, EGLBoolean returnVal = EGL_TRUE);
+void glTestCheckGlError(const char* op);
+void glTestPrintEGLConfiguration(EGLDisplay dpy, EGLConfig config);
diff --git a/opengl/tests/lib/Android.mk b/opengl/tests/lib/Android.mk
new file mode 100644
index 0000000..7542ac4
--- /dev/null
+++ b/opengl/tests/lib/Android.mk
@@ -0,0 +1,32 @@
+# Copyright (C) 2010 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.
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE_TAGS := tests
+LOCAL_MODULE:= libglTest
+LOCAL_SRC_FILES:= glTestLib.cpp
+LOCAL_C_INCLUDES += system/extras/tests/include \
+ bionic \
+ bionic/libstdc++/include \
+ external/stlport/stlport \
+ frameworks/base/opengl/tests/include \
+
+LOCAL_CFLAGS := -DGL_GLEXT_PROTOTYPES -DEGL_EGLEXT_PROTOTYPES
+
+LOCAL_SHARED_LIBRARIES += libcutils libutils libstlport
+LOCAL_PRELINK_MODULE := false
+
+include $(BUILD_STATIC_LIBRARY)
diff --git a/opengl/tests/lib/glTestLib.cpp b/opengl/tests/lib/glTestLib.cpp
new file mode 100644
index 0000000..052cbd7
--- /dev/null
+++ b/opengl/tests/lib/glTestLib.cpp
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2011 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.
+ *
+ */
+
+/*
+ * Graphics Test Library
+ */
+
+#include <glTestLib.h>
+
+#include <EGL/egl.h>
+#include <EGL/eglext.h>
+#include <GLES2/gl2.h>
+#include <GLES2/gl2ext.h>
+
+#include <ui/EGLUtils.h>
+
+#include <utils/Log.h>
+#include <testUtil.h>
+
+using namespace std;
+using namespace android;
+
+void glTestPrintGLString(const char *name, GLenum s)
+{
+ const char *v = (const char *) glGetString(s);
+
+ if (v == NULL) {
+ testPrintI("GL %s unknown", name);
+ } else {
+ testPrintI("GL %s = %s", name, v);
+ }
+}
+
+void glTestCheckEglError(const char* op, EGLBoolean returnVal)
+{
+ if (returnVal != EGL_TRUE) {
+ testPrintE("%s() returned %d", op, returnVal);
+ }
+
+ for (EGLint error = eglGetError(); error != EGL_SUCCESS; error
+ = eglGetError()) {
+ testPrintE("after %s() eglError %s (0x%x)",
+ op, EGLUtils::strerror(error), error);
+ }
+}
+
+void glTestCheckGlError(const char* op)
+{
+ for (GLint error = glGetError(); error; error
+ = glGetError()) {
+ testPrintE("after %s() glError (0x%x)", op, error);
+ }
+}
+
+void glTestPrintEGLConfiguration(EGLDisplay dpy, EGLConfig config)
+{
+
+#define X(VAL) {VAL, #VAL}
+ struct {EGLint attribute; const char* name;} names[] = {
+ X(EGL_BUFFER_SIZE),
+ X(EGL_ALPHA_SIZE),
+ X(EGL_BLUE_SIZE),
+ X(EGL_GREEN_SIZE),
+ X(EGL_RED_SIZE),
+ X(EGL_DEPTH_SIZE),
+ X(EGL_STENCIL_SIZE),
+ X(EGL_CONFIG_CAVEAT),
+ X(EGL_CONFIG_ID),
+ X(EGL_LEVEL),
+ X(EGL_MAX_PBUFFER_HEIGHT),
+ X(EGL_MAX_PBUFFER_PIXELS),
+ X(EGL_MAX_PBUFFER_WIDTH),
+ X(EGL_NATIVE_RENDERABLE),
+ X(EGL_NATIVE_VISUAL_ID),
+ X(EGL_NATIVE_VISUAL_TYPE),
+ X(EGL_SAMPLES),
+ X(EGL_SAMPLE_BUFFERS),
+ X(EGL_SURFACE_TYPE),
+ X(EGL_TRANSPARENT_TYPE),
+ X(EGL_TRANSPARENT_RED_VALUE),
+ X(EGL_TRANSPARENT_GREEN_VALUE),
+ X(EGL_TRANSPARENT_BLUE_VALUE),
+ X(EGL_BIND_TO_TEXTURE_RGB),
+ X(EGL_BIND_TO_TEXTURE_RGBA),
+ X(EGL_MIN_SWAP_INTERVAL),
+ X(EGL_MAX_SWAP_INTERVAL),
+ X(EGL_LUMINANCE_SIZE),
+ X(EGL_ALPHA_MASK_SIZE),
+ X(EGL_COLOR_BUFFER_TYPE),
+ X(EGL_RENDERABLE_TYPE),
+ X(EGL_CONFORMANT),
+ };
+#undef X
+
+ for (size_t j = 0; j < sizeof(names) / sizeof(names[0]); j++) {
+ EGLint value = -1;
+ EGLint returnVal = eglGetConfigAttrib(dpy, config, names[j].attribute,
+ &value);
+ EGLint error = eglGetError();
+ if (returnVal && error == EGL_SUCCESS) {
+ testPrintI(" %s: %d (%#x)", names[j].name, value, value);
+ }
+ }
+ testPrintI("");
+}
diff --git a/packages/SettingsProvider/res/values/defaults.xml b/packages/SettingsProvider/res/values/defaults.xml
index 8a6e82d..066b8e7 100644
--- a/packages/SettingsProvider/res/values/defaults.xml
+++ b/packages/SettingsProvider/res/values/defaults.xml
@@ -85,10 +85,10 @@
0x13=0x01000100;
<!-- DPAD/Trackball DOWN maps to traverse next on current axis and send an event. -->
0x14=0x01010100;
- <!-- DPAD/Trackball LEFT maps to action in non-android default navigation axis. -->
- 0x15=0x04000000;
- <!-- DPAD/Trackball RIGHT maps to no action in non-android default navigation axis. -->
- 0x16=0x04000000;
+ <!-- DPAD/Trackball LEFT maps to action in the android default navigation axis. -->
+ 0x15=0x04000100;
+ <!-- DPAD/Trackball RIGHT maps to no action in the android default navigation axis. -->
+ 0x16=0x04010100;
<!-- Left Alt+DPAD/Trackball UP transitions from an axis to another and sends an event. -->
<!-- Axis transitions: 2 -> 7; 1 -> 2; 0 -> 1; 3 -> 0; 4 -> 0; 5 -> 0; 6 -> 0; -->
0x120013=0x03020701:0x03010201:0x03000101:0x03030001:0x03040001:0x03050001:0x03060001;
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
index d11a18e..bc7473e 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
@@ -61,7 +61,7 @@
// database gets upgraded properly. At a minimum, please confirm that 'upgradeVersion'
// is properly propagated through your change. Not doing so will result in a loss of user
// settings.
- private static final int DATABASE_VERSION = 62;
+ private static final int DATABASE_VERSION = 63;
private Context mContext;
@@ -441,18 +441,7 @@
}
if (upgradeVersion == 39) {
- db.beginTransaction();
- try {
- String value =
- mContext.getResources().getBoolean(
- R.bool.def_screen_brightness_automatic_mode) ? "1" : "0";
- db.execSQL("INSERT OR IGNORE INTO system(name,value) values('" +
- Settings.System.SCREEN_BRIGHTNESS_MODE + "','" + value + "');");
- db.setTransactionSuccessful();
- } finally {
- db.endTransaction();
- }
-
+ upgradeAutoBrightness(db);
upgradeVersion = 40;
}
@@ -802,6 +791,12 @@
upgradeVersion = 62;
}
+ // Change the default for screen auto-brightness mode
+ if (upgradeVersion == 62) {
+ upgradeAutoBrightness(db);
+ upgradeVersion = 63;
+ }
+
// *** Remember to update DATABASE_VERSION above!
if (upgradeVersion != currentVersion) {
@@ -924,6 +919,20 @@
}
}
+ private void upgradeAutoBrightness(SQLiteDatabase db) {
+ db.beginTransaction();
+ try {
+ String value =
+ mContext.getResources().getBoolean(
+ R.bool.def_screen_brightness_automatic_mode) ? "1" : "0";
+ db.execSQL("INSERT OR REPLACE INTO system(name,value) values('" +
+ Settings.System.SCREEN_BRIGHTNESS_MODE + "','" + value + "');");
+ db.setTransactionSuccessful();
+ } finally {
+ db.endTransaction();
+ }
+ }
+
/**
* Loads the default set of bookmarked shortcuts from an xml file.
*
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
index 6e2bfdb..f8809d7 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProvider.java
@@ -262,11 +262,8 @@
// Watch for external modifications to the database file,
// keeping our cache in sync.
- // It's kinda lame to call mOpenHelper.getReadableDatabase()
- // during onCreate(), but since ensureAndroidIdIsSet has
- // already done it above and initialized/upgraded the
- // database, might as well just use it...
- SQLiteDatabase db = mOpenHelper.getReadableDatabase();
+ SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+ db.enableWriteAheadLogging();
sObserverInstance = new SettingsFileObserver(db.getPath());
sObserverInstance.startWatching();
startAsyncCachePopulation();
diff --git a/packages/SystemUI/AndroidManifest.xml b/packages/SystemUI/AndroidManifest.xml
index d824f30..d3d1750 100644
--- a/packages/SystemUI/AndroidManifest.xml
+++ b/packages/SystemUI/AndroidManifest.xml
@@ -12,6 +12,7 @@
<application
android:persistent="true"
android:allowClearUserData="false"
+ android:hardwareAccelerated="true"
android:label="@string/app_label"
android:icon="@drawable/ic_launcher_settings">
diff --git a/packages/SystemUI/res/drawable-hdpi/stat_sys_signal_flightmode.png b/packages/SystemUI/res/drawable-hdpi/stat_sys_signal_flightmode.png
index 7a419f1..7682bba 100644
--- a/packages/SystemUI/res/drawable-hdpi/stat_sys_signal_flightmode.png
+++ b/packages/SystemUI/res/drawable-hdpi/stat_sys_signal_flightmode.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-mdpi/stat_sys_signal_flightmode.png b/packages/SystemUI/res/drawable-mdpi/stat_sys_signal_flightmode.png
index 690b5f6c7..1534da3 100644
--- a/packages/SystemUI/res/drawable-mdpi/stat_sys_signal_flightmode.png
+++ b/packages/SystemUI/res/drawable-mdpi/stat_sys_signal_flightmode.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-nodpi/panel_notification.png b/packages/SystemUI/res/drawable-nodpi/panel_notification.png
index b0d9c18..437deff 100644
--- a/packages/SystemUI/res/drawable-nodpi/panel_notification.png
+++ b/packages/SystemUI/res/drawable-nodpi/panel_notification.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable/panel_notification_tiled.xml b/packages/SystemUI/res/drawable/panel_notification_tiled.xml
new file mode 100644
index 0000000..9d41e28
--- /dev/null
+++ b/packages/SystemUI/res/drawable/panel_notification_tiled.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 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.
+-->
+
+<bitmap
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:src="@drawable/panel_notification"
+ android:tileMode="repeat"
+ />
+
diff --git a/packages/SystemUI/res/layout-xlarge/status_bar_notification_panel.xml b/packages/SystemUI/res/layout-xlarge/status_bar_notification_panel.xml
index d3fe2e7..7f84b21 100644
--- a/packages/SystemUI/res/layout-xlarge/status_bar_notification_panel.xml
+++ b/packages/SystemUI/res/layout-xlarge/status_bar_notification_panel.xml
@@ -20,27 +20,35 @@
xmlns:systemui="http://schemas.android.com/apk/res/com.android.systemui"
android:layout_height="match_parent"
android:layout_width="match_parent"
- android:orientation="vertical"
android:gravity="right"
- android:paddingTop="32dp"
>
- <LinearLayout
+ <View
+ android:id="@+id/scrim"
+ android:background="@drawable/notify_panel_bg_protect"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:layout_alignParentTop="true"
+ android:layout_alignParentRight="true"
+ />
+
+ <RelativeLayout
android:id="@+id/content_parent"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
- android:animateLayoutChanges="true"
- android:orientation="vertical"
+ android:layout_alignParentBottom="true"
+ android:layout_alignParentRight="true"
>
-
- <com.android.systemui.statusbar.tablet.NotificationTitleArea
+ <RelativeLayout
android:id="@+id/title_area"
android:layout_height="160dp"
android:layout_width="384dp"
android:layout_marginLeft="24dp"
android:paddingTop="20dp"
android:orientation="vertical"
- android:animateLayoutChanges="true"
+ android:layout_alignParentTop="true"
+ android:layout_alignParentRight="true"
+ android:background="@drawable/panel_notification_tiled"
>
<com.android.systemui.statusbar.tablet.HoloClock
@@ -154,13 +162,15 @@
android:src="@drawable/status_bar_veto"
android:baseline="21dp"
/>
- </com.android.systemui.statusbar.tablet.NotificationTitleArea>
+ </RelativeLayout>
<LinearLayout
android:id="@+id/content_frame"
android:layout_height="wrap_content"
android:layout_width="408dp"
android:orientation="vertical"
+ android:layout_below="@id/title_area"
+ android:layout_alignParentRight="true"
>
<ScrollView
android:id="@+id/notification_scroller"
@@ -191,5 +201,17 @@
android:src="@drawable/notify_item_glow_bottom"
/>
</LinearLayout>
- </LinearLayout>
+ </RelativeLayout>
+
+ <View
+ android:id="@+id/glow"
+ android:background="@drawable/notify_glow_back"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignTop="@id/content_parent"
+ android:layout_alignLeft="@id/content_parent"
+ android:layout_marginLeft="100dip"
+ android:layout_marginTop="-100dip"
+ />
+
</com.android.systemui.statusbar.tablet.NotificationPanel>
diff --git a/packages/SystemUI/res/values-es-rUS-xlarge-land/strings.xml b/packages/SystemUI/res/values-es-rUS-xlarge-land/strings.xml
new file mode 100644
index 0000000..78a4c18
--- /dev/null
+++ b/packages/SystemUI/res/values-es-rUS-xlarge-land/strings.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <!-- XL -->
+ <string name="toast_rotation_locked" msgid="2686639138967158852">"La pantalla está bloqueada en orientación paisaje."</string>
+</resources>
diff --git a/packages/SystemUI/res/values-es-rUS-xlarge-port/strings.xml b/packages/SystemUI/res/values-es-rUS-xlarge-port/strings.xml
new file mode 100644
index 0000000..9daef6a
--- /dev/null
+++ b/packages/SystemUI/res/values-es-rUS-xlarge-port/strings.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <!-- XL -->
+ <string name="toast_rotation_locked" msgid="4297721709987511908">"La pantalla está bloqueada en orientación retrato."</string>
+</resources>
diff --git a/packages/SystemUI/res/values-es-rUS-xlarge/strings.xml b/packages/SystemUI/res/values-es-rUS-xlarge/strings.xml
index bf627f4..f29259a 100644
--- a/packages/SystemUI/res/values-es-rUS-xlarge/strings.xml
+++ b/packages/SystemUI/res/values-es-rUS-xlarge/strings.xml
@@ -1,26 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/**
- * Copyright (c) 2010, 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.
- */
- -->
-
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <!-- no translation found for status_bar_clear_all_button (4722520806446512408) -->
- <skip />
- <string name="status_bar_settings_signal_meter_disconnected" msgid="4684094636492991496">"Sin conexión a Int."</string>
- <string name="status_bar_settings_signal_meter_wifi_nossid" msgid="1456658018593445677">"WiFi conectado"</string>
+ <!-- XL xlarge -->
+ <string name="status_bar_clear_all_button" msgid="4341545325987974494">"Eliminar todos"</string>
+ <!-- XL -->
+ <string name="status_bar_no_notifications_title" msgid="2492933749414725897">"No tienes notificaciones"</string>
+ <!-- XL -->
+ <string name="status_bar_settings_rotation_lock" msgid="9125161825884157545">"Bloquear orient. de pant."</string>
+ <!-- XL -->
+ <string name="recent_tasks_app_label" msgid="5550538721034982973">"Google Apps"</string>
+ <!-- XL xlarge -->
+ <string name="status_bar_settings_signal_meter_disconnected" msgid="4866302415753953027">"Sin conexión a Internet"</string>
+ <!-- XL xlarge -->
+ <string name="status_bar_settings_signal_meter_wifi_nossid" msgid="3832182580451976589">"Wi-Fi conectado"</string>
</resources>
diff --git a/packages/SystemUI/res/values-port/strings.xml b/packages/SystemUI/res/values-port/strings.xml
index d3ab67b..67364a4 100644
--- a/packages/SystemUI/res/values-port/strings.xml
+++ b/packages/SystemUI/res/values-port/strings.xml
@@ -17,7 +17,4 @@
*/
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
- <!-- Rotation lock toast text: shown when rotation lock is turned on in portrait orientation.
- -->
- <string name="toast_rotation_locked">Screen is now locked in portrait orientation.</string>
</resources>
diff --git a/packages/SystemUI/res/values-xlarge/config.xml b/packages/SystemUI/res/values-xlarge/config.xml
index e140914..299ab97 100644
--- a/packages/SystemUI/res/values-xlarge/config.xml
+++ b/packages/SystemUI/res/values-xlarge/config.xml
@@ -24,7 +24,7 @@
<!-- Component to be used as the status bar service. Must implement the IStatusBar
interface. This name is in the ComponentName flattened format (package/class) -->
- <string name="config_statusBarComponent">com.android.systemui.statusbar.tablet.TabletStatusBar</string>
+ <string name="config_statusBarComponent" translatable="false">com.android.systemui.statusbar.tablet.TabletStatusBar</string>
<!-- Whether or not we show the number in the bar. -->
<bool name="config_statusBarShowNumber">false</bool>
diff --git a/packages/SystemUI/res/values-xlarge/strings.xml b/packages/SystemUI/res/values-xlarge/strings.xml
index 279a135..f7b642d 100644
--- a/packages/SystemUI/res/values-xlarge/strings.xml
+++ b/packages/SystemUI/res/values-xlarge/strings.xml
@@ -18,7 +18,7 @@
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<!-- The text for the button in the notification window-shade that clears
- all of the currently visible notifications. -->
+ all of the currently visible notifications. [CHAR LIMIT=10]-->
<string name="status_bar_clear_all_button">Clear all</string>
<!-- System panel ("Quick Settings") -->
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 9737028..caafbdb 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -108,11 +108,6 @@
<!-- Recent apps label. Shown as title on recent apps panel -->
<string name="recent_tasks_app_label">Apps</string>
- <!-- Rotation lock toast text: shown when rotation lock is turned off (and the screen will
- auto-rotate based on the accelerometer). [CHAR LIMIT=NONE]-->
- <string name="toast_rotation_free">Screen will rotate automatically.</string>
-
- <!-- Rotation lock toast text: shown when rotation lock is turned on and the orientation is
- undefined. [CHAR LIMIT=NONE] -->
- <string name="toast_rotation_locked">Screen rotation is now locked.</string>
+ <!-- Network connection string for Bluetooth Reverse Tethering -->
+ <string name="bluetooth_tethered">Bluetooth tethered"</string>
</resources>
diff --git a/packages/SystemUI/src/com/android/systemui/power/PowerUI.java b/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
index 9dfc9c3..a81484c 100644
--- a/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
+++ b/packages/SystemUI/src/com/android/systemui/power/PowerUI.java
@@ -186,7 +186,7 @@
b.setCancelable(true);
b.setTitle(R.string.battery_low_title);
b.setView(v);
- b.setIcon(android.R.drawable.ic_dialog_alert);
+ b.setIconAttribute(android.R.attr.alertDialogIcon);
b.setPositiveButton(android.R.string.ok, null);
final Intent intent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);
@@ -249,7 +249,7 @@
AlertDialog.Builder b = new AlertDialog.Builder(mContext);
b.setCancelable(true);
b.setMessage(R.string.invalid_charger);
- b.setIcon(android.R.drawable.ic_dialog_alert);
+ b.setIconAttribute(android.R.attr.alertDialogIcon);
b.setPositiveButton(android.R.string.ok, null);
AlertDialog d = b.create();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java
index 5374957b..3a7bd90 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/KeyButtonView.java
@@ -78,6 +78,8 @@
mWindowManager = IWindowManager.Stub.asInterface(
ServiceManager.getService(Context.WINDOW_SERVICE));
+
+ setClickable(true);
}
public boolean onTouchEvent(MotionEvent ev) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
index b0b93e0..cb5e361 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
@@ -77,7 +77,7 @@
int mDataDirectionIconId;
int mDataSignalIconId;
int mDataTypeIconId;
-
+
// wifi
final WifiManager mWifiManager;
boolean mWifiEnabled, mWifiConnected;
@@ -85,6 +85,11 @@
String mWifiSsid;
int mWifiIconId;
+ // bluetooth
+ private boolean mBluetoothTethered = false;
+ private int mBluetoothTetherIconId =
+ com.android.internal.R.drawable.stat_sys_tether_bluetooth;
+
// data connectivity (regardless of state, can we access the internet?)
// state of inet connection - 0 not connected, 100 connected
private int mInetCondition = 0;
@@ -104,7 +109,7 @@
int mLastCombinedSignalIconId = -1;
int mLastDataTypeIconId = -1;
String mLastLabel = "";
-
+
// yuck -- stop doing this here and put it in the framework
IBatteryStats mBatteryStats;
@@ -235,7 +240,7 @@
@Override
public void onDataConnectionStateChanged(int state, int networkType) {
if (DEBUG) {
- Slog.d(TAG, "onDataConnectionStateChanged: state=" + state
+ Slog.d(TAG, "onDataConnectionStateChanged: state=" + state
+ " type=" + networkType);
}
mDataState = state;
@@ -649,13 +654,22 @@
mInetCondition = inetCondition;
updateWifiIcons();
break;
+ case ConnectivityManager.TYPE_BLUETOOTH:
+ mInetCondition = inetCondition;
+ if (info != null) {
+ mBluetoothTethered = info.isConnected() ? true: false;
+ } else {
+ mBluetoothTethered = false;
+ }
+ break;
}
}
// ===== Update the views =======================================================
- // figure out what to show: first wifi, then 3G, then nothing
+ // figure out what to show- there should be one connected network or nothing
+ // General order of preference is: wifi, 3G than bluetooth. This might vary by product.
void refreshViews() {
Context context = mContext;
@@ -672,12 +686,16 @@
}
combinedSignalIconId = mWifiIconId;
dataTypeIconId = 0;
+ } else if (mDataConnected) {
+ label = mNetworkName;
+ combinedSignalIconId = mDataSignalIconId;
+ dataTypeIconId = mDataTypeIconId;
+ } else if (mBluetoothTethered) {
+ label = mContext.getString(R.string.bluetooth_tethered);
+ combinedSignalIconId = mBluetoothTetherIconId;
+ dataTypeIconId = 0;
} else {
- if (mDataConnected) {
- label = mNetworkName;
- } else {
- label = context.getString(R.string.status_bar_settings_signal_meter_disconnected);
- }
+ label = context.getString(R.string.status_bar_settings_signal_meter_disconnected);
combinedSignalIconId = mDataSignalIconId;
dataTypeIconId = mDataTypeIconId;
}
@@ -689,7 +707,8 @@
+ " mDataDirectionIconId=0x" + Integer.toHexString(mDataDirectionIconId)
+ " mDataSignalIconId=0x" + Integer.toHexString(mDataSignalIconId)
+ " mDataTypeIconId=0x" + Integer.toHexString(mDataTypeIconId)
- + " mWifiIconId=0x" + Integer.toHexString(mWifiIconId));
+ + " mWifiIconId=0x" + Integer.toHexString(mWifiIconId)
+ + "mBluetoothTetherIconId=0x" + Integer.toHexString(mBluetoothTetherIconId));
}
// the phone icon on phones
@@ -809,6 +828,10 @@
pw.print(" mWifiIconId=");
pw.println(mWifiIconId);
+ pw.println(" - Bluetooth ----");
+ pw.print(" mBtReverseTethered=");
+ pw.println(mBluetoothTethered);
+
pw.println(" - connectivity ------");
pw.print(" mInetCondition=");
pw.println(mInetCondition);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/NotificationPanel.java b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/NotificationPanel.java
index 3ca1e12..3201d06 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/NotificationPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/NotificationPanel.java
@@ -17,6 +17,7 @@
package com.android.systemui.statusbar.tablet;
import android.animation.Animator;
+import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
@@ -33,11 +34,13 @@
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
+import android.widget.RelativeLayout;
+import android.widget.FrameLayout;
import android.widget.TextView;
import com.android.systemui.R;
-public class NotificationPanel extends LinearLayout implements StatusBarPanel,
+public class NotificationPanel extends RelativeLayout implements StatusBarPanel,
View.OnClickListener {
static final String TAG = "Tablet/NotificationPanel";
static final boolean DEBUG = false;
@@ -51,12 +54,11 @@
ViewGroup mContentFrame;
Rect mContentArea;
View mSettingsView;
+ View mScrim, mGlow;
ViewGroup mContentParent;
Choreographer mChoreo = new Choreographer();
int mStatusBarHeight;
- Drawable mBgDrawable;
- Drawable mGlowDrawable;
public NotificationPanel(Context context, AttributeSet attrs) {
this(context, attrs, 0);
@@ -69,8 +71,6 @@
mStatusBarHeight = res.getDimensionPixelSize(
com.android.internal.R.dimen.status_bar_height);
- mBgDrawable = res.getDrawable(R.drawable.notify_panel_bg_protect);
- mGlowDrawable = res.getDrawable(R.drawable.notify_glow_back);
}
@Override
@@ -80,9 +80,13 @@
setWillNotDraw(false);
mContentParent = (ViewGroup)findViewById(R.id.content_parent);
+ mContentParent.bringToFront();
mTitleArea = findViewById(R.id.title_area);
mTitleArea.setOnClickListener(this);
+ mScrim = findViewById(R.id.scrim);
+ mGlow = findViewById(R.id.glow);
+
mSettingsButton = (ImageView)findViewById(R.id.settings_button);
mNotificationButton = (ImageView)findViewById(R.id.notification_button);
@@ -132,21 +136,6 @@
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
- // We know that none of our children are GONE, so don't worry about skipping GONE views.
- final int N = getChildCount();
- if (N == 0) {
- return;
- }
- final int allocatedBottom = getChildAt(N-1).getBottom();
- final int shift = b - allocatedBottom - getPaddingBottom();
- if (shift <= 0) {
- return;
- }
- for (int i=0; i<N; i++) {
- final View c = getChildAt(i);
- c.layout(c.getLeft(), c.getTop() + shift, c.getRight(), c.getBottom() + shift);
- }
-
mChoreo.setPanelHeight(mContentParent.getHeight());
}
@@ -154,26 +143,6 @@
public void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mContentArea = null;
- mBgDrawable.setBounds(0, 0, w, h-mStatusBarHeight);
- }
-
- @Override
- public void onDraw(Canvas canvas) {
- int saveCount;
- final int w = getWidth();
- final int h = getHeight();
-
- super.onDraw(canvas);
-
- // Background protection
- mBgDrawable.draw(canvas);
-
- // The panel glow (behind status bar)
-
- saveCount = canvas.save();
- canvas.clipRect(0, 0, w, h-mStatusBarHeight);
- mGlowDrawable.draw(canvas);
- canvas.restoreToCount(saveCount);
}
public void onClick(View v) {
@@ -227,85 +196,82 @@
private class Choreographer implements Animator.AnimatorListener {
boolean mVisible;
- int mBgAlpha;
- ValueAnimator mBgAnim;
int mPanelHeight;
- int mPanelBottom;
- ValueAnimator mPositionAnim;
+ AnimatorSet mContentAnim;
// should group this into a multi-property animation
- final int OPEN_DURATION = 200;
+ final int OPEN_DURATION = 250;
+
+ // the panel will start to appear this many px from the end
+ final int HYPERSPACE_OFFRAMP = 120;
Choreographer() {
}
- void createAnimation(boolean visible) {
- mBgAnim = ObjectAnimator.ofInt(this, "bgAlpha", mBgAlpha, visible ? 255 : 0)
- .setDuration(OPEN_DURATION);
- mBgAnim.addListener(this);
+ void createAnimation(boolean appearing) {
+ Animator bgAnim = ObjectAnimator.ofFloat(mScrim,
+ "alpha", mScrim.getAlpha(), appearing ? 1 : 0);
- mPositionAnim = ObjectAnimator.ofInt(this, "panelBottom", mPanelBottom,
- visible ? mPanelHeight : 0)
- .setDuration(OPEN_DURATION);
- }
+ float start, end;
- void startAnimation(boolean visible) {
- if (DEBUG) Slog.d(TAG, "startAnimation(visible=" + visible + ")");
- if (mBgAnim != null && mVisible != visible) {
- mBgAnim.reverse();
- mPositionAnim.reverse();
+ // 0: on-screen
+ // height: off-screen
+ float y = mContentParent.getTranslationY();
+ if (appearing) {
+ // we want to go from near-the-top to the top, unless we're half-open in the right
+ // general vicinity
+ start = (y < HYPERSPACE_OFFRAMP)
+ ? y
+ : HYPERSPACE_OFFRAMP;
+ end = 0;
} else {
- createAnimation(visible);
- mBgAnim.start();
- mPositionAnim.start();
+ start = y;
+ end = y + HYPERSPACE_OFFRAMP;
}
- mVisible = visible;
+ Animator posAnim = ObjectAnimator.ofFloat(mContentParent, "translationY", start, end);
+ posAnim.setInterpolator(appearing
+ ? new android.view.animation.DecelerateInterpolator(2.0f)
+ : new android.view.animation.AccelerateInterpolator(2.0f));
+
+ Animator glowAnim = ObjectAnimator.ofFloat(mGlow, "alpha",
+ mGlow.getAlpha(), appearing ? 1.0f : 0.0f);
+ glowAnim.setInterpolator(appearing
+ ? new android.view.animation.AccelerateInterpolator(1.0f)
+ : new android.view.animation.DecelerateInterpolator(1.0f));
+
+ mContentAnim = new AnimatorSet();
+ mContentAnim
+ .play(ObjectAnimator.ofFloat(mContentParent, "alpha", mContentParent.getAlpha(),
+ appearing ? 1.0f : 0.0f))
+ .with(glowAnim)
+ .with(bgAnim)
+ .with(posAnim)
+ ;
+ mContentAnim.setDuration(OPEN_DURATION);
+ mContentAnim.addListener(this);
}
- void jumpTo(boolean visible) {
- setBgAlpha(visible ? 255 : 0);
- setPanelBottom(visible ? mPanelHeight : 0);
+ void startAnimation(boolean appearing) {
+ if (DEBUG) Slog.d(TAG, "startAnimation(appearing=" + appearing + ")");
+
+ createAnimation(appearing);
+
+ mContentParent.setLayerType(View.LAYER_TYPE_HARDWARE, null);
+ mContentAnim.start();
+
+ mVisible = appearing;
}
- public void setBgAlpha(int alpha) {
- mBgAlpha = alpha;
- mBgDrawable.setAlpha((int)(alpha));
- invalidate();
- }
-
- // 0 is closed, the height of the panel is open
- public void setPanelBottom(int y) {
- mPanelBottom = y;
- int translationY = mPanelHeight - y;
- mContentParent.setTranslationY(translationY);
-
- final int glowXOffset = 100;
- final int glowYOffset = 100;
- int glowX = mContentParent.getLeft() - glowXOffset;
- int glowY = mContentParent.getTop() - glowYOffset + translationY;
- mGlowDrawable.setBounds(glowX, glowY, glowX + mGlowDrawable.getIntrinsicWidth(),
- glowY + mGlowDrawable.getIntrinsicHeight());
-
- float alpha;
- if (mPanelBottom > glowYOffset) {
- alpha = 1;
- } else {
- alpha = ((float)mPanelBottom) / glowYOffset;
- }
- mContentParent.setAlpha(alpha);
- mGlowDrawable.setAlpha((int)(255 * alpha));
-
- if (false) {
- Slog.d(TAG, "mPanelBottom=" + mPanelBottom + " translationY=" + translationY
- + " alpha=" + alpha + " glowY=" + glowY);
- }
+ void jumpTo(boolean appearing) {
+// setBgAlpha(appearing ? 255 : 0);
+ mContentParent.setTranslationY(appearing ? 0 : mPanelHeight);
}
public void setPanelHeight(int h) {
+ if (DEBUG) Slog.d(TAG, "panelHeight=" + h);
mPanelHeight = h;
- if (mPanelBottom == 0) {
+ if (mPanelHeight == 0) {
// fully closed, no animation necessary
- setPanelBottom(0);
} else if (mVisible) {
if (DEBUG) {
Slog.d(TAG, "panelHeight not zero but trying to open; scheduling an anim to open fully");
@@ -315,17 +281,18 @@
}
public void onAnimationCancel(Animator animation) {
- if (DEBUG) Slog.d(TAG, "onAnimationCancel mBgAlpha=" + mBgAlpha);
+ if (DEBUG) Slog.d(TAG, "onAnimationCancel");
// force this to zero so we close the window
- mBgAlpha = 0;
+ mVisible = false;
}
public void onAnimationEnd(Animator animation) {
- if (DEBUG) Slog.d(TAG, "onAnimationEnd mBgAlpha=" + mBgAlpha);
- if (mBgAlpha == 0) {
+ if (DEBUG) Slog.d(TAG, "onAnimationEnd");
+ if (! mVisible) {
setVisibility(View.GONE);
}
- mBgAnim = null;
+ mContentParent.setLayerType(View.LAYER_TYPE_NONE, null);
+ mContentAnim = null;
}
public void onAnimationRepeat(Animator animation) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/NotificationTitleArea.java b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/NotificationTitleArea.java
deleted file mode 100644
index d4413db..0000000
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/NotificationTitleArea.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2010 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.systemui.statusbar.tablet;
-
-import android.content.Context;
-import android.graphics.BitmapFactory;
-import android.graphics.Bitmap;
-import android.graphics.Paint;
-import android.graphics.Canvas;
-import android.util.AttributeSet;
-import android.util.Slog;
-import android.widget.ImageView;
-import android.widget.RelativeLayout;
-import android.widget.TextView;
-import android.view.View;
-import android.widget.FrameLayout;
-
-import com.android.systemui.R;
-
-public class NotificationTitleArea extends RelativeLayout {
- static final String TAG = "NotificationTitleArea";
-
- View mSettingsButton;
- View mNotificationButton;
- View mNotificationScroller;
- FrameLayout mSettingsFrame;
- View mSettingsPanel;
-
- // for drawing the background
- Bitmap mTexture;
- Paint mPaint;
- int mTextureWidth;
- int mTextureHeight;
-
-
- public NotificationTitleArea(Context context, AttributeSet attrs) {
- this(context, attrs, 0);
- }
-
- public NotificationTitleArea(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
-
- // for drawing the background
- mTexture = BitmapFactory.decodeResource(getResources(), R.drawable.panel_notification);
- mTextureWidth = mTexture.getWidth();
- mTextureHeight = mTexture.getHeight();
-
- mPaint = new Paint();
- mPaint.setDither(false);
- }
-
- public void onFinishInflate() {
- super.onFinishInflate();
- setWillNotDraw(false);
- }
-
- @Override
- public void onDraw(Canvas canvas) {
- final Bitmap texture = mTexture;
- final Paint paint = mPaint;
-
- final int width = getWidth();
- final int height = getHeight();
-
- final int textureWidth = mTextureWidth;
- final int textureHeight = mTextureHeight;
-
- int x = 0;
- int y;
-
- while (x < width) {
- y = 0;
- while (y < height) {
- canvas.drawBitmap(texture, x, y, paint);
- y += textureHeight;
- }
- x += textureWidth;
- }
- }
-}
-
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/RecentAppsPanel.java b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/RecentAppsPanel.java
index 612427b..53c30fe 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/RecentAppsPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/RecentAppsPanel.java
@@ -252,7 +252,11 @@
private void refreshApplicationList() {
mActivityDescriptions = getRecentTasks();
- updateUiElements(getResources().getConfiguration(), true);
+ if (mActivityDescriptions.size() > 0) {
+ updateUiElements(getResources().getConfiguration(), true);
+ } else {
+ mBar.animateCollapse();
+ }
}
private Bitmap compositeBitmap(Bitmap background, Bitmap thumbnail) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/ShirtPocket.java b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/ShirtPocket.java
index 14f2587..b9206ea 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/ShirtPocket.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/ShirtPocket.java
@@ -147,23 +147,23 @@
final ClipData clip = mClipping;
if (clip != null) {
final Bitmap icon = clip.getIcon();
- DragThumbnailBuilder thumb;
+ DragShadowBuilder shadow;
if (icon != null) {
- thumb = new DragThumbnailBuilder(v) {
- public void onProvideThumbnailMetrics(Point thumbnailSize, Point thumbnailTouchPoint) {
- thumbnailSize.set(icon.getWidth(), icon.getHeight());
- thumbnailTouchPoint.set(thumbnailSize.x / 2, thumbnailSize.y / 2);
+ shadow = new DragShadowBuilder(v) {
+ public void onProvideShadowMetrics(Point shadowSize, Point shadowTouchPoint) {
+ shadowSize.set(icon.getWidth(), icon.getHeight());
+ shadowTouchPoint.set(shadowSize.x / 2, shadowSize.y / 2);
}
- public void onDrawThumbnail(Canvas canvas) {
+ public void onDrawShadow(Canvas canvas) {
canvas.drawBitmap(icon, 0, 0, new Paint());
}
};
} else {
// uhhh, what now?
- thumb = new DragThumbnailBuilder(mWindow.findViewById(R.id.preview));
+ shadow = new DragShadowBuilder(mWindow.findViewById(R.id.preview));
}
- v.startDrag(clip, thumb, false, null);
+ v.startDrag(clip, shadow, false, null);
// TODO: only discard the clipping if it was accepted
stash(null);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
index bfc2aa1..cd39d71 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
@@ -183,7 +183,7 @@
mStatusBarView.setIgnoreChildren(0, mNotificationTrigger, mNotificationPanel);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
- ViewGroup.LayoutParams.MATCH_PARENT,
+ 720, // ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
@@ -196,6 +196,7 @@
lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
lp.windowAnimations = com.android.internal.R.style.Animation; // == no animation
+// lp.windowAnimations = com.android.internal.R.style.Animation_ZoomButtons; // simple fade
WindowManagerImpl.getDefault().addView(mNotificationPanel, lp);
@@ -1149,7 +1150,11 @@
}
});
} else {
- vetoButton.setVisibility(View.INVISIBLE);
+ if ((sbn.notification.flags & Notification.FLAG_ONGOING_EVENT) == 0) {
+ vetoButton.setVisibility(View.INVISIBLE);
+ } else {
+ vetoButton.setVisibility(View.GONE);
+ }
}
// the large icon
diff --git a/policy/src/com/android/internal/policy/impl/LockScreen.java b/policy/src/com/android/internal/policy/impl/LockScreen.java
index 50d10bf..79fbe0e 100644
--- a/policy/src/com/android/internal/policy/impl/LockScreen.java
+++ b/policy/src/com/android/internal/policy/impl/LockScreen.java
@@ -23,6 +23,7 @@
import com.android.internal.widget.WaveView;
import com.android.internal.widget.WaveView.OnTriggerListener;
+import android.app.ActivityManager;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
@@ -80,11 +81,6 @@
// last known battery level
private int mBatteryLevel = 100;
- private String mNextAlarm = null;
- private Drawable mAlarmIcon = null;
- private String mCharging = null;
- private Drawable mChargingIcon = null;
-
private boolean mSilentMode;
private AudioManager mAudioManager;
private String mDateFormatString;
@@ -255,9 +251,9 @@
private boolean shouldEnableMenuKey() {
final Resources res = getResources();
final boolean configDisabled = res.getBoolean(R.bool.config_disableMenuKeyInLockScreen);
- final boolean isMonkey = SystemProperties.getBoolean("ro.monkey", false);
+ final boolean isTestHarness = ActivityManager.isRunningInTestHarness();
final boolean fileOverride = (new File(ENABLE_MENU_KEY_FILE)).exists();
- return !configDisabled || isMonkey || fileOverride;
+ return !configDisabled || isTestHarness || fileOverride;
}
/**
@@ -356,9 +352,6 @@
mStatus = getCurrentStatus(updateMonitor.getSimState());
updateLayout(mStatus);
- refreshBatteryStringAndIcon();
- refreshAlarmDisplay();
-
mTimeFormat = DateFormat.getTimeFormat(getContext());
mDateFormatString = getContext().getString(R.string.full_wday_month_day_no_year);
refreshTimeAndDateDisplay();
@@ -417,14 +410,6 @@
private Runnable mPendingR1;
private Runnable mPendingR2;
- private void refreshAlarmDisplay() {
- mNextAlarm = mLockPatternUtils.getNextAlarm();
- if (mNextAlarm != null) {
- mAlarmIcon = getContext().getResources().getDrawable(R.drawable.ic_lock_idle_alarm);
- }
- updateStatusLines();
- }
-
/** {@inheritDoc} */
public void onRefreshBatteryInfo(boolean showBatteryInfo, boolean pluggedIn,
int batteryLevel) {
@@ -433,32 +418,9 @@
mPluggedIn = pluggedIn;
mBatteryLevel = batteryLevel;
- refreshBatteryStringAndIcon();
updateStatusLines();
}
- private void refreshBatteryStringAndIcon() {
- if (!mShowingBatteryInfo) {
- mCharging = null;
- return;
- }
-
- if (mChargingIcon == null) {
- mChargingIcon =
- getContext().getResources().getDrawable(R.drawable.ic_lock_idle_charging);
- }
-
- if (mPluggedIn) {
- if (mBatteryLevel >= 100) {
- mCharging = getContext().getString(R.string.lockscreen_charged);
- } else {
- mCharging = getContext().getString(R.string.lockscreen_plugged_in, mBatteryLevel);
- }
- } else {
- mCharging = getContext().getString(R.string.lockscreen_low_battery);
- }
- }
-
/** {@inheritDoc} */
public void onTimeChanged() {
refreshTimeAndDateDisplay();
@@ -469,7 +431,7 @@
}
private void updateStatusLines() {
- mStatusView.updateStatusLines(mStatus.showStatusLines(), mCharging, mChargingIcon, mAlarmIcon);
+ mStatusView.updateStatusLines(mStatus.showStatusLines());
}
/** {@inheritDoc} */
diff --git a/policy/src/com/android/internal/policy/impl/PatternUnlockScreen.java b/policy/src/com/android/internal/policy/impl/PatternUnlockScreen.java
index 35fa3e5..5d1455e 100644
--- a/policy/src/com/android/internal/policy/impl/PatternUnlockScreen.java
+++ b/policy/src/com/android/internal/policy/impl/PatternUnlockScreen.java
@@ -396,7 +396,7 @@
mLockPatternView
.setDisplayMode(LockPatternView.DisplayMode.Correct);
mStatusView.setInstructions("");
- mStatusView.updateStatusLines();
+ mStatusView.updateStatusLines(true);
mCallback.keyguardDone(true);
mCallback.reportSuccessfulUnlockAttempt();
} else {
@@ -416,7 +416,7 @@
// TODO mUnlockIcon.setVisibility(View.VISIBLE);
mStatusView.setInstructions(
getContext().getString(R.string.lockscreen_pattern_wrong));
- mStatusView.updateStatusLines();
+ mStatusView.updateStatusLines(true);
mLockPatternView.postDelayed(
mCancelPatternRunnable,
PATTERN_CLEAR_TIMEOUT_MS);
@@ -437,7 +437,7 @@
mStatusView.setInstructions(getContext().getString(
R.string.lockscreen_too_many_failed_attempts_countdown,
secondsRemaining));
- mStatusView.updateStatusLines();
+ mStatusView.updateStatusLines(true);
}
@Override
@@ -445,7 +445,7 @@
mLockPatternView.setEnabled(true);
mStatusView.setInstructions(getContext().getString(
R.string.lockscreen_pattern_instructions));
- mStatusView.updateStatusLines();
+ mStatusView.updateStatusLines(true);
// TODO mUnlockIcon.setVisibility(View.VISIBLE);
mFailedPatternAttemptsSinceLastTimeout = 0;
if (mEnableFallback) {
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindow.java b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
index 3b2aeaf..38eed50 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindow.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
@@ -21,15 +21,16 @@
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
-import static android.view.WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY;
import static android.view.WindowManager.LayoutParams.FLAG_SPLIT_TOUCH;
import com.android.internal.view.BaseSurfaceHolder;
import com.android.internal.view.RootViewSurfaceTaker;
import com.android.internal.view.StandaloneActionMode;
+import com.android.internal.view.menu.ActionMenuView;
import com.android.internal.view.menu.ContextMenuBuilder;
import com.android.internal.view.menu.MenuBuilder;
import com.android.internal.view.menu.MenuDialogHelper;
+import com.android.internal.view.menu.MenuItemImpl;
import com.android.internal.view.menu.MenuPopupHelper;
import com.android.internal.view.menu.MenuView;
import com.android.internal.view.menu.SubMenuBuilder;
@@ -57,7 +58,6 @@
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.Gravity;
-import android.view.HardwareRenderer;
import android.view.InputQueue;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
@@ -430,6 +430,21 @@
return;
}
+ // Don't open an options panel for honeycomb apps on xlarge devices.
+ // (The app should be using an action bar for menu items.)
+ if (st.featureId == FEATURE_OPTIONS_PANEL) {
+ Context context = getContext();
+ Configuration config = context.getResources().getConfiguration();
+ boolean isXLarge = (config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) ==
+ Configuration.SCREENLAYOUT_SIZE_XLARGE;
+ boolean isHoneycombApp = context.getApplicationInfo().targetSdkVersion >=
+ android.os.Build.VERSION_CODES.HONEYCOMB;
+
+ if (isXLarge && isHoneycombApp) {
+ return;
+ }
+ }
+
Callback cb = getCallback();
if ((cb != null) && (!cb.onMenuOpened(st.featureId, st.menu))) {
// Callback doesn't want the menu to open, reset any state
@@ -868,12 +883,16 @@
// The window manager will give us a valid window token
new MenuDialogHelper(subMenu).show(null);
} else if (hasFeature(FEATURE_ACTION_BAR)) {
- mActionButtonPopup = new ActionButtonSubmenu(getContext(), subMenu);
- mActionButtonPopup.show();
- Callback cb = getCallback();
- if (cb != null) {
- cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu);
- }
+ mDecor.post(new Runnable() {
+ public void run() {
+ mActionButtonPopup = new ActionButtonSubmenu(getContext(), subMenu);
+ mActionButtonPopup.show();
+ Callback cb = getCallback();
+ if (cb != null) {
+ cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu);
+ }
+ }
+ });
}
return true;
@@ -2996,6 +3015,20 @@
public ActionButtonSubmenu(Context context, SubMenuBuilder subMenu) {
super(context, subMenu);
mSubMenu = subMenu;
+
+ MenuBuilder parentMenu = subMenu.getRootMenu();
+ MenuItemImpl item = (MenuItemImpl) subMenu.getItem();
+ if (!item.isActionButton()) {
+ // Give a reasonable anchor to nested submenus.
+ ActionMenuView amv = (ActionMenuView) parentMenu.getMenuView(
+ MenuBuilder.TYPE_ACTION_BUTTON, null);
+
+ View anchor = amv.getOverflowButton();
+ if (anchor == null) {
+ anchor = amv;
+ }
+ setAnchorView(anchor);
+ }
}
@Override
@@ -3007,10 +3040,11 @@
@Override
public void run() {
- show();
- Callback cb = getCallback();
- if (cb != null) {
- cb.onMenuOpened(FEATURE_ACTION_BAR, mSubMenu);
+ if (tryShow()) {
+ Callback cb = getCallback();
+ if (cb != null) {
+ cb.onMenuOpened(FEATURE_ACTION_BAR, mSubMenu);
+ }
}
}
}
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
index 281ac2e..3e8318e 100755
--- a/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java
@@ -34,15 +34,16 @@
import android.database.ContentObserver;
import android.graphics.PixelFormat;
import android.graphics.Rect;
+import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.LocalPowerManager;
-import android.os.Looper;
import android.os.PowerManager;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
+import android.os.UEventObserver;
import android.os.Vibrator;
import android.provider.Settings;
@@ -120,6 +121,7 @@
import android.media.IAudioService;
import android.media.AudioManager;
+import java.io.File;
import java.util.ArrayList;
/**
@@ -236,6 +238,7 @@
boolean mSystemReady;
boolean mLidOpen;
+ boolean mHdmiPlugged;
int mUiMode = Configuration.UI_MODE_TYPE_NORMAL;
int mDockMode = Intent.EXTRA_DOCK_STATE_UNDOCKED;
int mLidOpenRotation;
@@ -351,6 +354,13 @@
final KeyCharacterMap.FallbackAction mFallbackAction = new KeyCharacterMap.FallbackAction();
+ private UEventObserver mHDMIObserver = new UEventObserver() {
+ @Override
+ public void onUEvent(UEventObserver.UEvent event) {
+ setHdmiPlugged("1".equals(event.get("SWITCH_STATE")));
+ }
+ };
+
class SettingsObserver extends ContentObserver {
SettingsObserver(Handler handler) {
super(handler);
@@ -698,6 +708,11 @@
mSafeModeEnabledVibePattern = getLongIntArray(mContext.getResources(),
com.android.internal.R.array.config_safeModeEnabledVibePattern);
+ // watch for HDMI plug messages if the hdmi switch exists
+ if (new File("/sys/devices/virtual/switch/hdmi/state").exists()) {
+ mHDMIObserver.startObserving("DEVPATH=/devices/virtual/switch/hdmi");
+ }
+
// Note: the Configuration is not stable here, so we cannot load mStatusBarCanHide from
// config_statusBarCanHide because the latter depends on the screen size
}
@@ -1003,23 +1018,16 @@
try {
Context context = mContext;
- boolean setTheme = false;
//Log.i(TAG, "addStartingWindow " + packageName + ": nonLocalizedLabel="
// + nonLocalizedLabel + " theme=" + Integer.toHexString(theme));
- if (theme != 0 || labelRes != 0) {
+ if (theme != context.getThemeResId() || labelRes != 0) {
try {
context = context.createPackageContext(packageName, 0);
- if (theme != 0) {
- context.setTheme(theme);
- setTheme = true;
- }
+ context.setTheme(theme);
} catch (PackageManager.NameNotFoundException e) {
// Ignore
}
}
- if (!setTheme) {
- context.setTheme(com.android.internal.R.style.Theme);
- }
Window win = PolicyManager.makeNewWindow(context);
if (win.getWindowStyle().getBoolean(
@@ -1963,7 +1971,7 @@
boolean awakeNow = mKeyguardMediator.doLidChangeTq(mLidOpen);
updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
if (awakeNow) {
- // If the lid opening and we don't have to keep the
+ // If the lid is opening and we don't have to keep the
// keyguard up, then we can turn on the screen
// immediately.
mKeyguardMediator.pokeWakelock();
@@ -1987,6 +1995,16 @@
}
}
+ void setHdmiPlugged(boolean plugged) {
+ if (mHdmiPlugged != plugged) {
+ mHdmiPlugged = plugged;
+ updateRotation(Surface.FLAGS_ORIENTATION_ANIMATION_DISABLE);
+ Intent intent = new Intent(ACTION_HDMI_PLUGGED);
+ intent.putExtra(EXTRA_HDMI_PLUGGED_STATE, plugged);
+ mContext.sendStickyBroadcast(intent);
+ }
+ }
+
/**
* @return Whether music is being played right now.
*/
@@ -2418,7 +2436,9 @@
// case for nosensor meaning ignore sensor and consider only lid
// or orientation sensor disabled
//or case.unspecified
- if (mLidOpen) {
+ if (mHdmiPlugged) {
+ return Surface.ROTATION_0;
+ } else if (mLidOpen) {
return mLidOpenRotation;
} else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
return mCarDockRotation;
@@ -2586,7 +2606,9 @@
void updateRotation(int animFlags) {
mPowerManager.setKeyboardVisibility(mLidOpen);
int rotation = Surface.ROTATION_0;
- if (mLidOpen) {
+ if (mHdmiPlugged) {
+ rotation = Surface.ROTATION_0;
+ } else if (mLidOpen) {
rotation = mLidOpenRotation;
} else if (mDockMode == Intent.EXTRA_DOCK_STATE_CAR && mCarDockRotation >= 0) {
rotation = mCarDockRotation;
diff --git a/policy/src/com/android/internal/policy/impl/StatusView.java b/policy/src/com/android/internal/policy/impl/StatusView.java
index 2b78851..1caf0b7 100644
--- a/policy/src/com/android/internal/policy/impl/StatusView.java
+++ b/policy/src/com/android/internal/policy/impl/StatusView.java
@@ -19,6 +19,11 @@
import android.widget.TextView;
class StatusView {
+ private static final int LOCK_ICON = R.drawable.ic_lock_idle_lock;
+ private static final int ALARM_ICON = R.drawable.ic_lock_idle_alarm;
+ private static final int CHARGING_ICON = R.drawable.ic_lock_idle_charging;
+ private static final int BATTERY_LOW_ICON = R.drawable.ic_lock_idle_low_battery;
+
private String mDateFormatString;
private TextView mCarrier;
@@ -33,20 +38,18 @@
// last known battery level
private int mBatteryLevel = 100;
- private String mNextAlarm = null;
-
private String mInstructions = null;
private TextView mStatus1;
- private TextView mStatus2;
private TextView mPropertyOf;
- private boolean mHasStatus2;
private boolean mHasCarrier;
private boolean mHasDate;
- private boolean mHasProperty;
private View mView;
+ private TextView mAlarmStatus;
+ private LockPatternUtils mLockPatternUtils;
+
private View findViewById(int id) {
return mView.findViewById(id);
}
@@ -69,7 +72,7 @@
mShowingBatteryInfo = showBatteryInfo;
mPluggedIn = pluggedIn;
mBatteryLevel = batteryLevel;
- updateStatusLines();
+ updateStatusLines(true);
}
void onTimeChanged() {
@@ -91,14 +94,14 @@
mDate = (TextView) findViewById(R.id.date);
mHasDate = (mDate != null);
mDateFormatString = getContext().getString(R.string.full_wday_month_day_no_year);
+ mLockPatternUtils = lockPatternUtils;
refreshTimeAndDateDisplay();
mStatus1 = (TextView) findViewById(R.id.status1);
- mStatus2 = (TextView) findViewById(R.id.status2);
- mHasStatus2 = (mStatus2 != null);
+ mAlarmStatus = (TextView) findViewById(R.id.alarm_status);
+ mAlarmStatus.setCompoundDrawablesWithIntrinsicBounds(ALARM_ICON, 0, 0, 0);
mPropertyOf = (TextView) findViewById(R.id.propertyOf);
- mHasProperty = (mPropertyOf != null);
resetStatusInfo(updateMonitor, lockPatternUtils);
@@ -107,7 +110,6 @@
mCarrier.setSelected(true);
mCarrier.setTextColor(0xffffffff);
}
-
}
void resetStatusInfo(KeyguardUpdateMonitor updateMonitor, LockPatternUtils lockPatternUtils) {
@@ -115,19 +117,18 @@
mShowingBatteryInfo = updateMonitor.shouldShowBatteryInfo();
mPluggedIn = updateMonitor.isDevicePluggedIn();
mBatteryLevel = updateMonitor.getBatteryLevel();
- mNextAlarm = lockPatternUtils.getNextAlarm();
- updateStatusLines();
+ updateStatusLines(true);
}
void setInstructionText(int stringId) {
mStatus1.setText(stringId);
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_idle_lock, 0, 0, 0);
+ mStatus1.setCompoundDrawablesWithIntrinsicBounds(LOCK_ICON, 0, 0, 0);
mStatus1.setVisibility(View.VISIBLE);
}
void setInstructionText(String string) {
mStatus1.setText(string);
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_idle_lock, 0, 0, 0);
+ mStatus1.setCompoundDrawablesWithIntrinsicBounds(LOCK_ICON, 0, 0, 0);
mStatus1.setVisibility(View.VISIBLE);
}
@@ -138,9 +139,22 @@
mCarrier.setText(string);
}
- /** Originated from PatternUnlockScreen **/
- void updateStatusLines() {
- if (mHasProperty) {
+ /**
+ * Update the status lines based on these rules:
+ * AlarmStatus: Alarm state always gets it's own line.
+ * Status1 is shared between help, battery status and generic unlock instructions,
+ * prioritized in that order.
+ * @param showStatusLines status lines are shown if true
+ */
+ void updateStatusLines(boolean showStatusLines) {
+ if (!showStatusLines) {
+ mStatus1.setVisibility(showStatusLines ? View.VISIBLE : View.GONE);
+ mAlarmStatus.setVisibility(showStatusLines ? View.VISIBLE : View.GONE);
+ return;
+ }
+
+ // Update owner info
+ if (mPropertyOf != null) {
ContentResolver res = getContext().getContentResolver();
String info = Settings.Secure.getString(res, Settings.Secure.LOCK_SCREEN_OWNER_INFO);
boolean enabled = Settings.Secure.getInt(res,
@@ -151,104 +165,44 @@
View.VISIBLE : View.INVISIBLE);
}
- if (!mHasStatus2) return;
+ // Update Alarm status
+ String nextAlarm = mLockPatternUtils.getNextAlarm();
+ if (!TextUtils.isEmpty(nextAlarm)) {
+ mAlarmStatus.setText(nextAlarm);
+ mAlarmStatus.setVisibility(View.VISIBLE);
+ } else {
+ mAlarmStatus.setVisibility(View.GONE);
+ }
+ // Update Status1
if (mInstructions != null) {
- // instructions only
+ // Instructions only
+ final int resId = TextUtils.isEmpty(mInstructions) ? 0 : LOCK_ICON;
mStatus1.setText(mInstructions);
- if (TextUtils.isEmpty(mInstructions)) {
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
- } else {
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(
- R.drawable.ic_lock_idle_lock, 0, 0, 0);
- }
-
+ mStatus1.setCompoundDrawablesWithIntrinsicBounds(resId, 0, 0, 0);
mStatus1.setVisibility(View.VISIBLE);
- mStatus2.setVisibility(View.INVISIBLE);
- } else if (mShowingBatteryInfo && mNextAlarm == null) {
- // battery only
+ } else if (mShowingBatteryInfo) {
+ // Battery status
if (mPluggedIn) {
- if (mBatteryLevel >= 100) {
- mStatus1.setText(getContext().getString(R.string.lockscreen_charged));
- } else {
- mStatus1.setText(getContext().getString(R.string.lockscreen_plugged_in,
- mBatteryLevel));
- }
+ // Charging or charged
+ if (mBatteryLevel >= 100) {
+ mStatus1.setText(getContext().getString(R.string.lockscreen_charged));
+ } else {
+ mStatus1.setText(getContext().getString(R.string.lockscreen_plugged_in,
+ mBatteryLevel));
+ }
+ mStatus1.setCompoundDrawablesWithIntrinsicBounds(CHARGING_ICON, 0, 0, 0);
} else {
+ // Battery is low
mStatus1.setText(getContext().getString(R.string.lockscreen_low_battery));
+ mStatus1.setCompoundDrawablesWithIntrinsicBounds(BATTERY_LOW_ICON, 0, 0, 0);
}
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_idle_charging, 0,
- 0, 0);
-
mStatus1.setVisibility(View.VISIBLE);
- mStatus2.setVisibility(View.INVISIBLE);
-
- } else if (mNextAlarm != null && !mShowingBatteryInfo) {
- // alarm only
- mStatus1.setText(mNextAlarm);
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_idle_alarm, 0,
- 0, 0);
-
- mStatus1.setVisibility(View.VISIBLE);
- mStatus2.setVisibility(View.INVISIBLE);
- } else if (mNextAlarm != null && mShowingBatteryInfo) {
- // both battery and next alarm
- mStatus1.setText(mNextAlarm);
- mStatus2.setText(getContext().getString(
- R.string.lockscreen_battery_short,
- Math.min(100, mBatteryLevel)));
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_idle_alarm, 0,
- 0, 0);
- if (mPluggedIn) {
- mStatus2.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_idle_charging,
- 0, 0, 0);
- } else {
- mStatus2.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
- }
-
- mStatus1.setVisibility(View.VISIBLE);
- mStatus2.setVisibility(View.VISIBLE);
} else {
// nothing specific to show; show general instructions
mStatus1.setText(R.string.lockscreen_pattern_instructions);
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_lock_idle_lock, 0,
- 0, 0);
-
+ mStatus1.setCompoundDrawablesWithIntrinsicBounds(LOCK_ICON, 0,0, 0);
mStatus1.setVisibility(View.VISIBLE);
- mStatus2.setVisibility(View.INVISIBLE);
- }
- }
-
- /** Originated from LockScreen **/
- // TODO Merge with function above
- void updateStatusLines(boolean showStatusLines, String charging, Drawable chargingIcon,
- Drawable alarmIcon) {
- if (!showStatusLines || (charging == null && mNextAlarm == null)) {
- mStatus1.setVisibility(View.INVISIBLE);
- mStatus2.setVisibility(View.INVISIBLE);
- } else if (charging != null && mNextAlarm == null) {
- // charging only
- mStatus1.setVisibility(View.VISIBLE);
- mStatus2.setVisibility(View.INVISIBLE);
-
- mStatus1.setText(charging);
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(chargingIcon, null, null, null);
- } else if (mNextAlarm != null && charging == null) {
- // next alarm only
- mStatus1.setVisibility(View.VISIBLE);
- mStatus2.setVisibility(View.INVISIBLE);
-
- mStatus1.setText(mNextAlarm);
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(alarmIcon, null, null, null);
- } else if (charging != null && mNextAlarm != null) {
- // both charging and next alarm
- mStatus1.setVisibility(View.VISIBLE);
- mStatus2.setVisibility(View.VISIBLE);
-
- mStatus1.setText(charging);
- mStatus1.setCompoundDrawablesWithIntrinsicBounds(chargingIcon, null, null, null);
- mStatus2.setText(mNextAlarm);
- mStatus2.setCompoundDrawablesWithIntrinsicBounds(alarmIcon, null, null, null);
}
}
diff --git a/services/audioflinger/AudioPolicyManagerBase.cpp b/services/audioflinger/AudioPolicyManagerBase.cpp
index 855af9f..eeca7ab 100644
--- a/services/audioflinger/AudioPolicyManagerBase.cpp
+++ b/services/audioflinger/AudioPolicyManagerBase.cpp
@@ -1587,6 +1587,10 @@
if (device) break;
device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
if (device) break;
+ device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
+ if (device) break;
+ device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
+ if (device) break;
device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
if (device) break;
#ifdef WITH_A2DP
@@ -1605,6 +1609,10 @@
break;
case AudioSystem::FORCE_SPEAKER:
+ device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
+ if (device) break;
+ device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
+ if (device) break;
device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
if (device) break;
#ifdef WITH_A2DP
diff --git a/services/camera/libcameraservice/Android.mk b/services/camera/libcameraservice/Android.mk
index 87975af..b52fc69 100644
--- a/services/camera/libcameraservice/Android.mk
+++ b/services/camera/libcameraservice/Android.mk
@@ -49,7 +49,8 @@
libcutils \
libmedia \
libcamera_client \
- libsurfaceflinger_client
+ libsurfaceflinger_client \
+ libgui
LOCAL_MODULE:= libcameraservice
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index 15f6a44..3d8ca7a 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -27,6 +27,7 @@
#include <binder/MemoryHeapBase.h>
#include <cutils/atomic.h>
#include <cutils/properties.h>
+#include <gui/SurfaceTextureClient.h>
#include <hardware/hardware.h>
#include <media/AudioSystem.h>
#include <media/mediaplayer.h>
@@ -306,6 +307,8 @@
mCameraFacing = cameraFacing;
mClientPid = clientPid;
mMsgEnabled = 0;
+ mSurface = 0;
+ mPreviewWindow = 0;
mHardware->setCallbacks(notifyCallback,
dataCallback,
dataCallbackTimestamp,
@@ -470,19 +473,16 @@
// return if no change in surface.
// asBinder() is safe on NULL (returns NULL)
- if (getISurface(surface)->asBinder() == mSurface->asBinder()) {
+ if (getISurface(surface)->asBinder() == mSurface) {
return result;
}
if (mSurface != 0) {
LOG1("clearing old preview surface %p", mSurface.get());
}
- if (surface != 0) {
- mSurface = getISurface(surface);
- } else {
- mSurface = 0;
- }
+ mSurface = getISurface(surface)->asBinder();
mPreviewWindow = surface;
+
// If preview has been already started, register preview
// buffers now.
if (mHardware->previewEnabled()) {
@@ -496,6 +496,45 @@
return result;
}
+// set the SurfaceTexture that the preview will use
+status_t CameraService::Client::setPreviewTexture(
+ const sp<ISurfaceTexture>& surfaceTexture) {
+ LOG1("setPreviewTexture(%p) (pid %d)", surfaceTexture.get(),
+ getCallingPid());
+ Mutex::Autolock lock(mLock);
+ status_t result = checkPidAndHardware();
+ if (result != NO_ERROR) return result;
+
+ // return if no change in surface.
+ // asBinder() is safe on NULL (returns NULL)
+ if (surfaceTexture->asBinder() == mSurface) {
+ return result;
+ }
+
+ if (mSurface != 0) {
+ LOG1("clearing old preview surface %p", mSurface.get());
+ }
+ mSurface = surfaceTexture->asBinder();
+ if (surfaceTexture != 0) {
+ mPreviewWindow = new SurfaceTextureClient(surfaceTexture);
+ } else {
+ mPreviewWindow = 0;
+ }
+
+ // If preview has been already started, set overlay or register preview
+ // buffers now.
+ if (mHardware->previewEnabled()) {
+ // XXX: What if the new preview window is 0?
+ if (mPreviewWindow != 0) {
+ native_window_set_buffers_transform(mPreviewWindow.get(),
+ mOrientation);
+ result = mHardware->setPreviewWindow(mPreviewWindow);
+ }
+ }
+
+ return result;
+}
+
// set the preview callback flag to affect how the received frames from
// preview are handled.
void CameraService::Client::setPreviewCallbackFlag(int callback_flag) {
@@ -960,23 +999,6 @@
}
disableMsgType(CAMERA_MSG_SHUTTER);
- // It takes some time before yuvPicture callback to be called.
- // Register the buffer for raw image here to reduce latency.
- if (mSurface != 0) {
- int w, h;
- CameraParameters params(mHardware->getParameters());
- if (size == NULL) {
- params.getPictureSize(&w, &h);
- } else {
- w = size->width;
- h = size->height;
- w &= ~1;
- h &= ~1;
- LOG1("Snapshot image width=%d, height=%d", w, h);
- }
- IPCThreadState::self()->flushCommands();
- }
-
mLock.unlock();
}
diff --git a/services/camera/libcameraservice/CameraService.h b/services/camera/libcameraservice/CameraService.h
index d78d7e5..ccb9cf7 100644
--- a/services/camera/libcameraservice/CameraService.h
+++ b/services/camera/libcameraservice/CameraService.h
@@ -94,6 +94,7 @@
virtual status_t lock();
virtual status_t unlock();
virtual status_t setPreviewDisplay(const sp<Surface>& surface);
+ virtual status_t setPreviewTexture(const sp<ISurfaceTexture>& surfaceTexture);
virtual void setPreviewCallbackFlag(int flag);
virtual status_t startPreview();
virtual void stopPreview();
@@ -180,7 +181,8 @@
// Ensures atomicity among the public methods
mutable Mutex mLock;
- sp<ISurface> mSurface;
+ // This is a binder of Surface or SurfaceTexture.
+ sp<IBinder> mSurface;
sp<ANativeWindow> mPreviewWindow;
// If the user want us to return a copy of the preview frame (instead
diff --git a/services/input/Android.mk b/services/input/Android.mk
index 37804ff..d7b61fc 100644
--- a/services/input/Android.mk
+++ b/services/input/Android.mk
@@ -21,6 +21,7 @@
InputDispatcher.cpp \
InputManager.cpp \
InputReader.cpp \
+ InputWindow.cpp \
PointerController.cpp
LOCAL_SHARED_LIBRARIES := \
diff --git a/services/input/InputApplication.h b/services/input/InputApplication.h
new file mode 100644
index 0000000..cc80062
--- /dev/null
+++ b/services/input/InputApplication.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2011 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 _UI_INPUT_APPLICATION_H
+#define _UI_INPUT_APPLICATION_H
+
+#include <ui/Input.h>
+
+#include <utils/RefBase.h>
+#include <utils/Timers.h>
+#include <utils/String8.h>
+
+namespace android {
+
+/*
+ * A handle to an application that can receive input.
+ * Used by the native input dispatcher to indirectly refer to the window manager objects
+ * that describe an application.
+ */
+class InputApplicationHandle : public RefBase {
+protected:
+ InputApplicationHandle() { }
+ virtual ~InputApplicationHandle() { }
+};
+
+
+/*
+ * An input application describes properties of an application that can receive input.
+ */
+struct InputApplication {
+ sp<InputApplicationHandle> inputApplicationHandle;
+ String8 name;
+ nsecs_t dispatchingTimeout;
+};
+
+} // namespace android
+
+#endif // _UI_INPUT_APPLICATION_H
diff --git a/services/input/InputDispatcher.cpp b/services/input/InputDispatcher.cpp
index 89a7751..b5a4bd2 100644
--- a/services/input/InputDispatcher.cpp
+++ b/services/input/InputDispatcher.cpp
@@ -72,6 +72,10 @@
// when an application takes too long to respond and the user has pressed an app switch key.
const nsecs_t APP_SWITCH_TIMEOUT = 500 * 1000000LL; // 0.5sec
+// Amount of time to allow for an event to be dispatched (measured since its eventTime)
+// before considering it stale and dropping it.
+const nsecs_t STALE_EVENT_TIMEOUT = 10000 * 1000000LL; // 10sec
+
static inline nsecs_t now() {
return systemTime(SYSTEM_TIME_MONOTONIC);
@@ -151,34 +155,12 @@
}
-// --- InputWindow ---
-
-bool InputWindow::touchableAreaContainsPoint(int32_t x, int32_t y) const {
- return x >= touchableAreaLeft && x <= touchableAreaRight
- && y >= touchableAreaTop && y <= touchableAreaBottom;
-}
-
-bool InputWindow::frameContainsPoint(int32_t x, int32_t y) const {
- return x >= frameLeft && x <= frameRight
- && y >= frameTop && y <= frameBottom;
-}
-
-bool InputWindow::isTrustedOverlay() const {
- return layoutParamsType == TYPE_INPUT_METHOD
- || layoutParamsType == TYPE_INPUT_METHOD_DIALOG
- || layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY;
-}
-
-bool InputWindow::supportsSplitTouch() const {
- return layoutParamsFlags & InputWindow::FLAG_SPLIT_TOUCH;
-}
-
-
// --- InputDispatcher ---
InputDispatcher::InputDispatcher(const sp<InputDispatcherPolicyInterface>& policy) :
mPolicy(policy),
- mPendingEvent(NULL), mAppSwitchDueTime(LONG_LONG_MAX),
+ mPendingEvent(NULL), mAppSwitchSawKeyDown(false), mAppSwitchDueTime(LONG_LONG_MAX),
+ mNextUnblockedEvent(NULL),
mDispatchEnabled(true), mDispatchFrozen(false),
mFocusedWindow(NULL),
mFocusedApplication(NULL),
@@ -368,6 +350,7 @@
}
// Now we have an event to dispatch.
+ // All events are eventually dequeued and processed this way, even if we intend to drop them.
assert(mPendingEvent != NULL);
bool done = false;
DropReason dropReason = DROP_REASON_NOT_DROPPED;
@@ -376,6 +359,11 @@
} else if (!mDispatchEnabled) {
dropReason = DROP_REASON_DISABLED;
}
+
+ if (mNextUnblockedEvent == mPendingEvent) {
+ mNextUnblockedEvent = NULL;
+ }
+
switch (mPendingEvent->type) {
case EventEntry::TYPE_CONFIGURATION_CHANGED: {
ConfigurationChangedEntry* typedEntry =
@@ -395,6 +383,13 @@
dropReason = DROP_REASON_APP_SWITCH;
}
}
+ if (dropReason == DROP_REASON_NOT_DROPPED
+ && isStaleEventLocked(currentTime, typedEntry)) {
+ dropReason = DROP_REASON_STALE;
+ }
+ if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
+ dropReason = DROP_REASON_BLOCKED;
+ }
done = dispatchKeyLocked(currentTime, typedEntry, keyRepeatTimeout,
&dropReason, nextWakeupTime);
break;
@@ -405,6 +400,13 @@
if (dropReason == DROP_REASON_NOT_DROPPED && isAppSwitchDue) {
dropReason = DROP_REASON_APP_SWITCH;
}
+ if (dropReason == DROP_REASON_NOT_DROPPED
+ && isStaleEventLocked(currentTime, typedEntry)) {
+ dropReason = DROP_REASON_STALE;
+ }
+ if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {
+ dropReason = DROP_REASON_BLOCKED;
+ }
done = dispatchMotionLocked(currentTime, typedEntry,
&dropReason, nextWakeupTime);
break;
@@ -431,6 +433,9 @@
switch (entry->type) {
case EventEntry::TYPE_KEY: {
+ // Optimize app switch latency.
+ // If the application takes too long to catch up then we drop all events preceding
+ // the app switch key.
KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);
if (isAppSwitchKeyEventLocked(keyEntry)) {
if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {
@@ -448,11 +453,63 @@
}
break;
}
+
+ case EventEntry::TYPE_MOTION: {
+ // Optimize case where the current application is unresponsive and the user
+ // decides to touch a window in a different application.
+ // If the application takes too long to catch up then we drop all events preceding
+ // the touch into the other window.
+ MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);
+ if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN
+ && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)
+ && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY
+ && mInputTargetWaitApplication != NULL) {
+ int32_t x = int32_t(motionEntry->firstSample.pointerCoords[0].x);
+ int32_t y = int32_t(motionEntry->firstSample.pointerCoords[0].y);
+ const InputWindow* touchedWindow = findTouchedWindowAtLocked(x, y);
+ if (touchedWindow
+ && touchedWindow->inputWindowHandle != NULL
+ && touchedWindow->inputWindowHandle->getInputApplicationHandle()
+ != mInputTargetWaitApplication) {
+ // User touched a different application than the one we are waiting on.
+ // Flag the event, and start pruning the input queue.
+ mNextUnblockedEvent = motionEntry;
+ needWake = true;
+ }
+ }
+ break;
+ }
}
return needWake;
}
+const InputWindow* InputDispatcher::findTouchedWindowAtLocked(int32_t x, int32_t y) {
+ // Traverse windows from front to back to find touched window.
+ size_t numWindows = mWindows.size();
+ for (size_t i = 0; i < numWindows; i++) {
+ const InputWindow* window = & mWindows.editItemAt(i);
+ int32_t flags = window->layoutParamsFlags;
+
+ if (window->visible) {
+ if (!(flags & InputWindow::FLAG_NOT_TOUCHABLE)) {
+ bool isTouchModal = (flags & (InputWindow::FLAG_NOT_FOCUSABLE
+ | InputWindow::FLAG_NOT_TOUCH_MODAL)) == 0;
+ if (isTouchModal || window->touchableAreaContainsPoint(x, y)) {
+ // Found window.
+ return window;
+ }
+ }
+ }
+
+ if (flags & InputWindow::FLAG_SYSTEM_ERROR) {
+ // Error window is on top but not visible, so touch is dropped.
+ return NULL;
+ }
+ }
+ return NULL;
+}
+
void InputDispatcher::dropInboundEventLocked(EventEntry* entry, DropReason dropReason) {
const char* reason;
switch (dropReason) {
@@ -470,6 +527,16 @@
LOGI("Dropped event because of pending overdue app switch.");
reason = "inbound event was dropped because of pending overdue app switch";
break;
+ case DROP_REASON_BLOCKED:
+ LOGI("Dropped event because the current application is not responding and the user "
+ "has started interating with a different application.");
+ reason = "inbound event was dropped because the current application is not responding "
+ "and the user has started interating with a different application";
+ break;
+ case DROP_REASON_STALE:
+ LOGI("Dropped event because it is stale.");
+ reason = "inbound event was dropped because it is stale";
+ break;
default:
assert(false);
return;
@@ -521,6 +588,10 @@
#endif
}
+bool InputDispatcher::isStaleEventLocked(nsecs_t currentTime, EventEntry* entry) {
+ return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
+}
+
bool InputDispatcher::runCommandsLockedInterruptible() {
if (mCommandQueue.isEmpty()) {
return false;
@@ -670,7 +741,7 @@
CommandEntry* commandEntry = postCommandLocked(
& InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
if (mFocusedWindow) {
- commandEntry->inputChannel = mFocusedWindow->inputChannel;
+ commandEntry->inputWindowHandle = mFocusedWindow->inputWindowHandle;
}
commandEntry->keyEntry = entry;
entry->refCount += 1;
@@ -848,6 +919,7 @@
mCurrentInputTargetsValid = false;
mCurrentInputTargets.clear();
mInputTargetWaitCause = INPUT_TARGET_WAIT_CAUSE_NONE;
+ mInputTargetWaitApplication.clear();
}
void InputDispatcher::commitTargetsLocked() {
@@ -866,6 +938,7 @@
mInputTargetWaitStartTime = currentTime;
mInputTargetWaitTimeoutTime = LONG_LONG_MAX;
mInputTargetWaitTimeoutExpired = false;
+ mInputTargetWaitApplication.clear();
}
} else {
if (mInputTargetWaitCause != INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY) {
@@ -880,6 +953,15 @@
mInputTargetWaitStartTime = currentTime;
mInputTargetWaitTimeoutTime = currentTime + timeout;
mInputTargetWaitTimeoutExpired = false;
+ mInputTargetWaitApplication.clear();
+
+ if (window && window->inputWindowHandle != NULL) {
+ mInputTargetWaitApplication =
+ window->inputWindowHandle->getInputApplicationHandle();
+ }
+ if (mInputTargetWaitApplication == NULL && application) {
+ mInputTargetWaitApplication = application->inputApplicationHandle;
+ }
}
}
@@ -2624,7 +2706,7 @@
void InputDispatcher::releaseFocusedApplicationLocked() {
if (mFocusedApplication) {
mFocusedApplication = NULL;
- mFocusedApplicationStorage.handle.clear();
+ mFocusedApplicationStorage.inputApplicationHandle.clear();
}
}
@@ -2860,7 +2942,8 @@
}
}
-status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor) {
+status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,
+ const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
#if DEBUG_REGISTRATION
LOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),
toString(monitor));
@@ -2875,7 +2958,7 @@
return BAD_VALUE;
}
- sp<Connection> connection = new Connection(inputChannel);
+ sp<Connection> connection = new Connection(inputChannel, inputWindowHandle);
status_t status = connection->initialize();
if (status) {
LOGE("Failed to initialize input publisher for input channel '%s', status=%d",
@@ -3002,9 +3085,10 @@
CommandEntry* commandEntry = postCommandLocked(
& InputDispatcher::doNotifyANRLockedInterruptible);
if (application) {
- commandEntry->inputApplicationHandle = application->handle;
+ commandEntry->inputApplicationHandle = application->inputApplicationHandle;
}
if (window) {
+ commandEntry->inputWindowHandle = window->inputWindowHandle;
commandEntry->inputChannel = window->inputChannel;
}
}
@@ -3025,7 +3109,7 @@
if (connection->status != Connection::STATUS_ZOMBIE) {
mLock.unlock();
- mPolicy->notifyInputChannelBroken(connection->inputChannel);
+ mPolicy->notifyInputChannelBroken(connection->inputWindowHandle);
mLock.lock();
}
@@ -3036,7 +3120,7 @@
mLock.unlock();
nsecs_t newTimeout = mPolicy->notifyANR(
- commandEntry->inputApplicationHandle, commandEntry->inputChannel);
+ commandEntry->inputApplicationHandle, commandEntry->inputWindowHandle);
mLock.lock();
@@ -3052,7 +3136,7 @@
mLock.unlock();
- bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputChannel,
+ bool consumed = mPolicy->interceptKeyBeforeDispatching(commandEntry->inputWindowHandle,
&event, entry->policyFlags);
mLock.lock();
@@ -3095,7 +3179,7 @@
mLock.unlock();
- bool fallback = mPolicy->dispatchUnhandledKey(connection->inputChannel,
+ bool fallback = mPolicy->dispatchUnhandledKey(connection->inputWindowHandle,
&event, keyEntry->policyFlags, &event);
mLock.lock();
@@ -3604,8 +3688,10 @@
// --- InputDispatcher::Connection ---
-InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel) :
- status(STATUS_NORMAL), inputChannel(inputChannel), inputPublisher(inputChannel),
+InputDispatcher::Connection::Connection(const sp<InputChannel>& inputChannel,
+ const sp<InputWindowHandle>& inputWindowHandle) :
+ status(STATUS_NORMAL), inputChannel(inputChannel), inputWindowHandle(inputWindowHandle),
+ inputPublisher(inputChannel),
lastEventTime(LONG_LONG_MAX), lastDispatchTime(LONG_LONG_MAX) {
}
diff --git a/services/input/InputDispatcher.h b/services/input/InputDispatcher.h
index c8beab2..11e5117 100644
--- a/services/input/InputDispatcher.h
+++ b/services/input/InputDispatcher.h
@@ -33,6 +33,9 @@
#include <unistd.h>
#include <limits.h>
+#include "InputWindow.h"
+#include "InputApplication.h"
+
namespace android {
@@ -116,137 +119,6 @@
/*
- * An input window describes the bounds of a window that can receive input.
- */
-struct InputWindow {
- // Window flags from WindowManager.LayoutParams
- enum {
- FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001,
- FLAG_DIM_BEHIND = 0x00000002,
- FLAG_BLUR_BEHIND = 0x00000004,
- FLAG_NOT_FOCUSABLE = 0x00000008,
- FLAG_NOT_TOUCHABLE = 0x00000010,
- FLAG_NOT_TOUCH_MODAL = 0x00000020,
- FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040,
- FLAG_KEEP_SCREEN_ON = 0x00000080,
- FLAG_LAYOUT_IN_SCREEN = 0x00000100,
- FLAG_LAYOUT_NO_LIMITS = 0x00000200,
- FLAG_FULLSCREEN = 0x00000400,
- FLAG_FORCE_NOT_FULLSCREEN = 0x00000800,
- FLAG_DITHER = 0x00001000,
- FLAG_SECURE = 0x00002000,
- FLAG_SCALED = 0x00004000,
- FLAG_IGNORE_CHEEK_PRESSES = 0x00008000,
- FLAG_LAYOUT_INSET_DECOR = 0x00010000,
- FLAG_ALT_FOCUSABLE_IM = 0x00020000,
- FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000,
- FLAG_SHOW_WHEN_LOCKED = 0x00080000,
- FLAG_SHOW_WALLPAPER = 0x00100000,
- FLAG_TURN_SCREEN_ON = 0x00200000,
- FLAG_DISMISS_KEYGUARD = 0x00400000,
- FLAG_SPLIT_TOUCH = 0x00800000,
- FLAG_KEEP_SURFACE_WHILE_ANIMATING = 0x10000000,
- FLAG_COMPATIBLE_WINDOW = 0x20000000,
- FLAG_SYSTEM_ERROR = 0x40000000,
- };
-
- // Window types from WindowManager.LayoutParams
- enum {
- FIRST_APPLICATION_WINDOW = 1,
- TYPE_BASE_APPLICATION = 1,
- TYPE_APPLICATION = 2,
- TYPE_APPLICATION_STARTING = 3,
- LAST_APPLICATION_WINDOW = 99,
- FIRST_SUB_WINDOW = 1000,
- TYPE_APPLICATION_PANEL = FIRST_SUB_WINDOW,
- TYPE_APPLICATION_MEDIA = FIRST_SUB_WINDOW+1,
- TYPE_APPLICATION_SUB_PANEL = FIRST_SUB_WINDOW+2,
- TYPE_APPLICATION_ATTACHED_DIALOG = FIRST_SUB_WINDOW+3,
- TYPE_APPLICATION_MEDIA_OVERLAY = FIRST_SUB_WINDOW+4,
- LAST_SUB_WINDOW = 1999,
- FIRST_SYSTEM_WINDOW = 2000,
- TYPE_STATUS_BAR = FIRST_SYSTEM_WINDOW,
- TYPE_SEARCH_BAR = FIRST_SYSTEM_WINDOW+1,
- TYPE_PHONE = FIRST_SYSTEM_WINDOW+2,
- TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3,
- TYPE_KEYGUARD = FIRST_SYSTEM_WINDOW+4,
- TYPE_TOAST = FIRST_SYSTEM_WINDOW+5,
- TYPE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+6,
- TYPE_PRIORITY_PHONE = FIRST_SYSTEM_WINDOW+7,
- TYPE_SYSTEM_DIALOG = FIRST_SYSTEM_WINDOW+8,
- TYPE_KEYGUARD_DIALOG = FIRST_SYSTEM_WINDOW+9,
- TYPE_SYSTEM_ERROR = FIRST_SYSTEM_WINDOW+10,
- TYPE_INPUT_METHOD = FIRST_SYSTEM_WINDOW+11,
- TYPE_INPUT_METHOD_DIALOG= FIRST_SYSTEM_WINDOW+12,
- TYPE_WALLPAPER = FIRST_SYSTEM_WINDOW+13,
- TYPE_STATUS_BAR_SUB_PANEL = FIRST_SYSTEM_WINDOW+14,
- TYPE_SECURE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+15,
- TYPE_DRAG = FIRST_SYSTEM_WINDOW+16,
- TYPE_STATUS_BAR_PANEL = FIRST_SYSTEM_WINDOW+17,
- LAST_SYSTEM_WINDOW = 2999,
- };
-
- sp<InputChannel> inputChannel;
- String8 name;
- int32_t layoutParamsFlags;
- int32_t layoutParamsType;
- nsecs_t dispatchingTimeout;
- int32_t frameLeft;
- int32_t frameTop;
- int32_t frameRight;
- int32_t frameBottom;
- int32_t visibleFrameLeft;
- int32_t visibleFrameTop;
- int32_t visibleFrameRight;
- int32_t visibleFrameBottom;
- int32_t touchableAreaLeft;
- int32_t touchableAreaTop;
- int32_t touchableAreaRight;
- int32_t touchableAreaBottom;
- bool visible;
- bool canReceiveKeys;
- bool hasFocus;
- bool hasWallpaper;
- bool paused;
- int32_t layer;
- int32_t ownerPid;
- int32_t ownerUid;
-
- bool touchableAreaContainsPoint(int32_t x, int32_t y) const;
- bool frameContainsPoint(int32_t x, int32_t y) const;
-
- /* Returns true if the window is of a trusted type that is allowed to silently
- * overlay other windows for the purpose of implementing the secure views feature.
- * Trusted overlays, such as IME windows, can partly obscure other windows without causing
- * motion events to be delivered to them with AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED.
- */
- bool isTrustedOverlay() const;
-
- bool supportsSplitTouch() const;
-};
-
-
-/*
- * A private handle type used by the input manager to track the window.
- */
-class InputApplicationHandle : public RefBase {
-protected:
- InputApplicationHandle() { }
- virtual ~InputApplicationHandle() { }
-};
-
-
-/*
- * An input application describes properties of an application that can receive input.
- */
-struct InputApplication {
- String8 name;
- nsecs_t dispatchingTimeout;
- sp<InputApplicationHandle> handle;
-};
-
-
-/*
* Input dispatcher policy interface.
*
* The input reader policy is used by the input reader to interact with the Window Manager
@@ -267,10 +139,10 @@
/* Notifies the system that an application is not responding.
* Returns a new timeout to continue waiting, or 0 to abort dispatch. */
virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
- const sp<InputChannel>& inputChannel) = 0;
+ const sp<InputWindowHandle>& inputWindowHandle) = 0;
/* Notifies the system that an input channel is unrecoverably broken. */
- virtual void notifyInputChannelBroken(const sp<InputChannel>& inputChannel) = 0;
+ virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) = 0;
/* Gets the key repeat initial timeout or -1 if automatic key repeating is disabled. */
virtual nsecs_t getKeyRepeatTimeout() = 0;
@@ -303,12 +175,12 @@
virtual void interceptGenericBeforeQueueing(nsecs_t when, uint32_t& policyFlags) = 0;
/* Allows the policy a chance to intercept a key before dispatching. */
- virtual bool interceptKeyBeforeDispatching(const sp<InputChannel>& inputChannel,
+ virtual bool interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,
const KeyEvent* keyEvent, uint32_t policyFlags) = 0;
/* Allows the policy a chance to perform default processing for an unhandled key.
* Returns an alternate keycode to redispatch as a fallback, or 0 to give up. */
- virtual bool dispatchUnhandledKey(const sp<InputChannel>& inputChannel,
+ virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) = 0;
/* Notifies the policy about switch events.
@@ -407,7 +279,8 @@
*
* These methods may be called on any thread (usually by the input manager).
*/
- virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor) = 0;
+ virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
+ const sp<InputWindowHandle>& inputWindowHandle, bool monitor) = 0;
virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel) = 0;
};
@@ -461,7 +334,8 @@
virtual bool transferTouchFocus(const sp<InputChannel>& fromChannel,
const sp<InputChannel>& toChannel);
- virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor);
+ virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
+ const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
virtual status_t unregisterInputChannel(const sp<InputChannel>& inputChannel);
private:
@@ -615,6 +489,7 @@
KeyEntry* keyEntry;
sp<InputChannel> inputChannel;
sp<InputApplicationHandle> inputApplicationHandle;
+ sp<InputWindowHandle> inputWindowHandle;
int32_t userActivityEventType;
bool handled;
};
@@ -815,7 +690,8 @@
};
Status status;
- sp<InputChannel> inputChannel;
+ sp<InputChannel> inputChannel; // never null
+ sp<InputWindowHandle> inputWindowHandle; // may be null
InputPublisher inputPublisher;
InputState inputState;
Queue<DispatchEntry> outboundQueue;
@@ -823,7 +699,8 @@
nsecs_t lastEventTime; // the time when the event was originally captured
nsecs_t lastDispatchTime; // the time when the last event was dispatched
- explicit Connection(const sp<InputChannel>& inputChannel);
+ explicit Connection(const sp<InputChannel>& inputChannel,
+ const sp<InputWindowHandle>& inputWindowHandle);
inline const char* getInputChannelName() const { return inputChannel->getName().string(); }
@@ -851,6 +728,8 @@
DROP_REASON_POLICY = 1,
DROP_REASON_APP_SWITCH = 2,
DROP_REASON_DISABLED = 3,
+ DROP_REASON_BLOCKED = 4,
+ DROP_REASON_STALE = 5,
};
sp<InputDispatcherPolicyInterface> mPolicy;
@@ -884,6 +763,15 @@
bool isAppSwitchPendingLocked();
void resetPendingAppSwitchLocked(bool handled);
+ // Stale event latency optimization.
+ static bool isStaleEventLocked(nsecs_t currentTime, EventEntry* entry);
+
+ // Blocked event latency optimization. Drops old events when the user intends
+ // to transfer focus to a new application.
+ EventEntry* mNextUnblockedEvent;
+
+ const InputWindow* findTouchedWindowAtLocked(int32_t x, int32_t y);
+
// All registered connections mapped by receive pipe file descriptor.
KeyedVector<int, sp<Connection> > mConnectionsByReceiveFd;
@@ -1006,6 +894,7 @@
nsecs_t mInputTargetWaitStartTime;
nsecs_t mInputTargetWaitTimeoutTime;
bool mInputTargetWaitTimeoutExpired;
+ sp<InputApplicationHandle> mInputTargetWaitApplication;
// Finding targets for input events.
void resetTargetsLocked();
diff --git a/services/input/InputWindow.cpp b/services/input/InputWindow.cpp
new file mode 100644
index 0000000..9ce45f5
--- /dev/null
+++ b/services/input/InputWindow.cpp
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2011 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 "InputWindow"
+
+#include "InputWindow.h"
+
+#include <cutils/log.h>
+
+namespace android {
+
+// --- InputWindow ---
+
+bool InputWindow::touchableAreaContainsPoint(int32_t x, int32_t y) const {
+ return x >= touchableAreaLeft && x <= touchableAreaRight
+ && y >= touchableAreaTop && y <= touchableAreaBottom;
+}
+
+bool InputWindow::frameContainsPoint(int32_t x, int32_t y) const {
+ return x >= frameLeft && x <= frameRight
+ && y >= frameTop && y <= frameBottom;
+}
+
+bool InputWindow::isTrustedOverlay() const {
+ return layoutParamsType == TYPE_INPUT_METHOD
+ || layoutParamsType == TYPE_INPUT_METHOD_DIALOG
+ || layoutParamsType == TYPE_SECURE_SYSTEM_OVERLAY;
+}
+
+bool InputWindow::supportsSplitTouch() const {
+ return layoutParamsFlags & InputWindow::FLAG_SPLIT_TOUCH;
+}
+
+} // namespace android
diff --git a/services/input/InputWindow.h b/services/input/InputWindow.h
new file mode 100644
index 0000000..b3d5a65
--- /dev/null
+++ b/services/input/InputWindow.h
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2011 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 _UI_INPUT_WINDOW_H
+#define _UI_INPUT_WINDOW_H
+
+#include <ui/Input.h>
+#include <ui/InputTransport.h>
+#include <utils/RefBase.h>
+#include <utils/Timers.h>
+#include <utils/String8.h>
+
+#include "InputApplication.h"
+
+namespace android {
+
+/*
+ * A handle to a window that can receive input.
+ * Used by the native input dispatcher to indirectly refer to the window manager objects
+ * that describe a window.
+ */
+class InputWindowHandle : public RefBase {
+protected:
+ InputWindowHandle(const sp<InputApplicationHandle>& inputApplicationHandle) :
+ mInputApplicationHandle(inputApplicationHandle) { }
+ virtual ~InputWindowHandle() { }
+
+public:
+ inline sp<InputApplicationHandle> getInputApplicationHandle() {
+ return mInputApplicationHandle;
+ }
+
+private:
+ sp<InputApplicationHandle> mInputApplicationHandle;
+};
+
+
+/*
+ * An input window describes the bounds of a window that can receive input.
+ */
+struct InputWindow {
+ // Window flags from WindowManager.LayoutParams
+ enum {
+ FLAG_ALLOW_LOCK_WHILE_SCREEN_ON = 0x00000001,
+ FLAG_DIM_BEHIND = 0x00000002,
+ FLAG_BLUR_BEHIND = 0x00000004,
+ FLAG_NOT_FOCUSABLE = 0x00000008,
+ FLAG_NOT_TOUCHABLE = 0x00000010,
+ FLAG_NOT_TOUCH_MODAL = 0x00000020,
+ FLAG_TOUCHABLE_WHEN_WAKING = 0x00000040,
+ FLAG_KEEP_SCREEN_ON = 0x00000080,
+ FLAG_LAYOUT_IN_SCREEN = 0x00000100,
+ FLAG_LAYOUT_NO_LIMITS = 0x00000200,
+ FLAG_FULLSCREEN = 0x00000400,
+ FLAG_FORCE_NOT_FULLSCREEN = 0x00000800,
+ FLAG_DITHER = 0x00001000,
+ FLAG_SECURE = 0x00002000,
+ FLAG_SCALED = 0x00004000,
+ FLAG_IGNORE_CHEEK_PRESSES = 0x00008000,
+ FLAG_LAYOUT_INSET_DECOR = 0x00010000,
+ FLAG_ALT_FOCUSABLE_IM = 0x00020000,
+ FLAG_WATCH_OUTSIDE_TOUCH = 0x00040000,
+ FLAG_SHOW_WHEN_LOCKED = 0x00080000,
+ FLAG_SHOW_WALLPAPER = 0x00100000,
+ FLAG_TURN_SCREEN_ON = 0x00200000,
+ FLAG_DISMISS_KEYGUARD = 0x00400000,
+ FLAG_SPLIT_TOUCH = 0x00800000,
+ FLAG_KEEP_SURFACE_WHILE_ANIMATING = 0x10000000,
+ FLAG_COMPATIBLE_WINDOW = 0x20000000,
+ FLAG_SYSTEM_ERROR = 0x40000000,
+ };
+
+ // Window types from WindowManager.LayoutParams
+ enum {
+ FIRST_APPLICATION_WINDOW = 1,
+ TYPE_BASE_APPLICATION = 1,
+ TYPE_APPLICATION = 2,
+ TYPE_APPLICATION_STARTING = 3,
+ LAST_APPLICATION_WINDOW = 99,
+ FIRST_SUB_WINDOW = 1000,
+ TYPE_APPLICATION_PANEL = FIRST_SUB_WINDOW,
+ TYPE_APPLICATION_MEDIA = FIRST_SUB_WINDOW+1,
+ TYPE_APPLICATION_SUB_PANEL = FIRST_SUB_WINDOW+2,
+ TYPE_APPLICATION_ATTACHED_DIALOG = FIRST_SUB_WINDOW+3,
+ TYPE_APPLICATION_MEDIA_OVERLAY = FIRST_SUB_WINDOW+4,
+ LAST_SUB_WINDOW = 1999,
+ FIRST_SYSTEM_WINDOW = 2000,
+ TYPE_STATUS_BAR = FIRST_SYSTEM_WINDOW,
+ TYPE_SEARCH_BAR = FIRST_SYSTEM_WINDOW+1,
+ TYPE_PHONE = FIRST_SYSTEM_WINDOW+2,
+ TYPE_SYSTEM_ALERT = FIRST_SYSTEM_WINDOW+3,
+ TYPE_KEYGUARD = FIRST_SYSTEM_WINDOW+4,
+ TYPE_TOAST = FIRST_SYSTEM_WINDOW+5,
+ TYPE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+6,
+ TYPE_PRIORITY_PHONE = FIRST_SYSTEM_WINDOW+7,
+ TYPE_SYSTEM_DIALOG = FIRST_SYSTEM_WINDOW+8,
+ TYPE_KEYGUARD_DIALOG = FIRST_SYSTEM_WINDOW+9,
+ TYPE_SYSTEM_ERROR = FIRST_SYSTEM_WINDOW+10,
+ TYPE_INPUT_METHOD = FIRST_SYSTEM_WINDOW+11,
+ TYPE_INPUT_METHOD_DIALOG= FIRST_SYSTEM_WINDOW+12,
+ TYPE_WALLPAPER = FIRST_SYSTEM_WINDOW+13,
+ TYPE_STATUS_BAR_SUB_PANEL = FIRST_SYSTEM_WINDOW+14,
+ TYPE_SECURE_SYSTEM_OVERLAY = FIRST_SYSTEM_WINDOW+15,
+ TYPE_DRAG = FIRST_SYSTEM_WINDOW+16,
+ TYPE_STATUS_BAR_PANEL = FIRST_SYSTEM_WINDOW+17,
+ LAST_SYSTEM_WINDOW = 2999,
+ };
+
+ sp<InputWindowHandle> inputWindowHandle;
+ sp<InputChannel> inputChannel;
+ String8 name;
+ int32_t layoutParamsFlags;
+ int32_t layoutParamsType;
+ nsecs_t dispatchingTimeout;
+ int32_t frameLeft;
+ int32_t frameTop;
+ int32_t frameRight;
+ int32_t frameBottom;
+ int32_t visibleFrameLeft;
+ int32_t visibleFrameTop;
+ int32_t visibleFrameRight;
+ int32_t visibleFrameBottom;
+ int32_t touchableAreaLeft;
+ int32_t touchableAreaTop;
+ int32_t touchableAreaRight;
+ int32_t touchableAreaBottom;
+ bool visible;
+ bool canReceiveKeys;
+ bool hasFocus;
+ bool hasWallpaper;
+ bool paused;
+ int32_t layer;
+ int32_t ownerPid;
+ int32_t ownerUid;
+
+ bool touchableAreaContainsPoint(int32_t x, int32_t y) const;
+ bool frameContainsPoint(int32_t x, int32_t y) const;
+
+ /* Returns true if the window is of a trusted type that is allowed to silently
+ * overlay other windows for the purpose of implementing the secure views feature.
+ * Trusted overlays, such as IME windows, can partly obscure other windows without causing
+ * motion events to be delivered to them with AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED.
+ */
+ bool isTrustedOverlay() const;
+
+ bool supportsSplitTouch() const;
+};
+
+} // namespace android
+
+#endif // _UI_INPUT_WINDOW_H
diff --git a/services/input/tests/InputDispatcher_test.cpp b/services/input/tests/InputDispatcher_test.cpp
index b79633a..5ba1867 100644
--- a/services/input/tests/InputDispatcher_test.cpp
+++ b/services/input/tests/InputDispatcher_test.cpp
@@ -36,11 +36,11 @@
}
virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
- const sp<InputChannel>& inputChannel) {
+ const sp<InputWindowHandle>& inputWindowHandle) {
return 0;
}
- virtual void notifyInputChannelBroken(const sp<InputChannel>& inputChannel) {
+ virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) {
}
virtual nsecs_t getKeyRepeatTimeout() {
@@ -61,12 +61,12 @@
virtual void interceptGenericBeforeQueueing(nsecs_t when, uint32_t& policyFlags) {
}
- virtual bool interceptKeyBeforeDispatching(const sp<InputChannel>& inputChannel,
+ virtual bool interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,
const KeyEvent* keyEvent, uint32_t policyFlags) {
return false;
}
- virtual bool dispatchUnhandledKey(const sp<InputChannel>& inputChannel,
+ virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) {
return false;
}
diff --git a/services/input/tests/InputReader_test.cpp b/services/input/tests/InputReader_test.cpp
index 9d2c52f..8ec6f53 100644
--- a/services/input/tests/InputReader_test.cpp
+++ b/services/input/tests/InputReader_test.cpp
@@ -368,7 +368,8 @@
return 0;
}
- virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel, bool monitor) {
+ virtual status_t registerInputChannel(const sp<InputChannel>& inputChannel,
+ const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
ADD_FAILURE() << "Should never be called by input reader.";
return 0;
}
diff --git a/services/java/com/android/server/AccessibilityManagerService.java b/services/java/com/android/server/AccessibilityManagerService.java
index 77b6dd0..63be030 100644
--- a/services/java/com/android/server/AccessibilityManagerService.java
+++ b/services/java/com/android/server/AccessibilityManagerService.java
@@ -532,11 +532,11 @@
for (int i = 0, count = services.size(); i < count; i++) {
Service service = services.get(i);
-
- service.unbind();
- mComponentNameToServiceMap.remove(service.mComponentName);
+ if (service.unbind()) {
+ i--;
+ count--;
+ }
}
- services.clear();
}
/**
@@ -578,7 +578,6 @@
Set<ComponentName> enabledServices) {
Map<ComponentName, Service> componentNameToServiceMap = mComponentNameToServiceMap;
- List<Service> services = mServices;
boolean isEnabled = mIsEnabled;
for (int i = 0, count = installedServices.size(); i < count; i++) {
@@ -588,15 +587,18 @@
Service service = componentNameToServiceMap.get(componentName);
if (isEnabled) {
- if (enabledServices.contains(componentName) && service == null) {
- new Service(componentName).bind();
- } else if (!enabledServices.contains(componentName) && service != null) {
- // clean up done in Service#onServiceDisconnected
- service.unbind();
+ if (enabledServices.contains(componentName)) {
+ if (service == null) {
+ service = new Service(componentName);
+ }
+ service.bind();
+ } else if (!enabledServices.contains(componentName)) {
+ if (service != null) {
+ service.unbind();
+ }
}
} else {
if (service != null) {
- // clean up done in Service#onServiceDisconnected
service.unbind();
}
}
@@ -665,21 +667,30 @@
/**
* Binds to the accessibility service.
+ *
+ * @return True if binding is successful.
*/
- public void bind() {
+ public boolean bind() {
if (mService == null) {
- mContext.bindService(mIntent, this, Context.BIND_AUTO_CREATE);
+ return mContext.bindService(mIntent, this, Context.BIND_AUTO_CREATE);
}
+ return false;
}
/**
* Unbinds form the accessibility service and removes it from the data
* structures for service management.
+ *
+ * @return True if unbinding is successful.
*/
- public void unbind() {
+ public boolean unbind() {
if (mService != null) {
mContext.unbindService(this);
+ mComponentNameToServiceMap.remove(mComponentName);
+ mServices.remove(this);
+ return true;
}
+ return false;
}
/**
diff --git a/services/java/com/android/server/AppWidgetService.java b/services/java/com/android/server/AppWidgetService.java
index ae408fc..22dd804 100644
--- a/services/java/com/android/server/AppWidgetService.java
+++ b/services/java/com/android/server/AppWidgetService.java
@@ -144,6 +144,7 @@
// update the provider list.
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
+ filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addDataScheme("package");
mContext.registerReceiver(mBroadcastReceiver, filter);
@@ -643,6 +644,12 @@
}
boolean addProviderLocked(ResolveInfo ri) {
+ if ((ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
+ return false;
+ }
+ if (!ri.activityInfo.isEnabled()) {
+ return false;
+ }
Provider p = parseProviderInfoXml(new ComponentName(ri.activityInfo.packageName,
ri.activityInfo.name), ri);
if (p != null) {
@@ -1160,6 +1167,7 @@
}
} else {
boolean added = false;
+ boolean changed = false;
String pkgList[] = null;
if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
@@ -1178,14 +1186,16 @@
}
pkgList = new String[] { pkgName };
added = Intent.ACTION_PACKAGE_ADDED.equals(action);
+ changed = Intent.ACTION_PACKAGE_CHANGED.equals(action);
}
if (pkgList == null || pkgList.length == 0) {
return;
}
- if (added) {
+ if (added || changed) {
synchronized (mAppWidgetIds) {
Bundle extras = intent.getExtras();
- if (extras != null && extras.getBoolean(Intent.EXTRA_REPLACING, false)) {
+ if (changed || (extras != null &&
+ extras.getBoolean(Intent.EXTRA_REPLACING, false))) {
for (String pkgName : pkgList) {
// The package was just upgraded
updateProvidersForPackageLocked(pkgName);
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index 3b47bce..b1eead2 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -1132,11 +1132,13 @@
}
}
- // returns null if no failover available
+ // returns null if no failover available, otherwise returns the highest
+ // priority network we're trying
private NetworkStateTracker tryFailover(int prevNetType) {
/*
- * If this is a default network, check if other defaults are available
- * or active
+ * If this is a default network, check if other defaults are available.
+ * Try to reconnect on all available and let them hash it out when
+ * more than one connects.
*/
NetworkStateTracker newNet = null;
if (mNetAttributes[prevNetType].isDefault()) {
@@ -1149,54 +1151,30 @@
for (int checkType=0; checkType <= ConnectivityManager.MAX_NETWORK_TYPE; checkType++) {
if (checkType == prevNetType) continue;
if (mNetAttributes[checkType] == null) continue;
- if (mNetAttributes[checkType].isDefault()) {
- /* TODO - if we have multiple nets we could use
- * we may want to put more thought into which we choose
- */
- if (checkType == mNetworkPreference) {
- newType = checkType;
- break;
- }
- if (mNetAttributes[checkType].mPriority > newPriority) {
- newType = checkType;
- newPriority = mNetAttributes[newType].mPriority;
- }
- }
- }
+ if (!mNetAttributes[checkType].isDefault()) continue;
+ if (!mNetTrackers[checkType].isAvailable()) continue;
- if (newType != -1) {
- newNet = mNetTrackers[newType];
- /**
- * See if the other network is available to fail over to.
- * If is not available, we enable it anyway, so that it
- * will be able to connect when it does become available,
- * but we report a total loss of connectivity rather than
- * report that we are attempting to fail over.
- */
- if (newNet.isAvailable()) {
- NetworkInfo switchTo = newNet.getNetworkInfo();
- switchTo.setFailover(true);
- if (!switchTo.isConnectedOrConnecting() ||
- newNet.isTeardownRequested()) {
- newNet.reconnect();
- }
- if (DBG) {
- if (switchTo.isConnected()) {
- log("Switching to already connected " + switchTo.getTypeName());
- } else {
- log("Attempting to switch to " + switchTo.getTypeName());
- }
- }
- } else {
- newNet.reconnect();
- newNet = null; // not officially avail.. try anyway, but
- // report no failover
+ NetworkStateTracker tracker = mNetTrackers[checkType];
+ NetworkInfo info = tracker.getNetworkInfo();
+ if (!info.isConnectedOrConnecting() ||
+ tracker.isTeardownRequested()) {
+ info.setFailover(true);
+ tracker.reconnect();
}
- } else {
- loge("Network failover failing.");
+ if (DBG) log("Attempting to switch to " + info.getTypeName());
+
+ // figure out if this is the highest priority network
+ // so we send an appropriate return value
+ if (checkType == mNetworkPreference) {
+ newType = checkType;
+ }
+ if (mNetAttributes[checkType].mPriority > newPriority &&
+ newType != mNetworkPreference) {
+ newType = checkType;
+ newPriority = mNetAttributes[newType].mPriority;
+ }
}
}
-
return newNet;
}
diff --git a/services/java/com/android/server/DeviceStorageMonitorService.java b/services/java/com/android/server/DeviceStorageMonitorService.java
index 0b1a4a3..0fba7c3 100644
--- a/services/java/com/android/server/DeviceStorageMonitorService.java
+++ b/services/java/com/android/server/DeviceStorageMonitorService.java
@@ -16,7 +16,6 @@
package com.android.server;
-import com.android.server.am.ActivityManagerService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
@@ -38,7 +37,6 @@
import android.util.Config;
import android.util.EventLog;
import android.util.Slog;
-import android.provider.Settings;
/**
* This class implements a service to monitor the amount of disk
@@ -66,6 +64,7 @@
private static final int MONITOR_INTERVAL = 1; //in minutes
private static final int LOW_MEMORY_NOTIFICATION_ID = 1;
private static final int DEFAULT_THRESHOLD_PERCENTAGE = 10;
+ private static final int DEFAULT_THRESHOLD_MAX_BYTES = 500*1024*1024; // 500MB
private static final int DEFAULT_FREE_STORAGE_LOG_INTERVAL_IN_MINUTES = 12*60; //in minutes
private static final long DEFAULT_DISK_FREE_CHANGE_REPORTING_THRESHOLD = 2 * 1024 * 1024; // 2MB
private static final long DEFAULT_CHECK_INTERVAL = MONITOR_INTERVAL*60*1000;
@@ -271,13 +270,18 @@
* any way
*/
private long getMemThreshold() {
- int value = Settings.Secure.getInt(
+ long value = Settings.Secure.getInt(
mContentResolver,
Settings.Secure.SYS_STORAGE_THRESHOLD_PERCENTAGE,
DEFAULT_THRESHOLD_PERCENTAGE);
if(localLOGV) Slog.v(TAG, "Threshold Percentage="+value);
+ value *= mTotalMemory;
+ long maxValue = Settings.Secure.getInt(
+ mContentResolver,
+ Settings.Secure.SYS_STORAGE_THRESHOLD_MAX_BYTES,
+ DEFAULT_THRESHOLD_MAX_BYTES);
//evaluate threshold value
- return mTotalMemory*value;
+ return value < maxValue ? value : maxValue;
}
/*
diff --git a/services/java/com/android/server/InputApplication.java b/services/java/com/android/server/InputApplication.java
index 38420d4..ae09484 100644
--- a/services/java/com/android/server/InputApplication.java
+++ b/services/java/com/android/server/InputApplication.java
@@ -18,16 +18,19 @@
/**
* Describes input-related application properties for use by the input dispatcher.
- *
* @hide
*/
public final class InputApplication {
+ // Application handle.
+ public InputApplicationHandle inputApplicationHandle;
+
// Application name.
public String name;
-
+
// Dispatching timeout.
public long dispatchingTimeoutNanos;
-
- // The application window token.
- public Object token;
+
+ public void recycle() {
+ inputApplicationHandle = null;
+ }
}
diff --git a/services/java/com/android/server/InputApplicationHandle.java b/services/java/com/android/server/InputApplicationHandle.java
new file mode 100644
index 0000000..d396d11
--- /dev/null
+++ b/services/java/com/android/server/InputApplicationHandle.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2011 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.server;
+
+/**
+ * Functions as a handle for an application that can receive input.
+ * Enables the native input dispatcher to refer indirectly to the window manager's
+ * application window token.
+ * @hide
+ */
+public final class InputApplicationHandle {
+ // Pointer to the native input application handle.
+ // This field is lazily initialized via JNI.
+ @SuppressWarnings("unused")
+ private int ptr;
+
+ // The window manager's application window token.
+ public final WindowManagerService.AppWindowToken appWindowToken;
+
+ private native void nativeDispose();
+
+ public InputApplicationHandle(WindowManagerService.AppWindowToken appWindowToken) {
+ this.appWindowToken = appWindowToken;
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ nativeDispose();
+ super.finalize();
+ }
+}
diff --git a/services/java/com/android/server/InputManager.java b/services/java/com/android/server/InputManager.java
index 410b8c2..5c2048b 100644
--- a/services/java/com/android/server/InputManager.java
+++ b/services/java/com/android/server/InputManager.java
@@ -77,7 +77,7 @@
private static native boolean nativeHasKeys(int deviceId, int sourceMask,
int[] keyCodes, boolean[] keyExists);
private static native void nativeRegisterInputChannel(InputChannel inputChannel,
- boolean monitor);
+ InputWindowHandle inputWindowHandle, boolean monitor);
private static native void nativeUnregisterInputChannel(InputChannel inputChannel);
private static native int nativeInjectInputEvent(InputEvent event,
int injectorPid, int injectorUid, int syncMode, int timeoutMillis);
@@ -240,7 +240,7 @@
}
InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
- nativeRegisterInputChannel(inputChannels[0], true);
+ nativeRegisterInputChannel(inputChannels[0], null, true);
inputChannels[0].dispose(); // don't need to retain the Java object reference
return inputChannels[1];
}
@@ -248,13 +248,16 @@
/**
* Registers an input channel so that it can be used as an input event target.
* @param inputChannel The input channel to register.
+ * @param inputWindowHandle The handle of the input window associated with the
+ * input channel, or null if none.
*/
- public void registerInputChannel(InputChannel inputChannel) {
+ public void registerInputChannel(InputChannel inputChannel,
+ InputWindowHandle inputWindowHandle) {
if (inputChannel == null) {
throw new IllegalArgumentException("inputChannel must not be null.");
}
- nativeRegisterInputChannel(inputChannel, false);
+ nativeRegisterInputChannel(inputChannel, inputWindowHandle, false);
}
/**
@@ -429,13 +432,15 @@
}
@SuppressWarnings("unused")
- public void notifyInputChannelBroken(InputChannel inputChannel) {
- mWindowManagerService.mInputMonitor.notifyInputChannelBroken(inputChannel);
+ public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
+ mWindowManagerService.mInputMonitor.notifyInputChannelBroken(inputWindowHandle);
}
@SuppressWarnings("unused")
- public long notifyANR(Object token, InputChannel inputChannel) {
- return mWindowManagerService.mInputMonitor.notifyANR(token, inputChannel);
+ public long notifyANR(InputApplicationHandle inputApplicationHandle,
+ InputWindowHandle inputWindowHandle) {
+ return mWindowManagerService.mInputMonitor.notifyANR(
+ inputApplicationHandle, inputWindowHandle);
}
@SuppressWarnings("unused")
@@ -445,14 +450,14 @@
}
@SuppressWarnings("unused")
- public boolean interceptKeyBeforeDispatching(InputChannel focus,
+ public boolean interceptKeyBeforeDispatching(InputWindowHandle focus,
KeyEvent event, int policyFlags) {
return mWindowManagerService.mInputMonitor.interceptKeyBeforeDispatching(
focus, event, policyFlags);
}
@SuppressWarnings("unused")
- public KeyEvent dispatchUnhandledKey(InputChannel focus,
+ public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
KeyEvent event, int policyFlags) {
return mWindowManagerService.mInputMonitor.dispatchUnhandledKey(
focus, event, policyFlags);
diff --git a/services/java/com/android/server/InputWindow.java b/services/java/com/android/server/InputWindow.java
index befc770..1515290 100644
--- a/services/java/com/android/server/InputWindow.java
+++ b/services/java/com/android/server/InputWindow.java
@@ -20,64 +20,67 @@
/**
* Describes input-related window properties for use by the input dispatcher.
- *
* @hide
*/
public final class InputWindow {
+ // The window handle.
+ public InputWindowHandle inputWindowHandle;
+
// The input channel associated with the window.
public InputChannel inputChannel;
-
+
// The window name.
public String name;
-
+
// Window layout params attributes. (WindowManager.LayoutParams)
public int layoutParamsFlags;
public int layoutParamsType;
-
+
// Dispatching timeout.
public long dispatchingTimeoutNanos;
-
+
// Window frame area.
public int frameLeft;
public int frameTop;
public int frameRight;
public int frameBottom;
-
+
// Window visible frame area.
public int visibleFrameLeft;
public int visibleFrameTop;
public int visibleFrameRight;
public int visibleFrameBottom;
-
+
// Window touchable area.
public int touchableAreaLeft;
public int touchableAreaTop;
public int touchableAreaRight;
public int touchableAreaBottom;
-
+
// Window is visible.
public boolean visible;
-
+
// Window can receive keys.
public boolean canReceiveKeys;
-
+
// Window has focus.
public boolean hasFocus;
-
+
// Window has wallpaper. (window is the current wallpaper target)
public boolean hasWallpaper;
-
+
// Input event dispatching is paused.
public boolean paused;
-
+
// Window layer.
public int layer;
-
+
// Id of process and user that owns the window.
public int ownerPid;
public int ownerUid;
-
+
public void recycle() {
+ inputWindowHandle = null;
inputChannel = null;
}
}
diff --git a/services/java/com/android/server/InputWindowHandle.java b/services/java/com/android/server/InputWindowHandle.java
new file mode 100644
index 0000000..4b92939
--- /dev/null
+++ b/services/java/com/android/server/InputWindowHandle.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2011 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.server;
+
+import android.view.WindowManagerPolicy;
+
+/**
+ * Functions as a handle for a window that can receive input.
+ * Enables the native input dispatcher to refer indirectly to the window manager's window state.
+ * @hide
+ */
+public final class InputWindowHandle {
+ // Pointer to the native input window handle.
+ // This field is lazily initialized via JNI.
+ @SuppressWarnings("unused")
+ private int ptr;
+
+ // The input application handle.
+ public final InputApplicationHandle inputApplicationHandle;
+
+ // The window manager's window state.
+ public final WindowManagerPolicy.WindowState windowState;
+
+ private native void nativeDispose();
+
+ public InputWindowHandle(InputApplicationHandle inputApplicationHandle,
+ WindowManagerPolicy.WindowState windowState) {
+ this.inputApplicationHandle = inputApplicationHandle;
+ this.windowState = windowState;
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ nativeDispose();
+ super.finalize();
+ }
+}
diff --git a/services/java/com/android/server/PackageManagerService.java b/services/java/com/android/server/PackageManagerService.java
index 7965dda..e323b3b 100644
--- a/services/java/com/android/server/PackageManagerService.java
+++ b/services/java/com/android/server/PackageManagerService.java
@@ -2927,24 +2927,23 @@
System.arraycopy(mTmpSharedLibraries, 0,
pkg.usesLibraryFiles, 0, num);
}
+ }
- if (pkg.reqFeatures != null) {
- N = pkg.reqFeatures.size();
- for (int i=0; i<N; i++) {
- FeatureInfo fi = pkg.reqFeatures.get(i);
- if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
- // Don't care.
- continue;
- }
+ if (pkg.reqFeatures != null) {
+ int N = pkg.reqFeatures.size();
+ for (int i = 0; i < N; i++) {
+ FeatureInfo fi = pkg.reqFeatures.get(i);
+ if ((fi.flags & FeatureInfo.FLAG_REQUIRED) == 0) {
+ // Don't care.
+ continue;
+ }
- if (fi.name != null) {
- if (mAvailableFeatures.get(fi.name) == null) {
- Slog.e(TAG, "Package " + pkg.packageName
- + " requires unavailable feature "
- + fi.name + "; failing!");
- mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
- return null;
- }
+ if (fi.name != null) {
+ if (mAvailableFeatures.get(fi.name) == null) {
+ Slog.e(TAG, "Package " + pkg.packageName
+ + " requires unavailable feature " + fi.name + "; failing!");
+ mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
+ return null;
}
}
}
@@ -3664,17 +3663,6 @@
mAppDirs.remove(pkg.mPath);
}
- PackageSetting ps = (PackageSetting)pkg.mExtras;
- if (ps != null && ps.sharedUser != null) {
- // XXX don't do this until the data is removed.
- if (false) {
- ps.sharedUser.packages.remove(ps);
- if (ps.sharedUser.packages.size() == 0) {
- // Remove.
- }
- }
- }
-
int N = pkg.providers.size();
StringBuilder r = null;
int i;
@@ -5770,12 +5758,26 @@
return;
}
}
+
+ killApplication(packageName, oldPkg.applicationInfo.uid);
+
res.removedInfo.uid = oldPkg.applicationInfo.uid;
res.removedInfo.removedPackage = packageName;
// Remove existing system package
removePackageLI(oldPkg, true);
synchronized (mPackages) {
- mSettings.disableSystemPackageLP(packageName);
+ if (!mSettings.disableSystemPackageLP(packageName) && deletedPackage != null) {
+ // We didn't need to disable the .apk as a current system package,
+ // which means we are replacing another update that is already
+ // installed. We need to make sure to delete the older one's .apk.
+ res.removedInfo.args = createInstallArgs(isExternal(pkg)
+ ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL,
+ deletedPackage.applicationInfo.sourceDir,
+ deletedPackage.applicationInfo.publicSourceDir,
+ deletedPackage.applicationInfo.nativeLibraryDir);
+ } else {
+ res.removedInfo.args = null;
+ }
}
// Successfully disabled the old package. Now proceed with re-installation
@@ -5814,17 +5816,6 @@
}
mSettings.writeLP();
}
- } else {
- // If this is an update to an existing update, setup
- // to remove the existing update.
- synchronized (mPackages) {
- PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
- if (ps != null && ps.codePathString != null &&
- !ps.codePathString.equals(oldPkgSetting.codePathString)) {
- res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
- oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
- }
- }
}
}
@@ -6327,24 +6318,21 @@
ps = mSettings.getDisabledSystemPkg(p.packageName);
}
if (ps == null) {
- Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
+ Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName);
return false;
} else {
Log.i(TAG, "Deleting system pkg from data partition");
}
// Delete the updated package
outInfo.isRemovedPackageSystemUpdate = true;
- final boolean deleteCodeAndResources;
if (ps.versionCode < p.mVersionCode) {
- // Delete code and resources for downgrades
- deleteCodeAndResources = true;
+ // Delete data for downgrades
flags &= ~PackageManager.DONT_DELETE_DATA;
} else {
// Preserve data by setting flag
- deleteCodeAndResources = false;
flags |= PackageManager.DONT_DELETE_DATA;
}
- boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
+ boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo,
writeSettings);
if (!ret) {
return false;
@@ -7932,6 +7920,20 @@
pkgFlags);
}
+ PackageSetting(PackageSetting orig) {
+ super(orig.name, orig.realName, orig.codePath, orig.resourcePath,
+ orig.nativeLibraryPathString, orig.versionCode, orig.pkgFlags);
+ copyFrom(orig);
+ }
+
+ public void copyFrom(PackageSetting base) {
+ super.copyFrom((PackageSettingBase) base);
+
+ userId = base.userId;
+ sharedUser = base.sharedUser;
+ pkg = base.pkg;
+ }
+
@Override
public String toString() {
return "PackageSetting{"
@@ -8144,21 +8146,29 @@
return s;
}
- int disableSystemPackageLP(String name) {
+ boolean disableSystemPackageLP(String name) {
PackageSetting p = mPackages.get(name);
if(p == null) {
Log.w(TAG, "Package:"+name+" is not an installed package");
- return -1;
+ return false;
}
PackageSetting dp = mDisabledSysPackages.get(name);
// always make sure the system package code and resource paths dont change
- if(dp == null) {
+ if (dp == null) {
if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
}
mDisabledSysPackages.put(name, p);
+
+ // a little trick... when we install the new package, we don't
+ // want to modify the existing PackageSetting for the built-in
+ // version. so at this point we need a new PackageSetting that
+ // is okay to much with.
+ PackageSetting newp = new PackageSetting(p);
+ replacePackageLP(name, newp);
+ return true;
}
- return removePackageLP(name);
+ return false;
}
PackageSetting enableSystemPackageLP(String name) {
@@ -8492,6 +8502,19 @@
return -1;
}
+ private void replacePackageLP(String name, PackageSetting newp) {
+ PackageSetting p = mPackages.get(name);
+ if (p != null) {
+ if (p.sharedUser != null) {
+ p.sharedUser.packages.remove(p);
+ p.sharedUser.packages.add(newp);
+ } else {
+ replaceUserIdLP(p.userId, newp);
+ }
+ }
+ mPackages.put(name, newp);
+ }
+
private boolean addUserIdLP(int uid, Object obj, Object name) {
if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
return false;
@@ -8554,6 +8577,16 @@
}
}
+ private void replaceUserIdLP(int uid, Object obj) {
+ if (uid >= FIRST_APPLICATION_UID) {
+ int N = mUserIds.size();
+ final int index = uid - FIRST_APPLICATION_UID;
+ if (index < N) mUserIds.set(index, obj);
+ } else {
+ mOtherUserIds.put(uid, obj);
+ }
+ }
+
void writeLP() {
//Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
diff --git a/services/java/com/android/server/WifiService.java b/services/java/com/android/server/WifiService.java
index a9d42e3..cff9892 100644
--- a/services/java/com/android/server/WifiService.java
+++ b/services/java/com/android/server/WifiService.java
@@ -20,10 +20,7 @@
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
-import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
@@ -91,7 +88,6 @@
private AlarmManager mAlarmManager;
private PendingIntent mIdleIntent;
- private BluetoothA2dp mBluetoothA2dp;
private static final int IDLE_REQUEST = 0;
private boolean mScreenOff;
private boolean mDeviceIdle;
@@ -943,10 +939,10 @@
mAlarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, mIdleIntent);
}
mPluggedType = pluggedType;
- } else if (action.equals(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED)) {
- int state = intent.getIntExtra(BluetoothProfile.EXTRA_STATE,
- BluetoothA2dp.STATE_NOT_PLAYING);
- mWifiStateMachine.setBluetoothScanMode(state == BluetoothA2dp.STATE_PLAYING);
+ } else if (action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)) {
+ int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
+ BluetoothAdapter.STATE_DISCONNECTED);
+ mWifiStateMachine.sendBluetoothAdapterStateChange(state);
}
}
@@ -1048,7 +1044,7 @@
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
intentFilter.addAction(ACTION_DEVICE_IDLE);
- intentFilter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);
+ intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
mContext.registerReceiver(mReceiver, intentFilter);
}
diff --git a/services/java/com/android/server/WindowManagerService.java b/services/java/com/android/server/WindowManagerService.java
index c33d19d..5c823ba 100644
--- a/services/java/com/android/server/WindowManagerService.java
+++ b/services/java/com/android/server/WindowManagerService.java
@@ -536,7 +536,7 @@
InputChannel[] channels = InputChannel.openInputChannelPair("drag");
mServerChannel = channels[0];
mClientChannel = channels[1];
- mInputManager.registerInputChannel(mServerChannel);
+ mInputManager.registerInputChannel(mServerChannel, null);
InputQueue.registerInputChannel(mClientChannel, mDragInputHandler,
mH.getLooper().getQueue());
}
@@ -2311,7 +2311,7 @@
win.mInputChannel = inputChannels[0];
inputChannels[1].transferToBinderOutParameter(outInputChannel);
- mInputManager.registerInputChannel(win.mInputChannel);
+ mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
}
// From now on, no exceptions or errors allowed!
@@ -5711,13 +5711,13 @@
*
* Called by the InputManager.
*/
- public void notifyInputChannelBroken(InputChannel inputChannel) {
+ public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
+ if (inputWindowHandle == null) {
+ return;
+ }
+
synchronized (mWindowMap) {
- WindowState windowState = getWindowStateForInputChannelLocked(inputChannel);
- if (windowState == null) {
- return; // irrelevant
- }
-
+ WindowState windowState = (WindowState) inputWindowHandle.windowState;
Slog.i(TAG, "WINDOW DIED " + windowState);
removeWindowLocked(windowState.mSession, windowState);
}
@@ -5728,11 +5728,12 @@
*
* Called by the InputManager.
*/
- public long notifyANR(Object token, InputChannel inputChannel) {
+ public long notifyANR(InputApplicationHandle inputApplicationHandle,
+ InputWindowHandle inputWindowHandle) {
AppWindowToken appWindowToken = null;
- if (inputChannel != null) {
+ if (inputWindowHandle != null) {
synchronized (mWindowMap) {
- WindowState windowState = getWindowStateForInputChannelLocked(inputChannel);
+ WindowState windowState = (WindowState) inputWindowHandle.windowState;
if (windowState != null) {
Slog.i(TAG, "Input event dispatching timed out sending to "
+ windowState.mAttrs.getTitle());
@@ -5741,8 +5742,8 @@
}
}
- if (appWindowToken == null && token != null) {
- appWindowToken = (AppWindowToken) token;
+ if (appWindowToken == null && inputApplicationHandle != null) {
+ appWindowToken = inputApplicationHandle.appWindowToken;
Slog.i(TAG, "Input event dispatching timed out sending to application "
+ appWindowToken.stringName);
}
@@ -5762,24 +5763,6 @@
}
return 0; // abort dispatching
}
-
- private WindowState getWindowStateForInputChannel(InputChannel inputChannel) {
- synchronized (mWindowMap) {
- return getWindowStateForInputChannelLocked(inputChannel);
- }
- }
-
- private WindowState getWindowStateForInputChannelLocked(InputChannel inputChannel) {
- int windowCount = mWindows.size();
- for (int i = 0; i < windowCount; i++) {
- WindowState windowState = mWindows.get(i);
- if (windowState.mInputChannel == inputChannel) {
- return windowState;
- }
- }
-
- return null;
- }
private void addDragInputWindowLw(InputWindowList windowList) {
final InputWindow inputWindow = windowList.add();
@@ -5856,6 +5839,7 @@
// Add a window to our list of input windows.
final InputWindow inputWindow = mTempInputWindows.add();
+ inputWindow.inputWindowHandle = child.mInputWindowHandle;
inputWindow.inputChannel = child.mInputChannel;
inputWindow.name = child.toString();
inputWindow.layoutParamsFlags = flags;
@@ -5934,16 +5918,16 @@
/* Provides an opportunity for the window manager policy to process a key before
* ordinary dispatch. */
public boolean interceptKeyBeforeDispatching(
- InputChannel focus, KeyEvent event, int policyFlags) {
- WindowState windowState = getWindowStateForInputChannel(focus);
+ InputWindowHandle focus, KeyEvent event, int policyFlags) {
+ WindowState windowState = (WindowState) focus.windowState;
return mPolicy.interceptKeyBeforeDispatching(windowState, event, policyFlags);
}
/* Provides an opportunity for the window manager policy to process a key that
* the application did not handle. */
public KeyEvent dispatchUnhandledKey(
- InputChannel focus, KeyEvent event, int policyFlags) {
- WindowState windowState = getWindowStateForInputChannel(focus);
+ InputWindowHandle focus, KeyEvent event, int policyFlags) {
+ WindowState windowState = (WindowState) focus.windowState;
return mPolicy.dispatchUnhandledKey(windowState, event, policyFlags);
}
@@ -5973,12 +5957,14 @@
if (newApp == null) {
mInputManager.setFocusedApplication(null);
} else {
+ mTempInputApplication.inputApplicationHandle = newApp.mInputApplicationHandle;
mTempInputApplication.name = newApp.toString();
mTempInputApplication.dispatchingTimeoutNanos =
newApp.inputDispatchingTimeoutNanos;
- mTempInputApplication.token = newApp;
-
+
mInputManager.setFocusedApplication(mTempInputApplication);
+
+ mTempInputApplication.recycle();
}
}
@@ -6823,7 +6809,8 @@
int mSurfaceLayer;
float mSurfaceAlpha;
- // Input channel
+ // Input channel and input window handle used by the input dispatcher.
+ InputWindowHandle mInputWindowHandle;
InputChannel mInputChannel;
// Used to improve performance of toString()
@@ -6915,6 +6902,8 @@
mLayer = 0;
mAnimLayer = 0;
mLastLayer = 0;
+ mInputWindowHandle = new InputWindowHandle(
+ mAppToken != null ? mAppToken.mInputApplicationHandle : null, this);
}
void attach() {
@@ -8304,11 +8293,15 @@
boolean startingMoved;
boolean firstWindowDrawn;
+ // Input application handle used by the input dispatcher.
+ InputApplicationHandle mInputApplicationHandle;
+
AppWindowToken(IApplicationToken _token) {
super(_token.asBinder(),
WindowManager.LayoutParams.TYPE_APPLICATION, true);
appWindowToken = this;
appToken = _token;
+ mInputApplicationHandle = new InputApplicationHandle(this);
}
public void setAnimation(Animation anim) {
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
old mode 100644
new mode 100755
index f1d5489..761dcd1
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -1324,6 +1324,7 @@
ActivityThread at = ActivityThread.systemMain();
mSystemThread = at;
Context context = at.getSystemContext();
+ context.setTheme(android.R.style.Theme_Holo);
m.mContext = context;
m.mFactoryTest = factoryTest;
m.mMainStack = new ActivityStack(m, context, true);
@@ -9573,7 +9574,7 @@
// r.record is null if findServiceLocked() failed the caller permission check
if (r.record == null) {
throw new SecurityException(
- "Permission Denial: Accessing service " + r.record.name
+ "Permission Denial: Accessing service "
+ " from pid=" + Binder.getCallingPid()
+ ", uid=" + Binder.getCallingUid()
+ " requires " + r.permission);
diff --git a/services/java/com/android/server/am/ActivityRecord.java b/services/java/com/android/server/am/ActivityRecord.java
index caaae1f..72ea7ce 100644
--- a/services/java/com/android/server/am/ActivityRecord.java
+++ b/services/java/com/android/server/am/ActivityRecord.java
@@ -26,6 +26,7 @@
import android.content.pm.ApplicationInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
+import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.Process;
@@ -69,6 +70,7 @@
int labelRes; // the label information from the package mgr.
int icon; // resource identifier of activity's icon.
int theme; // resource identifier of activity's theme.
+ int realTheme; // actual theme resource we will use, never 0.
int windowFlags; // custom window flags for preview window.
TaskRecord task; // the task this is in.
long launchTime; // when we starting launching this activity
@@ -246,6 +248,13 @@
}
icon = aInfo.getIconResource();
theme = aInfo.getThemeResource();
+ realTheme = theme;
+ if (realTheme == 0) {
+ realTheme = aInfo.applicationInfo.targetSdkVersion
+ < Build.VERSION_CODES.HONEYCOMB
+ ? android.R.style.Theme
+ : android.R.style.Theme_Holo;
+ }
if ((aInfo.flags&ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
windowFlags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
}
@@ -266,8 +275,7 @@
launchMode = aInfo.launchMode;
AttributeCache.Entry ent = AttributeCache.instance().get(packageName,
- theme != 0 ? theme : android.R.style.Theme,
- com.android.internal.R.styleable.Window);
+ realTheme, com.android.internal.R.styleable.Window);
fullscreen = ent != null && !ent.array.getBoolean(
com.android.internal.R.styleable.Window_windowIsFloating, false)
&& !ent.array.getBoolean(
diff --git a/services/java/com/android/server/am/BaseErrorDialog.java b/services/java/com/android/server/am/BaseErrorDialog.java
index 03e3272..d1e89bc 100644
--- a/services/java/com/android/server/am/BaseErrorDialog.java
+++ b/services/java/com/android/server/am/BaseErrorDialog.java
@@ -34,7 +34,7 @@
getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
getWindow().setTitle("Error Dialog");
- setIcon(R.drawable.ic_dialog_alert);
+ setIconAttribute(R.attr.alertDialogIcon);
}
public void onStart() {
diff --git a/services/java/com/android/server/am/LaunchWarningWindow.java b/services/java/com/android/server/am/LaunchWarningWindow.java
index 4130e33..1114a31 100644
--- a/services/java/com/android/server/am/LaunchWarningWindow.java
+++ b/services/java/com/android/server/am/LaunchWarningWindow.java
@@ -4,6 +4,7 @@
import android.app.Dialog;
import android.content.Context;
+import android.util.TypedValue;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
@@ -20,8 +21,11 @@
setContentView(R.layout.launch_warning);
setTitle(context.getText(R.string.launch_warning_title));
- getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
- R.drawable.ic_dialog_alert);
+
+ TypedValue out = new TypedValue();
+ getContext().getTheme().resolveAttribute(android.R.attr.alertDialogIcon, out, true);
+ getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, out.resourceId);
+
ImageView icon = (ImageView)findViewById(R.id.replace_app_icon);
icon.setImageDrawable(next.info.applicationInfo.loadIcon(context.getPackageManager()));
TextView text = (TextView)findViewById(R.id.replace_message);
diff --git a/services/jni/Android.mk b/services/jni/Android.mk
index ec85e54..f5a5b4d 100644
--- a/services/jni/Android.mk
+++ b/services/jni/Android.mk
@@ -4,7 +4,11 @@
LOCAL_SRC_FILES:= \
com_android_server_AlarmManagerService.cpp \
com_android_server_BatteryService.cpp \
+ com_android_server_InputApplication.cpp \
+ com_android_server_InputApplicationHandle.cpp \
com_android_server_InputManager.cpp \
+ com_android_server_InputWindow.cpp \
+ com_android_server_InputWindowHandle.cpp \
com_android_server_LightsService.cpp \
com_android_server_PowerManagerService.cpp \
com_android_server_SystemServer.cpp \
diff --git a/services/jni/com_android_server_InputApplication.cpp b/services/jni/com_android_server_InputApplication.cpp
new file mode 100644
index 0000000..a46a162
--- /dev/null
+++ b/services/jni/com_android_server_InputApplication.cpp
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2011 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 "InputApplication"
+
+#include "JNIHelp.h"
+#include "jni.h"
+#include <android_runtime/AndroidRuntime.h>
+
+#include "com_android_server_InputApplication.h"
+#include "com_android_server_InputApplicationHandle.h"
+
+namespace android {
+
+static struct {
+ jclass clazz;
+
+ jfieldID inputApplicationHandle;
+ jfieldID name;
+ jfieldID dispatchingTimeoutNanos;
+} gInputApplicationClassInfo;
+
+
+// --- Global functions ---
+
+void android_server_InputApplication_toNative(
+ JNIEnv* env, jobject inputApplicationObj, InputApplication* outInputApplication) {
+ jobject inputApplicationHandleObj = env->GetObjectField(inputApplicationObj,
+ gInputApplicationClassInfo.inputApplicationHandle);
+ if (inputApplicationHandleObj) {
+ outInputApplication->inputApplicationHandle =
+ android_server_InputApplicationHandle_getHandle(env, inputApplicationHandleObj);
+ env->DeleteLocalRef(inputApplicationHandleObj);
+ } else {
+ outInputApplication->inputApplicationHandle = NULL;
+ }
+
+ jstring nameObj = jstring(env->GetObjectField(inputApplicationObj,
+ gInputApplicationClassInfo.name));
+ if (nameObj) {
+ const char* nameStr = env->GetStringUTFChars(nameObj, NULL);
+ outInputApplication->name.setTo(nameStr);
+ env->ReleaseStringUTFChars(nameObj, nameStr);
+ env->DeleteLocalRef(nameObj);
+ } else {
+ LOGE("InputApplication.name should not be null.");
+ outInputApplication->name.setTo("unknown");
+ }
+
+ outInputApplication->dispatchingTimeout = env->GetLongField(inputApplicationObj,
+ gInputApplicationClassInfo.dispatchingTimeoutNanos);
+}
+
+
+// --- JNI ---
+
+#define FIND_CLASS(var, className) \
+ var = env->FindClass(className); \
+ LOG_FATAL_IF(! var, "Unable to find class " className); \
+ var = jclass(env->NewGlobalRef(var));
+
+#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \
+ var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \
+ LOG_FATAL_IF(! var, "Unable to find field " fieldName);
+
+int register_android_server_InputApplication(JNIEnv* env) {
+ FIND_CLASS(gInputApplicationClassInfo.clazz, "com/android/server/InputApplication");
+
+ GET_FIELD_ID(gInputApplicationClassInfo.inputApplicationHandle,
+ gInputApplicationClassInfo.clazz,
+ "inputApplicationHandle", "Lcom/android/server/InputApplicationHandle;");
+
+ GET_FIELD_ID(gInputApplicationClassInfo.name, gInputApplicationClassInfo.clazz,
+ "name", "Ljava/lang/String;");
+
+ GET_FIELD_ID(gInputApplicationClassInfo.dispatchingTimeoutNanos,
+ gInputApplicationClassInfo.clazz,
+ "dispatchingTimeoutNanos", "J");
+ return 0;
+}
+
+} /* namespace android */
diff --git a/services/jni/com_android_server_InputApplication.h b/services/jni/com_android_server_InputApplication.h
new file mode 100644
index 0000000..85fb891
--- /dev/null
+++ b/services/jni/com_android_server_InputApplication.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2011 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_SERVER_INPUT_APPLICATION_H
+#define _ANDROID_SERVER_INPUT_APPLICATION_H
+
+#include <input/InputApplication.h>
+
+#include "JNIHelp.h"
+#include "jni.h"
+
+namespace android {
+
+extern void android_server_InputApplication_toNative(
+ JNIEnv* env, jobject inputApplicationObj, InputApplication* outInputApplication);
+
+} // namespace android
+
+#endif // _ANDROID_SERVER_INPUT_APPLICATION_H
diff --git a/services/jni/com_android_server_InputApplicationHandle.cpp b/services/jni/com_android_server_InputApplicationHandle.cpp
new file mode 100644
index 0000000..ab82635
--- /dev/null
+++ b/services/jni/com_android_server_InputApplicationHandle.cpp
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2011 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 "InputApplicationHandle"
+
+#include "JNIHelp.h"
+#include "jni.h"
+#include <android_runtime/AndroidRuntime.h>
+#include <utils/threads.h>
+
+#include "com_android_server_InputApplicationHandle.h"
+
+namespace android {
+
+static struct {
+ jclass clazz;
+
+ jfieldID ptr;
+} gInputApplicationHandleClassInfo;
+
+static Mutex gHandleMutex;
+
+
+// --- NativeInputApplicationHandle ---
+
+NativeInputApplicationHandle::NativeInputApplicationHandle(jweak objWeak) :
+ mObjWeak(objWeak) {
+}
+
+NativeInputApplicationHandle::~NativeInputApplicationHandle() {
+ JNIEnv* env = AndroidRuntime::getJNIEnv();
+ env->DeleteWeakGlobalRef(mObjWeak);
+}
+
+jobject NativeInputApplicationHandle::getInputApplicationHandleObjLocalRef(JNIEnv* env) {
+ return env->NewLocalRef(mObjWeak);
+}
+
+
+// --- Global functions ---
+
+sp<InputApplicationHandle> android_server_InputApplicationHandle_getHandle(
+ JNIEnv* env, jobject inputApplicationHandleObj) {
+ if (!inputApplicationHandleObj) {
+ return NULL;
+ }
+
+ AutoMutex _l(gHandleMutex);
+
+ int ptr = env->GetIntField(inputApplicationHandleObj, gInputApplicationHandleClassInfo.ptr);
+ NativeInputApplicationHandle* handle;
+ if (ptr) {
+ handle = reinterpret_cast<NativeInputApplicationHandle*>(ptr);
+ } else {
+ jweak objWeak = env->NewWeakGlobalRef(inputApplicationHandleObj);
+ handle = new NativeInputApplicationHandle(objWeak);
+ handle->incStrong(inputApplicationHandleObj);
+ env->SetIntField(inputApplicationHandleObj, gInputApplicationHandleClassInfo.ptr,
+ reinterpret_cast<int>(handle));
+ }
+ return handle;
+}
+
+
+// --- JNI ---
+
+static void android_server_InputApplicationHandle_nativeDispose(JNIEnv* env, jobject obj) {
+ AutoMutex _l(gHandleMutex);
+
+ int ptr = env->GetIntField(obj, gInputApplicationHandleClassInfo.ptr);
+ if (ptr) {
+ env->SetIntField(obj, gInputApplicationHandleClassInfo.ptr, 0);
+
+ NativeInputApplicationHandle* handle = reinterpret_cast<NativeInputApplicationHandle*>(ptr);
+ handle->decStrong(obj);
+ }
+}
+
+
+static JNINativeMethod gInputApplicationHandleMethods[] = {
+ /* name, signature, funcPtr */
+ { "nativeDispose", "()V",
+ (void*) android_server_InputApplicationHandle_nativeDispose },
+};
+
+#define FIND_CLASS(var, className) \
+ var = env->FindClass(className); \
+ LOG_FATAL_IF(! var, "Unable to find class " className); \
+ var = jclass(env->NewGlobalRef(var));
+
+#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \
+ var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \
+ LOG_FATAL_IF(! var, "Unable to find field " fieldName);
+
+int register_android_server_InputApplicationHandle(JNIEnv* env) {
+ int res = jniRegisterNativeMethods(env, "com/android/server/InputApplicationHandle",
+ gInputApplicationHandleMethods, NELEM(gInputApplicationHandleMethods));
+ LOG_FATAL_IF(res < 0, "Unable to register native methods.");
+
+ FIND_CLASS(gInputApplicationHandleClassInfo.clazz, "com/android/server/InputApplicationHandle");
+
+ GET_FIELD_ID(gInputApplicationHandleClassInfo.ptr, gInputApplicationHandleClassInfo.clazz,
+ "ptr", "I");
+
+ return 0;
+}
+
+} /* namespace android */
diff --git a/services/jni/com_android_server_InputApplicationHandle.h b/services/jni/com_android_server_InputApplicationHandle.h
new file mode 100644
index 0000000..9d18721
--- /dev/null
+++ b/services/jni/com_android_server_InputApplicationHandle.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2011 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_SERVER_INPUT_APPLICATION_HANDLE_H
+#define _ANDROID_SERVER_INPUT_APPLICATION_HANDLE_H
+
+#include <input/InputApplication.h>
+
+#include "JNIHelp.h"
+#include "jni.h"
+
+namespace android {
+
+class NativeInputApplicationHandle : public InputApplicationHandle {
+public:
+ NativeInputApplicationHandle(jweak objWeak);
+ virtual ~NativeInputApplicationHandle();
+
+ jobject getInputApplicationHandleObjLocalRef(JNIEnv* env);
+
+private:
+ jweak mObjWeak;
+};
+
+
+extern sp<InputApplicationHandle> android_server_InputApplicationHandle_getHandle(
+ JNIEnv* env, jobject inputApplicationHandleObj);
+
+} // namespace android
+
+#endif // _ANDROID_SERVER_INPUT_APPLICATION_HANDLE_H
diff --git a/services/jni/com_android_server_InputManager.cpp b/services/jni/com_android_server_InputManager.cpp
index 5ed63f0..e04e4c3 100644
--- a/services/jni/com_android_server_InputManager.cpp
+++ b/services/jni/com_android_server_InputManager.cpp
@@ -42,11 +42,13 @@
#include <android/graphics/GraphicsJNI.h>
#include "com_android_server_PowerManagerService.h"
+#include "com_android_server_InputApplication.h"
+#include "com_android_server_InputApplicationHandle.h"
+#include "com_android_server_InputWindow.h"
+#include "com_android_server_InputWindowHandle.h"
namespace android {
-// ----------------------------------------------------------------------------
-
static struct {
jclass clazz;
@@ -68,44 +70,6 @@
static struct {
jclass clazz;
-
- jfieldID inputChannel;
- jfieldID name;
- jfieldID layoutParamsFlags;
- jfieldID layoutParamsType;
- jfieldID dispatchingTimeoutNanos;
- jfieldID frameLeft;
- jfieldID frameTop;
- jfieldID frameRight;
- jfieldID frameBottom;
- jfieldID visibleFrameLeft;
- jfieldID visibleFrameTop;
- jfieldID visibleFrameRight;
- jfieldID visibleFrameBottom;
- jfieldID touchableAreaLeft;
- jfieldID touchableAreaTop;
- jfieldID touchableAreaRight;
- jfieldID touchableAreaBottom;
- jfieldID visible;
- jfieldID canReceiveKeys;
- jfieldID hasFocus;
- jfieldID hasWallpaper;
- jfieldID paused;
- jfieldID layer;
- jfieldID ownerPid;
- jfieldID ownerUid;
-} gInputWindowClassInfo;
-
-static struct {
- jclass clazz;
-
- jfieldID name;
- jfieldID dispatchingTimeoutNanos;
- jfieldID token;
-} gInputApplicationClassInfo;
-
-static struct {
- jclass clazz;
} gKeyEventClassInfo;
static struct {
@@ -141,7 +105,29 @@
jfieldID hotSpotY;
} gPointerIconClassInfo;
-// ----------------------------------------------------------------------------
+
+// --- Global functions ---
+
+static jobject getInputApplicationHandleObjLocalRef(JNIEnv* env,
+ const sp<InputApplicationHandle>& inputApplicationHandle) {
+ if (inputApplicationHandle == NULL) {
+ return NULL;
+ }
+ return static_cast<NativeInputApplicationHandle*>(inputApplicationHandle.get())->
+ getInputApplicationHandleObjLocalRef(env);
+}
+
+static jobject getInputWindowHandleObjLocalRef(JNIEnv* env,
+ const sp<InputWindowHandle>& inputWindowHandle) {
+ if (inputWindowHandle == NULL) {
+ return NULL;
+ }
+ return static_cast<NativeInputWindowHandle*>(inputWindowHandle.get())->
+ getInputWindowHandleObjLocalRef(env);
+}
+
+
+// --- NativeInputManager ---
class NativeInputManager : public virtual RefBase,
public virtual InputReaderPolicyInterface,
@@ -160,7 +146,7 @@
void setDisplayOrientation(int32_t displayId, int32_t orientation);
status_t registerInputChannel(JNIEnv* env, const sp<InputChannel>& inputChannel,
- jweak inputChannelObjWeak, bool monitor);
+ const sp<InputWindowHandle>& inputWindowHandle, bool monitor);
status_t unregisterInputChannel(JNIEnv* env, const sp<InputChannel>& inputChannel);
void setInputWindows(JNIEnv* env, jobjectArray windowObjArray);
@@ -182,37 +168,22 @@
uint32_t policyFlags);
virtual void notifyConfigurationChanged(nsecs_t when);
virtual nsecs_t notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
- const sp<InputChannel>& inputChannel);
- virtual void notifyInputChannelBroken(const sp<InputChannel>& inputChannel);
+ const sp<InputWindowHandle>& inputWindowHandle);
+ virtual void notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle);
virtual nsecs_t getKeyRepeatTimeout();
virtual nsecs_t getKeyRepeatDelay();
virtual int32_t getMaxEventsPerSecond();
virtual void interceptKeyBeforeQueueing(const KeyEvent* keyEvent, uint32_t& policyFlags);
virtual void interceptGenericBeforeQueueing(nsecs_t when, uint32_t& policyFlags);
- virtual bool interceptKeyBeforeDispatching(const sp<InputChannel>& inputChannel,
+ virtual bool interceptKeyBeforeDispatching(const sp<InputWindowHandle>& inputWindowHandle,
const KeyEvent* keyEvent, uint32_t policyFlags);
- virtual bool dispatchUnhandledKey(const sp<InputChannel>& inputChannel,
+ virtual bool dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent);
virtual void pokeUserActivity(nsecs_t eventTime, int32_t eventType);
virtual bool checkInjectEventsPermissionNonReentrant(
int32_t injectorPid, int32_t injectorUid);
private:
- class ApplicationToken : public InputApplicationHandle {
- jweak mTokenObjWeak;
-
- public:
- ApplicationToken(jweak tokenObjWeak) :
- mTokenObjWeak(tokenObjWeak) { }
-
- virtual ~ApplicationToken() {
- JNIEnv* env = NativeInputManager::jniEnv();
- env->DeleteWeakGlobalRef(mTokenObjWeak);
- }
-
- inline jweak getTokenObj() { return mTokenObjWeak; }
- };
-
sp<InputManager> mInputManager;
jobject mCallbacksObj;
@@ -232,19 +203,12 @@
// Pointer controller singleton, created and destroyed as needed.
wp<PointerController> pointerController;
-
- // Weak references to all currently registered input channels by connection pointer.
- KeyedVector<InputChannel*, jweak> inputChannelObjWeakTable;
} mLocked;
// Power manager interactions.
bool isScreenOn();
bool isScreenBright();
- jobject getInputChannelObjLocal(JNIEnv* env, const sp<InputChannel>& inputChannel);
-
- static bool populateWindow(JNIEnv* env, jobject windowObj, InputWindow& outWindow);
-
static bool checkAndClearExceptionFromCallback(JNIEnv* env, const char* methodName);
static inline JNIEnv* jniEnv() {
@@ -252,7 +216,7 @@
}
};
-// ----------------------------------------------------------------------------
+
NativeInputManager::NativeInputManager(jobject callbacksObj) :
mFilterTouchEvents(-1), mFilterJumpyTouchEvents(-1),
@@ -328,88 +292,17 @@
}
status_t NativeInputManager::registerInputChannel(JNIEnv* env,
- const sp<InputChannel>& inputChannel, jobject inputChannelObj, bool monitor) {
- jweak inputChannelObjWeak = env->NewWeakGlobalRef(inputChannelObj);
- if (! inputChannelObjWeak) {
- LOGE("Could not create weak reference for input channel.");
- LOGE_EX(env);
- return NO_MEMORY;
- }
-
- status_t status;
- {
- AutoMutex _l(mLock);
-
- ssize_t index = mLocked.inputChannelObjWeakTable.indexOfKey(inputChannel.get());
- if (index >= 0) {
- LOGE("Input channel object '%s' has already been registered",
- inputChannel->getName().string());
- status = INVALID_OPERATION;
- goto DeleteWeakRef;
- }
-
- mLocked.inputChannelObjWeakTable.add(inputChannel.get(), inputChannelObjWeak);
- }
-
- status = mInputManager->getDispatcher()->registerInputChannel(inputChannel, monitor);
- if (! status) {
- // Success.
- return OK;
- }
-
- // Failed!
- {
- AutoMutex _l(mLock);
- mLocked.inputChannelObjWeakTable.removeItem(inputChannel.get());
- }
-
-DeleteWeakRef:
- env->DeleteWeakGlobalRef(inputChannelObjWeak);
- return status;
+ const sp<InputChannel>& inputChannel,
+ const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {
+ return mInputManager->getDispatcher()->registerInputChannel(
+ inputChannel, inputWindowHandle, monitor);
}
status_t NativeInputManager::unregisterInputChannel(JNIEnv* env,
const sp<InputChannel>& inputChannel) {
- jweak inputChannelObjWeak;
- {
- AutoMutex _l(mLock);
-
- ssize_t index = mLocked.inputChannelObjWeakTable.indexOfKey(inputChannel.get());
- if (index < 0) {
- LOGE("Input channel object '%s' is not currently registered",
- inputChannel->getName().string());
- return INVALID_OPERATION;
- }
-
- inputChannelObjWeak = mLocked.inputChannelObjWeakTable.valueAt(index);
- mLocked.inputChannelObjWeakTable.removeItemsAt(index);
- }
-
- env->DeleteWeakGlobalRef(inputChannelObjWeak);
-
return mInputManager->getDispatcher()->unregisterInputChannel(inputChannel);
}
-jobject NativeInputManager::getInputChannelObjLocal(JNIEnv* env,
- const sp<InputChannel>& inputChannel) {
- InputChannel* inputChannelPtr = inputChannel.get();
- if (! inputChannelPtr) {
- return NULL;
- }
-
- {
- AutoMutex _l(mLock);
-
- ssize_t index = mLocked.inputChannelObjWeakTable.indexOfKey(inputChannelPtr);
- if (index < 0) {
- return NULL;
- }
-
- jweak inputChannelObjWeak = mLocked.inputChannelObjWeakTable.valueAt(index);
- return env->NewLocalRef(inputChannelObjWeak);
- }
-}
-
bool NativeInputManager::getDisplayInfo(int32_t displayId,
int32_t* width, int32_t* height, int32_t* orientation) {
bool result = false;
@@ -549,50 +442,46 @@
}
nsecs_t NativeInputManager::notifyANR(const sp<InputApplicationHandle>& inputApplicationHandle,
- const sp<InputChannel>& inputChannel) {
+ const sp<InputWindowHandle>& inputWindowHandle) {
#if DEBUG_INPUT_DISPATCHER_POLICY
LOGD("notifyANR");
#endif
JNIEnv* env = jniEnv();
- jobject tokenObjLocal;
- if (inputApplicationHandle.get()) {
- ApplicationToken* token = static_cast<ApplicationToken*>(inputApplicationHandle.get());
- jweak tokenObjWeak = token->getTokenObj();
- tokenObjLocal = env->NewLocalRef(tokenObjWeak);
- } else {
- tokenObjLocal = NULL;
- }
+ jobject inputApplicationHandleObj =
+ getInputApplicationHandleObjLocalRef(env, inputApplicationHandle);
+ jobject inputWindowHandleObj =
+ getInputWindowHandleObjLocalRef(env, inputWindowHandle);
- jobject inputChannelObjLocal = getInputChannelObjLocal(env, inputChannel);
jlong newTimeout = env->CallLongMethod(mCallbacksObj,
- gCallbacksClassInfo.notifyANR, tokenObjLocal, inputChannelObjLocal);
+ gCallbacksClassInfo.notifyANR, inputApplicationHandleObj, inputWindowHandleObj);
if (checkAndClearExceptionFromCallback(env, "notifyANR")) {
newTimeout = 0; // abort dispatch
} else {
assert(newTimeout >= 0);
}
- env->DeleteLocalRef(tokenObjLocal);
- env->DeleteLocalRef(inputChannelObjLocal);
+ env->DeleteLocalRef(inputWindowHandleObj);
+ env->DeleteLocalRef(inputApplicationHandleObj);
return newTimeout;
}
-void NativeInputManager::notifyInputChannelBroken(const sp<InputChannel>& inputChannel) {
+void NativeInputManager::notifyInputChannelBroken(const sp<InputWindowHandle>& inputWindowHandle) {
#if DEBUG_INPUT_DISPATCHER_POLICY
- LOGD("notifyInputChannelBroken - inputChannel='%s'", inputChannel->getName().string());
+ LOGD("notifyInputChannelBroken");
#endif
JNIEnv* env = jniEnv();
- jobject inputChannelObjLocal = getInputChannelObjLocal(env, inputChannel);
- if (inputChannelObjLocal) {
+ jobject inputWindowHandleObj =
+ getInputWindowHandleObjLocalRef(env, inputWindowHandle);
+ if (inputWindowHandleObj) {
env->CallVoidMethod(mCallbacksObj, gCallbacksClassInfo.notifyInputChannelBroken,
- inputChannelObjLocal);
+ inputWindowHandleObj);
checkAndClearExceptionFromCallback(env, "notifyInputChannelBroken");
- env->DeleteLocalRef(inputChannelObjLocal);
+ env->DeleteLocalRef(inputWindowHandleObj);
}
}
@@ -630,160 +519,32 @@
jsize length = env->GetArrayLength(windowObjArray);
for (jsize i = 0; i < length; i++) {
- jobject inputTargetObj = env->GetObjectArrayElement(windowObjArray, i);
- if (! inputTargetObj) {
+ jobject windowObj = env->GetObjectArrayElement(windowObjArray, i);
+ if (! windowObj) {
break; // found null element indicating end of used portion of the array
}
windows.push();
InputWindow& window = windows.editTop();
- bool valid = populateWindow(env, inputTargetObj, window);
- if (! valid) {
+ android_server_InputWindow_toNative(env, windowObj, &window);
+ if (window.inputChannel == NULL) {
windows.pop();
}
-
- env->DeleteLocalRef(inputTargetObj);
+ env->DeleteLocalRef(windowObj);
}
mInputManager->getDispatcher()->setInputWindows(windows);
}
-bool NativeInputManager::populateWindow(JNIEnv* env, jobject windowObj,
- InputWindow& outWindow) {
- bool valid = false;
-
- jobject inputChannelObj = env->GetObjectField(windowObj,
- gInputWindowClassInfo.inputChannel);
- if (inputChannelObj) {
- sp<InputChannel> inputChannel =
- android_view_InputChannel_getInputChannel(env, inputChannelObj);
- if (inputChannel != NULL) {
- jstring name = jstring(env->GetObjectField(windowObj,
- gInputWindowClassInfo.name));
- jint layoutParamsFlags = env->GetIntField(windowObj,
- gInputWindowClassInfo.layoutParamsFlags);
- jint layoutParamsType = env->GetIntField(windowObj,
- gInputWindowClassInfo.layoutParamsType);
- jlong dispatchingTimeoutNanos = env->GetLongField(windowObj,
- gInputWindowClassInfo.dispatchingTimeoutNanos);
- jint frameLeft = env->GetIntField(windowObj,
- gInputWindowClassInfo.frameLeft);
- jint frameTop = env->GetIntField(windowObj,
- gInputWindowClassInfo.frameTop);
- jint frameRight = env->GetIntField(windowObj,
- gInputWindowClassInfo.frameRight);
- jint frameBottom = env->GetIntField(windowObj,
- gInputWindowClassInfo.frameBottom);
- jint visibleFrameLeft = env->GetIntField(windowObj,
- gInputWindowClassInfo.visibleFrameLeft);
- jint visibleFrameTop = env->GetIntField(windowObj,
- gInputWindowClassInfo.visibleFrameTop);
- jint visibleFrameRight = env->GetIntField(windowObj,
- gInputWindowClassInfo.visibleFrameRight);
- jint visibleFrameBottom = env->GetIntField(windowObj,
- gInputWindowClassInfo.visibleFrameBottom);
- jint touchableAreaLeft = env->GetIntField(windowObj,
- gInputWindowClassInfo.touchableAreaLeft);
- jint touchableAreaTop = env->GetIntField(windowObj,
- gInputWindowClassInfo.touchableAreaTop);
- jint touchableAreaRight = env->GetIntField(windowObj,
- gInputWindowClassInfo.touchableAreaRight);
- jint touchableAreaBottom = env->GetIntField(windowObj,
- gInputWindowClassInfo.touchableAreaBottom);
- jboolean visible = env->GetBooleanField(windowObj,
- gInputWindowClassInfo.visible);
- jboolean canReceiveKeys = env->GetBooleanField(windowObj,
- gInputWindowClassInfo.canReceiveKeys);
- jboolean hasFocus = env->GetBooleanField(windowObj,
- gInputWindowClassInfo.hasFocus);
- jboolean hasWallpaper = env->GetBooleanField(windowObj,
- gInputWindowClassInfo.hasWallpaper);
- jboolean paused = env->GetBooleanField(windowObj,
- gInputWindowClassInfo.paused);
- jint layer = env->GetIntField(windowObj,
- gInputWindowClassInfo.layer);
- jint ownerPid = env->GetIntField(windowObj,
- gInputWindowClassInfo.ownerPid);
- jint ownerUid = env->GetIntField(windowObj,
- gInputWindowClassInfo.ownerUid);
-
- const char* nameStr = env->GetStringUTFChars(name, NULL);
-
- outWindow.inputChannel = inputChannel;
- outWindow.name.setTo(nameStr);
- outWindow.layoutParamsFlags = layoutParamsFlags;
- outWindow.layoutParamsType = layoutParamsType;
- outWindow.dispatchingTimeout = dispatchingTimeoutNanos;
- outWindow.frameLeft = frameLeft;
- outWindow.frameTop = frameTop;
- outWindow.frameRight = frameRight;
- outWindow.frameBottom = frameBottom;
- outWindow.visibleFrameLeft = visibleFrameLeft;
- outWindow.visibleFrameTop = visibleFrameTop;
- outWindow.visibleFrameRight = visibleFrameRight;
- outWindow.visibleFrameBottom = visibleFrameBottom;
- outWindow.touchableAreaLeft = touchableAreaLeft;
- outWindow.touchableAreaTop = touchableAreaTop;
- outWindow.touchableAreaRight = touchableAreaRight;
- outWindow.touchableAreaBottom = touchableAreaBottom;
- outWindow.visible = visible;
- outWindow.canReceiveKeys = canReceiveKeys;
- outWindow.hasFocus = hasFocus;
- outWindow.hasWallpaper = hasWallpaper;
- outWindow.paused = paused;
- outWindow.layer = layer;
- outWindow.ownerPid = ownerPid;
- outWindow.ownerUid = ownerUid;
-
- env->ReleaseStringUTFChars(name, nameStr);
- env->DeleteLocalRef(name);
- valid = true;
- } else {
- LOGW("Dropping input target because its input channel is not initialized.");
- }
-
- env->DeleteLocalRef(inputChannelObj);
- } else {
- LOGW("Dropping input target because the input channel object was null.");
- }
- return valid;
-}
-
void NativeInputManager::setFocusedApplication(JNIEnv* env, jobject applicationObj) {
if (applicationObj) {
- jstring nameObj = jstring(env->GetObjectField(applicationObj,
- gInputApplicationClassInfo.name));
- jlong dispatchingTimeoutNanos = env->GetLongField(applicationObj,
- gInputApplicationClassInfo.dispatchingTimeoutNanos);
- jobject tokenObj = env->GetObjectField(applicationObj,
- gInputApplicationClassInfo.token);
- jweak tokenObjWeak = env->NewWeakGlobalRef(tokenObj);
- if (! tokenObjWeak) {
- LOGE("Could not create weak reference for application token.");
- LOGE_EX(env);
- env->ExceptionClear();
- }
- env->DeleteLocalRef(tokenObj);
-
- String8 name;
- if (nameObj) {
- const char* nameStr = env->GetStringUTFChars(nameObj, NULL);
- name.setTo(nameStr);
- env->ReleaseStringUTFChars(nameObj, nameStr);
- env->DeleteLocalRef(nameObj);
- } else {
- LOGE("InputApplication.name should not be null.");
- name.setTo("unknown");
- }
-
InputApplication application;
- application.name = name;
- application.dispatchingTimeout = dispatchingTimeoutNanos;
- application.handle = new ApplicationToken(tokenObjWeak);
- mInputManager->getDispatcher()->setFocusedApplication(& application);
- } else {
- mInputManager->getDispatcher()->setFocusedApplication(NULL);
+ android_server_InputApplication_toNative(env, applicationObj, &application);
+ if (application.inputApplicationHandle != NULL) {
+ mInputManager->getDispatcher()->setFocusedApplication(&application);
+ }
}
+ mInputManager->getDispatcher()->setFocusedApplication(NULL);
}
void NativeInputManager::setInputDispatchMode(bool enabled, bool frozen) {
@@ -875,7 +636,8 @@
}
}
-bool NativeInputManager::interceptKeyBeforeDispatching(const sp<InputChannel>& inputChannel,
+bool NativeInputManager::interceptKeyBeforeDispatching(
+ const sp<InputWindowHandle>& inputWindowHandle,
const KeyEvent* keyEvent, uint32_t policyFlags) {
// Policy:
// - Ignore untrusted events and pass them along.
@@ -885,13 +647,13 @@
if (policyFlags & POLICY_FLAG_TRUSTED) {
JNIEnv* env = jniEnv();
- // Note: inputChannel may be null.
- jobject inputChannelObj = getInputChannelObjLocal(env, inputChannel);
+ // Note: inputWindowHandle may be null.
+ jobject inputWindowHandleObj = getInputWindowHandleObjLocalRef(env, inputWindowHandle);
jobject keyEventObj = android_view_KeyEvent_fromNative(env, keyEvent);
if (keyEventObj) {
jboolean consumed = env->CallBooleanMethod(mCallbacksObj,
gCallbacksClassInfo.interceptKeyBeforeDispatching,
- inputChannelObj, keyEventObj, policyFlags);
+ inputWindowHandleObj, keyEventObj, policyFlags);
bool error = checkAndClearExceptionFromCallback(env, "interceptKeyBeforeDispatching");
android_view_KeyEvent_recycle(env, keyEventObj);
env->DeleteLocalRef(keyEventObj);
@@ -899,12 +661,12 @@
} else {
LOGE("Failed to obtain key event object for interceptKeyBeforeDispatching.");
}
- env->DeleteLocalRef(inputChannelObj);
+ env->DeleteLocalRef(inputWindowHandleObj);
}
return result;
}
-bool NativeInputManager::dispatchUnhandledKey(const sp<InputChannel>& inputChannel,
+bool NativeInputManager::dispatchUnhandledKey(const sp<InputWindowHandle>& inputWindowHandle,
const KeyEvent* keyEvent, uint32_t policyFlags, KeyEvent* outFallbackKeyEvent) {
// Policy:
// - Ignore untrusted events and do not perform default handling.
@@ -912,13 +674,13 @@
if (policyFlags & POLICY_FLAG_TRUSTED) {
JNIEnv* env = jniEnv();
- // Note: inputChannel may be null.
- jobject inputChannelObj = getInputChannelObjLocal(env, inputChannel);
+ // Note: inputWindowHandle may be null.
+ jobject inputWindowHandleObj = getInputWindowHandleObjLocalRef(env, inputWindowHandle);
jobject keyEventObj = android_view_KeyEvent_fromNative(env, keyEvent);
if (keyEventObj) {
jobject fallbackKeyEventObj = env->CallObjectMethod(mCallbacksObj,
gCallbacksClassInfo.dispatchUnhandledKey,
- inputChannelObj, keyEventObj, policyFlags);
+ inputWindowHandleObj, keyEventObj, policyFlags);
checkAndClearExceptionFromCallback(env, "dispatchUnhandledKey");
android_view_KeyEvent_recycle(env, keyEventObj);
env->DeleteLocalRef(keyEventObj);
@@ -935,7 +697,7 @@
} else {
LOGE("Failed to obtain key event object for dispatchUnhandledKey.");
}
- env->DeleteLocalRef(inputChannelObj);
+ env->DeleteLocalRef(inputWindowHandleObj);
}
return result;
}
@@ -1079,7 +841,7 @@
}
static void android_server_InputManager_nativeRegisterInputChannel(JNIEnv* env, jclass clazz,
- jobject inputChannelObj, jboolean monitor) {
+ jobject inputChannelObj, jobject inputWindowHandleObj, jboolean monitor) {
if (checkInputManagerUnitialized(env)) {
return;
}
@@ -1091,9 +853,11 @@
return;
}
+ sp<InputWindowHandle> inputWindowHandle =
+ android_server_InputWindowHandle_getHandle(env, inputWindowHandleObj);
status_t status = gNativeInputManager->registerInputChannel(
- env, inputChannel, inputChannelObj, monitor);
+ env, inputChannel, inputWindowHandle, monitor);
if (status) {
jniThrowRuntimeException(env, "Failed to register input channel. "
"Check logs for details.");
@@ -1311,7 +1075,8 @@
(void*) android_server_InputManager_nativeGetSwitchState },
{ "nativeHasKeys", "(II[I[Z)Z",
(void*) android_server_InputManager_nativeHasKeys },
- { "nativeRegisterInputChannel", "(Landroid/view/InputChannel;Z)V",
+ { "nativeRegisterInputChannel",
+ "(Landroid/view/InputChannel;Lcom/android/server/InputWindowHandle;Z)V",
(void*) android_server_InputManager_nativeRegisterInputChannel },
{ "nativeUnregisterInputChannel", "(Landroid/view/InputChannel;)V",
(void*) android_server_InputManager_nativeUnregisterInputChannel },
@@ -1364,21 +1129,22 @@
"notifyLidSwitchChanged", "(JZ)V");
GET_METHOD_ID(gCallbacksClassInfo.notifyInputChannelBroken, gCallbacksClassInfo.clazz,
- "notifyInputChannelBroken", "(Landroid/view/InputChannel;)V");
+ "notifyInputChannelBroken", "(Lcom/android/server/InputWindowHandle;)V");
GET_METHOD_ID(gCallbacksClassInfo.notifyANR, gCallbacksClassInfo.clazz,
- "notifyANR", "(Ljava/lang/Object;Landroid/view/InputChannel;)J");
+ "notifyANR",
+ "(Lcom/android/server/InputApplicationHandle;Lcom/android/server/InputWindowHandle;)J");
GET_METHOD_ID(gCallbacksClassInfo.interceptKeyBeforeQueueing, gCallbacksClassInfo.clazz,
"interceptKeyBeforeQueueing", "(Landroid/view/KeyEvent;IZ)I");
GET_METHOD_ID(gCallbacksClassInfo.interceptKeyBeforeDispatching, gCallbacksClassInfo.clazz,
"interceptKeyBeforeDispatching",
- "(Landroid/view/InputChannel;Landroid/view/KeyEvent;I)Z");
+ "(Lcom/android/server/InputWindowHandle;Landroid/view/KeyEvent;I)Z");
GET_METHOD_ID(gCallbacksClassInfo.dispatchUnhandledKey, gCallbacksClassInfo.clazz,
"dispatchUnhandledKey",
- "(Landroid/view/InputChannel;Landroid/view/KeyEvent;I)Landroid/view/KeyEvent;");
+ "(Lcom/android/server/InputWindowHandle;Landroid/view/KeyEvent;I)Landroid/view/KeyEvent;");
GET_METHOD_ID(gCallbacksClassInfo.checkInjectEventsPermission, gCallbacksClassInfo.clazz,
"checkInjectEventsPermission", "(II)Z");
@@ -1401,99 +1167,6 @@
GET_METHOD_ID(gCallbacksClassInfo.getPointerIcon, gCallbacksClassInfo.clazz,
"getPointerIcon", "()Lcom/android/server/InputManager$PointerIcon;");
- // InputWindow
-
- FIND_CLASS(gInputWindowClassInfo.clazz, "com/android/server/InputWindow");
-
- GET_FIELD_ID(gInputWindowClassInfo.inputChannel, gInputWindowClassInfo.clazz,
- "inputChannel", "Landroid/view/InputChannel;");
-
- GET_FIELD_ID(gInputWindowClassInfo.name, gInputWindowClassInfo.clazz,
- "name", "Ljava/lang/String;");
-
- GET_FIELD_ID(gInputWindowClassInfo.layoutParamsFlags, gInputWindowClassInfo.clazz,
- "layoutParamsFlags", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.layoutParamsType, gInputWindowClassInfo.clazz,
- "layoutParamsType", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.dispatchingTimeoutNanos, gInputWindowClassInfo.clazz,
- "dispatchingTimeoutNanos", "J");
-
- GET_FIELD_ID(gInputWindowClassInfo.frameLeft, gInputWindowClassInfo.clazz,
- "frameLeft", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.frameTop, gInputWindowClassInfo.clazz,
- "frameTop", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.frameRight, gInputWindowClassInfo.clazz,
- "frameRight", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.frameBottom, gInputWindowClassInfo.clazz,
- "frameBottom", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.visibleFrameLeft, gInputWindowClassInfo.clazz,
- "visibleFrameLeft", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.visibleFrameTop, gInputWindowClassInfo.clazz,
- "visibleFrameTop", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.visibleFrameRight, gInputWindowClassInfo.clazz,
- "visibleFrameRight", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.visibleFrameBottom, gInputWindowClassInfo.clazz,
- "visibleFrameBottom", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.touchableAreaLeft, gInputWindowClassInfo.clazz,
- "touchableAreaLeft", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.touchableAreaTop, gInputWindowClassInfo.clazz,
- "touchableAreaTop", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.touchableAreaRight, gInputWindowClassInfo.clazz,
- "touchableAreaRight", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.touchableAreaBottom, gInputWindowClassInfo.clazz,
- "touchableAreaBottom", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.visible, gInputWindowClassInfo.clazz,
- "visible", "Z");
-
- GET_FIELD_ID(gInputWindowClassInfo.canReceiveKeys, gInputWindowClassInfo.clazz,
- "canReceiveKeys", "Z");
-
- GET_FIELD_ID(gInputWindowClassInfo.hasFocus, gInputWindowClassInfo.clazz,
- "hasFocus", "Z");
-
- GET_FIELD_ID(gInputWindowClassInfo.hasWallpaper, gInputWindowClassInfo.clazz,
- "hasWallpaper", "Z");
-
- GET_FIELD_ID(gInputWindowClassInfo.paused, gInputWindowClassInfo.clazz,
- "paused", "Z");
-
- GET_FIELD_ID(gInputWindowClassInfo.layer, gInputWindowClassInfo.clazz,
- "layer", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.ownerPid, gInputWindowClassInfo.clazz,
- "ownerPid", "I");
-
- GET_FIELD_ID(gInputWindowClassInfo.ownerUid, gInputWindowClassInfo.clazz,
- "ownerUid", "I");
-
- // InputApplication
-
- FIND_CLASS(gInputApplicationClassInfo.clazz, "com/android/server/InputApplication");
-
- GET_FIELD_ID(gInputApplicationClassInfo.name, gInputApplicationClassInfo.clazz,
- "name", "Ljava/lang/String;");
-
- GET_FIELD_ID(gInputApplicationClassInfo.dispatchingTimeoutNanos,
- gInputApplicationClassInfo.clazz,
- "dispatchingTimeoutNanos", "J");
-
- GET_FIELD_ID(gInputApplicationClassInfo.token, gInputApplicationClassInfo.clazz,
- "token", "Ljava/lang/Object;");
-
// KeyEvent
FIND_CLASS(gKeyEventClassInfo.clazz, "android/view/KeyEvent");
diff --git a/services/jni/com_android_server_InputWindow.cpp b/services/jni/com_android_server_InputWindow.cpp
new file mode 100644
index 0000000..a4609a0
--- /dev/null
+++ b/services/jni/com_android_server_InputWindow.cpp
@@ -0,0 +1,240 @@
+/*
+ * Copyright (C) 2011 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 "InputWindow"
+
+#include "JNIHelp.h"
+#include "jni.h"
+#include <android_runtime/AndroidRuntime.h>
+
+#include <android_view_InputChannel.h>
+#include "com_android_server_InputWindow.h"
+#include "com_android_server_InputWindowHandle.h"
+
+namespace android {
+
+static struct {
+ jclass clazz;
+
+ jfieldID inputWindowHandle;
+ jfieldID inputChannel;
+ jfieldID name;
+ jfieldID layoutParamsFlags;
+ jfieldID layoutParamsType;
+ jfieldID dispatchingTimeoutNanos;
+ jfieldID frameLeft;
+ jfieldID frameTop;
+ jfieldID frameRight;
+ jfieldID frameBottom;
+ jfieldID visibleFrameLeft;
+ jfieldID visibleFrameTop;
+ jfieldID visibleFrameRight;
+ jfieldID visibleFrameBottom;
+ jfieldID touchableAreaLeft;
+ jfieldID touchableAreaTop;
+ jfieldID touchableAreaRight;
+ jfieldID touchableAreaBottom;
+ jfieldID visible;
+ jfieldID canReceiveKeys;
+ jfieldID hasFocus;
+ jfieldID hasWallpaper;
+ jfieldID paused;
+ jfieldID layer;
+ jfieldID ownerPid;
+ jfieldID ownerUid;
+} gInputWindowClassInfo;
+
+
+// --- Global functions ---
+
+void android_server_InputWindow_toNative(
+ JNIEnv* env, jobject inputWindowObj, InputWindow* outInputWindow) {
+ jobject inputWindowHandleObj = env->GetObjectField(inputWindowObj,
+ gInputWindowClassInfo.inputWindowHandle);
+ if (inputWindowHandleObj) {
+ outInputWindow->inputWindowHandle =
+ android_server_InputWindowHandle_getHandle(env, inputWindowHandleObj);
+ env->DeleteLocalRef(inputWindowHandleObj);
+ } else {
+ outInputWindow->inputWindowHandle = NULL;
+ }
+
+ jobject inputChannelObj = env->GetObjectField(inputWindowObj,
+ gInputWindowClassInfo.inputChannel);
+ if (inputChannelObj) {
+ outInputWindow->inputChannel =
+ android_view_InputChannel_getInputChannel(env, inputChannelObj);
+ env->DeleteLocalRef(inputChannelObj);
+ } else {
+ outInputWindow->inputChannel = NULL;
+ }
+
+ jstring nameObj = jstring(env->GetObjectField(inputWindowObj,
+ gInputWindowClassInfo.name));
+ if (nameObj) {
+ const char* nameStr = env->GetStringUTFChars(nameObj, NULL);
+ outInputWindow->name.setTo(nameStr);
+ env->ReleaseStringUTFChars(nameObj, nameStr);
+ env->DeleteLocalRef(nameObj);
+ } else {
+ LOGE("InputWindow.name should not be null.");
+ outInputWindow->name.setTo("unknown");
+ }
+
+ outInputWindow->layoutParamsFlags = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.layoutParamsFlags);
+ outInputWindow->layoutParamsType = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.layoutParamsType);
+ outInputWindow->dispatchingTimeout = env->GetLongField(inputWindowObj,
+ gInputWindowClassInfo.dispatchingTimeoutNanos);
+ outInputWindow->frameLeft = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.frameLeft);
+ outInputWindow->frameTop = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.frameTop);
+ outInputWindow->frameRight = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.frameRight);
+ outInputWindow->frameBottom = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.frameBottom);
+ outInputWindow->visibleFrameLeft = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.visibleFrameLeft);
+ outInputWindow->visibleFrameTop = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.visibleFrameTop);
+ outInputWindow->visibleFrameRight = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.visibleFrameRight);
+ outInputWindow->visibleFrameBottom = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.visibleFrameBottom);
+ outInputWindow->touchableAreaLeft = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.touchableAreaLeft);
+ outInputWindow->touchableAreaTop = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.touchableAreaTop);
+ outInputWindow->touchableAreaRight = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.touchableAreaRight);
+ outInputWindow->touchableAreaBottom = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.touchableAreaBottom);
+ outInputWindow->visible = env->GetBooleanField(inputWindowObj,
+ gInputWindowClassInfo.visible);
+ outInputWindow->canReceiveKeys = env->GetBooleanField(inputWindowObj,
+ gInputWindowClassInfo.canReceiveKeys);
+ outInputWindow->hasFocus = env->GetBooleanField(inputWindowObj,
+ gInputWindowClassInfo.hasFocus);
+ outInputWindow->hasWallpaper = env->GetBooleanField(inputWindowObj,
+ gInputWindowClassInfo.hasWallpaper);
+ outInputWindow->paused = env->GetBooleanField(inputWindowObj,
+ gInputWindowClassInfo.paused);
+ outInputWindow->layer = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.layer);
+ outInputWindow->ownerPid = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.ownerPid);
+ outInputWindow->ownerUid = env->GetIntField(inputWindowObj,
+ gInputWindowClassInfo.ownerUid);
+}
+
+
+// --- JNI ---
+
+#define FIND_CLASS(var, className) \
+ var = env->FindClass(className); \
+ LOG_FATAL_IF(! var, "Unable to find class " className); \
+ var = jclass(env->NewGlobalRef(var));
+
+#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \
+ var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \
+ LOG_FATAL_IF(! var, "Unable to find field " fieldName);
+
+int register_android_server_InputWindow(JNIEnv* env) {
+ FIND_CLASS(gInputWindowClassInfo.clazz, "com/android/server/InputWindow");
+
+ GET_FIELD_ID(gInputWindowClassInfo.inputWindowHandle, gInputWindowClassInfo.clazz,
+ "inputWindowHandle", "Lcom/android/server/InputWindowHandle;");
+
+ GET_FIELD_ID(gInputWindowClassInfo.inputChannel, gInputWindowClassInfo.clazz,
+ "inputChannel", "Landroid/view/InputChannel;");
+
+ GET_FIELD_ID(gInputWindowClassInfo.name, gInputWindowClassInfo.clazz,
+ "name", "Ljava/lang/String;");
+
+ GET_FIELD_ID(gInputWindowClassInfo.layoutParamsFlags, gInputWindowClassInfo.clazz,
+ "layoutParamsFlags", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.layoutParamsType, gInputWindowClassInfo.clazz,
+ "layoutParamsType", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.dispatchingTimeoutNanos, gInputWindowClassInfo.clazz,
+ "dispatchingTimeoutNanos", "J");
+
+ GET_FIELD_ID(gInputWindowClassInfo.frameLeft, gInputWindowClassInfo.clazz,
+ "frameLeft", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.frameTop, gInputWindowClassInfo.clazz,
+ "frameTop", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.frameRight, gInputWindowClassInfo.clazz,
+ "frameRight", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.frameBottom, gInputWindowClassInfo.clazz,
+ "frameBottom", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.visibleFrameLeft, gInputWindowClassInfo.clazz,
+ "visibleFrameLeft", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.visibleFrameTop, gInputWindowClassInfo.clazz,
+ "visibleFrameTop", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.visibleFrameRight, gInputWindowClassInfo.clazz,
+ "visibleFrameRight", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.visibleFrameBottom, gInputWindowClassInfo.clazz,
+ "visibleFrameBottom", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.touchableAreaLeft, gInputWindowClassInfo.clazz,
+ "touchableAreaLeft", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.touchableAreaTop, gInputWindowClassInfo.clazz,
+ "touchableAreaTop", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.touchableAreaRight, gInputWindowClassInfo.clazz,
+ "touchableAreaRight", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.touchableAreaBottom, gInputWindowClassInfo.clazz,
+ "touchableAreaBottom", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.visible, gInputWindowClassInfo.clazz,
+ "visible", "Z");
+
+ GET_FIELD_ID(gInputWindowClassInfo.canReceiveKeys, gInputWindowClassInfo.clazz,
+ "canReceiveKeys", "Z");
+
+ GET_FIELD_ID(gInputWindowClassInfo.hasFocus, gInputWindowClassInfo.clazz,
+ "hasFocus", "Z");
+
+ GET_FIELD_ID(gInputWindowClassInfo.hasWallpaper, gInputWindowClassInfo.clazz,
+ "hasWallpaper", "Z");
+
+ GET_FIELD_ID(gInputWindowClassInfo.paused, gInputWindowClassInfo.clazz,
+ "paused", "Z");
+
+ GET_FIELD_ID(gInputWindowClassInfo.layer, gInputWindowClassInfo.clazz,
+ "layer", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.ownerPid, gInputWindowClassInfo.clazz,
+ "ownerPid", "I");
+
+ GET_FIELD_ID(gInputWindowClassInfo.ownerUid, gInputWindowClassInfo.clazz,
+ "ownerUid", "I");
+ return 0;
+}
+
+} /* namespace android */
diff --git a/services/jni/com_android_server_InputWindow.h b/services/jni/com_android_server_InputWindow.h
new file mode 100644
index 0000000..eaf7bde
--- /dev/null
+++ b/services/jni/com_android_server_InputWindow.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2011 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_SERVER_INPUT_WINDOW_H
+#define _ANDROID_SERVER_INPUT_WINDOW_H
+
+#include <input/InputWindow.h>
+
+#include "JNIHelp.h"
+#include "jni.h"
+
+namespace android {
+
+extern void android_server_InputWindow_toNative(
+ JNIEnv* env, jobject inputWindowObj, InputWindow* outInputWindow);
+
+} // namespace android
+
+#endif // _ANDROID_SERVER_INPUT_WINDOW_H
diff --git a/services/jni/com_android_server_InputWindowHandle.cpp b/services/jni/com_android_server_InputWindowHandle.cpp
new file mode 100644
index 0000000..4d66212
--- /dev/null
+++ b/services/jni/com_android_server_InputWindowHandle.cpp
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2011 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 "InputWindowHandle"
+
+#include "JNIHelp.h"
+#include "jni.h"
+#include <android_runtime/AndroidRuntime.h>
+#include <utils/threads.h>
+
+#include "com_android_server_InputWindowHandle.h"
+#include "com_android_server_InputApplicationHandle.h"
+
+namespace android {
+
+static struct {
+ jclass clazz;
+
+ jfieldID ptr;
+ jfieldID inputApplicationHandle;
+} gInputWindowHandleClassInfo;
+
+static Mutex gHandleMutex;
+
+
+// --- NativeInputWindowHandle ---
+
+NativeInputWindowHandle::NativeInputWindowHandle(
+ const sp<InputApplicationHandle>& inputApplicationHandle, jweak objWeak) :
+ InputWindowHandle(inputApplicationHandle),
+ mObjWeak(objWeak) {
+}
+
+NativeInputWindowHandle::~NativeInputWindowHandle() {
+ JNIEnv* env = AndroidRuntime::getJNIEnv();
+ env->DeleteWeakGlobalRef(mObjWeak);
+}
+
+jobject NativeInputWindowHandle::getInputWindowHandleObjLocalRef(JNIEnv* env) {
+ return env->NewLocalRef(mObjWeak);
+}
+
+
+// --- Global functions ---
+
+sp<NativeInputWindowHandle> android_server_InputWindowHandle_getHandle(
+ JNIEnv* env, jobject inputWindowHandleObj) {
+ if (!inputWindowHandleObj) {
+ return NULL;
+ }
+
+ AutoMutex _l(gHandleMutex);
+
+ int ptr = env->GetIntField(inputWindowHandleObj, gInputWindowHandleClassInfo.ptr);
+ NativeInputWindowHandle* handle;
+ if (ptr) {
+ handle = reinterpret_cast<NativeInputWindowHandle*>(ptr);
+ } else {
+ jobject inputApplicationHandleObj = env->GetObjectField(inputWindowHandleObj,
+ gInputWindowHandleClassInfo.inputApplicationHandle);
+ sp<InputApplicationHandle> inputApplicationHandle =
+ android_server_InputApplicationHandle_getHandle(env, inputApplicationHandleObj);
+ env->DeleteLocalRef(inputApplicationHandleObj);
+
+ jweak objWeak = env->NewWeakGlobalRef(inputWindowHandleObj);
+ handle = new NativeInputWindowHandle(inputApplicationHandle, objWeak);
+ handle->incStrong(inputWindowHandleObj);
+ env->SetIntField(inputWindowHandleObj, gInputWindowHandleClassInfo.ptr,
+ reinterpret_cast<int>(handle));
+ }
+ return handle;
+}
+
+
+// --- JNI ---
+
+static void android_server_InputWindowHandle_nativeDispose(JNIEnv* env, jobject obj) {
+ AutoMutex _l(gHandleMutex);
+
+ int ptr = env->GetIntField(obj, gInputWindowHandleClassInfo.ptr);
+ if (ptr) {
+ env->SetIntField(obj, gInputWindowHandleClassInfo.ptr, 0);
+
+ NativeInputWindowHandle* handle = reinterpret_cast<NativeInputWindowHandle*>(ptr);
+ handle->decStrong(obj);
+ }
+}
+
+
+static JNINativeMethod gInputWindowHandleMethods[] = {
+ /* name, signature, funcPtr */
+ { "nativeDispose", "()V",
+ (void*) android_server_InputWindowHandle_nativeDispose },
+};
+
+#define FIND_CLASS(var, className) \
+ var = env->FindClass(className); \
+ LOG_FATAL_IF(! var, "Unable to find class " className); \
+ var = jclass(env->NewGlobalRef(var));
+
+#define GET_FIELD_ID(var, clazz, fieldName, fieldDescriptor) \
+ var = env->GetFieldID(clazz, fieldName, fieldDescriptor); \
+ LOG_FATAL_IF(! var, "Unable to find field " fieldName);
+
+int register_android_server_InputWindowHandle(JNIEnv* env) {
+ int res = jniRegisterNativeMethods(env, "com/android/server/InputWindowHandle",
+ gInputWindowHandleMethods, NELEM(gInputWindowHandleMethods));
+ LOG_FATAL_IF(res < 0, "Unable to register native methods.");
+
+ FIND_CLASS(gInputWindowHandleClassInfo.clazz, "com/android/server/InputWindowHandle");
+
+ GET_FIELD_ID(gInputWindowHandleClassInfo.ptr, gInputWindowHandleClassInfo.clazz,
+ "ptr", "I");
+
+ GET_FIELD_ID(gInputWindowHandleClassInfo.inputApplicationHandle,
+ gInputWindowHandleClassInfo.clazz,
+ "inputApplicationHandle", "Lcom/android/server/InputApplicationHandle;");
+
+ return 0;
+}
+
+} /* namespace android */
diff --git a/services/jni/com_android_server_InputWindowHandle.h b/services/jni/com_android_server_InputWindowHandle.h
new file mode 100644
index 0000000..43f2a6b
--- /dev/null
+++ b/services/jni/com_android_server_InputWindowHandle.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2011 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_SERVER_INPUT_WINDOW_HANDLE_H
+#define _ANDROID_SERVER_INPUT_WINDOW_HANDLE_H
+
+#include <input/InputWindow.h>
+
+#include "JNIHelp.h"
+#include "jni.h"
+
+namespace android {
+
+class NativeInputWindowHandle : public InputWindowHandle {
+public:
+ NativeInputWindowHandle(const sp<InputApplicationHandle>& inputApplicationHandle,
+ jweak objWeak);
+ virtual ~NativeInputWindowHandle();
+
+ jobject getInputWindowHandleObjLocalRef(JNIEnv* env);
+
+private:
+ jweak mObjWeak;
+};
+
+
+extern sp<NativeInputWindowHandle> android_server_InputWindowHandle_getHandle(
+ JNIEnv* env, jobject inputWindowHandleObj);
+
+} // namespace android
+
+#endif // _ANDROID_SERVER_INPUT_WINDOW_HANDLE_H
diff --git a/services/jni/onload.cpp b/services/jni/onload.cpp
index cd4f0a4..bdd6d80 100644
--- a/services/jni/onload.cpp
+++ b/services/jni/onload.cpp
@@ -6,6 +6,10 @@
namespace android {
int register_android_server_AlarmManagerService(JNIEnv* env);
int register_android_server_BatteryService(JNIEnv* env);
+int register_android_server_InputApplication(JNIEnv* env);
+int register_android_server_InputApplicationHandle(JNIEnv* env);
+int register_android_server_InputWindow(JNIEnv* env);
+int register_android_server_InputWindowHandle(JNIEnv* env);
int register_android_server_InputManager(JNIEnv* env);
int register_android_server_LightsService(JNIEnv* env);
int register_android_server_PowerManagerService(JNIEnv* env);
@@ -28,6 +32,10 @@
LOG_ASSERT(env, "Could not retrieve the env!");
register_android_server_PowerManagerService(env);
+ register_android_server_InputApplication(env);
+ register_android_server_InputApplicationHandle(env);
+ register_android_server_InputWindow(env);
+ register_android_server_InputWindowHandle(env);
register_android_server_InputManager(env);
register_android_server_LightsService(env);
register_android_server_AlarmManagerService(env);
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 825d90b..c982ea5 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -2267,6 +2267,25 @@
// ---------------------------------------------------------------------------
+sp<GraphicBuffer> SurfaceFlinger::createGraphicBuffer(uint32_t w, uint32_t h,
+ PixelFormat format, uint32_t usage) const {
+ // XXX: HACK HACK HACK!!! This should NOT be static, but it is to fix a
+ // race between SurfaceFlinger unref'ing the buffer and the client ref'ing
+ // it.
+ static sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
+ status_t err = graphicBuffer->initCheck();
+ if (err != 0) {
+ LOGE("createGraphicBuffer: init check failed: %d", err);
+ return 0;
+ } else if (graphicBuffer->handle == 0) {
+ LOGE("createGraphicBuffer: unable to create GraphicBuffer");
+ return 0;
+ }
+ return graphicBuffer;
+}
+
+// ---------------------------------------------------------------------------
+
Client::Client(const sp<SurfaceFlinger>& flinger)
: mFlinger(flinger), mNameGenerator(1)
{
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index ca7d27d..48642d4 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -322,6 +322,8 @@
status_t electronBeamOnAnimationImplLocked();
status_t renderScreenToTextureLocked(DisplayID dpy,
GLuint* textureName, GLfloat* uOut, GLfloat* vOut);
+ sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
+ PixelFormat format, uint32_t usage) const;
friend class FreezeLock;
sp<FreezeLock> getFreezeLock() const;
diff --git a/telephony/java/com/android/internal/telephony/SMSDispatcher.java b/telephony/java/com/android/internal/telephony/SMSDispatcher.java
index e7cfe75..99123af 100644
--- a/telephony/java/com/android/internal/telephony/SMSDispatcher.java
+++ b/telephony/java/com/android/internal/telephony/SMSDispatcher.java
@@ -37,6 +37,7 @@
import android.os.Message;
import android.os.PowerManager;
import android.os.StatFs;
+import android.os.SystemProperties;
import android.provider.Telephony;
import android.provider.Telephony.Sms.Intents;
import android.provider.Settings;
@@ -156,8 +157,10 @@
protected boolean mStorageAvailable = true;
protected boolean mReportMemoryStatusPending = false;
- /* Flag indicating whether the current device allows sms service */
+ /* Flags indicating whether the current device allows sms service */
protected boolean mSmsCapable = true;
+ protected boolean mSmsReceiveDisabled;
+ protected boolean mSmsSendDisabled;
protected static int getNextConcatenatedRef() {
sConcatenatedRef += 1;
@@ -255,6 +258,13 @@
mSmsCapable = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_sms_capable);
+ mSmsReceiveDisabled = !SystemProperties.getBoolean(
+ TelephonyProperties.PROPERTY_SMS_RECEIVE, mSmsCapable);
+ mSmsSendDisabled = !SystemProperties.getBoolean(
+ TelephonyProperties.PROPERTY_SMS_SEND, mSmsCapable);
+ Log.d(TAG, "SMSDispatcher: ctor mSmsCapable=" + mSmsCapable
+ + " mSmsReceiveDisabled=" + mSmsReceiveDisabled
+ + " mSmsSendDisabled=" + mSmsSendDisabled);
}
public void dispose() {
@@ -783,13 +793,13 @@
*/
protected void sendRawPdu(byte[] smsc, byte[] pdu, PendingIntent sentIntent,
PendingIntent deliveryIntent) {
- if (!mSmsCapable) {
+ if (mSmsSendDisabled) {
if (sentIntent != null) {
try {
sentIntent.send(RESULT_ERROR_NO_SERVICE);
} catch (CanceledException ex) {}
}
- Log.d(TAG, "Device does not support sms service.");
+ Log.d(TAG, "Device does not support sending sms.");
return;
}
diff --git a/telephony/java/com/android/internal/telephony/TelephonyProperties.java b/telephony/java/com/android/internal/telephony/TelephonyProperties.java
index 136d5b1..e6189be 100644
--- a/telephony/java/com/android/internal/telephony/TelephonyProperties.java
+++ b/telephony/java/com/android/internal/telephony/TelephonyProperties.java
@@ -147,4 +147,16 @@
* when there is a radio technology change.
*/
static final String PROPERTY_RESET_ON_RADIO_TECH_CHANGE = "persist.radio.reset_on_switch";
+
+ /**
+ * Set to false to disable SMS receiving, default is
+ * the value of config_sms_capable
+ */
+ static final String PROPERTY_SMS_RECEIVE = "telephony.sms.receive";
+
+ /**
+ * Set to false to disable SMS sending, default is
+ * the value of config_sms_capable
+ */
+ static final String PROPERTY_SMS_SEND = "telephony.sms.send";
}
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java b/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java
index 01234b0..6bd2d09 100644
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaSMSDispatcher.java
@@ -107,10 +107,10 @@
return Activity.RESULT_OK;
}
- if (!mSmsCapable) {
- // Device doesn't support SMS service,
+ if (mSmsReceiveDisabled) {
+ // Device doesn't support receiving SMS,
Log.d(TAG, "Received short message on device which doesn't support "
- + "SMS service. Ignored.");
+ + "receiving SMS. Ignored.");
return Intents.RESULT_SMS_HANDLED;
}
diff --git a/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java b/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java
index de15408..17cf36d 100755
--- a/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CdmaServiceStateTracker.java
@@ -605,7 +605,11 @@
// mOperatorAlphaLong contains the ERI text
String plmn = ss.getOperatorAlphaLong();
if (!TextUtils.equals(plmn, curPlmn)) {
- boolean showPlmn = !TextUtils.isEmpty(plmn);
+ // Allow A blank plmn, "" to set showPlmn to true. Previously, we
+ // would set showPlmn to true only if plmn was not empty, i.e. was not
+ // null and not blank. But this would cause us to incorrectly display
+ // "No Service". Now showPlmn is set to true for any non null string.
+ boolean showPlmn = plmn != null;
Log.d(LOG_TAG,
String.format("updateSpnDisplay: changed sending intent" +
" showPlmn='%b' plmn='%s'", showPlmn, plmn));
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java b/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
index 497c552..bbe579d 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmSMSDispatcher.java
@@ -110,7 +110,7 @@
return Intents.RESULT_SMS_HANDLED;
}
- if (!mSmsCapable) {
+ if (mSmsReceiveDisabled) {
// Device doesn't support SMS service,
Log.d(TAG, "Received short message on device which doesn't support "
+ "SMS service. Ignored.");
diff --git a/test-runner/src/android/test/ActivityTestCase.java b/test-runner/src/android/test/ActivityTestCase.java
index 18bfccc..c7b1d70 100644
--- a/test-runner/src/android/test/ActivityTestCase.java
+++ b/test-runner/src/android/test/ActivityTestCase.java
@@ -19,10 +19,11 @@
import android.app.Activity;
import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
/**
* This is common code used to support Activity test cases. For more useful classes, please see
- * {@link android.test.ActivityUnitTestCase} and
+ * {@link android.test.ActivityUnitTestCase} and
* {@link android.test.ActivityInstrumentationTestCase}.
*/
public abstract class ActivityTestCase extends InstrumentationTestCase {
@@ -38,7 +39,7 @@
protected Activity getActivity() {
return mActivity;
}
-
+
/**
* Set the activity under test.
* @param testActivity The activity under test
@@ -46,15 +47,15 @@
protected void setActivity(Activity testActivity) {
mActivity = testActivity;
}
-
+
/**
* This function is called by various TestCase implementations, at tearDown() time, in order
* to scrub out any class variables. This protects against memory leaks in the case where a
* test case creates a non-static inner class (thus referencing the test case) and gives it to
* someone else to hold onto.
- *
+ *
* @param testCaseClass The class of the derived TestCase implementation.
- *
+ *
* @throws IllegalAccessException
*/
protected void scrubClass(final Class<?> testCaseClass)
@@ -62,7 +63,8 @@
final Field[] fields = getClass().getDeclaredFields();
for (Field field : fields) {
final Class<?> fieldClass = field.getDeclaringClass();
- if (testCaseClass.isAssignableFrom(fieldClass) && !field.getType().isPrimitive()) {
+ if (testCaseClass.isAssignableFrom(fieldClass) && !field.getType().isPrimitive()
+ && (field.getModifiers() & Modifier.FINAL) == 0) {
try {
field.setAccessible(true);
field.set(this, null);
@@ -77,6 +79,6 @@
}
}
-
+
}
diff --git a/tests/CoreTests/android/core/HeapTest.java b/tests/CoreTests/android/core/HeapTest.java
index 6116f5e..98cb28a 100644
--- a/tests/CoreTests/android/core/HeapTest.java
+++ b/tests/CoreTests/android/core/HeapTest.java
@@ -540,94 +540,4 @@
objSize = (objSize * 4) / 5;
}
}
-
- // TODO: flaky test
- //@SmallTest
- public void testExternalOomeLarge() {
- /* Just shy of the typical max heap size so that it will actually
- * try to allocate it instead of short-circuiting.
- */
- final int HUGE_SIZE = (16 * 1024 * 1024 - 32);
-
- assertFalse(VMRuntime.getRuntime().trackExternalAllocation(HUGE_SIZE));
- }
-
- /**
- * "Allocates" external memory in progressively smaller chunks until there's
- * only roughly 16 bytes left.
- *
- * @return the number of bytes allocated
- */
- private long allocateMaxExternal() {
- final VMRuntime runtime = VMRuntime.getRuntime();
- final int SIXTEEN_MB = (16 * 1024 * 1024);
- final int MIN_SIZE = 16;
- long totalAllocated = 0;
- boolean success;
-
- success = false;
- try {
- /* "Allocate" progressively smaller chunks to "fill up" the entire heap.
- */
- int objSize = 1 * 1024 * 1024;
- while (objSize >= MIN_SIZE) {
- boolean sawFailure = false;
- for (int i = 0; i < SIXTEEN_MB / objSize; i++) {
- if (runtime.trackExternalAllocation(objSize)) {
- totalAllocated += objSize;
- } else {
- sawFailure = true;
- break;
- }
- }
-
- if (!sawFailure) {
- throw new RuntimeException("Test failed: " +
- "no failure while filling heap");
- }
-
- objSize = (objSize * 4) / 5;
- }
- success = true;
- } finally {
- if (!success) {
- runtime.trackExternalFree(totalAllocated);
- totalAllocated = 0;
- }
- }
- return totalAllocated;
- }
-
- public void xxtest00ExternalOomeSmall() {
- VMRuntime.getRuntime().trackExternalFree(allocateMaxExternal());
- }
-
- /**
- * Allocates as much external memory as possible, then allocates from the heap
- * until an OOME is caught.
- *
- * It's nice to run this test while the real heap is small, hence the '00' in its
- * name to force it to run before testOomeSmall().
- */
- public void xxtest00CombinedOomeSmall() {
- long totalAllocated = 0;
- boolean sawEx = false;
- try {
- totalAllocated = allocateMaxExternal();
- LinkedList<Object> list = new LinkedList<Object>();
- try {
- while (true) {
- list.add((Object)new byte[8192]);
- }
- /*NOTREACHED*/
- } catch (OutOfMemoryError oom) {
- sawEx = true;
- }
- } finally {
- VMRuntime.getRuntime().trackExternalFree(totalAllocated);
- }
- assertTrue(sawEx);
- }
-
- //TODO: test external alloc debugging/inspection
}
diff --git a/tests/HwAccelerationTest/AndroidManifest.xml b/tests/HwAccelerationTest/AndroidManifest.xml
index c60613c..0fdc030 100644
--- a/tests/HwAccelerationTest/AndroidManifest.xml
+++ b/tests/HwAccelerationTest/AndroidManifest.xml
@@ -18,13 +18,22 @@
package="com.android.test.hwui">
<uses-permission android:name="android.permission.INTERNET" />
- <uses-sdk android:minSdkVersion="Froyo" />
+ <uses-sdk android:minSdkVersion="Honeycomb" />
<application
android:label="HwUi"
android:hardwareAccelerated="true">
<activity
+ android:name="ViewLayersActivity"
+ android:label="_ViewLayers">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+
+ <activity
android:name="AlphaLayersActivity"
android:label="_αLayers">
<intent-filter>
diff --git a/tests/HwAccelerationTest/res/layout/_advanced_blend.xml b/tests/HwAccelerationTest/res/layout/_advanced_blend.xml
index 6efdd73..5b6fd3c 100644
--- a/tests/HwAccelerationTest/res/layout/_advanced_blend.xml
+++ b/tests/HwAccelerationTest/res/layout/_advanced_blend.xml
@@ -1,6 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2010 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.
+-->
<com.android.test.hwui.AdvancedBlendActivity.ShadersView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-</com.android.test.hwui.AdvancedBlendActivity.ShadersView>
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent" />
diff --git a/tests/HwAccelerationTest/res/layout/_advanced_gradient.xml b/tests/HwAccelerationTest/res/layout/_advanced_gradient.xml
index dd937f9..5e32ed2 100644
--- a/tests/HwAccelerationTest/res/layout/_advanced_gradient.xml
+++ b/tests/HwAccelerationTest/res/layout/_advanced_gradient.xml
@@ -1,6 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2010 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.
+-->
<com.android.test.hwui.AdvancedGradientsActivity.GradientsView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-</com.android.test.hwui.AdvancedGradientsActivity.GradientsView>
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent" />
diff --git a/tests/HwAccelerationTest/res/layout/_layers.xml b/tests/HwAccelerationTest/res/layout/_layers.xml
index c2b186d..25c76ac 100644
--- a/tests/HwAccelerationTest/res/layout/_layers.xml
+++ b/tests/HwAccelerationTest/res/layout/_layers.xml
@@ -1,6 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2010 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.
+-->
<com.android.test.hwui.LayersActivity.LayersView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-</com.android.test.hwui.LayersActivity.LayersView>
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent" />
+
diff --git a/tests/HwAccelerationTest/res/layout/_lines.xml b/tests/HwAccelerationTest/res/layout/_lines.xml
index 00f2556..c24dc25 100644
--- a/tests/HwAccelerationTest/res/layout/_lines.xml
+++ b/tests/HwAccelerationTest/res/layout/_lines.xml
@@ -1,6 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2010 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.
+-->
<com.android.test.hwui.LinesActivity.LinesView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-</com.android.test.hwui.LinesActivity.LinesView>
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent" />
+
diff --git a/tests/HwAccelerationTest/res/layout/_newlayers.xml b/tests/HwAccelerationTest/res/layout/_newlayers.xml
index 062a2e1..5c37e37 100644
--- a/tests/HwAccelerationTest/res/layout/_newlayers.xml
+++ b/tests/HwAccelerationTest/res/layout/_newlayers.xml
@@ -1,6 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2010 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.
+-->
<com.android.test.hwui.NewLayersActivity.LayersView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-</com.android.test.hwui.NewLayersActivity.LayersView>
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent" />
+
diff --git a/tests/HwAccelerationTest/res/layout/_paths.xml b/tests/HwAccelerationTest/res/layout/_paths.xml
index b053482..34baf84 100644
--- a/tests/HwAccelerationTest/res/layout/_paths.xml
+++ b/tests/HwAccelerationTest/res/layout/_paths.xml
@@ -1,6 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2010 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.
+-->
<com.android.test.hwui.PathsActivity.PathsView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-</com.android.test.hwui.PathsActivity.PathsView>
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent" />
diff --git a/tests/HwAccelerationTest/res/layout/_shaders.xml b/tests/HwAccelerationTest/res/layout/_shaders.xml
index dcb42fb..070ac12 100644
--- a/tests/HwAccelerationTest/res/layout/_shaders.xml
+++ b/tests/HwAccelerationTest/res/layout/_shaders.xml
@@ -1,6 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2010 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.
+-->
<com.android.test.hwui.ShadersActivity.ShadersView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-</com.android.test.hwui.ShadersActivity.ShadersView>
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="fill_parent"
+ android:layout_height="fill_parent" />
+
diff --git a/tests/HwAccelerationTest/res/layout/view_layers.xml b/tests/HwAccelerationTest/res/layout/view_layers.xml
new file mode 100644
index 0000000..e0cdc78
--- /dev/null
+++ b/tests/HwAccelerationTest/res/layout/view_layers.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 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.
+-->
+
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:orientation="horizontal"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent">
+
+ <ListView
+ android:id="@+id/list1"
+ android:layout_width="0dip"
+ android:layout_height="match_parent"
+ android:layout_weight="1" />
+
+ <ListView
+ android:id="@+id/list2"
+ android:layout_width="0dip"
+ android:layout_height="match_parent"
+ android:layout_weight="1" />
+
+ <ListView
+ android:id="@+id/list3"
+ android:layout_width="0dip"
+ android:layout_height="match_parent"
+ android:layout_weight="1" />
+
+</LinearLayout>
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/LinesActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/LinesActivity.java
index 91e3b84..8ca842e 100644
--- a/tests/HwAccelerationTest/src/com/android/test/hwui/LinesActivity.java
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/LinesActivity.java
@@ -23,6 +23,7 @@
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
+import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
@@ -31,7 +32,9 @@
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ getWindow().setBackgroundDrawable(new ColorDrawable(0xffffffff));
final LinesView view = new LinesView(this);
+ //view.setAlpha(0.80f);
setContentView(view);
}
@@ -91,8 +94,6 @@
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
- canvas.drawARGB(255, 255, 255, 255);
-
canvas.save();
canvas.translate(100.0f, 20.0f);
diff --git a/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity.java b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity.java
new file mode 100644
index 0000000..359447d
--- /dev/null
+++ b/tests/HwAccelerationTest/src/com/android/test/hwui/ViewLayersActivity.java
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2011 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.test.hwui;
+
+import android.animation.ObjectAnimator;
+import android.app.Activity;
+import android.content.Context;
+import android.content.res.Resources;
+import android.graphics.Paint;
+import android.graphics.PorterDuff;
+import android.graphics.PorterDuffColorFilter;
+import android.os.Bundle;
+import android.util.DisplayMetrics;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+import android.widget.TextView;
+
+@SuppressWarnings({"UnusedDeclaration"})
+public class ViewLayersActivity extends Activity {
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ setContentView(R.layout.view_layers);
+
+ setupList(R.id.list1);
+ setupList(R.id.list2);
+ setupList(R.id.list3);
+
+ getWindow().getDecorView().postDelayed(new Runnable() {
+ @Override
+ public void run() {
+ final View leftList = findViewById(R.id.list1);
+ final View middleList = findViewById(R.id.list2);
+ final View rightList = findViewById(R.id.list3);
+
+ final ObjectAnimator moveRight = ObjectAnimator.ofFloat(leftList,
+ "x", 0, rightList.getLeft());
+ moveRight.setDuration(1500);
+ moveRight.setRepeatCount(ObjectAnimator.INFINITE);
+ moveRight.setRepeatMode(ObjectAnimator.REVERSE);
+
+ final ObjectAnimator moveLeft = ObjectAnimator.ofFloat(rightList,
+ "x", rightList.getLeft(), 0);
+ moveLeft.setDuration(1500);
+ moveLeft.setRepeatCount(ObjectAnimator.INFINITE);
+ moveLeft.setRepeatMode(ObjectAnimator.REVERSE);
+
+ final ObjectAnimator rotate = ObjectAnimator.ofFloat(middleList,
+ "rotationY", 0, 360);
+ rotate.setDuration(3000);
+ rotate.setRepeatCount(ObjectAnimator.INFINITE);
+ rotate.setRepeatMode(ObjectAnimator.REVERSE);
+
+ Paint p = new Paint();
+ p.setColorFilter(new PorterDuffColorFilter(0xffff0000, PorterDuff.Mode.MULTIPLY));
+
+ Paint p2 = new Paint();
+ p2.setAlpha(127);
+
+ Paint p3 = new Paint();
+ p3.setColorFilter(new PorterDuffColorFilter(0xff00ff00, PorterDuff.Mode.MULTIPLY));
+
+ leftList.setLayerType(View.LAYER_TYPE_SOFTWARE, p);
+ leftList.setAlpha(0.5f);
+ middleList.setLayerType(View.LAYER_TYPE_HARDWARE, p3);
+ middleList.setAlpha(0.5f);
+ rightList.setLayerType(View.LAYER_TYPE_SOFTWARE, p2);
+
+ moveRight.start();
+ moveLeft.start();
+ rotate.start();
+ }
+ }, 2000);
+ }
+
+ private void setupList(int listId) {
+ final ListView list = (ListView) findViewById(listId);
+ list.setAdapter(new SimpleListAdapter(this));
+ }
+
+ private static class SimpleListAdapter extends ArrayAdapter<String> {
+ public SimpleListAdapter(Context context) {
+ super(context, android.R.layout.simple_list_item_1, DATA_LIST);
+ }
+
+ @Override
+ public View getView(int position, View convertView, ViewGroup parent) {
+ TextView v = (TextView) super.getView(position, convertView, parent);
+ final Resources r = getContext().getResources();
+ final DisplayMetrics metrics = r.getDisplayMetrics();
+ v.setCompoundDrawablePadding((int) (6 * metrics.density + 0.5f));
+ v.setCompoundDrawablesWithIntrinsicBounds(r.getDrawable(R.drawable.icon),
+ null, null, null);
+ return v;
+ }
+ }
+
+ private static final String[] DATA_LIST = {
+ "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
+ "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
+ "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
+ "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
+ "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
+ "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil",
+ "British Indian Ocean Territory", "British Virgin Islands", "Brunei", "Bulgaria",
+ "Burkina Faso", "Burundi", "Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
+ "Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
+ "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
+ "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
+ "Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
+ "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
+ "Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
+ "Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
+ "French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
+ "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
+ "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
+ "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
+ "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
+ "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
+ "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
+ "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
+ "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
+ "Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
+ "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
+ "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
+ "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
+ "Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
+ "Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
+ "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
+ "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
+ "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
+ "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
+ "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
+ "The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
+ "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
+ "Ukraine", "United Arab Emirates", "United Kingdom",
+ "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
+ "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
+ "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
+ };
+}
diff --git a/tests/StatusBar/AndroidManifest.xml b/tests/StatusBar/AndroidManifest.xml
index ddb756b..81442bf 100644
--- a/tests/StatusBar/AndroidManifest.xml
+++ b/tests/StatusBar/AndroidManifest.xml
@@ -5,6 +5,7 @@
<uses-permission android:name="android.permission.STATUS_BAR" />
<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
<uses-permission android:name="android.permission.VIBRATE" />
+ <uses-permission android:name="android.permission.CHANGE_COMPONENT_ENABLED_STATE" />
<application>
<activity android:name="StatusBarTest" android:label="_StatusBar">
diff --git a/tests/StatusBar/src/com/android/statusbartest/PowerTest.java b/tests/StatusBar/src/com/android/statusbartest/PowerTest.java
index 92d5bee..31a1cf5a 100644
--- a/tests/StatusBar/src/com/android/statusbartest/PowerTest.java
+++ b/tests/StatusBar/src/com/android/statusbartest/PowerTest.java
@@ -26,6 +26,8 @@
import android.os.IPowerManager;
import android.widget.ListView;
import android.content.Intent;
+import android.content.ComponentName;
+import android.content.pm.PackageManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.StatusBarManager;
@@ -66,6 +68,24 @@
return mTests;
}
private Test[] mTests = new Test[] {
+ new Test("Enable settings widget") {
+ public void run() {
+ PackageManager pm = getPackageManager();
+ pm.setComponentEnabledSetting(new ComponentName("com.android.settings",
+ "com.android.settings.widget.SettingsAppWidgetProvider"),
+ PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
+
+ }
+ },
+ new Test("Disable settings widget") {
+ public void run() {
+ PackageManager pm = getPackageManager();
+ pm.setComponentEnabledSetting(new ComponentName("com.android.settings",
+ "com.android.settings.widget.SettingsAppWidgetProvider"),
+ PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
+
+ }
+ },
new Test("Enable proximity") {
public void run() {
mProx.acquire();
diff --git a/tools/layoutlib/bridge/src/android/graphics/BitmapFactory.java b/tools/layoutlib/bridge/src/android/graphics/BitmapFactory.java
index c57aef6..096498b 100644
--- a/tools/layoutlib/bridge/src/android/graphics/BitmapFactory.java
+++ b/tools/layoutlib/bridge/src/android/graphics/BitmapFactory.java
@@ -351,7 +351,8 @@
If the exception happened on open, bm will be null.
If it happened on close, bm is still valid.
*/
- Bridge.getLog().error(null, e);
+ Bridge.getLog().error(null,
+ String.format("Error decoding bitmap of id 0x%x", id), e);
} finally {
try {
if (is != null) is.close();
diff --git a/tools/layoutlib/bridge/src/android/graphics/Canvas_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Canvas_Delegate.java
index def0f02..26b43cd 100644
--- a/tools/layoutlib/bridge/src/android/graphics/Canvas_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Canvas_Delegate.java
@@ -20,6 +20,7 @@
import com.android.layoutlib.bridge.impl.DelegateManager;
import com.android.layoutlib.bridge.impl.GcSnapshot;
+import android.graphics.Bitmap.Config;
import android.graphics.Paint_Delegate.FontInfo;
import android.text.TextUtils;
@@ -98,8 +99,13 @@
// ---- native methods ----
/*package*/ static boolean isOpaque(Canvas thisCanvas) {
- // FIXME
- throw new UnsupportedOperationException();
+ // get the delegate from the native int.
+ Canvas_Delegate canvasDelegate = sManager.getDelegate(thisCanvas.mNativeCanvas);
+ if (canvasDelegate == null) {
+ return false;
+ }
+
+ return canvasDelegate.mBitmap.getConfig() == Config.RGB_565;
}
/*package*/ static int getWidth(Canvas thisCanvas) {
@@ -418,7 +424,7 @@
assert false;
Bridge.getLog().fidelityWarning(null,
"android.graphics.Canvas#setMatrix(android.graphics.Matrix) only " +
- "supports affine transformations in the Layout Preview.", null);
+ "supports affine transformations.", null);
}
}
@@ -499,19 +505,31 @@
}
Rectangle rect = canvasDelegate.getSnapshot().getClip().getBounds();
- if (rect != null) {
+ if (rect != null && rect.isEmpty() == false) {
bounds.left = rect.x;
bounds.top = rect.y;
bounds.right = rect.x + rect.width;
bounds.bottom = rect.y + rect.height;
return true;
}
+
return false;
}
/*package*/ static void native_getCTM(int canvas, int matrix) {
- // FIXME
- throw new UnsupportedOperationException();
+ // get the delegate from the native int.
+ Canvas_Delegate canvasDelegate = sManager.getDelegate(canvas);
+ if (canvasDelegate == null) {
+ return;
+ }
+
+ Matrix_Delegate matrixDelegate = Matrix_Delegate.getDelegate(matrix);
+ if (matrixDelegate == null) {
+ return;
+ }
+
+ AffineTransform transform = canvasDelegate.getSnapshot().getTransform();
+ matrixDelegate.set(Matrix_Delegate.makeValues(transform));
}
/*package*/ static boolean native_quickReject(int nativeCanvas,
diff --git a/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java
index 94beef3..c1f34dc 100644
--- a/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Matrix_Delegate.java
@@ -17,6 +17,7 @@
package android.graphics;
+import com.android.layoutlib.bridge.Bridge;
import com.android.layoutlib.bridge.impl.DelegateManager;
import android.graphics.Matrix.ScaleToFit;
@@ -83,6 +84,14 @@
}
/**
+ * Sets the content of the matrix with the content of another matrix represented as an array
+ * of values.
+ */
+ public void set(float[] values) {
+ System.arraycopy(values, 0, mValues, 0, MATRIX_SIZE);
+ }
+
+ /**
* Resets the matrix to be the identity matrix.
*/
public void reset() {
@@ -104,7 +113,7 @@
return true;
}
- public static Matrix_Delegate make(AffineTransform matrix) {
+ public static float[] makeValues(AffineTransform matrix) {
float[] values = new float[MATRIX_SIZE];
values[0] = (float) matrix.getScaleX();
values[1] = (float) matrix.getShearX();
@@ -116,7 +125,11 @@
values[7] = 0.f;
values[8] = 1.f;
- return new Matrix_Delegate(values);
+ return values;
+ }
+
+ public static Matrix_Delegate make(AffineTransform matrix) {
+ return new Matrix_Delegate(makeValues(matrix));
}
public boolean mapRect(RectF dst, RectF src) {
@@ -599,7 +612,10 @@
/*package*/ static boolean native_setPolyToPoly(int native_object, float[] src, int srcIndex,
float[] dst, int dstIndex, int pointCount) {
// FIXME
- throw new UnsupportedOperationException("Native delegate needed: Matrix_Delegate.native_setPolyToPoly");
+ Bridge.getLog().fidelityWarning(null,
+ "Matrix.setPolyToPoly is not supported.",
+ null);
+ return false;
}
/*package*/ static boolean native_invert(int native_object, int inverse) {
@@ -639,9 +655,7 @@
if (isPts) {
d.mapPoints(dst, dstIndex, src, srcIndex, ptCount);
} else {
- // src is vectors
- // FIXME
- throw new UnsupportedOperationException("Native delegate needed: Matrix_Delegate.native_mapPoints");
+ d.mapVectors(dst, dstIndex, src, srcIndex, ptCount);
}
}
@@ -655,8 +669,18 @@
}
/*package*/ static float native_mapRadius(int native_object, float radius) {
- // FIXME
- throw new UnsupportedOperationException("Native delegate needed: Matrix_Delegate.native_mapRadius");
+ Matrix_Delegate d = sManager.getDelegate(native_object);
+ if (d == null) {
+ return 0.f;
+ }
+
+ float[] src = new float[] { radius, 0.f, 0.f, radius };
+ d.mapVectors(src, 0, src, 0, 2);
+
+ float l1 = getPointLength(src, 0);
+ float l2 = getPointLength(src, 2);
+
+ return (float) Math.sqrt(l1 * l2);
}
/*package*/ static void native_getValues(int native_object, float[] values) {
@@ -842,15 +866,15 @@
private void mapPoints(float[] dst, int dstIndex, float[] src, int srcIndex,
int pointCount) {
- //checkPointArrays(src, srcIndex, dst, dstIndex, pointCount);
+ final int count = pointCount * 2;
float[] tmpDest = dst;
boolean inPlace = dst == src;
if (inPlace) {
- tmpDest = new float[dstIndex + pointCount * 2];
+ tmpDest = new float[dstIndex + count];
}
- for (int i = 0 ; i < pointCount * 2 ; i += 2) {
+ for (int i = 0 ; i < count ; i += 2) {
// just in case we are doing in place, we better put this in temp vars
float x = mValues[0] * src[i + srcIndex] +
mValues[1] * src[i + srcIndex + 1] +
@@ -864,7 +888,7 @@
}
if (inPlace) {
- System.arraycopy(tmpDest, dstIndex, dst, dstIndex, pointCount * 2);
+ System.arraycopy(tmpDest, dstIndex, dst, dstIndex, count);
}
}
@@ -879,6 +903,37 @@
mapPoints(pts, 0, pts, 0, pts.length >> 1);
}
+ private void mapVectors(float[] dst, int dstIndex, float[] src, int srcIndex, int ptCount) {
+ if (hasPerspective()) {
+ // transform the (0,0) point
+ float[] origin = new float[] { 0.f, 0.f};
+ mapPoints(origin);
+
+ // translate the vector data as points
+ mapPoints(dst, dstIndex, src, srcIndex, ptCount);
+
+ // then substract the transformed origin.
+ final int count = ptCount * 2;
+ for (int i = 0 ; i < count ; i += 2) {
+ dst[dstIndex + i] = dst[dstIndex + i] - origin[0];
+ dst[dstIndex + i + 1] = dst[dstIndex + i + 1] - origin[1];
+ }
+ } else {
+ // make a copy of the matrix
+ Matrix_Delegate copy = new Matrix_Delegate(mValues);
+
+ // remove the translation
+ setTranslate(copy.mValues, 0, 0);
+
+ // map the content as points.
+ copy.mapPoints(dst, dstIndex, src, srcIndex, ptCount);
+ }
+ }
+
+ private static float getPointLength(float[] src, int index) {
+ return (float) Math.sqrt(src[index] * src[index] + src[index + 1] * src[index + 1]);
+ }
+
/**
* multiply two matrices and store them in a 3rd.
* <p/>This in effect does dest = a*b
diff --git a/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java
index e9fb30a..5524f4f 100644
--- a/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/NinePatch_Delegate.java
@@ -73,7 +73,7 @@
oos = new ObjectOutputStream(baos);
oos.writeObject(chunk);
} catch (IOException e) {
- Bridge.getLog().error("Failed to serialize NinePatchChunk.", e);
+ Bridge.getLog().error(null, "Failed to serialize NinePatchChunk.", e);
return null;
} finally {
if (oos != null) {
@@ -196,10 +196,10 @@
sChunkCache.put(array, new SoftReference<NinePatchChunk>(chunk));
}
} catch (IOException e) {
- Bridge.getLog().error("Failed to deserialize NinePatchChunk content.", e);
+ Bridge.getLog().error(null, "Failed to deserialize NinePatchChunk content.", e);
return null;
} catch (ClassNotFoundException e) {
- Bridge.getLog().error("Failed to deserialize NinePatchChunk class.", e);
+ Bridge.getLog().error(null, "Failed to deserialize NinePatchChunk class.", e);
return null;
} finally {
if (ois != null) {
diff --git a/tools/layoutlib/bridge/src/android/graphics/Paint_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Paint_Delegate.java
index 9d4970f..43cf91a 100644
--- a/tools/layoutlib/bridge/src/android/graphics/Paint_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Paint_Delegate.java
@@ -375,7 +375,7 @@
/*package*/ static void nSetShadowLayer(Paint thisPaint, float radius, float dx, float dy,
int color) {
// FIXME
- throw new UnsupportedOperationException();
+ Bridge.getLog().fidelityWarning(null, "Paint.setShadowLayer is not supported.", null);
}
/*package*/ static float getTextSize(Paint thisPaint) {
diff --git a/tools/layoutlib/bridge/src/android/graphics/Path_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Path_Delegate.java
index 66ab29c..8a50b34 100644
--- a/tools/layoutlib/bridge/src/android/graphics/Path_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Path_Delegate.java
@@ -237,8 +237,7 @@
pathDelegate.quadTo(x1, y1, x2, y2);
}
- /*package*/ static void native_rQuadTo(int nPath, float dx1, float dy1,
- float dx2, float dy2) {
+ /*package*/ static void native_rQuadTo(int nPath, float dx1, float dy1, float dx2, float dy2) {
Path_Delegate pathDelegate = sManager.getDelegate(nPath);
if (pathDelegate == null) {
return;
@@ -248,7 +247,7 @@
}
/*package*/ static void native_cubicTo(int nPath, float x1, float y1,
- float x2, float y2, float x3, float y3) {
+ float x2, float y2, float x3, float y3) {
Path_Delegate pathDelegate = sManager.getDelegate(nPath);
if (pathDelegate == null) {
return;
@@ -258,7 +257,7 @@
}
/*package*/ static void native_rCubicTo(int nPath, float x1, float y1,
- float x2, float y2, float x3, float y3) {
+ float x2, float y2, float x3, float y3) {
Path_Delegate pathDelegate = sManager.getDelegate(nPath);
if (pathDelegate == null) {
return;
@@ -295,8 +294,8 @@
pathDelegate.addRect(rect.left, rect.top, rect.right, rect.bottom, dir);
}
- /*package*/ static void native_addRect(int nPath, float left, float top,
- float right, float bottom, int dir) {
+ /*package*/ static void native_addRect(int nPath,
+ float left, float top, float right, float bottom, int dir) {
Path_Delegate pathDelegate = sManager.getDelegate(nPath);
if (pathDelegate == null) {
return;
@@ -310,39 +309,35 @@
throw new UnsupportedOperationException();
}
- /*package*/ static void native_addCircle(int nPath, float x, float y,
- float radius, int dir) {
+ /*package*/ static void native_addCircle(int nPath, float x, float y, float radius, int dir) {
// FIXME
throw new UnsupportedOperationException();
}
/*package*/ static void native_addArc(int nPath, RectF oval,
- float startAngle, float sweepAngle) {
+ float startAngle, float sweepAngle) {
// FIXME
throw new UnsupportedOperationException();
}
/*package*/ static void native_addRoundRect(int nPath, RectF rect,
- float rx, float ry, int dir) {
+ float rx, float ry, int dir) {
// FIXME
throw new UnsupportedOperationException();
}
- /*package*/ static void native_addRoundRect(int nPath, RectF r,
- float[] radii, int dir) {
+ /*package*/ static void native_addRoundRect(int nPath, RectF r, float[] radii, int dir) {
// FIXME
throw new UnsupportedOperationException();
}
- /*package*/ static void native_addPath(int nPath, int src, float dx,
- float dy) {
+ /*package*/ static void native_addPath(int nPath, int src, float dx, float dy) {
// FIXME
throw new UnsupportedOperationException();
}
/*package*/ static void native_addPath(int nPath, int src) {
- // FIXME
- throw new UnsupportedOperationException();
+ native_addPath(nPath, src, 0, 0);
}
/*package*/ static void native_addPath(int nPath, int src, int matrix) {
@@ -350,8 +345,7 @@
throw new UnsupportedOperationException();
}
- /*package*/ static void native_offset(int nPath, float dx, float dy,
- int dst_path) {
+ /*package*/ static void native_offset(int nPath, float dx, float dy, int dst_path) {
Path_Delegate pathDelegate = sManager.getDelegate(nPath);
if (pathDelegate == null) {
return;
@@ -703,7 +697,7 @@
assert false;
Bridge.getLog().fidelityWarning(null,
"android.graphics.Path#transform() only " +
- "supports affine transformations in the Layout Preview.", null);
+ "supports affine transformations.", null);
}
GeneralPath newPath = new GeneralPath();
diff --git a/tools/layoutlib/bridge/src/android/graphics/Region_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Region_Delegate.java
index 684bb90..33c2aed 100644
--- a/tools/layoutlib/bridge/src/android/graphics/Region_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Region_Delegate.java
@@ -69,39 +69,64 @@
*
* If the Op is not one that combines two shapes, then this return null
*
- * @param shape1 the firt shape to combine
+ * @param shape1 the firt shape to combine which can be null if there's no original clip.
* @param shape2 the 2nd shape to combine
* @param regionOp the operande for the combine
* @return a new area or null.
*/
public static Area combineShapes(Shape shape1, Shape shape2, int regionOp) {
if (regionOp == Region.Op.DIFFERENCE.nativeInt) {
+ // if shape1 is null (empty), then the result is null.
+ if (shape1 == null) {
+ return null;
+ }
+
// result is always a new area.
Area result = new Area(shape1);
result.subtract(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
return result;
} else if (regionOp == Region.Op.INTERSECT.nativeInt) {
+ // if shape1 is null, then the result is simply shape2.
+ if (shape1 == null) {
+ return new Area(shape2);
+ }
+
// result is always a new area.
Area result = new Area(shape1);
result.intersect(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
return result;
} else if (regionOp == Region.Op.UNION.nativeInt) {
+ // if shape1 is null, then the result is simply shape2.
+ if (shape1 == null) {
+ return new Area(shape2);
+ }
+
// result is always a new area.
Area result = new Area(shape1);
result.add(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
return result;
} else if (regionOp == Region.Op.XOR.nativeInt) {
+ // if shape1 is null, then the result is simply shape2
+ if (shape1 == null) {
+ return new Area(shape2);
+ }
+
// result is always a new area.
Area result = new Area(shape1);
result.exclusiveOr(shape2 instanceof Area ? (Area) shape2 : new Area(shape2));
+ return result;
} else if (regionOp == Region.Op.REVERSE_DIFFERENCE.nativeInt) {
// result is always a new area.
Area result = new Area(shape2);
- result.subtract(shape1 instanceof Area ? (Area) shape1 : new Area(shape1));
+
+ if (shape1 != null) {
+ result.subtract(shape1 instanceof Area ? (Area) shape1 : new Area(shape1));
+ }
+
return result;
}
@@ -110,6 +135,123 @@
// ---- native methods ----
+ /*package*/ static boolean isEmpty(Region thisRegion) {
+ Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+ if (regionDelegate == null) {
+ return true;
+ }
+
+ return regionDelegate.mArea.isEmpty();
+ }
+
+ /*package*/ static boolean isRect(Region thisRegion) {
+ Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+ if (regionDelegate == null) {
+ return true;
+ }
+
+ return regionDelegate.mArea.isRectangular();
+ }
+
+ /*package*/ static boolean isComplex(Region thisRegion) {
+ Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+ if (regionDelegate == null) {
+ return true;
+ }
+
+ return regionDelegate.mArea.isSingular() == false;
+ }
+
+ /*package*/ static boolean contains(Region thisRegion, int x, int y) {
+ Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+ if (regionDelegate == null) {
+ return false;
+ }
+
+ return regionDelegate.mArea.contains(x, y);
+ }
+
+ /*package*/ static boolean quickContains(Region thisRegion,
+ int left, int top, int right, int bottom) {
+ Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+ if (regionDelegate == null) {
+ return false;
+ }
+
+ return regionDelegate.mArea.isRectangular() &&
+ regionDelegate.mArea.contains(left, top, right - left, bottom - top);
+ }
+
+ /*package*/ static boolean quickReject(Region thisRegion,
+ int left, int top, int right, int bottom) {
+ Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+ if (regionDelegate == null) {
+ return false;
+ }
+
+ return regionDelegate.mArea.isEmpty() ||
+ regionDelegate.mArea.intersects(left, top, right - left, bottom - top) == false;
+ }
+
+ /*package*/ static boolean quickReject(Region thisRegion, Region rgn) {
+ Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+ if (regionDelegate == null) {
+ return false;
+ }
+
+ Region_Delegate targetRegionDelegate = sManager.getDelegate(rgn.mNativeRegion);
+ if (targetRegionDelegate == null) {
+ return false;
+ }
+
+ return regionDelegate.mArea.isEmpty() ||
+ regionDelegate.mArea.getBounds().intersects(
+ targetRegionDelegate.mArea.getBounds()) == false;
+
+ }
+
+ /*package*/ static void translate(Region thisRegion, int dx, int dy, Region dst) {
+ Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+ if (regionDelegate == null) {
+ return;
+ }
+
+ Region_Delegate targetRegionDelegate = sManager.getDelegate(dst.mNativeRegion);
+ if (targetRegionDelegate == null) {
+ return;
+ }
+
+ if (regionDelegate.mArea.isEmpty()) {
+ targetRegionDelegate.mArea = new Area();
+ } else {
+ targetRegionDelegate.mArea = new Area(regionDelegate.mArea);
+ AffineTransform mtx = new AffineTransform();
+ mtx.translate(dx, dy);
+ targetRegionDelegate.mArea.transform(mtx);
+ }
+ }
+
+ /*package*/ static void scale(Region thisRegion, float scale, Region dst) {
+ Region_Delegate regionDelegate = sManager.getDelegate(thisRegion.mNativeRegion);
+ if (regionDelegate == null) {
+ return;
+ }
+
+ Region_Delegate targetRegionDelegate = sManager.getDelegate(dst.mNativeRegion);
+ if (targetRegionDelegate == null) {
+ return;
+ }
+
+ if (regionDelegate.mArea.isEmpty()) {
+ targetRegionDelegate.mArea = new Area();
+ } else {
+ targetRegionDelegate.mArea = new Area(regionDelegate.mArea);
+ AffineTransform mtx = new AffineTransform();
+ mtx.scale(scale, scale);
+ targetRegionDelegate.mArea.transform(mtx);
+ }
+ }
+
/*package*/ static int nativeConstructor() {
Region_Delegate newDelegate = new Region_Delegate();
return sManager.addDelegate(newDelegate);
diff --git a/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java b/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java
index c7362c0..11e1ca7 100644
--- a/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java
+++ b/tools/layoutlib/bridge/src/android/graphics/Typeface_Delegate.java
@@ -16,6 +16,7 @@
package android.graphics;
+import com.android.layoutlib.bridge.Bridge;
import com.android.layoutlib.bridge.impl.DelegateManager;
import com.android.layoutlib.bridge.impl.FontLoader;
@@ -84,7 +85,6 @@
return delegate.mFonts;
}
-
// ---- native methods ----
/*package*/ static synchronized int nativeCreate(String familyName, int style) {
@@ -125,13 +125,13 @@
}
/*package*/ static synchronized int nativeCreateFromAsset(AssetManager mgr, String path) {
- // FIXME
- throw new UnsupportedOperationException("Native delegate needed: Typeface_Delegate.nativeCreateFromAsset");
+ Bridge.getLog().fidelityWarning(null, "Typeface.createFromAsset() is not supported.", null);
+ return 0;
}
/*package*/ static synchronized int nativeCreateFromFile(String path) {
- // FIXME
- throw new UnsupportedOperationException("Native delegate needed: Typeface_Delegate.nativeCreateFromFile");
+ Bridge.getLog().fidelityWarning(null, "Typeface.createFromFile() is not supported.", null);
+ return 0;
}
/*package*/ static void nativeUnref(int native_instance) {
diff --git a/tools/layoutlib/bridge/src/com/android/internal/util/XmlUtils_Delegate.java b/tools/layoutlib/bridge/src/com/android/internal/util/XmlUtils_Delegate.java
new file mode 100644
index 0000000..7fa1679
--- /dev/null
+++ b/tools/layoutlib/bridge/src/com/android/internal/util/XmlUtils_Delegate.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2011 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.internal.util;
+
+
+/**
+ * Delegate used to provide new implementation of a select few methods of {@link XmlUtils}
+ *
+ * Through the layoutlib_create tool, the original methods of XmlUtils have been replaced
+ * by calls to methods of the same name in this delegate class.
+ *
+ */
+public class XmlUtils_Delegate {
+ /*package*/ static final int convertValueToInt(CharSequence charSeq, int defaultValue) {
+ if (null == charSeq)
+ return defaultValue;
+
+ String nm = charSeq.toString();
+
+ // This code is copied from the original implementation. The issue is that
+ // The Dalvik libraries are able to handle Integer.parse("XXXXXXXX", 16) where XXXXXXX
+ // is > 80000000 but the Java VM cannot.
+
+ int sign = 1;
+ int index = 0;
+ int len = nm.length();
+ int base = 10;
+
+ if ('-' == nm.charAt(0)) {
+ sign = -1;
+ index++;
+ }
+
+ if ('0' == nm.charAt(index)) {
+ // Quick check for a zero by itself
+ if (index == (len - 1))
+ return 0;
+
+ char c = nm.charAt(index + 1);
+
+ if ('x' == c || 'X' == c) {
+ index += 2;
+ base = 16;
+ } else {
+ index++;
+ base = 8;
+ }
+ }
+ else if ('#' == nm.charAt(index)) {
+ index++;
+ base = 16;
+ }
+
+ return ((int)Long.parseLong(nm.substring(index), base)) * sign;
+ }
+}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
index a717375..7713f4b 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/Bridge.java
@@ -32,6 +32,7 @@
import com.android.tools.layoutlib.create.OverrideMethod;
import android.graphics.Bitmap;
+import android.graphics.Typeface;
import android.graphics.Typeface_Delegate;
import android.os.Looper;
@@ -141,16 +142,6 @@
}
@Override
- public void error(String tag, Throwable t) {
- String message = t.getMessage();
- if (message == null) {
- message = t.getClass().getName();
- }
-
- System.err.println(message);
- }
-
- @Override
public void error(String tag, String message, Throwable throwable) {
System.err.println(message);
}
@@ -194,7 +185,8 @@
Capability.RENDER,
Capability.EMBEDDED_LAYOUT,
Capability.VIEW_MANIPULATION,
- Capability.ANIMATE);
+ Capability.PLAY_ANIMATION,
+ Capability.ANIMATED_VIEW_MANIPULATION);
BridgeAssetManager.initSystem();
@@ -283,6 +275,10 @@
@Override
public boolean dispose() {
BridgeAssetManager.clearSystem();
+
+ // dispose of the default typeface.
+ Typeface.sDefaults = null;
+
return true;
}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java
index 791e53b..194687e 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/BridgeConstants.java
@@ -48,6 +48,7 @@
public final static String PREFIX_ANDROID = "android:";
+ public final static String RES_ANIMATOR = "animator";
public final static String RES_STYLE = "style";
public final static String RES_ATTR = "attr";
public final static String RES_DIMEN = "dimen";
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
index 7269227..fb79473 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeContext.java
@@ -92,7 +92,7 @@
// cache for TypedArray generated from IStyleResourceValue object
private Map<int[], Map<Integer, TypedArray>> mTypedArrayCache;
- private BridgeInflater mInflater;
+ private BridgeInflater mBridgeInflater;
private final IProjectCallback mProjectCallback;
private BridgeContentResolver mContentResolver;
@@ -160,7 +160,7 @@
}
public void setBridgeInflater(BridgeInflater inflater) {
- mInflater = inflater;
+ mBridgeInflater = inflater;
}
public void addViewKey(View view, Object viewKey) {
@@ -221,7 +221,7 @@
@Override
public LayoutInflater getLayoutInflater() {
- return mInflater;
+ return mBridgeInflater;
}
// ------------ Context methods
@@ -244,7 +244,7 @@
@Override
public Object getSystemService(String service) {
if (LAYOUT_INFLATER_SERVICE.equals(service)) {
- return mInflater;
+ return mBridgeInflater;
}
// AutoCompleteTextView and MultiAutoCompleteTextView want a window
@@ -493,12 +493,12 @@
/**
* Resolves the value of a resource, if the value references a theme or resource value.
* <p/>
- * This method ensures that it returns a {@link IResourceValue} object that does not
+ * This method ensures that it returns a {@link ResourceValue} object that does not
* reference another resource.
* If the resource cannot be resolved, it returns <code>null</code>.
* <p/>
* If a value that does not need to be resolved is given, the method will return a new
- * instance of IResourceValue that contains the input value.
+ * instance of {@link ResourceValue} that contains the input value.
*
* @param type the type of the resource
* @param name the name of the attribute containing this value.
@@ -510,11 +510,11 @@
return null;
}
- // get the IResourceValue referenced by this value
+ // get the ResourceValue referenced by this value
ResourceValue resValue = findResValue(value, false /*forceFrameworkOnly*/);
// if resValue is null, but value is not null, this means it was not a reference.
- // we return the name/value wrapper in a IResourceValue. the isFramework flag doesn't
+ // we return the name/value wrapper in a ResourceValue. the isFramework flag doesn't
// matter.
if (resValue == null) {
return new ResourceValue(type, name, value, false /*isFramework*/);
@@ -525,9 +525,9 @@
}
/**
- * Returns the {@link IResourceValue} referenced by the value of <var>value</var>.
+ * Returns the {@link ResourceValue} referenced by the value of <var>value</var>.
* <p/>
- * This method ensures that it returns a {@link IResourceValue} object that does not
+ * This method ensures that it returns a {@link ResourceValue} object that does not
* reference another resource.
* If the resource cannot be resolved, it returns <code>null</code>.
* <p/>
@@ -535,7 +535,7 @@
* value.
*
* @param value the value containing the reference to resolve.
- * @return a {@link IResourceValue} object or <code>null</code>
+ * @return a {@link ResourceValue} object or <code>null</code>
*/
public ResourceValue resolveResValue(ResourceValue value) {
if (value == null) {
@@ -547,7 +547,7 @@
return value;
}
- // else attempt to find another IResourceValue referenced by this one.
+ // else attempt to find another ResourceValue referenced by this one.
ResourceValue resolvedValue = findResValue(value.getValue(), value.isFramework());
// if the value did not reference anything, then we simply return the input value
@@ -560,7 +560,7 @@
}
/**
- * Searches for, and returns a {@link IResourceValue} by its reference.
+ * Searches for, and returns a {@link ResourceValue} by its reference.
* <p/>
* The reference format can be:
* <pre>@resType/resName</pre>
@@ -577,7 +577,7 @@
* @param reference the resource reference to search for.
* @param forceFrameworkOnly if true all references are considered to be toward framework
* resource even if the reference does not include the android: prefix.
- * @return a {@link IResourceValue} or <code>null</code>.
+ * @return a {@link ResourceValue} or <code>null</code>.
*/
ResourceValue findResValue(String reference, boolean forceFrameworkOnly) {
if (reference == null) {
@@ -591,7 +591,7 @@
boolean frameworkOnly = false;
- // eleminate the prefix from the string
+ // eliminate the prefix from the string
if (reference.startsWith(BridgeConstants.PREFIX_ANDROID_THEME_REF)) {
frameworkOnly = true;
reference = reference.substring(BridgeConstants.PREFIX_ANDROID_THEME_REF.length());
@@ -670,14 +670,14 @@
}
/**
- * Searches for, and returns a {@link IResourceValue} by its name, and type.
+ * Searches for, and returns a {@link ResourceValue} by its name, and type.
* @param resType the type of the resource
* @param resName the name of the resource
* @param frameworkOnly if <code>true</code>, the method does not search in the
* project resources
*/
private ResourceValue findResValue(String resType, String resName, boolean frameworkOnly) {
- // map of IResouceValue for the given type
+ // map of ResouceValue for the given type
Map<String, ResourceValue> typeMap;
// if allowed, search in the project resources first.
@@ -701,6 +701,13 @@
}
// didn't find the resource anywhere.
+ // This is normal if the resource is an ID that is generated automatically.
+ // For other resources, we output a warning
+ if ("+id".equals(resType) == false && "+android:id".equals(resType) == false) { //$NON-NLS-1$ //$NON-NLS-2$
+ Bridge.getLog().warning("resources", //$NON-NLS-1$
+ "Couldn't resolve resource @" +
+ (frameworkOnly ? "android:" : "") + resType + "/" + resName);
+ }
return null;
}
@@ -739,11 +746,11 @@
}
/**
- * Returns the {@link IResourceValue} matching a given name in a given style. If the
+ * Returns the {@link ResourceValue} matching a given name in a given style. If the
* item is not directly available in the style, the method looks in its parent style.
* @param style the style to search in
* @param itemName the name of the item to search for.
- * @return the {@link IResourceValue} object or <code>null</code>
+ * @return the {@link ResourceValue} object or <code>null</code>
*/
public ResourceValue findItemInStyle(StyleResourceValue style, String itemName) {
ResourceValue item = style.findValue(itemName);
@@ -871,8 +878,8 @@
return null;
}
- int getFrameworkIdValue(String idName, int defValue) {
- Integer value = Bridge.getResourceValue(BridgeConstants.RES_ID, idName);
+ int getFrameworkResourceValue(String resType, String resName, int defValue) {
+ Integer value = Bridge.getResourceValue(resType, resName);
if (value != null) {
return value.intValue();
}
@@ -880,9 +887,9 @@
return defValue;
}
- int getProjectIdValue(String idName, int defValue) {
+ int getProjectResourceValue(String resType, String resName, int defValue) {
if (mProjectCallback != null) {
- Integer value = mProjectCallback.getResourceValue(BridgeConstants.RES_ID, idName);
+ Integer value = mProjectCallback.getResourceValue(resType, resName);
if (value != null) {
return value.intValue();
}
@@ -1303,4 +1310,15 @@
public Context getApplicationContext() {
throw new UnsupportedOperationException();
}
+
+ @Override
+ public void startActivities(Intent[] arg0) {
+ // TODO Auto-generated method stub
+
+ }
+
+ @Override
+ public boolean isRestricted() {
+ return false;
+ }
}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeInflater.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeInflater.java
index 1b59621..36aa335 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeInflater.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeInflater.java
@@ -178,8 +178,10 @@
return inflate(bridgeParser, root);
} catch (Exception e) {
- Bridge.getLog().error(null, e);
- // return null below.
+ Bridge.getLog().error(null,
+ "Failed to parse file " + f.getAbsolutePath(), e);
+
+ return null;
}
}
}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java
index 2ea5281..a56800c 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeResources.java
@@ -43,7 +43,6 @@
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
-import java.io.IOException;
import java.io.InputStream;
/**
@@ -173,14 +172,13 @@
return ColorStateList.createFromXml(this,
new BridgeXmlBlockParser(parser, mContext, resValue.isFramework()));
- } catch (XmlPullParserException e) {
- Bridge.getLog().error(null, e);
- } catch (FileNotFoundException e) {
- // will not happen, since we pre-check
- } catch (IOException e) {
- Bridge.getLog().error(null, e);
- }
+ } catch (Exception e) {
+ // this is an error and not warning since the file existence is checked before
+ // attempting to parse it.
+ Bridge.getLog().error(null, "Failed to parse file " + value, e);
+ return null;
+ }
} else {
// try to load the color state list from an int
try {
@@ -245,7 +243,8 @@
return new BridgeXmlBlockParser(parser, mContext, mPlatformResourceFlag[0]);
}
} catch (XmlPullParserException e) {
- Bridge.getLog().error(null, e);
+ Bridge.getLog().error(null,
+ "Failed to configure parser for " + value.getValue(), e);
// we'll return null below.
} catch (FileNotFoundException e) {
// this shouldn't happen since we check above.
@@ -279,7 +278,8 @@
return new BridgeXmlBlockParser(parser, mContext, mPlatformResourceFlag[0]);
}
} catch (XmlPullParserException e) {
- Bridge.getLog().error(null, e);
+ Bridge.getLog().error(null,
+ "Failed to configure parser for " + value.getValue(), e);
// we'll return null below.
} catch (FileNotFoundException e) {
// this shouldn't happen since we check above.
@@ -294,7 +294,6 @@
return null;
}
-
@Override
public TypedArray obtainAttributes(AttributeSet set, int[] attrs) {
return mContext.obtainStyledAttributes(set, attrs);
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java
index 6ae7e03..7f11897 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeTypedArray.java
@@ -43,25 +43,25 @@
*/
public final class BridgeTypedArray extends TypedArray {
- private BridgeResources mResources;
+ private BridgeResources mBridgeResources;
private BridgeContext mContext;
- private ResourceValue[] mData;
+ private ResourceValue[] mResourceData;
private String[] mNames;
private final boolean mPlatformFile;
public BridgeTypedArray(BridgeResources resources, BridgeContext context, int len,
boolean platformFile) {
super(null, null, null, 0);
- mResources = resources;
+ mBridgeResources = resources;
mContext = context;
mPlatformFile = platformFile;
- mData = new ResourceValue[len];
+ mResourceData = new ResourceValue[len];
mNames = new String[len];
}
/** A bridge-specific method that sets a value in the type array */
public void bridgeSetValue(int index, String name, ResourceValue value) {
- mData[index] = value;
+ mResourceData[index] = value;
mNames[index] = name;
}
@@ -75,7 +75,7 @@
// fills TypedArray.mIndices which is used to implement getIndexCount/getIndexAt
// first count the array size
int count = 0;
- for (ResourceValue data : mData) {
+ for (ResourceValue data : mResourceData) {
if (data != null) {
count++;
}
@@ -87,8 +87,8 @@
// fill the array with the indices.
int index = 1;
- for (int i = 0 ; i < mData.length ; i++) {
- if (mData[i] != null) {
+ for (int i = 0 ; i < mResourceData.length ; i++) {
+ if (mResourceData[i] != null) {
mIndices[index++] = i;
}
}
@@ -99,7 +99,7 @@
*/
@Override
public int length() {
- return mData.length;
+ return mResourceData.length;
}
/**
@@ -107,7 +107,7 @@
*/
@Override
public Resources getResources() {
- return mResources;
+ return mBridgeResources;
}
/**
@@ -120,9 +120,9 @@
*/
@Override
public CharSequence getText(int index) {
- if (mData[index] != null) {
+ if (mResourceData[index] != null) {
// FIXME: handle styled strings!
- return mData[index].getValue();
+ return mResourceData[index].getValue();
}
return null;
@@ -138,8 +138,8 @@
*/
@Override
public String getString(int index) {
- if (mData[index] != null) {
- return mData[index].getValue();
+ if (mResourceData[index] != null) {
+ return mResourceData[index].getValue();
}
return null;
@@ -155,11 +155,11 @@
*/
@Override
public boolean getBoolean(int index, boolean defValue) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return defValue;
}
- String s = mData[index].getValue();
+ String s = mResourceData[index].getValue();
if (s != null) {
return XmlUtils.convertValueToBoolean(s, defValue);
}
@@ -177,11 +177,11 @@
*/
@Override
public int getInt(int index, int defValue) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return defValue;
}
- String s = mData[index].getValue();
+ String s = mResourceData[index].getValue();
try {
return (s == null) ? defValue : XmlUtils.convertValueToInt(s, defValue);
@@ -225,11 +225,11 @@
*/
@Override
public float getFloat(int index, float defValue) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return defValue;
}
- String s = mData[index].getValue();
+ String s = mResourceData[index].getValue();
if (s != null) {
try {
@@ -259,11 +259,11 @@
*/
@Override
public int getColor(int index, int defValue) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return defValue;
}
- String s = mData[index].getValue();
+ String s = mResourceData[index].getValue();
try {
return ResourceHelper.getColor(s);
} catch (NumberFormatException e) {
@@ -288,11 +288,11 @@
*/
@Override
public ColorStateList getColorStateList(int index) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return null;
}
- String value = mData[index].getValue();
+ String value = mResourceData[index].getValue();
if (value == null) {
return null;
@@ -322,17 +322,18 @@
} catch (Exception e) {
// this is an error and not warning since the file existence is checked before
// attempting to parse it.
- Bridge.getLog().error(null, e);
+ Bridge.getLog().error(null, "Failed to parse file " + value, e);
- // return null below.
+ return null;
}
// looks like were unable to resolve the color value.
- assert false;
Bridge.getLog().warning(null, String.format(
"Unable to resolve color value \"%1$s\" in attribute \"%2$s\"",
value, mNames[index]));
+ assert false;
+
return null;
}
@@ -347,11 +348,11 @@
*/
@Override
public int getInteger(int index, int defValue) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return defValue;
}
- String s = mData[index].getValue();
+ String s = mResourceData[index].getValue();
if (s != null) {
try {
@@ -386,11 +387,11 @@
*/
@Override
public float getDimension(int index, float defValue) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return defValue;
}
- String s = mData[index].getValue();
+ String s = mResourceData[index].getValue();
if (s == null) {
return defValue;
@@ -402,15 +403,16 @@
}
if (ResourceHelper.stringToFloat(s, mValue)) {
- return mValue.getDimension(mResources.mMetrics);
+ return mValue.getDimension(mBridgeResources.mMetrics);
}
// looks like we were unable to resolve the dimension value
- assert false;
Bridge.getLog().warning(null, String.format(
"Unable to resolve dimension value \"%1$s\" in attribute \"%2$s\"",
s, mNames[index]));
+ assert false;
+
return defValue;
}
@@ -456,11 +458,11 @@
*/
@Override
public int getDimensionPixelSize(int index, int defValue) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return defValue;
}
- String s = mData[index].getValue();
+ String s = mResourceData[index].getValue();
if (s == null) {
return defValue;
@@ -522,11 +524,11 @@
*/
@Override
public float getFraction(int index, int base, int pbase, float defValue) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return defValue;
}
- String value = mData[index].getValue();
+ String value = mResourceData[index].getValue();
if (value == null) {
return defValue;
}
@@ -536,11 +538,12 @@
}
// looks like we were unable to resolve the fraction value
- assert false;
Bridge.getLog().warning(null, String.format(
"Unable to resolve fraction value \"%1$s\" in attribute \"%2$s\"",
value, mNames[index]));
+ assert false;
+
return defValue;
}
@@ -560,8 +563,8 @@
*/
@Override
public int getResourceId(int index, int defValue) {
- // get the IResource for this index
- ResourceValue resValue = mData[index];
+ // get the Resource for this index
+ ResourceValue resValue = mResourceData[index];
// no data, return the default value.
if (resValue == null) {
@@ -574,19 +577,21 @@
return mContext.getDynamicIdByStyle((StyleResourceValue)resValue);
}
- // if the attribute was a reference to an id, and not a declaration of an id (@+id), then
- // the xml attribute value was "resolved" which leads us to a IResourceValue with
- // getType() returning "id" and getName() returning the id name
+ // if the attribute was a reference to a resource, and not a declaration of an id (@+id),
+ // then the xml attribute value was "resolved" which leads us to a ResourceValue with a
+ // valid getType() and getName() returning a resource name.
// (and getValue() returning null!). We need to handle this!
- if (resValue.getType() != null && resValue.getType().equals(BridgeConstants.RES_ID)) {
+ if (resValue.getType() != null && resValue.getType().startsWith("@+") == false) {
// if this is a framework id
if (mPlatformFile || resValue.isFramework()) {
// look for idName in the android R classes
- return mContext.getFrameworkIdValue(resValue.getName(), defValue);
+ return mContext.getFrameworkResourceValue(
+ resValue.getType(), resValue.getName(), defValue);
}
// look for idName in the project R class.
- return mContext.getProjectIdValue(resValue.getName(), defValue);
+ return mContext.getProjectResourceValue(
+ resValue.getType(), resValue.getName(), defValue);
}
// else, try to get the value, and resolve it somehow.
@@ -623,11 +628,11 @@
// if this is a framework id
if (mPlatformFile || value.startsWith("@android") || value.startsWith("@+android")) {
// look for idName in the android R classes
- return mContext.getFrameworkIdValue(idName, defValue);
+ return mContext.getFrameworkResourceValue(BridgeConstants.RES_ID, idName, defValue);
}
// look for idName in the project R class.
- return mContext.getProjectIdValue(idName, defValue);
+ return mContext.getProjectResourceValue(BridgeConstants.RES_ID, idName, defValue);
}
// not a direct id valid reference? resolve it
@@ -644,9 +649,11 @@
return idValue.intValue();
}
- assert false;
Bridge.getLog().warning(null, String.format(
"Unable to resolve id \"%1$s\" for attribute \"%2$s\"", value, mNames[index]));
+
+ assert false;
+
return defValue;
}
@@ -662,28 +669,29 @@
*/
@Override
public Drawable getDrawable(int index) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return null;
}
- ResourceValue value = mData[index];
+ ResourceValue value = mResourceData[index];
String stringValue = value.getValue();
if (stringValue == null || BridgeConstants.REFERENCE_NULL.equals(stringValue)) {
return null;
}
- Drawable d = ResourceHelper.getDrawable(value, mContext, mData[index].isFramework());
+ Drawable d = ResourceHelper.getDrawable(value, mContext, mResourceData[index].isFramework());
if (d != null) {
return d;
}
// looks like we were unable to resolve the drawable
- assert false;
Bridge.getLog().warning(null, String.format(
"Unable to resolve drawable \"%1$s\" in attribute \"%2$s\"", stringValue,
mNames[index]));
+ assert false;
+
return null;
}
@@ -700,18 +708,18 @@
*/
@Override
public CharSequence[] getTextArray(int index) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return null;
}
- String value = mData[index].getValue();
+ String value = mResourceData[index].getValue();
if (value != null) {
return new CharSequence[] { value };
}
Bridge.getLog().warning(null, String.format(
String.format("Unknown value for getTextArray(%d) => %s", //DEBUG
- index, mData[index].getName())));
+ index, mResourceData[index].getName())));
return null;
}
@@ -727,11 +735,11 @@
*/
@Override
public boolean getValue(int index, TypedValue outValue) {
- if (mData[index] == null) {
+ if (mResourceData[index] == null) {
return false;
}
- String s = mData[index].getValue();
+ String s = mResourceData[index].getValue();
return ResourceHelper.stringToFloat(s, outValue);
}
@@ -745,7 +753,7 @@
*/
@Override
public boolean hasValue(int index) {
- return mData[index] != null;
+ return mResourceData[index] != null;
}
/**
@@ -792,6 +800,6 @@
@Override
public String toString() {
- return mData.toString();
+ return mResourceData.toString();
}
}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/AnimationThread.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/AnimationThread.java
index 1651d6a..033e065 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/AnimationThread.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/AnimationThread.java
@@ -28,7 +28,7 @@
import android.os.Message;
import android.os.Handler_Delegate.IHandlerCallback;
-import java.util.LinkedList;
+import java.util.PriorityQueue;
import java.util.Queue;
/**
@@ -39,13 +39,13 @@
* <p/>
* Classes should implement {@link #preAnimation()} and {@link #postAnimation()}.
* <p/>
- * If {@link #preAnimation()} does not start an animation something then the thread doesn't do
+ * If {@link #preAnimation()} does not start an animation somehow then the thread doesn't do
* anything.
*
*/
public abstract class AnimationThread extends Thread {
- private static class MessageBundle {
+ private static class MessageBundle implements Comparable<MessageBundle> {
final Handler mTarget;
final Message mMessage;
final long mUptimeMillis;
@@ -55,11 +55,18 @@
mMessage = message;
mUptimeMillis = uptimeMillis;
}
+
+ public int compareTo(MessageBundle bundle) {
+ if (mUptimeMillis < bundle.mUptimeMillis) {
+ return -1;
+ }
+ return 1;
+ }
}
private final RenderSessionImpl mSession;
- Queue<MessageBundle> mQueue = new LinkedList<MessageBundle>();
+ private Queue<MessageBundle> mQueue = new PriorityQueue<MessageBundle>();
private final IAnimationListener mListener;
public AnimationThread(RenderSessionImpl scene, String threadName,
@@ -148,6 +155,13 @@
} while (mListener.isCanceled() == false && mQueue.size() > 0);
mListener.done(Status.SUCCESS.createResult());
+
+ } catch (Throwable throwable) {
+ // can't use Bridge.getLog() as the exception might be thrown outside
+ // of an acquire/release block.
+ mSession.getLog().error(null, "Error playing animation", throwable);
+ mListener.done(Status.ERROR_UNKNOWN.createResult("Error playing animation", throwable));
+
} finally {
postAnimation();
Handler_Delegate.setCallback(null);
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/GcSnapshot.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/GcSnapshot.java
index a2fcb3b..72773c8 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/GcSnapshot.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/GcSnapshot.java
@@ -170,6 +170,29 @@
mBitmap.change();
}
}
+
+ /**
+ * Sets the clip for the graphics2D object associated with the layer.
+ * This should be used over the normal Graphics2D setClip method.
+ *
+ * @param clipShape the shape to use a the clip shape.
+ */
+ void setClip(Shape clipShape) {
+ // because setClip is only guaranteed to work with rectangle shape,
+ // first reset the clip to max and then intersect the current (empty)
+ // clip with the shap.
+ mGraphics.setClip(null);
+ mGraphics.clip(clipShape);
+ }
+
+ /**
+ * Clips the layer with the given shape. This performs an intersect between the current
+ * clip shape and the given shape.
+ * @param shape the new clip shape.
+ */
+ public void clip(Shape shape) {
+ mGraphics.clip(shape);
+ }
}
/**
@@ -287,12 +310,13 @@
AffineTransform currentMtx = baseLayer.getGraphics().getTransform();
layerGraphics.setTransform(currentMtx);
- Shape currentClip = baseLayer.getGraphics().getClip();
- layerGraphics.setClip(currentClip);
-
// create a new layer for this new layer and add it to the list at the end.
mLayers.add(mLocalLayer = new Layer(layerGraphics, layerImage, flags));
+ // set the clip on it.
+ Shape currentClip = baseLayer.getGraphics().getClip();
+ mLocalLayer.setClip(currentClip);
+
// if the drawing is not clipped to the local layer only, we save the current content
// of all other layers. We are only interested in the part that will actually
// be drawn, so we create as small bitmaps as we can.
@@ -369,15 +393,24 @@
*/
public void setBitmap(Bitmap_Delegate bitmap) {
assert mLayers.size() == 0;
+
+ // create a new Layer for the bitmap. This will be the base layer.
Graphics2D graphics2D = bitmap.getImage().createGraphics();
- mLayers.add(new Layer(graphics2D, bitmap));
+ Layer baseLayer = new Layer(graphics2D, bitmap);
+
+ // add it to the list.
+ mLayers.add(baseLayer);
+
+ // if transform and clip where modified before, get the information and give it to the
+ // layer.
+
if (mTransform != null) {
graphics2D.setTransform(mTransform);
mTransform = null;
}
if (mClip != null) {
- graphics2D.setClip(mClip);
+ baseLayer.setClip(mClip);
mClip = null;
}
}
@@ -447,7 +480,20 @@
}
public boolean clip(Shape shape, int regionOp) {
+ // Simple case of intersect with existing layers.
+ // Because Graphics2D#setClip works a bit peculiarly, we optimize
+ // the case of clipping by intersection, as it's supported natively.
+ if (regionOp == Region.Op.INTERSECT.nativeInt && mLayers.size() > 0) {
+ for (Layer layer : mLayers) {
+ layer.clip(shape);
+ }
+
+ Shape currentClip = getClip();
+ return currentClip != null && currentClip.getBounds().isEmpty() == false;
+ }
+
Area area = null;
+
if (regionOp == Region.Op.REPLACE.nativeInt) {
area = new Area(shape);
} else {
@@ -459,11 +505,12 @@
if (mLayers.size() > 0) {
if (area != null) {
for (Layer layer : mLayers) {
- layer.getGraphics().setClip(area);
+ layer.setClip(area);
}
}
- return getClip().getBounds().isEmpty() == false;
+ Shape currentClip = getClip();
+ return currentClip != null && currentClip.getBounds().isEmpty() == false;
} else {
if (area != null) {
mClip = area;
@@ -479,14 +526,14 @@
return clip(new Rectangle2D.Float(left, top, right - left, bottom - top), regionOp);
}
+ /**
+ * Returns the current clip, or null if none have been setup.
+ */
public Shape getClip() {
if (mLayers.size() > 0) {
// they all have the same clip
return mLayers.get(0).getGraphics().getClip();
} else {
- if (mClip == null) {
- mClip = new Area();
- }
return mClip;
}
}
@@ -603,7 +650,7 @@
if ((mFlags & Canvas.CLIP_SAVE_FLAG) == 0) {
Shape clip = getClip();
for (Layer layer : mPrevious.mLayers) {
- layer.getGraphics().setClip(clip);
+ layer.setClip(clip);
}
}
}
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
index 5f86c92d..5d5f2a1 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/RenderSessionImpl.java
@@ -28,6 +28,7 @@
import com.android.ide.common.rendering.api.IAnimationListener;
import com.android.ide.common.rendering.api.ILayoutPullParser;
import com.android.ide.common.rendering.api.IProjectCallback;
+import com.android.ide.common.rendering.api.LayoutLog;
import com.android.ide.common.rendering.api.Params;
import com.android.ide.common.rendering.api.RenderSession;
import com.android.ide.common.rendering.api.ResourceDensity;
@@ -50,6 +51,7 @@
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.LayoutTransition;
+import android.animation.LayoutTransition.TransitionListener;
import android.app.Fragment_Delegate;
import android.graphics.Bitmap;
import android.graphics.Bitmap_Delegate;
@@ -342,6 +344,7 @@
info.mHasWindowFocus = true;
info.mWindowVisibility = View.VISIBLE;
info.mInTouchMode = false; // this is so that we can display selections.
+ info.mHardwareAccelerated = false;
mViewRoot.dispatchAttachedToWindow(info, 0);
// get the background drawable
@@ -362,7 +365,7 @@
}
// log it
- mParams.getLog().error("Scene inflate failed", t);
+ mParams.getLog().error(null, "Scene inflate failed", t);
return ERROR_INFLATION.createResult(t.getMessage(), t);
}
@@ -478,7 +481,7 @@
}
// log it
- mParams.getLog().error("Scene Render failed", t);
+ mParams.getLog().error(null, "Scene Render failed", t);
return ERROR_UNKNOWN.createResult(t.getMessage(), t);
}
@@ -502,14 +505,18 @@
ResourceValue animationResource = null;
int animationId = 0;
if (isFrameworkAnimation) {
- animationResource = mContext.getFrameworkResource("anim", animationName);
+ animationResource = mContext.getFrameworkResource(BridgeConstants.RES_ANIMATOR,
+ animationName);
if (animationResource != null) {
- animationId = Bridge.getResourceValue("anim", animationName);
+ animationId = Bridge.getResourceValue(BridgeConstants.RES_ANIMATOR,
+ animationName);
}
} else {
- animationResource = mContext.getProjectResource("anim", animationName);
+ animationResource = mContext.getProjectResource(BridgeConstants.RES_ANIMATOR,
+ animationName);
if (animationResource != null) {
- animationId = mContext.getProjectCallback().getResourceValue("anim", animationName);
+ animationId = mContext.getProjectCallback().getResourceValue(
+ BridgeConstants.RES_ANIMATOR, animationName);
}
}
@@ -626,8 +633,8 @@
*
* @see LayoutScene#moveChild(Object, Object, int, Map, IAnimationListener)
*/
- public Result moveChild(final ViewGroup parentView, final View childView, final int index,
- Map<String, String> layoutParamsMap, IAnimationListener listener) {
+ public Result moveChild(final ViewGroup newParentView, final View childView, final int index,
+ Map<String, String> layoutParamsMap, final IAnimationListener listener) {
checkLock();
invalidateRenderingSize();
@@ -635,31 +642,88 @@
LayoutParams layoutParams = null;
if (layoutParamsMap != null) {
// need to create a new LayoutParams object for the new parent.
- layoutParams = parentView.generateLayoutParams(
+ layoutParams = newParentView.generateLayoutParams(
new BridgeLayoutParamsMapAttributes(layoutParamsMap));
}
+ // get the current parent of the view that needs to be moved.
+ final ViewGroup previousParent = (ViewGroup) childView.getParent();
+
if (listener != null) {
final LayoutParams params = layoutParams;
- new AnimationThread(this, "moveChild", listener) {
- @Override
- public Result preAnimation() {
- parentView.setLayoutTransition(new LayoutTransition());
- return moveView(parentView, childView, index, params);
- }
+ // there is no support for animating views across layouts, so in case the new and old
+ // parent views are different we fake the animation through a no animation thread.
+ if (previousParent != newParentView) {
+ new Thread("not animated moveChild") {
+ @Override
+ public void run() {
+ Result result = moveView(previousParent, newParentView, childView, index,
+ params);
+ if (result.isSuccess() == false) {
+ listener.done(result);
+ }
- @Override
- public void postAnimation() {
- parentView.setLayoutTransition(null);
- }
- }.start();
+ // ready to do the work, acquire the scene.
+ result = acquire(250);
+ if (result.isSuccess() == false) {
+ listener.done(result);
+ return;
+ }
+
+ try {
+ result = render();
+ if (result.isSuccess()) {
+ listener.onNewFrame(RenderSessionImpl.this.getSession());
+ }
+ } finally {
+ release();
+ }
+
+ listener.done(result);
+ }
+ }.start();
+ } else {
+ new AnimationThread(this, "moveChild", listener) {
+
+ @Override
+ public Result preAnimation() {
+ // set up the transition for the parent.
+ LayoutTransition transition = new LayoutTransition();
+ previousParent.setLayoutTransition(transition);
+
+ // tweak the animation durations and start delays (to match the duration of
+ // animation playing just before).
+ // Note: Cannot user Animation.setDuration() directly. Have to set it
+ // on the LayoutTransition.
+ transition.setDuration(LayoutTransition.DISAPPEARING, 100);
+ // CHANGE_DISAPPEARING plays after DISAPPEARING
+ transition.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 100);
+
+ transition.setDuration(LayoutTransition.CHANGE_DISAPPEARING, 100);
+
+ transition.setDuration(LayoutTransition.CHANGE_APPEARING, 100);
+ // CHANGE_APPEARING plays after CHANGE_APPEARING
+ transition.setStartDelay(LayoutTransition.APPEARING, 100);
+
+ transition.setDuration(LayoutTransition.APPEARING, 100);
+
+ return moveView(previousParent, newParentView, childView, index, params);
+ }
+
+ @Override
+ public void postAnimation() {
+ previousParent.setLayoutTransition(null);
+ newParentView.setLayoutTransition(null);
+ }
+ }.start();
+ }
// always return success since the real status will come through the listener.
return SUCCESS.createResult(layoutParams);
}
- Result result = moveView(parentView, childView, index, layoutParams);
+ Result result = moveView(previousParent, newParentView, childView, index, layoutParams);
if (result.isSuccess() == false) {
return result;
}
@@ -676,8 +740,9 @@
* Moves a View from its current parent to a new given parent at a new given location, with
* an optional new {@link LayoutParams} instance
*
- * @param parent the new parent
- * @param view the view to move
+ * @param previousParent the previous parent, still owning the child at the time of the call.
+ * @param newParent the new parent
+ * @param movedView the view to move
* @param index the new location in the new parent
* @param params an option (can be null) {@link LayoutParams} instance.
*
@@ -685,20 +750,69 @@
* {@link Status#ERROR_VIEWGROUP_NO_CHILDREN} if the given parent doesn't support
* adding views.
*/
- private Result moveView(ViewGroup parent, View view, int index, LayoutParams params) {
+ private Result moveView(ViewGroup previousParent, final ViewGroup newParent,
+ final View movedView, final int index, final LayoutParams params) {
try {
- ViewGroup previousParent = (ViewGroup) view.getParent();
- previousParent.removeView(view);
+ // check if there is a transition on the previousParent.
+ LayoutTransition previousTransition = previousParent.getLayoutTransition();
+ if (previousTransition != null) {
+ // in this case there is an animation. This means we have to wait for the child's
+ // parent reference to be null'ed out so that we can add it to the new parent.
+ // It is technically removed right before the DISAPPEARING animation is done (if
+ // the animation of this type is not null, otherwise it's after which is impossible
+ // to handle).
+ // Because there is no move animation, if the new parent is the same as the old
+ // parent, we need to wait until the CHANGE_DISAPPEARING animation is done before
+ // adding the child or the child will appear in its new location before the
+ // other children have made room for it.
- // add it to the parentView in the correct location
+ // add a listener to the transition to be notified of the actual removal.
+ previousTransition.addTransitionListener(new TransitionListener() {
+ private int mChangeDisappearingCount = 0;
- if (params != null) {
- parent.addView(view, index, params);
+ public void startTransition(LayoutTransition transition, ViewGroup container,
+ View view, int transitionType) {
+ if (transitionType == LayoutTransition.CHANGE_DISAPPEARING) {
+ mChangeDisappearingCount++;
+ }
+ }
+
+ public void endTransition(LayoutTransition transition, ViewGroup container,
+ View view, int transitionType) {
+ if (transitionType == LayoutTransition.CHANGE_DISAPPEARING) {
+ mChangeDisappearingCount--;
+ }
+
+ if (transitionType == LayoutTransition.CHANGE_DISAPPEARING &&
+ mChangeDisappearingCount == 0) {
+ // add it to the parentView in the correct location
+ if (params != null) {
+ newParent.addView(movedView, index, params);
+ } else {
+ newParent.addView(movedView, index);
+ }
+ }
+ }
+ });
+
+ // remove the view from the current parent.
+ previousParent.removeView(movedView);
+
+ // and return since adding the view to the new parent is done in the listener.
+ return SUCCESS.createResult();
} else {
- parent.addView(view, index);
- }
+ // standard code with no animation. pretty simple.
+ previousParent.removeView(movedView);
- return SUCCESS.createResult();
+ // add it to the parentView in the correct location
+ if (params != null) {
+ newParent.addView(movedView, index, params);
+ } else {
+ newParent.addView(movedView, index);
+ }
+
+ return SUCCESS.createResult();
+ }
} catch (UnsupportedOperationException e) {
// looks like this is a view class that doesn't support children manipulation!
return ERROR_VIEWGROUP_NO_CHILDREN.createResult();
@@ -769,6 +883,18 @@
}
/**
+ * Returns the log associated with the session.
+ * @return the log or null if there are none.
+ */
+ public LayoutLog getLog() {
+ if (mParams != null) {
+ return mParams.getLog();
+ }
+
+ return null;
+ }
+
+ /**
* Checks that the lock is owned by the current thread and that the current context is the one
* from this scene.
*
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
index 5427f142..fb52c86 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/impl/ResourceHelper.java
@@ -27,7 +27,6 @@
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
import android.graphics.Bitmap;
import android.graphics.Bitmap_Delegate;
@@ -40,7 +39,6 @@
import android.util.TypedValue;
import java.io.File;
-import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.MalformedURLException;
@@ -162,7 +160,7 @@
// URL is wrong, we'll return null below
} catch (IOException e) {
// failed to read the file, we'll return null below.
- Bridge.getLog().error(null, e);
+ Bridge.getLog().error(null, "Failed lot load " + file.getAbsolutePath(), e);
}
}
@@ -190,13 +188,14 @@
d = Drawable.createFromXml(context.getResources(),
new BridgeXmlBlockParser(parser, context, isFramework));
return d;
- } catch (XmlPullParserException e) {
- Bridge.getLog().error(null, e);
- } catch (FileNotFoundException e) {
- // will not happen, since we pre-check
- } catch (IOException e) {
- Bridge.getLog().error(null, e);
+ } catch (Exception e) {
+ // this is an error and not warning since the file existence is checked before
+ // attempting to parse it.
+ Bridge.getLog().error(null, "Failed to parse file " + value, e);
}
+ } else {
+ Bridge.getLog().error(null,
+ String.format("File %s does not exist (or is not a file)", stringValue));
}
return null;
@@ -222,7 +221,7 @@
return new BitmapDrawable(context.getResources(), bitmap);
} catch (IOException e) {
// we'll return null below
- Bridge.getLog().error(null, e);
+ Bridge.getLog().error(null, "Failed lot load " + bmpFile.getAbsolutePath(), e);
}
} else {
// attempt to get a color from the value
diff --git a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
index 6b589d7..4198006 100644
--- a/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
+++ b/tools/layoutlib/create/src/com/android/tools/layoutlib/create/CreateInfo.java
@@ -97,6 +97,7 @@
"android.app.Fragment#instantiate", //(Landroid/content/Context;Ljava/lang/String;Landroid/os/Bundle;)Landroid/app/Fragment;",
"android.os.Handler#sendMessageAtTime",
"android.view.View#isInEditMode",
+ "com.android.internal.util.XmlUtils#convertValueToInt"
// TODO: comment out once DelegateClass is working
// "android.content.res.Resources$Theme#obtainStyledAttributes",
};
diff --git a/wifi/java/android/net/wifi/SupplicantStateTracker.java b/wifi/java/android/net/wifi/SupplicantStateTracker.java
index 1a00507..f96a5ae 100644
--- a/wifi/java/android/net/wifi/SupplicantStateTracker.java
+++ b/wifi/java/android/net/wifi/SupplicantStateTracker.java
@@ -192,27 +192,16 @@
@Override
public void enter() {
if (DBG) Log.d(TAG, getName() + "\n");
- mWifiStateMachine.setNetworkAvailable(false);
}
- @Override
- public void exit() {
- mWifiStateMachine.setNetworkAvailable(true);
- }
}
class InactiveState extends HierarchicalState {
@Override
public void enter() {
if (DBG) Log.d(TAG, getName() + "\n");
- mWifiStateMachine.setNetworkAvailable(false);
}
- @Override
- public void exit() {
- mWifiStateMachine.setNetworkAvailable(true);
- }
}
-
class DisconnectedState extends HierarchicalState {
@Override
public void enter() {
@@ -336,4 +325,4 @@
if (DBG) Log.d(TAG, getName() + "\n");
}
}
-}
\ No newline at end of file
+}
diff --git a/wifi/java/android/net/wifi/WifiStateMachine.java b/wifi/java/android/net/wifi/WifiStateMachine.java
index f03a9e5..8718117 100644
--- a/wifi/java/android/net/wifi/WifiStateMachine.java
+++ b/wifi/java/android/net/wifi/WifiStateMachine.java
@@ -62,11 +62,7 @@
import android.util.Log;
import android.util.Slog;
import android.app.backup.IBackupManager;
-import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothHeadset;
-import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
@@ -120,6 +116,8 @@
private int mReconnectCount = 0;
private boolean mIsScanMode = false;
+ private boolean mBluetoothConnectionActive = false;
+
/**
* Interval in milliseconds between polling for RSSI
* and linkspeed information
@@ -138,16 +136,6 @@
private int mSupplicantRestartCount = 0;
- /**
- * Instance of the bluetooth headset helper. This needs to be created
- * early because there is a delay before it actually 'connects', as
- * noted by its javadoc. If we check before it is connected, it will be
- * in an error state and we will not disable coexistence.
- */
- private BluetoothHeadset mBluetoothHeadset;
-
- private BluetoothA2dp mBluetoothA2dp;
-
private LinkProperties mLinkProperties;
// Wakelock held during wifi start/stop and driver load/unload
@@ -186,10 +174,6 @@
static final int CMD_UNLOAD_DRIVER_SUCCESS = 5;
/* Indicates driver unload failed */
static final int CMD_UNLOAD_DRIVER_FAILURE = 6;
- /* Set bluetooth headset proxy */
- static final int CMD_SET_BLUETOOTH_HEADSET_PROXY = 7;
- /* Set bluetooth A2dp proxy */
- static final int CMD_SET_BLUETOOTH_A2DP_PROXY = 8;
/* Start the supplicant */
static final int CMD_START_SUPPLICANT = 11;
@@ -209,6 +193,7 @@
/* Stop the soft access point */
static final int CMD_STOP_AP = 22;
+ static final int CMD_BLUETOOTH_ADAPTER_STATE_CHANGE = 23;
/* Supplicant events */
/* Connection to supplicant established */
@@ -277,17 +262,6 @@
* - DTIM wake up settings
*/
static final int CMD_SET_HIGH_PERF_MODE = 77;
- /* Set bluetooth co-existence
- * BLUETOOTH_COEXISTENCE_MODE_ENABLED
- * BLUETOOTH_COEXISTENCE_MODE_DISABLED
- * BLUETOOTH_COEXISTENCE_MODE_SENSE
- */
- static final int CMD_SET_BLUETOOTH_COEXISTENCE = 78;
- /* Enable/disable bluetooth scan mode
- * true(1)
- * false(0)
- */
- static final int CMD_SET_BLUETOOTH_SCAN_MODE = 79;
/* Set the country code */
static final int CMD_SET_COUNTRY_CODE = 80;
/* Request connectivity manager wake lock before driver stop */
@@ -325,10 +299,8 @@
static final int CMD_SET_FREQUENCY_BAND = 90;
/* Commands from/to the SupplicantStateTracker */
- /* Indicates whether a wifi network is available for connection */
- static final int CMD_SET_NETWORK_AVAILABLE = 111;
/* Reset the supplicant state tracker */
- static final int CMD_RESET_SUPPLICANT_STATE = 112;
+ static final int CMD_RESET_SUPPLICANT_STATE = 111;
/* Commands/events reported by WpsStateMachine */
@@ -476,15 +448,7 @@
mInterfaceName = SystemProperties.get("wifi.interface", "tiwlan0");
mSupplicantStateTracker = new SupplicantStateTracker(context, this, getHandler());
mWpsStateMachine = new WpsStateMachine(context, this, getHandler());
-
mLinkProperties = new LinkProperties();
- BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
- if (adapter != null) {
- adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
- BluetoothProfile.A2DP);
- adapter.getProfileProxy(mContext, mBluetoothProfileServiceListener,
- BluetoothProfile.HEADSET);
- }
mNetworkInfo.setIsAvailable(false);
mLinkProperties.clear();
@@ -914,26 +878,10 @@
}
/**
- * Set bluetooth coex mode:
- *
- * @param mode
- * BLUETOOTH_COEXISTENCE_MODE_ENABLED
- * BLUETOOTH_COEXISTENCE_MODE_DISABLED
- * BLUETOOTH_COEXISTENCE_MODE_SENSE
+ * Send a message indicating bluetooth adapter connection state changed
*/
- public void setBluetoothCoexistenceMode(int mode) {
- sendMessage(obtainMessage(CMD_SET_BLUETOOTH_COEXISTENCE, mode, 0));
- }
-
- /**
- * Enable or disable Bluetooth coexistence scan mode. When this mode is on,
- * some of the low-level scan parameters used by the driver are changed to
- * reduce interference with A2DP streaming.
- *
- * @param isBluetoothPlaying whether to enable or disable this mode
- */
- public void setBluetoothScanMode(boolean isBluetoothPlaying) {
- sendMessage(obtainMessage(CMD_SET_BLUETOOTH_SCAN_MODE, isBluetoothPlaying ? 1 : 0, 0));
+ public void sendBluetoothAdapterStateChange(int state) {
+ sendMessage(obtainMessage(CMD_BLUETOOTH_ADAPTER_STATE_CHANGE, state, 0));
}
/**
@@ -1312,54 +1260,6 @@
DEFAULT_MAX_DHCP_RETRIES);
}
- /**
- * Whether to disable coexistence mode while obtaining IP address. We
- * disable coexistence if the headset indicates that there are no
- * connected devices. If we have not got an indication of the service
- * connection yet, we go ahead with disabling coexistence mode.
- *
- * @return Whether to disable coexistence mode.
- */
- private boolean shouldDisableCoexistenceMode() {
- if (mBluetoothHeadset == null) return true;
- List<BluetoothDevice> devices = mBluetoothHeadset.getConnectedDevices();
- return (devices.size() != 0 ? false : true);
- }
-
- private void checkIsBluetoothPlaying() {
- boolean isBluetoothPlaying = false;
- if (mBluetoothA2dp != null) {
- List<BluetoothDevice> connected = mBluetoothA2dp.getConnectedDevices();
-
- for (BluetoothDevice device : connected) {
- if (mBluetoothA2dp.isA2dpPlaying(device)) {
- isBluetoothPlaying = true;
- break;
- }
- }
- }
- setBluetoothScanMode(isBluetoothPlaying);
- }
-
- private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener =
- new BluetoothProfile.ServiceListener() {
- public void onServiceConnected(int profile, BluetoothProfile proxy) {
- if (profile == BluetoothProfile.HEADSET) {
- sendMessage(CMD_SET_BLUETOOTH_HEADSET_PROXY, proxy);
- } else if (profile == BluetoothProfile.A2DP) {
- sendMessage(CMD_SET_BLUETOOTH_A2DP_PROXY, proxy);
- }
- }
-
- public void onServiceDisconnected(int profile) {
- if (profile == BluetoothProfile.HEADSET) {
- sendMessage(CMD_SET_BLUETOOTH_HEADSET_PROXY, null);
- } else if (profile == BluetoothProfile.A2DP) {
- sendMessage(CMD_SET_BLUETOOTH_A2DP_PROXY, null);
- }
- }
- };
-
private void sendScanResultsAvailableBroadcast() {
Intent intent = new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
@@ -1549,10 +1449,6 @@
setWifiEnabled(true);
}
- void setNetworkAvailable(boolean available) {
- sendMessage(obtainMessage(CMD_SET_NETWORK_AVAILABLE, available ? 1 : 0, 0));
- }
-
/********************************************************
* HSM states
*******************************************************/
@@ -1562,11 +1458,9 @@
public boolean processMessage(Message message) {
if (DBG) Log.d(TAG, getName() + message.toString() + "\n");
switch (message.what) {
- case CMD_SET_BLUETOOTH_HEADSET_PROXY:
- mBluetoothHeadset = (BluetoothHeadset) message.obj;
- break;
- case CMD_SET_BLUETOOTH_A2DP_PROXY:
- mBluetoothA2dp = (BluetoothA2dp) message.obj;
+ case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE:
+ mBluetoothConnectionActive = (message.arg1 !=
+ BluetoothAdapter.STATE_DISCONNECTED);
break;
/* Synchronous call returns */
case CMD_PING_SUPPLICANT:
@@ -1580,9 +1474,6 @@
case CMD_ENABLE_RSSI_POLL:
mEnableRssiPolling = (message.arg1 == 1);
break;
- case CMD_SET_NETWORK_AVAILABLE:
- mNetworkInfo.setIsAvailable(message.arg1 == 1);
- break;
/* Discard */
case CMD_LOAD_DRIVER:
case CMD_UNLOAD_DRIVER:
@@ -1610,8 +1501,6 @@
case CMD_SET_SCAN_MODE:
case CMD_SET_SCAN_TYPE:
case CMD_SET_HIGH_PERF_MODE:
- case CMD_SET_BLUETOOTH_COEXISTENCE:
- case CMD_SET_BLUETOOTH_SCAN_MODE:
case CMD_SET_COUNTRY_CODE:
case CMD_SET_FREQUENCY_BAND:
case CMD_REQUEST_CM_WAKELOCK:
@@ -1722,8 +1611,6 @@
case CMD_SET_SCAN_MODE:
case CMD_SET_SCAN_TYPE:
case CMD_SET_HIGH_PERF_MODE:
- case CMD_SET_BLUETOOTH_COEXISTENCE:
- case CMD_SET_BLUETOOTH_SCAN_MODE:
case CMD_SET_COUNTRY_CODE:
case CMD_SET_FREQUENCY_BAND:
case CMD_START_PACKET_FILTERING:
@@ -1850,8 +1737,6 @@
case CMD_SET_SCAN_MODE:
case CMD_SET_SCAN_TYPE:
case CMD_SET_HIGH_PERF_MODE:
- case CMD_SET_BLUETOOTH_COEXISTENCE:
- case CMD_SET_BLUETOOTH_SCAN_MODE:
case CMD_SET_COUNTRY_CODE:
case CMD_SET_FREQUENCY_BAND:
case CMD_START_PACKET_FILTERING:
@@ -1930,8 +1815,6 @@
//TODO: initialize and fix multicast filtering
//mWM.initializeMulticastFiltering();
- checkIsBluetoothPlaying();
-
sendSupplicantConnectionChangedBroadcast(true);
transitionTo(mDriverStartedState);
break;
@@ -1960,8 +1843,6 @@
case CMD_SET_SCAN_MODE:
case CMD_SET_SCAN_TYPE:
case CMD_SET_HIGH_PERF_MODE:
- case CMD_SET_BLUETOOTH_COEXISTENCE:
- case CMD_SET_BLUETOOTH_SCAN_MODE:
case CMD_SET_COUNTRY_CODE:
case CMD_SET_FREQUENCY_BAND:
case CMD_START_PACKET_FILTERING:
@@ -1983,6 +1864,8 @@
EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
/* Initialize for connect mode operation at start */
mIsScanMode = false;
+ /* Wifi is available as long as we have a connection to supplicant */
+ mNetworkInfo.setIsAvailable(true);
}
@Override
public boolean processMessage(Message message) {
@@ -1996,6 +1879,7 @@
Log.e(TAG, "Failed to stop supplicant, issue kill");
WifiNative.killSupplicant();
}
+ mNetworkInfo.setIsAvailable(false);
handleNetworkDisconnect();
setWifiState(WIFI_STATE_DISABLING);
sendSupplicantConnectionChangedBroadcast(false);
@@ -2006,6 +1890,7 @@
Log.e(TAG, "Connection lost, restart supplicant");
WifiNative.killSupplicant();
WifiNative.closeSupplicantConnection();
+ mNetworkInfo.setIsAvailable(false);
handleNetworkDisconnect();
sendSupplicantConnectionChangedBroadcast(false);
mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE);
@@ -2085,6 +1970,11 @@
}
return HANDLED;
}
+
+ @Override
+ public void exit() {
+ mNetworkInfo.setIsAvailable(false);
+ }
}
class SupplicantStoppingState extends HierarchicalState {
@@ -2116,8 +2006,6 @@
case CMD_SET_SCAN_MODE:
case CMD_SET_SCAN_TYPE:
case CMD_SET_HIGH_PERF_MODE:
- case CMD_SET_BLUETOOTH_COEXISTENCE:
- case CMD_SET_BLUETOOTH_SCAN_MODE:
case CMD_SET_COUNTRY_CODE:
case CMD_SET_FREQUENCY_BAND:
case CMD_START_PACKET_FILTERING:
@@ -2154,8 +2042,6 @@
case PASSWORD_MAY_BE_INCORRECT_EVENT:
case CMD_SET_SCAN_TYPE:
case CMD_SET_HIGH_PERF_MODE:
- case CMD_SET_BLUETOOTH_COEXISTENCE:
- case CMD_SET_BLUETOOTH_SCAN_MODE:
case CMD_SET_COUNTRY_CODE:
case CMD_SET_FREQUENCY_BAND:
case CMD_START_PACKET_FILTERING:
@@ -2183,6 +2069,12 @@
mIsRunning = true;
updateBatteryWorkSource(null);
+ /**
+ * Enable bluetooth coexistence scan mode when bluetooth connection is active.
+ * When this mode is on, some of the low-level scan parameters used by the
+ * driver are changed to reduce interference with bluetooth
+ */
+ WifiNative.setBluetoothCoexistenceScanModeCommand(mBluetoothConnectionActive);
/* set country code */
setCountryCode();
/* set frequency band of operation */
@@ -2219,12 +2111,6 @@
case CMD_SET_HIGH_PERF_MODE:
setHighPerfModeEnabledNative(message.arg1 == 1);
break;
- case CMD_SET_BLUETOOTH_COEXISTENCE:
- WifiNative.setBluetoothCoexistenceModeCommand(message.arg1);
- break;
- case CMD_SET_BLUETOOTH_SCAN_MODE:
- WifiNative.setBluetoothCoexistenceScanModeCommand(message.arg1 == 1);
- break;
case CMD_SET_COUNTRY_CODE:
String country = (String) message.obj;
Log.d(TAG, "set country code " + country);
@@ -2243,6 +2129,11 @@
Log.e(TAG, "Failed to set frequency band " + band);
}
break;
+ case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE:
+ mBluetoothConnectionActive = (message.arg1 !=
+ BluetoothAdapter.STATE_DISCONNECTED);
+ WifiNative.setBluetoothCoexistenceScanModeCommand(mBluetoothConnectionActive);
+ break;
case CMD_STOP_DRIVER:
mWakeLock.acquire();
WifiNative.stopDriverCommand();
@@ -2290,8 +2181,6 @@
case CMD_STOP_DRIVER:
case CMD_SET_SCAN_TYPE:
case CMD_SET_HIGH_PERF_MODE:
- case CMD_SET_BLUETOOTH_COEXISTENCE:
- case CMD_SET_BLUETOOTH_SCAN_MODE:
case CMD_SET_COUNTRY_CODE:
case CMD_SET_FREQUENCY_BAND:
case CMD_START_PACKET_FILTERING:
@@ -2490,7 +2379,7 @@
mModifiedBluetoothCoexistenceMode = false;
mPowerMode = POWER_MODE_AUTO;
- if (shouldDisableCoexistenceMode()) {
+ if (!mBluetoothConnectionActive) {
/*
* There are problems setting the Wi-Fi driver's power
* mode to active when bluetooth coexistence mode is