Merge "Add an OMX IL API for querying buffer usage flags."
diff --git a/Android.mk b/Android.mk
index 6e41f96..52ebd6f 100644
--- a/Android.mk
+++ b/Android.mk
@@ -417,8 +417,8 @@
resources/samples/NotePad "Note Pad" \
-samplecode $(sample_dir)/SampleSyncAdapter \
resources/samples/SampleSyncAdapter "Sample Sync Adapter" \
- -samplecode frameworks/base/libs/rs/java \
- resources/samples/Renderscript "Renderscript" \
+ -samplecode $(sample_dir)/RenderScript \
+ resources/samples/RenderScript "RenderScript" \
-samplecode $(sample_dir)/SearchableDictionary \
resources/samples/SearchableDictionary "Searchable Dictionary v2" \
-samplecode $(sample_dir)/SipDemo \
diff --git a/api/current.xml b/api/current.xml
index 6adf8aa..2663c53 100644
--- a/api/current.xml
+++ b/api/current.xml
@@ -111,17 +111,6 @@
visibility="public"
>
</field>
-<field name="ACCESS_USB"
- type="java.lang.String"
- transient="false"
- volatile="false"
- value=""android.permission.ACCESS_USB""
- static="true"
- final="true"
- deprecated="not deprecated"
- visibility="public"
->
-</field>
<field name="ACCESS_WIFI_STATE"
type="java.lang.String"
transient="false"
@@ -39947,7 +39936,7 @@
visibility="public"
>
</field>
-<field name="resizableMode"
+<field name="resizeMode"
type="int"
transient="false"
volatile="false"
@@ -61267,6 +61256,28 @@
visibility="public"
>
</field>
+<field name="FEATURE_USB_ACCESSORY"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value=""android.hardware.usb.accessory""
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
+<field name="FEATURE_USB_HOST"
+ type="java.lang.String"
+ transient="false"
+ volatile="false"
+ value=""android.hardware.usb.host""
+ static="true"
+ final="true"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</field>
<field name="FEATURE_WIFI"
type="java.lang.String"
transient="false"
@@ -149691,6 +149702,17 @@
visibility="public"
>
</method>
+<method name="detachFd"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
<method name="fromSocket"
return="android.os.ParcelFileDescriptor"
abstract="false"
@@ -149704,6 +149726,17 @@
<parameter name="socket" type="java.net.Socket">
</parameter>
</method>
+<method name="getFd"
+ return="int"
+ abstract="false"
+ native="false"
+ synchronized="false"
+ static="false"
+ final="false"
+ deprecated="not deprecated"
+ visibility="public"
+>
+</method>
<method name="getFileDescriptor"
return="java.io.FileDescriptor"
abstract="false"
diff --git a/core/java/android/accounts/AccountManagerService.java b/core/java/android/accounts/AccountManagerService.java
index 2e70a56..a1c2867 100644
--- a/core/java/android/accounts/AccountManagerService.java
+++ b/core/java/android/accounts/AccountManagerService.java
@@ -101,7 +101,6 @@
private final IAccountAuthenticatorCache mAuthenticatorCache;
private final DatabaseHelper mOpenHelper;
- private final SimWatcher mSimWatcher;
private static final String TABLE_ACCOUNTS = "accounts";
private static final String ACCOUNTS_ID = "_id";
@@ -208,12 +207,46 @@
mAuthenticatorCache = authenticatorCache;
mAuthenticatorCache.setListener(this, null /* Handler */);
- mSimWatcher = new SimWatcher(mContext);
sThis.set(this);
+ IntentFilter intentFilter = new IntentFilter();
+ intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
+ intentFilter.addDataScheme("package");
+ mContext.registerReceiver(new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context1, Intent intent) {
+ purgeOldGrants();
+ }
+ }, intentFilter);
+ purgeOldGrants();
+
validateAccountsAndPopulateCache();
}
+ private void purgeOldGrants() {
+ synchronized (mCacheLock) {
+ final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+ final Cursor cursor = db.query(TABLE_GRANTS,
+ new String[]{GRANTS_GRANTEE_UID},
+ null, null, GRANTS_GRANTEE_UID, null, null);
+ try {
+ while (cursor.moveToNext()) {
+ final int uid = cursor.getInt(0);
+ final boolean packageExists = mPackageManager.getPackagesForUid(uid) != null;
+ if (packageExists) {
+ continue;
+ }
+ Log.d(TAG, "deleting grants for UID " + uid
+ + " because its package is no longer installed");
+ db.delete(TABLE_GRANTS, GRANTS_GRANTEE_UID + "=?",
+ new String[]{Integer.toString(uid)});
+ }
+ } finally {
+ cursor.close();
+ }
+ }
+ }
+
private void validateAccountsAndPopulateCache() {
boolean accountDeleted = false;
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
@@ -1739,100 +1772,6 @@
}
}
- private class SimWatcher extends BroadcastReceiver {
- public SimWatcher(Context context) {
- // Re-scan the SIM card when the SIM state changes, and also if
- // the disk recovers from a full state (we may have failed to handle
- // things properly while the disk was full).
- final IntentFilter filter = new IntentFilter();
- filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
- filter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
- context.registerReceiver(this, filter);
- }
-
- /**
- * Compare the IMSI to the one stored in the login service's
- * database. If they differ, erase all passwords and
- * authtokens (and store the new IMSI).
- */
- @Override
- public void onReceive(Context context, Intent intent) {
- // Check IMSI on every update; nothing happens if the IMSI
- // is missing or unchanged.
- TelephonyManager telephonyManager =
- (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
- if (telephonyManager == null) {
- Log.w(TAG, "failed to get TelephonyManager");
- return;
- }
- String imsi = telephonyManager.getSubscriberId();
-
- // If the subscriber ID is an empty string, don't do anything.
- if (TextUtils.isEmpty(imsi)) return;
-
- // If the current IMSI matches what's stored, don't do anything.
- String storedImsi = getMetaValue("imsi");
- if (Log.isLoggable(TAG, Log.VERBOSE)) {
- Log.v(TAG, "current IMSI=" + imsi + "; stored IMSI=" + storedImsi);
- }
- if (imsi.equals(storedImsi)) return;
-
- // If a CDMA phone is unprovisioned, getSubscriberId()
- // will return a different value, but we *don't* erase the
- // passwords. We only erase them if it has a different
- // subscriber ID once it's provisioned.
- if (telephonyManager.getCurrentPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
- IBinder service = ServiceManager.checkService(Context.TELEPHONY_SERVICE);
- if (service == null) {
- Log.w(TAG, "call to checkService(TELEPHONY_SERVICE) failed");
- return;
- }
- ITelephony telephony = ITelephony.Stub.asInterface(service);
- if (telephony == null) {
- Log.w(TAG, "failed to get ITelephony interface");
- return;
- }
- boolean needsProvisioning;
- try {
- needsProvisioning = telephony.needsOtaServiceProvisioning();
- } catch (RemoteException e) {
- Log.w(TAG, "exception while checking provisioning", e);
- // default to NOT wiping out the passwords
- needsProvisioning = true;
- }
- if (needsProvisioning) {
- // if the phone needs re-provisioning, don't do anything.
- if (Log.isLoggable(TAG, Log.VERBOSE)) {
- Log.v(TAG, "current IMSI=" + imsi + " (needs provisioning); stored IMSI=" +
- storedImsi);
- }
- return;
- }
- }
-
- if (!imsi.equals(storedImsi) && !TextUtils.isEmpty(storedImsi)) {
- Log.w(TAG, "wiping all passwords and authtokens because IMSI changed ("
- + "stored=" + storedImsi + ", current=" + imsi + ")");
- SQLiteDatabase db = mOpenHelper.getWritableDatabase();
- db.beginTransaction();
- try {
- db.execSQL("DELETE from " + TABLE_AUTHTOKENS);
- db.execSQL("UPDATE " + TABLE_ACCOUNTS + " SET " + ACCOUNTS_PASSWORD + " = ''");
-
- synchronized (mCacheLock) {
- mAuthTokenCache = new HashMap<Account, HashMap<String, String>>();
- }
-
- db.setTransactionSuccessful();
- } finally {
- db.endTransaction();
- }
- sendAccountsChangedBroadcast();
- }
- setMetaValue("imsi", imsi);
- }
- }
-
public IBinder onBind(Intent intent) {
return asBinder();
}
diff --git a/core/java/android/app/FragmentManager.java b/core/java/android/app/FragmentManager.java
index 52b3108..d8d0a5b 100644
--- a/core/java/android/app/FragmentManager.java
+++ b/core/java/android/app/FragmentManager.java
@@ -167,10 +167,9 @@
public static final int POP_BACK_STACK_INCLUSIVE = 1<<0;
/**
- * Pop the top state off the back stack. Returns true if there was one
- * to pop, else false. This function is asynchronous -- it enqueues the
- * request to pop, but the action will not be performed until the application
- * returns to its event loop.
+ * Pop the top state off the back stack. This function is asynchronous -- it
+ * enqueues the request to pop, but the action will not be performed until the
+ * application returns to its event loop.
*/
public abstract void popBackStack();
diff --git a/core/java/android/app/backup/WallpaperBackupHelper.java b/core/java/android/app/backup/WallpaperBackupHelper.java
index d70b3d3..6539711 100644
--- a/core/java/android/app/backup/WallpaperBackupHelper.java
+++ b/core/java/android/app/backup/WallpaperBackupHelper.java
@@ -21,6 +21,8 @@
import android.graphics.BitmapFactory;
import android.os.ParcelFileDescriptor;
import android.util.Slog;
+import android.view.Display;
+import android.view.WindowManager;
import java.io.File;
@@ -65,6 +67,13 @@
mDesiredMinWidth = (double) wpm.getDesiredMinimumWidth();
mDesiredMinHeight = (double) wpm.getDesiredMinimumHeight();
+ if (mDesiredMinWidth <= 0 || mDesiredMinHeight <= 0) {
+ WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
+ Display d = wm.getDefaultDisplay();
+ mDesiredMinWidth = d.getWidth();
+ mDesiredMinHeight = d.getHeight();
+ }
+
if (DEBUG) {
Slog.d(TAG, "dmW=" + mDesiredMinWidth + " dmH=" + mDesiredMinHeight);
}
diff --git a/core/java/android/appwidget/AppWidgetProviderInfo.java b/core/java/android/appwidget/AppWidgetProviderInfo.java
index 32c2397..b46802e 100644
--- a/core/java/android/appwidget/AppWidgetProviderInfo.java
+++ b/core/java/android/appwidget/AppWidgetProviderInfo.java
@@ -130,6 +130,9 @@
/**
* The view id of the AppWidget subview which should be auto-advanced by the widget's host.
+ *
+ * <p>This field corresponds to the <code>android:autoAdvanceViewId</code> attribute in
+ * the AppWidget meta-data file.
*/
public int autoAdvanceViewId;
@@ -146,8 +149,11 @@
* The rules by which a widget can be resized. See {@link #RESIZE_NONE},
* {@link #RESIZE_NONE}, {@link #RESIZE_HORIZONTAL},
* {@link #RESIZE_VERTICAL}, {@link #RESIZE_BOTH}.
+ *
+ * <p>This field corresponds to the <code>android:resizeMode</code> attribute in
+ * the AppWidget meta-data file.
*/
- public int resizableMode;
+ public int resizeMode;
public AppWidgetProviderInfo() {
}
@@ -170,7 +176,7 @@
this.icon = in.readInt();
this.previewImage = in.readInt();
this.autoAdvanceViewId = in.readInt();
- this.resizableMode = in.readInt();
+ this.resizeMode = in.readInt();
}
public void writeToParcel(android.os.Parcel out, int flags) {
@@ -194,7 +200,7 @@
out.writeInt(this.icon);
out.writeInt(this.previewImage);
out.writeInt(this.autoAdvanceViewId);
- out.writeInt(this.resizableMode);
+ out.writeInt(this.resizeMode);
}
public int describeContents() {
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index a589216..7525749 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -785,6 +785,21 @@
/**
* Feature for {@link #getSystemAvailableFeatures} and
+ * {@link #hasSystemFeature}: The device supports connecting to USB devices
+ * as the USB host.
+ */
+ @SdkConstant(SdkConstantType.FEATURE)
+ public static final String FEATURE_USB_HOST = "android.hardware.usb.host";
+
+ /**
+ * Feature for {@link #getSystemAvailableFeatures} and
+ * {@link #hasSystemFeature}: The device supports connecting to USB accessories.
+ */
+ @SdkConstant(SdkConstantType.FEATURE)
+ public static final String FEATURE_USB_ACCESSORY = "android.hardware.usb.accessory";
+
+ /**
+ * Feature for {@link #getSystemAvailableFeatures} and
* {@link #hasSystemFeature}: The SIP API is enabled on the device.
*/
@SdkConstant(SdkConstantType.FEATURE)
diff --git a/core/java/android/hardware/IUsbManager.aidl b/core/java/android/hardware/IUsbManager.aidl
index 6c99ab3..8086f37 100644
--- a/core/java/android/hardware/IUsbManager.aidl
+++ b/core/java/android/hardware/IUsbManager.aidl
@@ -17,6 +17,7 @@
package android.hardware;
import android.hardware.UsbAccessory;
+import android.hardware.UsbDevice;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
@@ -25,7 +26,39 @@
{
/* Returns a list of all currently attached USB devices */
void getDeviceList(out Bundle devices);
+
+ /* Returns a file descriptor for communicating with the USB device.
+ * The native fd can be passed to usb_device_new() in libusbhost.
+ */
ParcelFileDescriptor openDevice(String deviceName);
+
+ /* Returns the currently attached USB accessory */
UsbAccessory getCurrentAccessory();
- ParcelFileDescriptor openAccessory();
+
+ /* Returns a file descriptor for communicating with the USB accessory.
+ * This file descriptor can be used with standard Java file operations.
+ */
+ ParcelFileDescriptor openAccessory(in UsbAccessory accessory);
+
+ /* Sets the default package for a USB device
+ * (or clears it if the package name is null)
+ */
+ oneway void setDevicePackage(in UsbDevice device, String packageName);
+
+ /* Sets the default package for a USB device
+ * (or clears it if the package name is null)
+ */
+ void setAccessoryPackage(in UsbAccessory accessory, String packageName);
+
+ /* Grants permission for the given UID to access the device */
+ void grantDevicePermission(in UsbDevice device, int uid);
+
+ /* Grants permission for the given UID to access the accessory */
+ void grantAccessoryPermission(in UsbAccessory accessory, int uid);
+
+ /* Returns true if the USB manager has default preferences or permissions for the package */
+ boolean hasDefaults(String packageName, int uid);
+
+ /* Clears default preferences and permissions for the package */
+ oneway void clearDefaults(String packageName, int uid);
}
diff --git a/core/java/android/hardware/UsbAccessory.java b/core/java/android/hardware/UsbAccessory.java
index 71672fa..15dff3e 100644
--- a/core/java/android/hardware/UsbAccessory.java
+++ b/core/java/android/hardware/UsbAccessory.java
@@ -95,6 +95,23 @@
return mVersion;
}
+ private static boolean compare(String s1, String s2) {
+ if (s1 == null) return (s2 == null);
+ return s1.equals(s2);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof UsbAccessory) {
+ UsbAccessory accessory = (UsbAccessory)obj;
+ return (compare(mManufacturer, accessory.getManufacturer()) &&
+ compare(mModel, accessory.getModel()) &&
+ compare(mType, accessory.getType()) &&
+ compare(mVersion, accessory.getVersion()));
+ }
+ return false;
+ }
+
@Override
public String toString() {
return "UsbAccessory[mManufacturer=" + mManufacturer +
diff --git a/core/java/android/hardware/UsbManager.java b/core/java/android/hardware/UsbManager.java
index dcfdcf4..e9a34ea 100644
--- a/core/java/android/hardware/UsbManager.java
+++ b/core/java/android/hardware/UsbManager.java
@@ -98,7 +98,7 @@
*
* This intent is sent when a USB accessory is detached.
* <ul>
- * <li> {@link #EXTRA_ACCESSORY} containing the {@link android.hardware.UsbAccessory}
+ * <li> {@link #EXTRA_ACCESSORY} containing the {@link android.hardware.UsbAccessory}
* for the attached accessory that was detached
* </ul>
*/
@@ -163,14 +163,15 @@
/**
* Name of extra for {@link #ACTION_USB_DEVICE_ATTACHED} and
- * {@link #ACTION_USB_DEVICE_DETACHED} broadcasts.
+ * {@link #ACTION_USB_DEVICE_DETACHED} broadcasts
* containing the UsbDevice object for the device.
*/
public static final String EXTRA_DEVICE = "device";
/**
- * Name of extra for {@link #ACTION_USB_ACCESSORY_ATTACHED} broadcast
+ * Name of extra for {@link #ACTION_USB_ACCESSORY_ATTACHED} and
+ * {@link #ACTION_USB_ACCESSORY_DETACHED} broadcasts
* containing the UsbAccessory object for the accessory.
*/
public static final String EXTRA_ACCESSORY = "accessory";
@@ -244,7 +245,7 @@
return new UsbAccessory[] { accessory };
}
} catch (RemoteException e) {
- Log.e(TAG, "RemoteException in openAccessory" , e);
+ Log.e(TAG, "RemoteException in getAccessoryList" , e);
return null;
}
}
@@ -257,7 +258,7 @@
*/
public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
try {
- return mService.openAccessory();
+ return mService.openAccessory(accessory);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in openAccessory" , e);
return null;
diff --git a/core/java/android/os/Parcel.java b/core/java/android/os/Parcel.java
index 31f8719..eca34848 100644
--- a/core/java/android/os/Parcel.java
+++ b/core/java/android/os/Parcel.java
@@ -31,6 +31,7 @@
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -356,7 +357,7 @@
public final native void enforceInterface(String interfaceName);
/**
- * Write a byte array into the parcel at the current {#link #dataPosition},
+ * Write a byte array into the parcel at the current {@link #dataPosition},
* growing {@link #dataCapacity} if needed.
* @param b Bytes to place into the parcel.
*/
@@ -365,7 +366,7 @@
}
/**
- * Write an byte array into the parcel at the current {#link #dataPosition},
+ * Write an byte array into the parcel at the current {@link #dataPosition},
* growing {@link #dataCapacity} if needed.
* @param b Bytes to place into the parcel.
* @param offset Index of first byte to be written.
@@ -376,9 +377,7 @@
writeInt(-1);
return;
}
- if (b.length < offset + len || len < 0 || offset < 0) {
- throw new ArrayIndexOutOfBoundsException();
- }
+ Arrays.checkOffsetAndCount(b.length, offset, len);
writeNative(b, offset, len);
}
@@ -1386,6 +1385,7 @@
int mode) throws FileNotFoundException;
/*package*/ static native void closeFileDescriptor(FileDescriptor desc)
throws IOException;
+ /*package*/ static native void clearFileDescriptor(FileDescriptor desc);
/**
* Read a byte value from the parcel at the current dataPosition().
diff --git a/core/java/android/os/ParcelFileDescriptor.java b/core/java/android/os/ParcelFileDescriptor.java
index 3a5d26b..5bd129f 100644
--- a/core/java/android/os/ParcelFileDescriptor.java
+++ b/core/java/android/os/ParcelFileDescriptor.java
@@ -197,6 +197,40 @@
public native long seekTo(long pos);
/**
+ * Return the native fd int for this ParcelFileDescriptor. The
+ * ParcelFileDescriptor still owns the fd, and it still must be closed
+ * through this API.
+ */
+ public int getFd() {
+ if (mClosed) {
+ throw new IllegalStateException("Already closed");
+ }
+ return getFdNative();
+ }
+
+ private native int getFdNative();
+
+ /**
+ * Return the native fd int for this ParcelFileDescriptor and detach it
+ * from the object here. You are now responsible for closing the fd in
+ * native code.
+ */
+ public int detachFd() {
+ if (mClosed) {
+ throw new IllegalStateException("Already closed");
+ }
+ if (mParcelDescriptor != null) {
+ int fd = mParcelDescriptor.detachFd();
+ mClosed = true;
+ return fd;
+ }
+ int fd = getFd();
+ mClosed = true;
+ Parcel.clearFileDescriptor(mFileDescriptor);
+ return fd;
+ }
+
+ /**
* Close the ParcelFileDescriptor. This implementation closes the underlying
* OS resources allocated to represent this stream.
*
diff --git a/core/java/android/view/Display.java b/core/java/android/view/Display.java
index b74806486..126f409 100644
--- a/core/java/android/view/Display.java
+++ b/core/java/android/view/Display.java
@@ -79,6 +79,11 @@
*/
native public int getHeight();
+ /** @hide special for when we are faking the screen size. */
+ native public int getRealWidth();
+ /** @hide special for when we are faking the screen size. */
+ native public int getRealHeight();
+
/**
* Returns the rotation of the screen from its "natural" orientation.
* The returned value may be {@link Surface#ROTATION_0 Surface.ROTATION_0}
@@ -136,11 +141,6 @@
outMetrics.ydpi = mDpiY;
}
- /**
- * @hide Helper for our fake display size hack.
- */
- native public static int unmapDisplaySize(int newSize);
-
/*
* We use a class initializer to allow the native code to cache some
* field offsets.
diff --git a/core/java/android/view/ScaleGestureDetector.java b/core/java/android/view/ScaleGestureDetector.java
index 218ee4f..0124151 100644
--- a/core/java/android/view/ScaleGestureDetector.java
+++ b/core/java/android/view/ScaleGestureDetector.java
@@ -245,6 +245,7 @@
final float bottomSlop = mBottomSlopEdge;
int index0 = event.findPointerIndex(mActiveId0);
int index1 = event.findPointerIndex(mActiveId1);
+
float x0 = getRawX(event, index0);
float y0 = getRawY(event, index0);
float x1 = getRawX(event, index1);
@@ -353,14 +354,24 @@
if (actionId == mActiveId0) {
final int newIndex = findNewActiveIndex(event, mActiveId1, actionIndex);
if (newIndex >= 0) {
+ mListener.onScaleEnd(this);
mActiveId0 = event.getPointerId(newIndex);
+ mActive0MostRecent = true;
+ mPrevEvent = MotionEvent.obtain(event);
+ setContext(event);
+ mGestureInProgress = mListener.onScaleBegin(this);
} else {
gestureEnded = true;
}
} else if (actionId == mActiveId1) {
final int newIndex = findNewActiveIndex(event, mActiveId0, actionIndex);
if (newIndex >= 0) {
+ mListener.onScaleEnd(this);
mActiveId1 = event.getPointerId(newIndex);
+ mActive0MostRecent = false;
+ mPrevEvent = MotionEvent.obtain(event);
+ setContext(event);
+ mGestureInProgress = mListener.onScaleBegin(this);
} else {
gestureEnded = true;
}
@@ -449,6 +460,7 @@
* MotionEvent has no getRawX(int) method; simulate it pending future API approval.
*/
private static float getRawX(MotionEvent event, int pointerIndex) {
+ if (pointerIndex < 0) return Float.MIN_VALUE;
if (pointerIndex == 0) return event.getRawX();
float offset = event.getRawX() - event.getX();
return event.getX(pointerIndex) + offset;
@@ -458,6 +470,7 @@
* MotionEvent has no getRawY(int) method; simulate it pending future API approval.
*/
private static float getRawY(MotionEvent event, int pointerIndex) {
+ if (pointerIndex < 0) return Float.MIN_VALUE;
if (pointerIndex == 0) return event.getRawY();
float offset = event.getRawY() - event.getY();
return event.getY(pointerIndex) + offset;
diff --git a/core/java/android/view/ViewPropertyAnimator.java b/core/java/android/view/ViewPropertyAnimator.java
index 27e7db1..1d56e9d 100644
--- a/core/java/android/view/ViewPropertyAnimator.java
+++ b/core/java/android/view/ViewPropertyAnimator.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2010 The Android Open Source Project
+ * 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.
@@ -33,11 +33,11 @@
* more convenient syntax to animate a specific property, then ViewPropertyAnimator might be
* more well-suited to the task.
*
- * <p>This class could provide better performance for several simultaneous animations, because
- * it will optimize invalidatesionto take place only once for several properties instead of each
- * aniamted property independently causing its own invalidation. Also, the syntax of using this
+ * <p>This class may provide better performance for several simultaneous animations, because
+ * it will optimize invalidate calls to take place only once for several properties instead of each
+ * animated property independently causing its own invalidation. Also, the syntax of using this
* class could be easier to use because the caller need only tell the View object which
- * property to animate, and the value to animate either to or by, and this calss handles the
+ * property to animate, and the value to animate either to or by, and this class handles the
* details of configuring the underlying Animator class and starting it.</p>
*
* <p>This class is not constructed by the caller, but rather by the View whose properties
@@ -103,7 +103,7 @@
/**
* Constants used to associate a property being requested and the mechanism used to set
- * the property (this calss calls directly into View to set the properties in question).
+ * the property (this class calls directly into View to set the properties in question).
*/
private static final int NONE = 0x0000;
private static final int TRANSLATION_X = 0x0001;
@@ -260,7 +260,7 @@
/**
* This method will cause the View's <code>x</code> property to be animated to the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setX(float)
@@ -273,7 +273,7 @@
/**
* This method will cause the View's <code>x</code> property to be animated by the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setX(float)
@@ -286,7 +286,7 @@
/**
* This method will cause the View's <code>y</code> property to be animated to the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setY(float)
@@ -299,7 +299,7 @@
/**
* This method will cause the View's <code>y</code> property to be animated by the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setY(float)
@@ -312,7 +312,7 @@
/**
* This method will cause the View's <code>rotation</code> property to be animated to the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setRotation(float)
@@ -325,7 +325,7 @@
/**
* This method will cause the View's <code>rotation</code> property to be animated by the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setRotation(float)
@@ -338,7 +338,7 @@
/**
* This method will cause the View's <code>rotationX</code> property to be animated to the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setRotationX(float)
@@ -351,7 +351,7 @@
/**
* This method will cause the View's <code>rotationX</code> property to be animated by the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setRotationX(float)
@@ -364,7 +364,7 @@
/**
* This method will cause the View's <code>rotationY</code> property to be animated to the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setRotationY(float)
@@ -377,7 +377,7 @@
/**
* This method will cause the View's <code>rotationY</code> property to be animated by the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setRotationY(float)
@@ -390,7 +390,7 @@
/**
* This method will cause the View's <code>translationX</code> property to be animated to the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setTranslationX(float)
@@ -403,7 +403,7 @@
/**
* This method will cause the View's <code>translationX</code> property to be animated by the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setTranslationX(float)
@@ -416,7 +416,7 @@
/**
* This method will cause the View's <code>translationY</code> property to be animated to the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setTranslationY(float)
@@ -429,7 +429,7 @@
/**
* This method will cause the View's <code>translationY</code> property to be animated by the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setTranslationY(float)
@@ -442,7 +442,7 @@
/**
* This method will cause the View's <code>scaleX</code> property to be animated to the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setScaleX(float)
@@ -455,7 +455,7 @@
/**
* This method will cause the View's <code>scaleX</code> property to be animated by the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setScaleX(float)
@@ -468,7 +468,7 @@
/**
* This method will cause the View's <code>scaleY</code> property to be animated to the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setScaleY(float)
@@ -481,7 +481,7 @@
/**
* This method will cause the View's <code>scaleY</code> property to be animated by the
- * specifed value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setScaleY(float)
@@ -494,7 +494,7 @@
/**
* This method will cause the View's <code>alpha</code> property to be animated to the
- * specified value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The value to be animated to.
* @see View#setAlpha(float)
@@ -507,7 +507,7 @@
/**
* This method will cause the View's <code>alpha</code> property to be animated by the
- * specified value.
+ * specified value. Animations already running on the property will be canceled.
*
* @param value The amount to be animated by, as an offset from the current value.
* @see View#setAlpha(float)
@@ -548,7 +548,7 @@
/**
* Utility function, called by the various x(), y(), etc. methods. This stores the
- * constnat name for the property along with the from/delta values that will be used to
+ * constant name for the property along with the from/delta values that will be used to
* calculate and set the property during the animation. This structure is added to the
* pending animations, awaiting the eventual start() of the underlying animator. A
* Runnable is posted to start the animation, and any pending such Runnable is canceled
@@ -578,14 +578,14 @@
}
/**
- * Utility function, called by animatePropert() and animatePropertyBy(), which handles the
+ * Utility function, called by animateProperty() and animatePropertyBy(), which handles the
* details of adding a pending animation and posting the request to start the animation.
*
* @param constantName The specifier for the property being animated
- * @param fromValue The starting value of the property
+ * @param startValue The starting value of the property
* @param byValue The amount by which the property will change
*/
- private void animatePropertyBy(int constantName, float fromValue, float byValue) {
+ private void animatePropertyBy(int constantName, float startValue, float byValue) {
// First, cancel any existing animations on this property
if (mAnimatorMap.size() > 0) {
Animator animatorToCancel = null;
@@ -598,7 +598,7 @@
// on a property will cancel a previous animation on that property, so
// there can only ever be one such animation running.
if (bundle.mPropertyMask == NONE) {
- // the animation is not longer changing animthing - cancel it
+ // the animation is not longer changing anything - cancel it
animatorToCancel = runningAnim;
break;
}
@@ -609,7 +609,6 @@
}
}
- float startValue = getValue(constantName);
NameValuesHolder nameValuePair = new NameValuesHolder(constantName, startValue, byValue);
mPendingAnimations.add(nameValuePair);
mView.getHandler().removeCallbacks(mAnimationStarter);
diff --git a/core/java/android/webkit/ZoomManager.java b/core/java/android/webkit/ZoomManager.java
index 5e0de27..6303850 100644
--- a/core/java/android/webkit/ZoomManager.java
+++ b/core/java/android/webkit/ZoomManager.java
@@ -227,10 +227,13 @@
assert density > 0;
if (Math.abs(density - mDefaultScale) > MINIMUM_SCALE_INCREMENT) {
+ // Remember the current zoom density before it gets changed.
+ final float originalDefault = mDefaultScale;
// set the new default density
setDefaultZoomScale(density);
+ float scaleChange = (originalDefault > 0.0) ? density / originalDefault: 1.0f;
// adjust the scale if it falls outside the new zoom bounds
- setZoomScale(mActualScale, true);
+ setZoomScale(mActualScale * scaleChange, true);
}
}
@@ -721,10 +724,7 @@
}
public boolean onScale(ScaleGestureDetector detector) {
- // Prevent scaling beyond overview scale.
- float scale = Math.max(
- computeScaleWithLimits(detector.getScaleFactor() * mActualScale),
- getZoomOverviewScale());
+ float scale = computeScaleWithLimits(detector.getScaleFactor() * mActualScale);
if (mPinchToZoomAnimating || willScaleTriggerZoom(scale)) {
mPinchToZoomAnimating = true;
// limit the scale change per step
@@ -780,13 +780,6 @@
// update mMinZoomScale if the minimum zoom scale is not fixed
if (!mMinZoomScaleFixed) {
- // when change from narrow screen to wide screen, the new viewWidth
- // can be wider than the old content width. We limit the minimum
- // scale to 1.0f. The proper minimum scale will be calculated when
- // the new picture shows up.
- mMinZoomScale = Math.min(1.0f, (float) mWebView.getViewWidth()
- / (mWebView.drawHistory() ? mWebView.getHistoryPictureWidth()
- : mZoomOverviewWidth));
// limit the minZoomScale to the initialScale if it is set
if (mInitialScale > 0 && mInitialScale < mMinZoomScale) {
mMinZoomScale = mInitialScale;
@@ -823,7 +816,7 @@
// Keep overview mode unchanged when rotating.
final float zoomOverviewScale = getZoomOverviewScale();
final float newScale = (mInZoomOverviewBeforeSizeChange) ?
- zoomOverviewScale : Math.max(mActualScale, zoomOverviewScale);
+ zoomOverviewScale : mActualScale;
setZoomScale(newScale, mUpdateTextWrap, true);
// update the zoom buttons as the scale can be changed
updateZoomPicker();
@@ -879,21 +872,15 @@
}
}
- if (!mMinZoomScaleFixed) {
- mMinZoomScale = newZoomOverviewScale;
- }
// fit the content width to the current view for the first new picture
// after first layout.
boolean scaleHasDiff = exceedsMinScaleIncrement(newZoomOverviewScale, mActualScale);
- // Make sure the actual scale is no less than zoom overview scale.
- boolean scaleLessThanOverview =
- (newZoomOverviewScale - mActualScale) >= MINIMUM_SCALE_INCREMENT;
// Make sure mobile sites are correctly handled since mobile site will
// change content width after rotating.
boolean mobileSiteInOverview = mInZoomOverview &&
!exceedsMinScaleIncrement(newZoomOverviewScale, 1.0f);
if (!mWebView.drawHistory() &&
- (mInitialZoomOverview || scaleLessThanOverview || mobileSiteInOverview) &&
+ (mInitialZoomOverview || mobileSiteInOverview) &&
scaleHasDiff && zoomOverviewWidthChanged) {
mInitialZoomOverview = false;
setZoomScale(newZoomOverviewScale, !willScaleTriggerZoom(mTextWrapScale) &&
@@ -967,10 +954,11 @@
mTextWrapScale = viewState.mTextWrapScale;
scale = viewState.mViewScale;
} else {
- scale = overviewScale;
- if (!settings.getUseWideViewPort()
- || !settings.getLoadWithOverviewMode()) {
- scale = Math.max(viewState.mTextWrapScale, scale);
+ scale = mDefaultScale;
+ mTextWrapScale = mDefaultScale;
+ if (settings.getUseWideViewPort()
+ && settings.getLoadWithOverviewMode()) {
+ scale = Math.max(overviewScale, scale);
}
if (settings.isNarrowColumnLayout() &&
settings.getUseFixedViewport()) {
@@ -981,7 +969,7 @@
}
boolean reflowText = false;
if (!viewState.mIsRestored) {
- if (settings.getUseFixedViewport()) {
+ if (settings.getUseFixedViewport() && settings.getLoadWithOverviewMode()) {
// Override the scale only in case of fixed viewport.
scale = Math.max(scale, overviewScale);
mTextWrapScale = Math.max(mTextWrapScale, overviewScale);
diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java
index c2c8d16..47bf57f 100644
--- a/core/java/android/widget/AbsListView.java
+++ b/core/java/android/widget/AbsListView.java
@@ -3241,6 +3241,27 @@
mLastY = y;
break;
}
+
+ case MotionEvent.ACTION_POINTER_DOWN: {
+ // New pointers take over dragging duties
+ final int index = ev.getActionIndex();
+ final int id = ev.getPointerId(index);
+ final int x = (int) ev.getX(index);
+ final int y = (int) ev.getY(index);
+ mMotionCorrection = 0;
+ mActivePointerId = id;
+ mMotionX = x;
+ mMotionY = y;
+ final int motionPosition = pointToPosition(x, y);
+ if (motionPosition >= 0) {
+ // Remember where the motion event started
+ v = getChildAt(motionPosition - mFirstPosition);
+ mMotionViewOriginalTop = v.getTop();
+ mMotionPosition = motionPosition;
+ }
+ mLastY = y;
+ break;
+ }
}
return true;
@@ -3270,7 +3291,7 @@
final float vscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
if (vscroll != 0) {
final int delta = (int) (vscroll * getVerticalScrollFactor());
- if (trackMotionScroll(delta, delta)) {
+ if (!trackMotionScroll(delta, delta)) {
return true;
}
}
@@ -3412,9 +3433,6 @@
mMotionY = (int) ev.getY(newPointerIndex);
mMotionCorrection = 0;
mActivePointerId = ev.getPointerId(newPointerIndex);
- if (mVelocityTracker != null) {
- mVelocityTracker.clear();
- }
}
}
@@ -3529,6 +3547,7 @@
post(this);
} else {
mTouchMode = TOUCH_MODE_REST;
+ reportScrollStateChange(OnScrollListener.SCROLL_STATE_IDLE);
}
}
diff --git a/core/java/android/widget/ExpandableListView.java b/core/java/android/widget/ExpandableListView.java
index 8279ee5..f862368 100644
--- a/core/java/android/widget/ExpandableListView.java
+++ b/core/java/android/widget/ExpandableListView.java
@@ -299,6 +299,9 @@
indicatorRect.right = mIndicatorRight;
}
+ indicatorRect.left += mPaddingLeft;
+ indicatorRect.right += mPaddingLeft;
+
lastItemType = pos.position.type;
}
diff --git a/core/java/android/widget/HorizontalScrollView.java b/core/java/android/widget/HorizontalScrollView.java
index 3255f6f..d92588cb 100644
--- a/core/java/android/widget/HorizontalScrollView.java
+++ b/core/java/android/widget/HorizontalScrollView.java
@@ -475,8 +475,16 @@
invalidate();
}
break;
+ case MotionEvent.ACTION_POINTER_DOWN: {
+ final int index = ev.getActionIndex();
+ final float x = ev.getX(index);
+ mLastMotionX = x;
+ mActivePointerId = ev.getPointerId(index);
+ break;
+ }
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
+ mLastMotionX = ev.getX(ev.findPointerIndex(mActivePointerId));
break;
}
diff --git a/core/java/android/widget/NumberPicker.java b/core/java/android/widget/NumberPicker.java
index 7a59178..2947ebe 100644
--- a/core/java/android/widget/NumberPicker.java
+++ b/core/java/android/widget/NumberPicker.java
@@ -608,7 +608,7 @@
case MotionEvent.ACTION_DOWN:
mLastMotionEventY = mLastDownEventY = event.getY();
removeAllCallbacks();
- hideInputControls();
+ mShowInputControlsAnimator.cancel();
mBeginEditOnUpEvent = false;
mAdjustScrollerOnUpEvent = true;
if (mDrawSelectorWheel) {
@@ -621,6 +621,7 @@
}
mBeginEditOnUpEvent = scrollersFinished;
mAdjustScrollerOnUpEvent = true;
+ hideInputControls();
return true;
}
if (isEventInViewHitRect(event, mInputText)
@@ -630,6 +631,7 @@
&& isEventInViewHitRect(event, mDecrementButton))) {
mAdjustScrollerOnUpEvent = false;
setDrawSelectorWheel(true);
+ hideInputControls();
return true;
}
break;
@@ -640,6 +642,7 @@
mBeginEditOnUpEvent = false;
onScrollStateChange(OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
setDrawSelectorWheel(true);
+ hideInputControls();
return true;
}
break;
diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java
index 7aca0db..4b4f5f2 100644
--- a/core/java/android/widget/ScrollView.java
+++ b/core/java/android/widget/ScrollView.java
@@ -607,8 +607,16 @@
endDrag();
}
break;
+ case MotionEvent.ACTION_POINTER_DOWN: {
+ final int index = ev.getActionIndex();
+ final float y = ev.getY(index);
+ mLastMotionY = y;
+ mActivePointerId = ev.getPointerId(index);
+ break;
+ }
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
+ mLastMotionY = ev.getY(ev.findPointerIndex(mActivePointerId));
break;
}
return true;
diff --git a/core/java/android/widget/TabWidget.java b/core/java/android/widget/TabWidget.java
index 22f6f4e..d74ef24 100644
--- a/core/java/android/widget/TabWidget.java
+++ b/core/java/android/widget/TabWidget.java
@@ -174,8 +174,8 @@
void measureHorizontal(int widthMeasureSpec, int heightMeasureSpec) {
// First, measure with no constraint
final int unspecifiedWidth = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
- super.measureHorizontal(unspecifiedWidth, heightMeasureSpec);
mImposedTabsHeight = -1;
+ super.measureHorizontal(unspecifiedWidth, heightMeasureSpec);
int extraWidth = getMeasuredWidth() - MeasureSpec.getSize(widthMeasureSpec);
if (extraWidth > 0) {
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 33d1225..09c1ac5 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -7091,6 +7091,11 @@
// Only track when onStartTemporaryDetach() is called directly,
// usually because this instance is an editable field in a list
if (!mDispatchTemporaryDetach) mTemporaryDetach = true;
+
+ // Because of View recycling in ListView, there is no easy way to know when a TextView with
+ // selection becomes visible again. Until a better solution is found, stop text selection
+ // mode (if any) as soon as this TextView is recycled.
+ stopSelectionActionMode();
}
@Override
diff --git a/core/java/com/android/internal/app/ResolverActivity.java b/core/java/com/android/internal/app/ResolverActivity.java
index 841de06..fb2a72b 100644
--- a/core/java/com/android/internal/app/ResolverActivity.java
+++ b/core/java/com/android/internal/app/ResolverActivity.java
@@ -68,7 +68,7 @@
protected void onCreate(Bundle savedInstanceState, Intent intent,
CharSequence title, Intent[] initialIntents, List<ResolveInfo> rList,
- boolean alwaysUseOption) {
+ boolean alwaysUseOption, boolean alwaysChoose) {
super.onCreate(savedInstanceState);
mPm = getPackageManager();
intent.setComponent(null);
@@ -90,9 +90,10 @@
mClearDefaultHint.setVisibility(View.GONE);
}
mAdapter = new ResolveListAdapter(this, intent, initialIntents, rList);
- if (mAdapter.getCount() > 1) {
+ int count = mAdapter.getCount();
+ if (count > 1 || (count == 1 && alwaysChoose)) {
ap.mAdapter = mAdapter;
- } else if (mAdapter.getCount() == 1) {
+ } else if (count == 1) {
startActivity(mAdapter.intentForPosition(0));
finish();
return;
@@ -103,11 +104,22 @@
setupAlert();
}
+ protected void onCreate(Bundle savedInstanceState, Intent intent,
+ CharSequence title, Intent[] initialIntents, List<ResolveInfo> rList,
+ boolean alwaysUseOption) {
+ onCreate(savedInstanceState, intent, title, initialIntents, rList, alwaysUseOption, false);
+ }
+
public void onClick(DialogInterface dialog, int which) {
ResolveInfo ri = mAdapter.resolveInfoForPosition(which);
Intent intent = mAdapter.intentForPosition(which);
+ boolean alwaysCheck = (mAlwaysCheck != null && mAlwaysCheck.isChecked());
+ onIntentSelected(ri, intent, alwaysCheck);
+ finish();
+ }
- if ((mAlwaysCheck != null) && mAlwaysCheck.isChecked()) {
+ protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) {
+ if (alwaysCheck) {
// Build a reasonable intent filter, based on what matched.
IntentFilter filter = new IntentFilter();
@@ -190,7 +202,6 @@
if (intent != null) {
startActivity(intent);
}
- finish();
}
private final class DisplayResolveInfo {
diff --git a/core/jni/android_os_ParcelFileDescriptor.cpp b/core/jni/android_os_ParcelFileDescriptor.cpp
index eceef1c..1f737f9 100644
--- a/core/jni/android_os_ParcelFileDescriptor.cpp
+++ b/core/jni/android_os_ParcelFileDescriptor.cpp
@@ -126,6 +126,17 @@
return lseek(fd, pos, SEEK_SET);
}
+static jlong android_os_ParcelFileDescriptor_getFdNative(JNIEnv* env, jobject clazz)
+{
+ jint fd = getFd(env, clazz);
+ if (fd < 0) {
+ jniThrowException(env, "java/lang/IllegalArgumentException", "bad file descriptor");
+ return -1;
+ }
+
+ return fd;
+}
+
static const JNINativeMethod gParcelFileDescriptorMethods[] = {
{"getFileDescriptorFromSocket", "(Ljava/net/Socket;)Ljava/io/FileDescriptor;",
(void*)android_os_ParcelFileDescriptor_getFileDescriptorFromSocket},
@@ -134,7 +145,9 @@
{"getStatSize", "()J",
(void*)android_os_ParcelFileDescriptor_getStatSize},
{"seekTo", "(J)J",
- (void*)android_os_ParcelFileDescriptor_seekTo}
+ (void*)android_os_ParcelFileDescriptor_seekTo},
+ {"getFdNative", "()I",
+ (void*)android_os_ParcelFileDescriptor_getFdNative}
};
const char* const kParcelFileDescriptorPathName = "android/os/ParcelFileDescriptor";
diff --git a/core/jni/android_util_Binder.cpp b/core/jni/android_util_Binder.cpp
index 7a53874..15362eb 100644
--- a/core/jni/android_util_Binder.cpp
+++ b/core/jni/android_util_Binder.cpp
@@ -31,6 +31,8 @@
#include <binder/IPCThreadState.h>
#include <utils/Log.h>
#include <utils/SystemClock.h>
+#include <utils/List.h>
+#include <utils/KeyedVector.h>
#include <cutils/logger.h>
#include <binder/Parcel.h>
#include <binder/ProcessState.h>
@@ -322,25 +324,15 @@
class JavaBBinderHolder : public RefBase
{
public:
- JavaBBinderHolder(JNIEnv* env, jobject object)
- : mObject(object)
- {
- LOGV("Creating JavaBBinderHolder for Object %p\n", object);
- }
- ~JavaBBinderHolder()
- {
- LOGV("Destroying JavaBBinderHolder for Object %p\n", mObject);
- }
-
- sp<JavaBBinder> get(JNIEnv* env)
+ sp<JavaBBinder> get(JNIEnv* env, jobject obj)
{
AutoMutex _l(mLock);
sp<JavaBBinder> b = mBinder.promote();
if (b == NULL) {
- b = new JavaBBinder(env, mObject);
+ b = new JavaBBinder(env, obj);
mBinder = b;
LOGV("Creating JavaBinder %p (refs %p) for Object %p, weakCount=%d\n",
- b.get(), b->getWeakRefs(), mObject, b->getWeakRefs()->getWeakCount());
+ b.get(), b->getWeakRefs(), obj, b->getWeakRefs()->getWeakCount());
}
return b;
@@ -354,20 +346,41 @@
private:
Mutex mLock;
- jobject mObject;
wp<JavaBBinder> mBinder;
};
// ----------------------------------------------------------------------------
+// Per-IBinder death recipient bookkeeping. This is how we reconcile local jobject
+// death recipient references passed in through JNI with the permanent corresponding
+// JavaDeathRecipient objects.
+
+class JavaDeathRecipient;
+
+class DeathRecipientList : public RefBase {
+ List< sp<JavaDeathRecipient> > mList;
+ Mutex mLock;
+
+public:
+ ~DeathRecipientList();
+
+ void add(const sp<JavaDeathRecipient>& recipient);
+ void remove(const sp<JavaDeathRecipient>& recipient);
+ sp<JavaDeathRecipient> find(jobject recipient);
+};
+
+// ----------------------------------------------------------------------------
+
class JavaDeathRecipient : public IBinder::DeathRecipient
{
public:
- JavaDeathRecipient(JNIEnv* env, jobject object)
- : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)),
- mHoldsRef(true)
+ JavaDeathRecipient(JNIEnv* env, jobject object, sp<DeathRecipientList>& list)
+ : mVM(jnienv_to_javavm(env)), mObject(env->NewGlobalRef(object)), mList(list)
{
- incStrong(this);
+ // These objects manage their own lifetimes so are responsible for final bookkeeping.
+ // The list holds a strong reference to this object.
+ mList->add(this);
+
android_atomic_inc(&gNumDeathRefs);
incRefsCreated(env);
}
@@ -391,16 +404,12 @@
void clearReference()
{
- bool release = false;
- mLock.lock();
- if (mHoldsRef) {
- mHoldsRef = false;
- release = true;
- }
- mLock.unlock();
- if (release) {
- decStrong(this);
- }
+ mList->remove(this);
+ }
+
+ bool matches(jobject obj) {
+ JNIEnv* env = javavm_to_jnienv(mVM);
+ return env->IsSameObject(obj, mObject);
}
protected:
@@ -415,12 +424,57 @@
private:
JavaVM* const mVM;
jobject const mObject;
- Mutex mLock;
- bool mHoldsRef;
+ sp<DeathRecipientList> mList;
};
// ----------------------------------------------------------------------------
+DeathRecipientList::~DeathRecipientList() {
+ AutoMutex _l(mLock);
+
+ // Should never happen -- the JavaDeathRecipient objects that have added themselves
+ // to the list are holding references on the list object. Only when they are torn
+ // down can the list header be destroyed.
+ if (mList.size() > 0) {
+ LOGE("Retiring binder %p with extant death recipients\n", this);
+ }
+}
+
+void DeathRecipientList::add(const sp<JavaDeathRecipient>& recipient) {
+ AutoMutex _l(mLock);
+
+ mList.push_back(recipient);
+}
+
+void DeathRecipientList::remove(const sp<JavaDeathRecipient>& recipient) {
+ AutoMutex _l(mLock);
+
+ List< sp<JavaDeathRecipient> >::iterator iter;
+ for (iter = mList.begin(); iter != mList.end(); iter++) {
+ if (*iter == recipient) {
+ mList.erase(iter);
+ return;
+ }
+ }
+}
+
+sp<JavaDeathRecipient> DeathRecipientList::find(jobject recipient) {
+ AutoMutex _l(mLock);
+
+ List< sp<JavaDeathRecipient> >::iterator iter;
+ for (iter = mList.begin(); iter != mList.end(); iter++) {
+ if ((*iter)->matches(recipient)) {
+ return *iter;
+ }
+ }
+ return NULL;
+}
+
+static KeyedVector<IBinder*, sp<DeathRecipientList> > gDeathRecipientsByIBinder;
+static Mutex gDeathRecipientMapLock;
+
+// ----------------------------------------------------------------------------
+
namespace android {
static void proxy_cleanup(const void* id, void* obj, void* cleanupCookie)
@@ -490,7 +544,7 @@
if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
JavaBBinderHolder* jbh = (JavaBBinderHolder*)
env->GetIntField(obj, gBinderOffsets.mObject);
- return jbh != NULL ? jbh->get(env) : NULL;
+ return jbh != NULL ? jbh->get(env, obj) : NULL;
}
if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
@@ -621,26 +675,26 @@
IPCThreadState::self()->flushCommands();
}
-static void android_os_Binder_init(JNIEnv* env, jobject clazz)
+static void android_os_Binder_init(JNIEnv* env, jobject obj)
{
- JavaBBinderHolder* jbh = new JavaBBinderHolder(env, clazz);
+ JavaBBinderHolder* jbh = new JavaBBinderHolder();
if (jbh == NULL) {
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
return;
}
- LOGV("Java Binder %p: acquiring first ref on holder %p", clazz, jbh);
- jbh->incStrong(clazz);
- env->SetIntField(clazz, gBinderOffsets.mObject, (int)jbh);
+ LOGV("Java Binder %p: acquiring first ref on holder %p", obj, jbh);
+ jbh->incStrong((void*)android_os_Binder_init);
+ env->SetIntField(obj, gBinderOffsets.mObject, (int)jbh);
}
-static void android_os_Binder_destroy(JNIEnv* env, jobject clazz)
+static void android_os_Binder_destroy(JNIEnv* env, jobject obj)
{
JavaBBinderHolder* jbh = (JavaBBinderHolder*)
- env->GetIntField(clazz, gBinderOffsets.mObject);
+ env->GetIntField(obj, gBinderOffsets.mObject);
if (jbh != NULL) {
- env->SetIntField(clazz, gBinderOffsets.mObject, 0);
- LOGV("Java Binder %p: removing ref on holder %p", clazz, jbh);
- jbh->decStrong(clazz);
+ env->SetIntField(obj, gBinderOffsets.mObject, 0);
+ LOGV("Java Binder %p: removing ref on holder %p", obj, jbh);
+ jbh->decStrong((void*)android_os_Binder_init);
} else {
// Encountering an uninitialized binder is harmless. All it means is that
// the Binder was only partially initialized when its finalizer ran and called
@@ -648,7 +702,7 @@
// For example, a Binder subclass constructor might have thrown an exception before
// it could delegate to its superclass's constructor. Consequently init() would
// not have been called and the holder pointer would remain NULL.
- LOGV("Java Binder %p: ignoring uninitialized binder", clazz);
+ LOGV("Java Binder %p: ignoring uninitialized binder", obj);
}
}
@@ -973,8 +1027,25 @@
LOGV("linkToDeath: binder=%p recipient=%p\n", target, recipient);
if (!target->localBinder()) {
- sp<JavaDeathRecipient> jdr = new JavaDeathRecipient(env, recipient);
- status_t err = target->linkToDeath(jdr, recipient, flags);
+ sp<JavaDeathRecipient> jdr;
+
+ {
+ sp<DeathRecipientList> list;
+ AutoMutex _maplocker(gDeathRecipientMapLock);
+
+ ssize_t listIndex = gDeathRecipientsByIBinder.indexOfKey(target);
+ if (listIndex < 0) {
+ // Set up the death notice bookkeeping for this binder lazily
+ list = new DeathRecipientList;
+ gDeathRecipientsByIBinder.add(target, list);
+ } else {
+ list = gDeathRecipientsByIBinder.valueAt(listIndex);
+ }
+
+ jdr = new JavaDeathRecipient(env, recipient, list);
+ }
+
+ status_t err = target->linkToDeath(jdr, NULL, flags);
if (err != NO_ERROR) {
// Failure adding the death recipient, so clear its reference
// now.
@@ -1003,15 +1074,33 @@
LOGV("unlinkToDeath: binder=%p recipient=%p\n", target, recipient);
if (!target->localBinder()) {
- wp<IBinder::DeathRecipient> dr;
- status_t err = target->unlinkToDeath(NULL, recipient, flags, &dr);
- if (err == NO_ERROR && dr != NULL) {
- sp<IBinder::DeathRecipient> sdr = dr.promote();
- JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
- if (jdr != NULL) {
- jdr->clearReference();
+ status_t err = NAME_NOT_FOUND;
+ sp<JavaDeathRecipient> origJDR;
+ {
+ AutoMutex _maplocker(gDeathRecipientMapLock);
+ ssize_t listIndex = gDeathRecipientsByIBinder.indexOfKey(target);
+ if (listIndex >= 0) {
+ sp<DeathRecipientList> list = gDeathRecipientsByIBinder.valueAt(listIndex);
+ origJDR = list->find(recipient);
+ } else {
+ // If there is no DeathRecipientList for this binder, it means the binder
+ // is dead and in the process of being cleaned up.
+ err = DEAD_OBJECT;
}
}
+ // If we found the matching recipient, proceed to unlink using that
+ if (origJDR != NULL) {
+ wp<IBinder::DeathRecipient> dr;
+ err = target->unlinkToDeath(origJDR, NULL, flags, &dr);
+ if (err == NO_ERROR && dr != NULL) {
+ sp<IBinder::DeathRecipient> sdr = dr.promote();
+ JavaDeathRecipient* jdr = static_cast<JavaDeathRecipient*>(sdr.get());
+ if (jdr != NULL) {
+ jdr->clearReference();
+ }
+ }
+ }
+
if (err == NO_ERROR || err == DEAD_OBJECT) {
res = JNI_TRUE;
} else {
@@ -1031,6 +1120,15 @@
env->SetIntField(obj, gBinderProxyOffsets.mObject, 0);
b->decStrong(obj);
IPCThreadState::self()->flushCommands();
+
+ // tear down the death recipient bookkeeping
+ {
+ AutoMutex _maplocker(gDeathRecipientMapLock);
+ ssize_t listIndex = gDeathRecipientsByIBinder.indexOfKey(b);
+ if (listIndex >= 0) {
+ gDeathRecipientsByIBinder.removeItemsAt((size_t)listIndex);
+ }
+ }
}
// ----------------------------------------------------------------------------
@@ -1152,15 +1250,13 @@
if (parcel == NULL) {
return;
}
- void *dest;
const status_t err = parcel->writeInt32(length);
if (err != NO_ERROR) {
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
}
- dest = parcel->writeInplace(length);
-
+ void* dest = parcel->writeInplace(length);
if (dest == NULL) {
jniThrowException(env, "java/lang/OutOfMemoryError", NULL);
return;
@@ -1168,7 +1264,7 @@
jbyte* ar = (jbyte*)env->GetPrimitiveArrayCritical((jarray)data, 0);
if (ar) {
- memcpy(dest, ar, length);
+ memcpy(dest, ar + offset, length);
env->ReleasePrimitiveArrayCritical((jarray)data, ar, 0);
}
}
@@ -1424,6 +1520,14 @@
}
}
+static void android_os_Parcel_clearFileDescriptor(JNIEnv* env, jobject clazz, jobject object)
+{
+ int fd = env->GetIntField(object, gFileDescriptorOffsets.mDescriptor);
+ if (fd >= 0) {
+ env->SetIntField(object, gFileDescriptorOffsets.mDescriptor, -1);
+ }
+}
+
static void android_os_Parcel_freeBuffer(JNIEnv* env, jobject clazz)
{
int32_t own = env->GetIntField(clazz, gParcelOffsets.mOwnObject);
@@ -1623,6 +1727,7 @@
{"internalReadFileDescriptor", "()Ljava/io/FileDescriptor;", (void*)android_os_Parcel_readFileDescriptor},
{"openFileDescriptor", "(Ljava/lang/String;I)Ljava/io/FileDescriptor;", (void*)android_os_Parcel_openFileDescriptor},
{"closeFileDescriptor", "(Ljava/io/FileDescriptor;)V", (void*)android_os_Parcel_closeFileDescriptor},
+ {"clearFileDescriptor", "(Ljava/io/FileDescriptor;)V", (void*)android_os_Parcel_clearFileDescriptor},
{"freeBuffer", "()V", (void*)android_os_Parcel_freeBuffer},
{"init", "(I)V", (void*)android_os_Parcel_init},
{"destroy", "()V", (void*)android_os_Parcel_destroy},
diff --git a/core/jni/android_view_Display.cpp b/core/jni/android_view_Display.cpp
index ac8835a..160d654 100644
--- a/core/jni/android_view_Display.cpp
+++ b/core/jni/android_view_Display.cpp
@@ -44,6 +44,8 @@
};
static offsets_t offsets;
+static int gShortSize = -1;
+static int gLongSize = -1;
static int gOldSize = -1;
static int gNewSize = -1;
@@ -76,6 +78,10 @@
{
DisplayID dpy = env->GetIntField(clazz, offsets.display);
jint w = SurfaceComposerClient::getDisplayWidth(dpy);
+ if (gShortSize > 0) {
+ jint h = SurfaceComposerClient::getDisplayHeight(dpy);
+ return w < h ? gShortSize : gLongSize;
+ }
return w == gOldSize ? gNewSize : w;
}
@@ -84,9 +90,27 @@
{
DisplayID dpy = env->GetIntField(clazz, offsets.display);
int h = SurfaceComposerClient::getDisplayHeight(dpy);
+ if (gShortSize > 0) {
+ jint w = SurfaceComposerClient::getDisplayWidth(dpy);
+ return h < w ? gShortSize : gLongSize;
+ }
return h == gOldSize ? gNewSize : h;
}
+static jint android_view_Display_getRealWidth(
+ JNIEnv* env, jobject clazz)
+{
+ DisplayID dpy = env->GetIntField(clazz, offsets.display);
+ return SurfaceComposerClient::getDisplayWidth(dpy);
+}
+
+static jint android_view_Display_getRealHeight(
+ JNIEnv* env, jobject clazz)
+{
+ DisplayID dpy = env->GetIntField(clazz, offsets.display);
+ return SurfaceComposerClient::getDisplayHeight(dpy);
+}
+
static jint android_view_Display_getOrientation(
JNIEnv* env, jobject clazz)
{
@@ -100,13 +124,6 @@
return SurfaceComposerClient::getNumberOfDisplays();
}
-static jint android_view_Display_unmapDisplaySize(
- JNIEnv* env, jclass clazz, jint newSize)
-{
- if (newSize == gNewSize) return gOldSize;
- return newSize;
-}
-
// ----------------------------------------------------------------------------
const char* const kClassPathName = "android/view/Display";
@@ -124,10 +141,12 @@
(void*)android_view_Display_getWidth },
{ "getHeight", "()I",
(void*)android_view_Display_getHeight },
+ { "getRealWidth", "()I",
+ (void*)android_view_Display_getRealWidth },
+ { "getRealHeight", "()I",
+ (void*)android_view_Display_getRealHeight },
{ "getOrientation", "()I",
- (void*)android_view_Display_getOrientation },
- { "unmapDisplaySize", "(I)I",
- (void*)android_view_Display_unmapDisplaySize }
+ (void*)android_view_Display_getOrientation }
};
void nativeClassInit(JNIEnv* env, jclass clazz)
@@ -146,7 +165,15 @@
int len = property_get("persist.demo.screensizehack", buf, "");
if (len > 0) {
int temp1, temp2;
- if (sscanf(buf, "%d=%d", &temp1, &temp2) == 2) {
+ if (sscanf(buf, "%dx%d", &temp1, &temp2) == 2) {
+ if (temp1 < temp2) {
+ gShortSize = temp1;
+ gLongSize = temp2;
+ } else {
+ gShortSize = temp2;
+ gLongSize = temp1;
+ }
+ } else if (sscanf(buf, "%d=%d", &temp1, &temp2) == 2) {
gOldSize = temp1;
gNewSize = temp2;
}
@@ -157,4 +184,3 @@
}
};
-
diff --git a/core/jni/android_view_Surface.cpp b/core/jni/android_view_Surface.cpp
index be66e9c..bd2e669 100644
--- a/core/jni/android_view_Surface.cpp
+++ b/core/jni/android_view_Surface.cpp
@@ -177,7 +177,7 @@
sp<ANativeWindow> android_Surface_getNativeWindow(
JNIEnv* env, jobject clazz) {
- return getSurface(env, clazz).get();
+ return getSurface(env, clazz);
}
static void setSurface(JNIEnv* env, jobject clazz, const sp<Surface>& surface)
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index beb824c..50d3fb8 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -466,12 +466,13 @@
android:label="@string/permlab_flashlight"
android:description="@string/permdesc_flashlight" />
- <!-- Allows an application to access USB devices -->
- <permission android:name="android.permission.ACCESS_USB"
+ <!-- Allows an application to manage preferences and permissions for USB devices
+ @hide -->
+ <permission android:name="android.permission.MANAGE_USB"
android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
- android:protectionLevel="normal"
- android:label="@string/permlab_accessUsb"
- android:description="@string/permdesc_accessUsb" />
+ android:protectionLevel="signatureOrSystem"
+ android:label="@string/permlab_manageUsb"
+ android:description="@string/permdesc_manageUsb" />
<!-- Allows an application to access the MTP USB kernel driver.
For use only by the device side MTP implementation.
@@ -1372,11 +1373,18 @@
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
+
<activity android:name="com.android.internal.app.NetInitiatedActivity"
android:theme="@style/Theme.Holo.Dialog.Alert"
android:excludeFromRecents="true">
</activity>
+ <activity android:name="com.android.server.usb.UsbResolverActivity"
+ android:theme="@style/Theme.Holo.Dialog.Alert"
+ android:finishOnCloseSystemDialogs="true"
+ android:excludeFromRecents="true">
+ </activity>
+
<service android:name="com.android.server.LoadAverageService"
android:exported="true" />
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index cb44a3a..c815758 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -296,9 +296,6 @@
<!-- Indicate whether the SD card is accessible without removing the battery. -->
<bool name="config_batterySdCardAccessibility">false</bool>
- <!-- Indicate whether the device has USB host support. -->
- <bool name="config_hasUsbHostSupport">false</bool>
-
<!-- List of file paths for USB host busses to exclude from USB host support.
For example, if the first USB bus on the device is used to communicate
with the modem or some other restricted hardware, add "/dev/bus/usb/001/"
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 28690f5..8ef9a3b 100755
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -1031,9 +1031,9 @@
the flashlight.</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_accessUsb">access USB devices</string>
+ <string name="permlab_manageUsb">manage preferences and permissions for USB devices</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_accessUsb">Allows the application to access USB devices.</string>
+ <string name="permdesc_manageUsb">Allows the application to manage preferences and permissions for 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>
@@ -2302,6 +2302,8 @@
<string name="clearDefaultHintMsg">Clear default in Home Settings > Applications > Manage applications.</string>
<!-- Default title for the activity chooser, when one is not given. Android allows multiple activities to perform an action. for example, there may be many ringtone pickers installed. A dialog is shown to the user allowing him to pick which activity should be used. This is the title. -->
<string name="chooseActivity">Select an action</string>
+ <!-- title for the USB activity chooser. -->
+ <string name="chooseUsbActivity">Select an application for the USB device</string>
<!-- Text to display when there are no activities found to display in the
activity chooser. See the "Select an action" title. -->
<string name="noApplications">No applications can perform this action.</string>
diff --git a/data/etc/android.hardware.usb.accessory.xml b/data/etc/android.hardware.usb.accessory.xml
new file mode 100644
index 0000000..29df966
--- /dev/null
+++ b/data/etc/android.hardware.usb.accessory.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.
+-->
+
+<!-- This is the standard feature indicating that the device supports USB accessories. -->
+<permissions>
+ <feature name="android.hardware.usb.accessory" />
+</permissions>
diff --git a/data/etc/android.hardware.usb.host.xml b/data/etc/android.hardware.usb.host.xml
new file mode 100644
index 0000000..b0ca82c
--- /dev/null
+++ b/data/etc/android.hardware.usb.host.xml
@@ -0,0 +1,21 @@
+<?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.
+-->
+
+<!-- This is the standard feature indicating that the device can communicate
+ with USB devices as the USB host. -->
+<permissions>
+ <feature name="android.hardware.usb.host" />
+</permissions>
diff --git a/data/etc/com.google.android.usb.xml b/data/etc/com.google.android.usb.xml
new file mode 100644
index 0000000..fae3d23
--- /dev/null
+++ b/data/etc/com.google.android.usb.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.
+-->
+
+<permissions>
+ <library name="com.google.android.usb"
+ file="/system/framework/com.google.android.usb.jar" />
+</permissions>
diff --git a/docs/html/resources/resources-data.js b/docs/html/resources/resources-data.js
index e919de9..14118bb 100644
--- a/docs/html/resources/resources-data.js
+++ b/docs/html/resources/resources-data.js
@@ -497,12 +497,12 @@
},
{
tags: ['sample', 'new', 'newfeature', 'performance', 'gamedev', 'gl'],
- path: 'samples/Renderscript/index.html',
+ path: 'samples/RenderScript/index.html',
title: {
- en: 'Renderscript'
+ en: 'RenderScript'
},
description: {
- en: 'A set of samples that demonstrate how to use various features of the Renderscript APIs.'
+ en: 'A set of samples that demonstrate how to use various features of the RenderScript APIs.'
}
},
{
diff --git a/graphics/java/android/renderscript/Element.java b/graphics/java/android/renderscript/Element.java
index 4fc419c..fae22f00 100644
--- a/graphics/java/android/renderscript/Element.java
+++ b/graphics/java/android/renderscript/Element.java
@@ -21,7 +21,7 @@
/**
* <p>The most basic data type. An element represents one cell of a memory allocation.
- * Element is the basic data type of Renderscript. An element can be of two forms: Basic elements or Complex forms.
+ * Element is the basic data type of Renderscript. An element can be of two forms: Basic elements or Complex forms.
* Examples of basic elements are:</p>
* <ul>
* <li>Single float value</li>
@@ -29,7 +29,7 @@
* <li>single RGB-565 color</li>
* <li>single unsigned int 16</li>
* </ul>
- * <p>Complex elements contain a list of sub-elements and names that
+ * <p>Complex elements contain a list of sub-elements and names that
* represents a structure of data. The fields can be accessed by name
* from a script or shader. The memory layout is defined and ordered. Data
* alignment is determinied by the most basic primitive type. i.e. a float4
@@ -403,7 +403,7 @@
if(rs.mElement_MATRIX_3X3 == null) {
rs.mElement_MATRIX_3X3 = createUser(rs, DataType.MATRIX_3X3);
}
- return rs.mElement_MATRIX_4X4;
+ return rs.mElement_MATRIX_3X3;
}
public static Element MATRIX_2X2(RenderScript rs) {
diff --git a/include/binder/IBinder.h b/include/binder/IBinder.h
index 749a977..81b56c2 100644
--- a/include/binder/IBinder.h
+++ b/include/binder/IBinder.h
@@ -98,7 +98,7 @@
* Register the @a recipient for a notification if this binder
* goes away. If this binder object unexpectedly goes away
* (typically because its hosting process has been killed),
- * then DeathRecipient::binderDied() will be called with a referene
+ * then DeathRecipient::binderDied() will be called with a reference
* to this.
*
* The @a cookie is optional -- if non-NULL, it should be a
diff --git a/include/utils/StrongPointer.h b/include/utils/StrongPointer.h
index a8c9897..49fa3a8 100644
--- a/include/utils/StrongPointer.h
+++ b/include/utils/StrongPointer.h
@@ -133,7 +133,7 @@
template<typename T> template<typename U>
sp<T>::sp(U* other) : m_ptr(other)
{
- if (other) other->incStrong(this);
+ if (other) ((T*)other)->incStrong(this);
}
template<typename T> template<typename U>
@@ -170,7 +170,7 @@
template<typename T> template<typename U>
sp<T>& sp<T>::operator = (const sp<U>& other)
{
- U* otherPtr(other.m_ptr);
+ T* otherPtr(other.m_ptr);
if (otherPtr) otherPtr->incStrong(this);
if (m_ptr) m_ptr->decStrong(this);
m_ptr = otherPtr;
@@ -180,7 +180,7 @@
template<typename T> template<typename U>
sp<T>& sp<T>::operator = (U* other)
{
- if (other) other->incStrong(this);
+ if (other) ((T*)other)->incStrong(this);
if (m_ptr) m_ptr->decStrong(this);
m_ptr = other;
return *this;
diff --git a/libs/rs/Android.mk b/libs/rs/Android.mk
index 25c8beb..5ab4804 100644
--- a/libs/rs/Android.mk
+++ b/libs/rs/Android.mk
@@ -152,9 +152,4 @@
include $(BUILD_HOST_STATIC_LIBRARY)
-# include the java examples
-include $(addprefix $(LOCAL_PATH)/,$(addsuffix /Android.mk,\
- java \
- ))
-
endif #simulator
diff --git a/libs/rs/java/Android.mk b/libs/rs/java/Android.mk
deleted file mode 100644
index 5053e7d..0000000
--- a/libs/rs/java/Android.mk
+++ /dev/null
@@ -1 +0,0 @@
-include $(call all-subdir-makefiles)
diff --git a/libs/rs/java/Balls/Android.mk b/libs/rs/java/Balls/Android.mk
deleted file mode 100644
index 5b65628..0000000
--- a/libs/rs/java/Balls/Android.mk
+++ /dev/null
@@ -1,31 +0,0 @@
-#
-# Copyright (C) 2008 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-ifneq ($(TARGET_SIMULATOR),true)
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src) $(call all-renderscript-files-under, src)
-#LOCAL_STATIC_JAVA_LIBRARIES := android.renderscript
-
-LOCAL_PACKAGE_NAME := Balls
-
-include $(BUILD_PACKAGE)
-
-endif
diff --git a/libs/rs/java/Balls/AndroidManifest.xml b/libs/rs/java/Balls/AndroidManifest.xml
deleted file mode 100644
index f3384ec..0000000
--- a/libs/rs/java/Balls/AndroidManifest.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.balls">
- <uses-sdk android:minSdkVersion="11" />
- <application
- android:label="Balls"
- android:icon="@drawable/test_pattern">
- <activity android:name="Balls"
- android:screenOrientation="landscape">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
-</manifest>
diff --git a/libs/rs/java/Balls/_index.html b/libs/rs/java/Balls/_index.html
deleted file mode 100644
index 8760485..0000000
--- a/libs/rs/java/Balls/_index.html
+++ /dev/null
@@ -1 +0,0 @@
-<p>A brute force physics simulation that renders many balls onto the screen and moves them according to user touch and gravity.</p>
\ No newline at end of file
diff --git a/libs/rs/java/Balls/res/drawable/flares.png b/libs/rs/java/Balls/res/drawable/flares.png
deleted file mode 100644
index 3a5c970..0000000
--- a/libs/rs/java/Balls/res/drawable/flares.png
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/Balls/res/drawable/test_pattern.png b/libs/rs/java/Balls/res/drawable/test_pattern.png
deleted file mode 100644
index e7d1455..0000000
--- a/libs/rs/java/Balls/res/drawable/test_pattern.png
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/Balls/src/com/android/balls/Balls.java b/libs/rs/java/Balls/src/com/android/balls/Balls.java
deleted file mode 100644
index c24e616..0000000
--- a/libs/rs/java/Balls/src/com/android/balls/Balls.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.balls;
-
-import android.renderscript.RSSurfaceView;
-import android.renderscript.RenderScript;
-
-import android.app.Activity;
-import android.content.res.Configuration;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.provider.Settings.System;
-import android.util.Config;
-import android.util.Log;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.Window;
-import android.widget.Button;
-import android.widget.ListView;
-
-import java.lang.Runtime;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Bundle;
-import android.view.View;
-import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.SensorEventListener;
-import android.hardware.SensorManager;
-
-public class Balls extends Activity implements SensorEventListener {
- //EventListener mListener = new EventListener();
-
- private static final String LOG_TAG = "libRS_jni";
- private static final boolean DEBUG = false;
- private static final boolean LOG_ENABLED = DEBUG ? Config.LOGD : Config.LOGV;
-
- private BallsView mView;
- private SensorManager mSensorManager;
-
- // get the current looper (from your Activity UI thread for instance
-
-
- public void onSensorChanged(SensorEvent event) {
- //android.util.Log.d("rs", "sensor: " + event.sensor + ", x: " + event.values[0] + ", y: " + event.values[1] + ", z: " + event.values[2]);
- synchronized (this) {
- if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
- if(mView != null) {
- mView.setAccel(event.values[0], event.values[1], event.values[2]);
- }
- }
- }
- }
-
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- }
-
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
-
- mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
-
- // Create our Preview view and set it as the content of our
- // Activity
- mView = new BallsView(this);
- setContentView(mView);
- }
-
- @Override
- protected void onResume() {
- mSensorManager.registerListener(this,
- mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
- SensorManager.SENSOR_DELAY_FASTEST);
-
- // Ideally a game should implement onResume() and onPause()
- // to take appropriate action when the activity looses focus
- super.onResume();
- mView.resume();
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- mView.pause();
- Runtime.getRuntime().exit(0);
- }
-
- @Override
- protected void onStop() {
- mSensorManager.unregisterListener(this);
- super.onStop();
- }
-
- static void log(String message) {
- if (LOG_ENABLED) {
- Log.v(LOG_TAG, message);
- }
- }
-
-
-}
-
diff --git a/libs/rs/java/Balls/src/com/android/balls/BallsRS.java b/libs/rs/java/Balls/src/com/android/balls/BallsRS.java
deleted file mode 100644
index 50ee921..0000000
--- a/libs/rs/java/Balls/src/com/android/balls/BallsRS.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.balls;
-
-import android.content.res.Resources;
-import android.renderscript.*;
-import android.util.Log;
-
-public class BallsRS {
- public static final int PART_COUNT = 900;
-
- public BallsRS() {
- }
-
- private Resources mRes;
- private RenderScriptGL mRS;
- private ScriptC_balls mScript;
- private ScriptC_ball_physics mPhysicsScript;
- private ProgramFragment mPFLines;
- private ProgramFragment mPFPoints;
- private ProgramVertex mPV;
- private ScriptField_Point mPoints;
- private ScriptField_VpConsts mVpConsts;
-
- void updateProjectionMatrices() {
- mVpConsts = new ScriptField_VpConsts(mRS, 1,
- Allocation.USAGE_SCRIPT |
- Allocation.USAGE_GRAPHICS_CONSTANTS);
- ScriptField_VpConsts.Item i = new ScriptField_VpConsts.Item();
- Matrix4f mvp = new Matrix4f();
- mvp.loadOrtho(0, mRS.getWidth(), mRS.getHeight(), 0, -1, 1);
- i.MVP = mvp;
- mVpConsts.set(i, 0, true);
- }
-
- private void createProgramVertex() {
- updateProjectionMatrices();
-
- ProgramVertex.Builder sb = new ProgramVertex.Builder(mRS);
- String t = "varying vec4 varColor;\n" +
- "void main() {\n" +
- " vec4 pos = vec4(0.0, 0.0, 0.0, 1.0);\n" +
- " pos.xy = ATTRIB_position;\n" +
- " gl_Position = UNI_MVP * pos;\n" +
- " varColor = vec4(1.0, 1.0, 1.0, 1.0);\n" +
- " gl_PointSize = ATTRIB_size;\n" +
- "}\n";
- sb.setShader(t);
- sb.addConstant(mVpConsts.getType());
- sb.addInput(mPoints.getElement());
- ProgramVertex pvs = sb.create();
- pvs.bindConstants(mVpConsts.getAllocation(), 0);
- mRS.bindProgramVertex(pvs);
- }
-
- private Allocation loadTexture(int id) {
- final Allocation allocation =
- Allocation.createFromBitmapResource(mRS, mRes,
- id, Allocation.MipmapControl.MIPMAP_NONE,
- Allocation.USAGE_GRAPHICS_TEXTURE);
- return allocation;
- }
-
- ProgramStore BLEND_ADD_DEPTH_NONE(RenderScript rs) {
- ProgramStore.Builder builder = new ProgramStore.Builder(rs);
- builder.setDepthFunc(ProgramStore.DepthFunc.ALWAYS);
- builder.setBlendFunc(ProgramStore.BlendSrcFunc.ONE, ProgramStore.BlendDstFunc.ONE);
- builder.setDitherEnabled(false);
- builder.setDepthMaskEnabled(false);
- return builder.create();
- }
-
- public void init(RenderScriptGL rs, Resources res, int width, int height) {
- mRS = rs;
- mRes = res;
-
- ProgramFragmentFixedFunction.Builder pfb = new ProgramFragmentFixedFunction.Builder(rs);
- pfb.setPointSpriteTexCoordinateReplacement(true);
- pfb.setTexture(ProgramFragmentFixedFunction.Builder.EnvMode.MODULATE,
- ProgramFragmentFixedFunction.Builder.Format.RGBA, 0);
- pfb.setVaryingColor(true);
- mPFPoints = pfb.create();
-
- pfb = new ProgramFragmentFixedFunction.Builder(rs);
- pfb.setVaryingColor(true);
- mPFLines = pfb.create();
-
- android.util.Log.e("rs", "Load texture");
- mPFPoints.bindTexture(loadTexture(R.drawable.flares), 0);
-
- mPoints = new ScriptField_Point(mRS, PART_COUNT, Allocation.USAGE_SCRIPT);
-
- Mesh.AllocationBuilder smb = new Mesh.AllocationBuilder(mRS);
- smb.addVertexAllocation(mPoints.getAllocation());
- smb.addIndexSetType(Mesh.Primitive.POINT);
- Mesh smP = smb.create();
-
- mPhysicsScript = new ScriptC_ball_physics(mRS, mRes, R.raw.ball_physics);
-
- mScript = new ScriptC_balls(mRS, mRes, R.raw.balls);
- mScript.set_partMesh(smP);
- mScript.set_physics_script(mPhysicsScript);
- mScript.bind_point(mPoints);
- mScript.bind_balls1(new ScriptField_Ball(mRS, PART_COUNT, Allocation.USAGE_SCRIPT));
- mScript.bind_balls2(new ScriptField_Ball(mRS, PART_COUNT, Allocation.USAGE_SCRIPT));
-
- mScript.set_gPFLines(mPFLines);
- mScript.set_gPFPoints(mPFPoints);
- createProgramVertex();
-
- mRS.bindProgramStore(BLEND_ADD_DEPTH_NONE(mRS));
-
- mPhysicsScript.set_gMinPos(new Float2(5, 5));
- mPhysicsScript.set_gMaxPos(new Float2(width - 5, height - 5));
-
- mScript.invoke_initParts(width, height);
-
- mRS.bindRootScript(mScript);
- }
-
- public void newTouchPosition(float x, float y, float pressure, int id) {
- mPhysicsScript.invoke_touch(x, y, pressure, id);
- }
-
- public void setAccel(float x, float y) {
- mPhysicsScript.set_gGravityVector(new Float2(x, y));
- }
-
-}
diff --git a/libs/rs/java/Balls/src/com/android/balls/BallsView.java b/libs/rs/java/Balls/src/com/android/balls/BallsView.java
deleted file mode 100644
index 4442eec..0000000
--- a/libs/rs/java/Balls/src/com/android/balls/BallsView.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.balls;
-
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.concurrent.Semaphore;
-
-import android.renderscript.RSSurfaceView;
-import android.renderscript.RenderScript;
-import android.renderscript.RenderScriptGL;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.Drawable;
-import android.os.Handler;
-import android.os.Message;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.view.Surface;
-import android.view.SurfaceHolder;
-import android.view.SurfaceView;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-
-public class BallsView extends RSSurfaceView {
-
- public BallsView(Context context) {
- super(context);
- //setFocusable(true);
- }
-
- private RenderScriptGL mRS;
- private BallsRS mRender;
-
- public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
- super.surfaceChanged(holder, format, w, h);
- if (mRS == null) {
- RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig();
- mRS = createRenderScriptGL(sc);
- mRS.setSurface(holder, w, h);
- mRender = new BallsRS();
- mRender.init(mRS, getResources(), w, h);
- }
- mRender.updateProjectionMatrices();
- }
-
- @Override
- protected void onDetachedFromWindow() {
- if(mRS != null) {
- mRS = null;
- destroyRenderScriptGL();
- }
- }
-
-
- @Override
- public boolean onTouchEvent(MotionEvent ev)
- {
- int act = ev.getActionMasked();
- if (act == ev.ACTION_UP) {
- mRender.newTouchPosition(0, 0, 0, ev.getPointerId(0));
- return false;
- } else if (act == MotionEvent.ACTION_POINTER_UP) {
- // only one pointer going up, we can get the index like this
- int pointerIndex = ev.getActionIndex();
- int pointerId = ev.getPointerId(pointerIndex);
- mRender.newTouchPosition(0, 0, 0, pointerId);
- return false;
- }
- int count = ev.getHistorySize();
- int pcount = ev.getPointerCount();
-
- for (int p=0; p < pcount; p++) {
- int id = ev.getPointerId(p);
- mRender.newTouchPosition(ev.getX(p),
- ev.getY(p),
- ev.getPressure(p),
- id);
-
- for (int i=0; i < count; i++) {
- mRender.newTouchPosition(ev.getHistoricalX(p, i),
- ev.getHistoricalY(p, i),
- ev.getHistoricalPressure(p, i),
- id);
- }
- }
- return true;
- }
-
- void setAccel(float x, float y, float z) {
- if (mRender == null) {
- return;
- }
- mRender.setAccel(x, -y);
- }
-
-}
-
-
diff --git a/libs/rs/java/Balls/src/com/android/balls/ball_physics.rs b/libs/rs/java/Balls/src/com/android/balls/ball_physics.rs
deleted file mode 100644
index ff38be5..0000000
--- a/libs/rs/java/Balls/src/com/android/balls/ball_physics.rs
+++ /dev/null
@@ -1,146 +0,0 @@
-#pragma version(1)
-#pragma rs java_package_name(com.android.balls)
-
-#include "balls.rsh"
-
-float2 gGravityVector = {0.f, 9.8f};
-
-float2 gMinPos = {0.f, 0.f};
-float2 gMaxPos = {1280.f, 700.f};
-
-static float2 touchPos[10];
-static float touchPressure[10];
-
-void touch(float x, float y, float pressure, int id) {
- if (id >= 10) {
- return;
- }
-
- touchPos[id].x = x;
- touchPos[id].y = y;
- touchPressure[id] = pressure;
-}
-
-void root(const Ball_t *ballIn, Ball_t *ballOut, const BallControl_t *ctl, uint32_t x) {
- float2 fv = {0, 0};
- float2 pos = ballIn->position;
-
- int arcID = -1;
- float arcInvStr = 100000;
-
- const Ball_t * bPtr = rsGetElementAt(ctl->ain, 0);
- for (uint32_t xin = 0; xin < ctl->dimX; xin++) {
- float2 vec = bPtr[xin].position - pos;
- float2 vec2 = vec * vec;
- float len2 = vec2.x + vec2.y;
-
- if (len2 < 10000) {
- //float minDist = ballIn->size + bPtr[xin].size;
- float forceScale = ballIn->size * bPtr[xin].size;
- forceScale *= forceScale;
-
- if (len2 > 16 /* (minDist*minDist)*/) {
- // Repulsion
- float len = sqrt(len2);
- fv -= (vec / (len * len * len)) * 20000.f * forceScale;
- } else {
- if (len2 < 1) {
- if (xin == x) {
- continue;
- }
- ballOut->delta = 0.f;
- ballOut->position = ballIn->position;
- if (xin > x) {
- ballOut->position.x += 1.f;
- } else {
- ballOut->position.x -= 1.f;
- }
- //ballOut->color.rgb = 1.f;
- //ballOut->arcID = -1;
- //ballOut->arcStr = 0;
- return;
- }
- // Collision
- float2 axis = normalize(vec);
- float e1 = dot(axis, ballIn->delta);
- float e2 = dot(axis, bPtr[xin].delta);
- float e = (e1 - e2) * 0.45f;
- if (e1 > 0) {
- fv -= axis * e;
- } else {
- fv += axis * e;
- }
- }
- }
- }
-
- fv /= ballIn->size * ballIn->size * ballIn->size;
- fv -= gGravityVector * 4.f;
- fv *= ctl->dt;
-
- for (int i=0; i < 10; i++) {
- if (touchPressure[i] > 0.1f) {
- float2 vec = touchPos[i] - ballIn->position;
- float2 vec2 = vec * vec;
- float len2 = max(2.f, vec2.x + vec2.y);
- fv -= (vec / len2) * touchPressure[i] * 300.f;
- }
- }
-
- ballOut->delta = (ballIn->delta * (1.f - 0.004f)) + fv;
- ballOut->position = ballIn->position + (ballOut->delta * ctl->dt);
-
- const float wallForce = 400.f;
- if (ballOut->position.x > (gMaxPos.x - 20.f)) {
- float d = gMaxPos.x - ballOut->position.x;
- if (d < 0.f) {
- if (ballOut->delta.x > 0) {
- ballOut->delta.x *= -0.7;
- }
- ballOut->position.x = gMaxPos.x;
- } else {
- ballOut->delta.x -= min(wallForce / (d * d), 10.f);
- }
- }
-
- if (ballOut->position.x < (gMinPos.x + 20.f)) {
- float d = ballOut->position.x - gMinPos.x;
- if (d < 0.f) {
- if (ballOut->delta.x < 0) {
- ballOut->delta.x *= -0.7;
- }
- ballOut->position.x = gMinPos.x + 1.f;
- } else {
- ballOut->delta.x += min(wallForce / (d * d), 10.f);
- }
- }
-
- if (ballOut->position.y > (gMaxPos.y - 20.f)) {
- float d = gMaxPos.y - ballOut->position.y;
- if (d < 0.f) {
- if (ballOut->delta.y > 0) {
- ballOut->delta.y *= -0.7;
- }
- ballOut->position.y = gMaxPos.y;
- } else {
- ballOut->delta.y -= min(wallForce / (d * d), 10.f);
- }
- }
-
- if (ballOut->position.y < (gMinPos.y + 20.f)) {
- float d = ballOut->position.y - gMinPos.y;
- if (d < 0.f) {
- if (ballOut->delta.y < 0) {
- ballOut->delta.y *= -0.7;
- }
- ballOut->position.y = gMinPos.y + 1.f;
- } else {
- ballOut->delta.y += min(wallForce / (d * d * d), 10.f);
- }
- }
-
- ballOut->size = ballIn->size;
-
- //rsDebug("physics pos out", ballOut->position);
-}
-
diff --git a/libs/rs/java/Balls/src/com/android/balls/balls.rs b/libs/rs/java/Balls/src/com/android/balls/balls.rs
deleted file mode 100644
index 7dc7660..0000000
--- a/libs/rs/java/Balls/src/com/android/balls/balls.rs
+++ /dev/null
@@ -1,85 +0,0 @@
-#pragma version(1)
-#pragma rs java_package_name(com.android.balls)
-#include "rs_graphics.rsh"
-
-#include "balls.rsh"
-
-#pragma stateVertex(parent)
-#pragma stateStore(parent)
-
-rs_program_fragment gPFPoints;
-rs_program_fragment gPFLines;
-rs_mesh partMesh;
-
-typedef struct __attribute__((packed, aligned(4))) Point {
- float2 position;
- float size;
-} Point_t;
-Point_t *point;
-
-typedef struct VpConsts {
- rs_matrix4x4 MVP;
-} VpConsts_t;
-VpConsts_t *vpConstants;
-
-rs_script physics_script;
-
-Ball_t *balls1;
-Ball_t *balls2;
-
-static int frame = 0;
-
-void initParts(int w, int h)
-{
- uint32_t dimX = rsAllocationGetDimX(rsGetAllocation(balls1));
-
- for (uint32_t ct=0; ct < dimX; ct++) {
- balls1[ct].position.x = rsRand(0.f, (float)w);
- balls1[ct].position.y = rsRand(0.f, (float)h);
- balls1[ct].delta.x = 0.f;
- balls1[ct].delta.y = 0.f;
- balls1[ct].size = 1.f;
-
- float r = rsRand(100.f);
- if (r > 90.f) {
- balls1[ct].size += pow(10.f, rsRand(0.f, 2.f)) * 0.07;
- }
- }
-}
-
-
-
-int root() {
- rsgClearColor(0.f, 0.f, 0.f, 1.f);
-
- BallControl_t bc;
- Ball_t *bout;
-
- if (frame & 1) {
- rsSetObject(&bc.ain, rsGetAllocation(balls2));
- rsSetObject(&bc.aout, rsGetAllocation(balls1));
- bout = balls2;
- } else {
- rsSetObject(&bc.ain, rsGetAllocation(balls1));
- rsSetObject(&bc.aout, rsGetAllocation(balls2));
- bout = balls1;
- }
-
- bc.dimX = rsAllocationGetDimX(bc.ain);
- bc.dt = 1.f / 30.f;
-
- rsForEach(physics_script, bc.ain, bc.aout, &bc);
-
- for (uint32_t ct=0; ct < bc.dimX; ct++) {
- point[ct].position = bout[ct].position;
- point[ct].size = 6.f /*+ bout[ct].color.g * 6.f*/ * bout[ct].size;
- }
-
- frame++;
- rsgBindProgramFragment(gPFPoints);
- rsgDrawMesh(partMesh);
- rsClearObject(&bc.ain);
- rsClearObject(&bc.aout);
- return 1;
-}
-
diff --git a/libs/rs/java/Balls/src/com/android/balls/balls.rsh b/libs/rs/java/Balls/src/com/android/balls/balls.rsh
deleted file mode 100644
index fc886f9..0000000
--- a/libs/rs/java/Balls/src/com/android/balls/balls.rsh
+++ /dev/null
@@ -1,18 +0,0 @@
-
-typedef struct __attribute__((packed, aligned(4))) Ball {
- float2 delta;
- float2 position;
- //float3 color;
- float size;
- //int arcID;
- //float arcStr;
-} Ball_t;
-Ball_t *balls;
-
-
-typedef struct BallControl {
- uint32_t dimX;
- rs_allocation ain;
- rs_allocation aout;
- float dt;
-} BallControl_t;
diff --git a/libs/rs/java/Fountain/AndroidManifest.xml b/libs/rs/java/Fountain/AndroidManifest.xml
deleted file mode 100644
index 5126e5c..0000000
--- a/libs/rs/java/Fountain/AndroidManifest.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.fountain">
- <uses-sdk android:minSdkVersion="11" />
- <application
- android:label="Fountain"
- android:icon="@drawable/test_pattern">
- <activity android:name="Fountain">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
-</manifest>
diff --git a/libs/rs/java/Fountain/_index.html b/libs/rs/java/Fountain/_index.html
deleted file mode 100644
index 223242f..0000000
--- a/libs/rs/java/Fountain/_index.html
+++ /dev/null
@@ -1,5 +0,0 @@
-<p>An example that renders many dots on the screen that follow a user's touch. The dots fall
-to the bottom of the screen when the user releases the finger.</p>
-
-
-
diff --git a/libs/rs/java/Fountain/res/drawable/test_pattern.png b/libs/rs/java/Fountain/res/drawable/test_pattern.png
deleted file mode 100644
index e7d1455..0000000
--- a/libs/rs/java/Fountain/res/drawable/test_pattern.png
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/Fountain/src/com/android/fountain/Fountain.java b/libs/rs/java/Fountain/src/com/android/fountain/Fountain.java
deleted file mode 100644
index 116c478..0000000
--- a/libs/rs/java/Fountain/src/com/android/fountain/Fountain.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.fountain;
-
-import android.renderscript.RSSurfaceView;
-import android.renderscript.RenderScript;
-
-import android.app.Activity;
-import android.content.res.Configuration;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.provider.Settings.System;
-import android.util.Config;
-import android.util.Log;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.View;
-import android.view.Window;
-import android.widget.Button;
-import android.widget.ListView;
-
-import java.lang.Runtime;
-
-public class Fountain extends Activity {
- //EventListener mListener = new EventListener();
-
- private static final String LOG_TAG = "libRS_jni";
- private static final boolean DEBUG = false;
- private static final boolean LOG_ENABLED = DEBUG ? Config.LOGD : Config.LOGV;
-
- private FountainView mView;
-
- // get the current looper (from your Activity UI thread for instance
-
-
-
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
-
- // Create our Preview view and set it as the content of our
- // Activity
- mView = new FountainView(this);
- setContentView(mView);
- }
-
- @Override
- protected void onResume() {
- Log.e("rs", "onResume");
-
- // Ideally a game should implement onResume() and onPause()
- // to take appropriate action when the activity looses focus
- super.onResume();
- mView.resume();
- }
-
- @Override
- protected void onPause() {
- Log.e("rs", "onPause");
-
- // Ideally a game should implement onResume() and onPause()
- // to take appropriate action when the activity looses focus
- super.onPause();
- mView.pause();
-
-
-
- //Runtime.getRuntime().exit(0);
- }
-
-
- static void log(String message) {
- if (LOG_ENABLED) {
- Log.v(LOG_TAG, message);
- }
- }
-
-
-}
-
diff --git a/libs/rs/java/Fountain/src/com/android/fountain/FountainRS.java b/libs/rs/java/Fountain/src/com/android/fountain/FountainRS.java
deleted file mode 100644
index be2f9ca..0000000
--- a/libs/rs/java/Fountain/src/com/android/fountain/FountainRS.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.fountain;
-
-import android.content.res.Resources;
-import android.renderscript.*;
-import android.util.Log;
-
-
-public class FountainRS {
- public static final int PART_COUNT = 50000;
-
- public FountainRS() {
- }
-
- private Resources mRes;
- private RenderScriptGL mRS;
- private ScriptC_fountain mScript;
- public void init(RenderScriptGL rs, Resources res, int width, int height) {
- mRS = rs;
- mRes = res;
-
- ProgramFragmentFixedFunction.Builder pfb = new ProgramFragmentFixedFunction.Builder(rs);
- pfb.setVaryingColor(true);
- rs.bindProgramFragment(pfb.create());
-
- ScriptField_Point points = new ScriptField_Point(mRS, PART_COUNT);//
- // Allocation.USAGE_GRAPHICS_VERTEX);
-
- Mesh.AllocationBuilder smb = new Mesh.AllocationBuilder(mRS);
- smb.addVertexAllocation(points.getAllocation());
- smb.addIndexSetType(Mesh.Primitive.POINT);
- Mesh sm = smb.create();
-
- mScript = new ScriptC_fountain(mRS, mRes, R.raw.fountain);
- mScript.set_partMesh(sm);
- mScript.bind_point(points);
- mRS.bindRootScript(mScript);
- }
-
- boolean holdingColor[] = new boolean[10];
- public void newTouchPosition(float x, float y, float pressure, int id) {
- if (id >= holdingColor.length) {
- return;
- }
- int rate = (int)(pressure * pressure * 500.f);
- if (rate > 500) {
- rate = 500;
- }
- if (rate > 0) {
- mScript.invoke_addParticles(rate, x, y, id, !holdingColor[id]);
- holdingColor[id] = true;
- } else {
- holdingColor[id] = false;
- }
-
- }
-}
diff --git a/libs/rs/java/Fountain/src/com/android/fountain/FountainView.java b/libs/rs/java/Fountain/src/com/android/fountain/FountainView.java
deleted file mode 100644
index 69b181d..0000000
--- a/libs/rs/java/Fountain/src/com/android/fountain/FountainView.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.fountain;
-
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.concurrent.Semaphore;
-
-import android.renderscript.RSSurfaceView;
-import android.renderscript.RenderScript;
-import android.renderscript.RenderScriptGL;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.Drawable;
-import android.os.Handler;
-import android.os.Message;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.view.Surface;
-import android.view.SurfaceHolder;
-import android.view.SurfaceView;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-
-public class FountainView extends RSSurfaceView {
-
- public FountainView(Context context) {
- super(context);
- //setFocusable(true);
- }
-
- private RenderScriptGL mRS;
- private FountainRS mRender;
-
- public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
- super.surfaceChanged(holder, format, w, h);
- if (mRS == null) {
- RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig();
- mRS = createRenderScriptGL(sc);
- mRS.setSurface(holder, w, h);
- mRender = new FountainRS();
- mRender.init(mRS, getResources(), w, h);
- }
- }
-
- @Override
- protected void onDetachedFromWindow() {
- if (mRS != null) {
- mRS = null;
- destroyRenderScriptGL();
- }
- }
-
-
- @Override
- public boolean onTouchEvent(MotionEvent ev)
- {
- int act = ev.getActionMasked();
- if (act == ev.ACTION_UP) {
- mRender.newTouchPosition(0, 0, 0, ev.getPointerId(0));
- return false;
- } else if (act == MotionEvent.ACTION_POINTER_UP) {
- // only one pointer going up, we can get the index like this
- int pointerIndex = ev.getActionIndex();
- int pointerId = ev.getPointerId(pointerIndex);
- mRender.newTouchPosition(0, 0, 0, pointerId);
- }
- int count = ev.getHistorySize();
- int pcount = ev.getPointerCount();
-
- for (int p=0; p < pcount; p++) {
- int id = ev.getPointerId(p);
- mRender.newTouchPosition(ev.getX(p),
- ev.getY(p),
- ev.getPressure(p),
- id);
-
- for (int i=0; i < count; i++) {
- mRender.newTouchPosition(ev.getHistoricalX(p, i),
- ev.getHistoricalY(p, i),
- ev.getHistoricalPressure(p, i),
- id);
- }
- }
- return true;
- }
-}
-
-
diff --git a/libs/rs/java/Fountain/src/com/android/fountain/fountain.rs b/libs/rs/java/Fountain/src/com/android/fountain/fountain.rs
deleted file mode 100644
index b8f57a3..0000000
--- a/libs/rs/java/Fountain/src/com/android/fountain/fountain.rs
+++ /dev/null
@@ -1,69 +0,0 @@
-// Fountain test script
-#pragma version(1)
-
-#pragma rs java_package_name(com.android.fountain)
-
-#pragma stateFragment(parent)
-
-#include "rs_graphics.rsh"
-
-static int newPart = 0;
-rs_mesh partMesh;
-
-typedef struct __attribute__((packed, aligned(4))) Point {
- float2 delta;
- float2 position;
- uchar4 color;
-} Point_t;
-Point_t *point;
-
-int root() {
- float dt = min(rsGetDt(), 0.1f);
- rsgClearColor(0.f, 0.f, 0.f, 1.f);
- const float height = rsgGetHeight();
- const int size = rsAllocationGetDimX(rsGetAllocation(point));
- float dy2 = dt * (10.f);
- Point_t * p = point;
- for (int ct=0; ct < size; ct++) {
- p->delta.y += dy2;
- p->position += p->delta;
- if ((p->position.y > height) && (p->delta.y > 0)) {
- p->delta.y *= -0.3f;
- }
- p++;
- }
-
- rsgDrawMesh(partMesh);
- return 1;
-}
-
-static float4 partColor[10];
-void addParticles(int rate, float x, float y, int index, bool newColor)
-{
- if (newColor) {
- partColor[index].x = rsRand(0.5f, 1.0f);
- partColor[index].y = rsRand(1.0f);
- partColor[index].z = rsRand(1.0f);
- }
- float rMax = ((float)rate) * 0.02f;
- int size = rsAllocationGetDimX(rsGetAllocation(point));
- uchar4 c = rsPackColorTo8888(partColor[index]);
-
- Point_t * np = &point[newPart];
- float2 p = {x, y};
- while (rate--) {
- float angle = rsRand(3.14f * 2.f);
- float len = rsRand(rMax);
- np->delta.x = len * sin(angle);
- np->delta.y = len * cos(angle);
- np->position = p;
- np->color = c;
- newPart++;
- np++;
- if (newPart >= size) {
- newPart = 0;
- np = &point[newPart];
- }
- }
-}
-
diff --git a/libs/rs/java/HelloCompute/Android.mk b/libs/rs/java/HelloCompute/Android.mk
deleted file mode 100644
index 3881bb0..0000000
--- a/libs/rs/java/HelloCompute/Android.mk
+++ /dev/null
@@ -1,31 +0,0 @@
-#
-# 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.
-#
-
-ifneq ($(TARGET_SIMULATOR),true)
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src) \
- $(call all-renderscript-files-under, src)
-
-LOCAL_PACKAGE_NAME := HelloCompute
-
-include $(BUILD_PACKAGE)
-
-endif
diff --git a/libs/rs/java/HelloCompute/AndroidManifest.xml b/libs/rs/java/HelloCompute/AndroidManifest.xml
deleted file mode 100644
index 8c7ac2f..0000000
--- a/libs/rs/java/HelloCompute/AndroidManifest.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?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.
--->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.example.hellocompute">
-
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <uses-sdk android:minSdkVersion="11" />
- <application android:label="HelloCompute">
- <activity android:name="HelloCompute">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
-</manifest>
diff --git a/libs/rs/java/HelloCompute/_index.html b/libs/rs/java/HelloCompute/_index.html
deleted file mode 100644
index abfd978..0000000
--- a/libs/rs/java/HelloCompute/_index.html
+++ /dev/null
@@ -1,2 +0,0 @@
-<p>A Renderscript compute sample that filters a bitmap. No Renderscript graphics APIs are used
-in this sample.</p>
\ No newline at end of file
diff --git a/libs/rs/java/HelloCompute/res/drawable/data.jpg b/libs/rs/java/HelloCompute/res/drawable/data.jpg
deleted file mode 100644
index 81a87b1..0000000
--- a/libs/rs/java/HelloCompute/res/drawable/data.jpg
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/HelloCompute/res/layout/main.xml b/libs/rs/java/HelloCompute/res/layout/main.xml
deleted file mode 100644
index 3f7de43..0000000
--- a/libs/rs/java/HelloCompute/res/layout/main.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?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:layout_width="match_parent"
- android:layout_height="match_parent">
-
- <ImageView
- android:id="@+id/displayin"
- android:layout_width="320dip"
- android:layout_height="266dip" />
-
- <ImageView
- android:id="@+id/displayout"
- android:layout_width="320dip"
- android:layout_height="266dip" />
-
-</LinearLayout>
diff --git a/libs/rs/java/HelloCompute/src/com/android/example/hellocompute/HelloCompute.java b/libs/rs/java/HelloCompute/src/com/android/example/hellocompute/HelloCompute.java
deleted file mode 100644
index 123c37b..0000000
--- a/libs/rs/java/HelloCompute/src/com/android/example/hellocompute/HelloCompute.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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.example.hellocompute;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.graphics.BitmapFactory;
-import android.graphics.Bitmap;
-import android.renderscript.RenderScript;
-import android.renderscript.Allocation;
-import android.widget.ImageView;
-
-public class HelloCompute extends Activity {
- private Bitmap mBitmapIn;
- private Bitmap mBitmapOut;
-
- private RenderScript mRS;
- private Allocation mInAllocation;
- private Allocation mOutAllocation;
- private ScriptC_mono mScript;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- mBitmapIn = loadBitmap(R.drawable.data);
- mBitmapOut = Bitmap.createBitmap(mBitmapIn.getWidth(), mBitmapIn.getHeight(),
- mBitmapIn.getConfig());
-
- ImageView in = (ImageView) findViewById(R.id.displayin);
- in.setImageBitmap(mBitmapIn);
-
- ImageView out = (ImageView) findViewById(R.id.displayout);
- out.setImageBitmap(mBitmapOut);
-
- createScript();
- }
-
-
- private void createScript() {
- mRS = RenderScript.create(this);
-
- mInAllocation = Allocation.createFromBitmap(mRS, mBitmapIn,
- Allocation.MipmapControl.MIPMAP_NONE,
- Allocation.USAGE_SCRIPT);
- mOutAllocation = Allocation.createTyped(mRS, mInAllocation.getType());
-
- mScript = new ScriptC_mono(mRS, getResources(), R.raw.mono);
-
- mScript.set_gIn(mInAllocation);
- mScript.set_gOut(mOutAllocation);
- mScript.set_gScript(mScript);
- mScript.invoke_filter();
- mOutAllocation.copyTo(mBitmapOut);
- }
-
- private Bitmap loadBitmap(int resource) {
- final BitmapFactory.Options options = new BitmapFactory.Options();
- options.inPreferredConfig = Bitmap.Config.ARGB_8888;
- return BitmapFactory.decodeResource(getResources(), resource, options);
- }
-}
diff --git a/libs/rs/java/HelloCompute/src/com/android/example/hellocompute/mono.rs b/libs/rs/java/HelloCompute/src/com/android/example/hellocompute/mono.rs
deleted file mode 100644
index 9647c61..0000000
--- a/libs/rs/java/HelloCompute/src/com/android/example/hellocompute/mono.rs
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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.
- */
-
-#pragma version(1)
-#pragma rs java_package_name(com.android.example.hellocompute)
-
-rs_allocation gIn;
-rs_allocation gOut;
-rs_script gScript;
-
-const static float3 gMonoMult = {0.299f, 0.587f, 0.114f};
-
-void root(const uchar4 *v_in, uchar4 *v_out, const void *usrData, uint32_t x, uint32_t y) {
- float4 f4 = rsUnpackColor8888(*v_in);
-
- float3 mono = dot(f4.rgb, gMonoMult);
- *v_out = rsPackColorTo8888(mono);
-}
-
-void filter() {
- rsForEach(gScript, gIn, gOut, 0);
-}
-
diff --git a/libs/rs/java/HelloWorld/Android.mk b/libs/rs/java/HelloWorld/Android.mk
deleted file mode 100644
index 72f0f03..0000000
--- a/libs/rs/java/HelloWorld/Android.mk
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# 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.
-#
-
-ifneq ($(TARGET_SIMULATOR),true)
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src) $(call all-renderscript-files-under, src)
-
-LOCAL_PACKAGE_NAME := HelloWorld
-
-include $(BUILD_PACKAGE)
-
-endif
diff --git a/libs/rs/java/HelloWorld/AndroidManifest.xml b/libs/rs/java/HelloWorld/AndroidManifest.xml
deleted file mode 100644
index e7c9a95..0000000
--- a/libs/rs/java/HelloWorld/AndroidManifest.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?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.
--->
-
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.rs.helloworld">
- <uses-sdk android:minSdkVersion="11" />
- <application android:label="HelloWorld"
- android:icon="@drawable/test_pattern">
- <activity android:name="HelloWorld"
- android:label="HelloWorld"
- android:theme="@android:style/Theme.Black.NoTitleBar">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
-</manifest>
diff --git a/libs/rs/java/HelloWorld/_index.html b/libs/rs/java/HelloWorld/_index.html
deleted file mode 100644
index 4cab738..0000000
--- a/libs/rs/java/HelloWorld/_index.html
+++ /dev/null
@@ -1 +0,0 @@
-<p>A Renderscript graphics application that draws the text "Hello, World!" where the user touches.</p>
\ No newline at end of file
diff --git a/libs/rs/java/HelloWorld/res/drawable/test_pattern.png b/libs/rs/java/HelloWorld/res/drawable/test_pattern.png
deleted file mode 100644
index e7d1455..0000000
--- a/libs/rs/java/HelloWorld/res/drawable/test_pattern.png
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/HelloWorld.java b/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/HelloWorld.java
deleted file mode 100644
index f63015e7..0000000
--- a/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/HelloWorld.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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.rs.helloworld;
-
-import android.app.Activity;
-import android.os.Bundle;
-
-// Renderscript activity
-public class HelloWorld extends Activity {
-
- // Custom view to use with RenderScript
- private HelloWorldView mView;
-
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
-
- // Create our view and set it as the content of our Activity
- mView = new HelloWorldView(this);
- setContentView(mView);
- }
-
- @Override
- protected void onResume() {
- // Ideally an app should implement onResume() and onPause()
- // to take appropriate action when the activity loses focus
- super.onResume();
- mView.resume();
- }
-
- @Override
- protected void onPause() {
- // Ideally an app should implement onResume() and onPause()
- // to take appropriate action when the activity loses focus
- super.onPause();
- mView.pause();
- }
-
-}
-
diff --git a/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/HelloWorldRS.java b/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/HelloWorldRS.java
deleted file mode 100644
index c9c1316..0000000
--- a/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/HelloWorldRS.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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.rs.helloworld;
-
-import android.content.res.Resources;
-import android.renderscript.*;
-
-// This is the renderer for the HelloWorldView
-public class HelloWorldRS {
- private Resources mRes;
- private RenderScriptGL mRS;
-
- private ScriptC_helloworld mScript;
-
- public HelloWorldRS() {
- }
-
- // This provides us with the renderscript context and resources that
- // allow us to create the script that does rendering
- public void init(RenderScriptGL rs, Resources res) {
- mRS = rs;
- mRes = res;
- initRS();
- }
-
- public void onActionDown(int x, int y) {
- mScript.set_gTouchX(x);
- mScript.set_gTouchY(y);
- }
-
- private void initRS() {
- mScript = new ScriptC_helloworld(mRS, mRes, R.raw.helloworld);
- mRS.bindRootScript(mScript);
- }
-}
-
-
-
diff --git a/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/HelloWorldView.java b/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/HelloWorldView.java
deleted file mode 100644
index 8cddb2a..0000000
--- a/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/HelloWorldView.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * 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.rs.helloworld;
-
-import android.renderscript.RSSurfaceView;
-import android.renderscript.RenderScriptGL;
-
-import android.content.Context;
-import android.view.MotionEvent;
-
-public class HelloWorldView extends RSSurfaceView {
- // Renderscipt context
- private RenderScriptGL mRS;
- // Script that does the rendering
- private HelloWorldRS mRender;
-
- public HelloWorldView(Context context) {
- super(context);
- ensureRenderScript();
- }
-
- private void ensureRenderScript() {
- if (mRS == null) {
- // Initialize renderscript with desired surface characteristics.
- // In this case, just use the defaults
- RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig();
- mRS = createRenderScriptGL(sc);
- // Create an instance of the script that does the rendering
- mRender = new HelloWorldRS();
- mRender.init(mRS, getResources());
- }
- }
-
- @Override
- protected void onAttachedToWindow() {
- super.onAttachedToWindow();
- ensureRenderScript();
- }
-
- @Override
- protected void onDetachedFromWindow() {
- // Handle the system event and clean up
- mRender = null;
- if (mRS != null) {
- mRS = null;
- destroyRenderScriptGL();
- }
- }
-
- @Override
- public boolean onTouchEvent(MotionEvent ev) {
- // Pass touch events from the system to the rendering script
- if (ev.getAction() == MotionEvent.ACTION_DOWN) {
- mRender.onActionDown((int)ev.getX(), (int)ev.getY());
- return true;
- }
-
- return false;
- }
-}
-
-
diff --git a/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/helloworld.rs b/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/helloworld.rs
deleted file mode 100644
index fa171f5..0000000
--- a/libs/rs/java/HelloWorld/src/com/android/rs/helloworld/helloworld.rs
+++ /dev/null
@@ -1,47 +0,0 @@
-// 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.
-
-#pragma version(1)
-
-// Tell which java package name the reflected files should belong to
-#pragma rs java_package_name(com.android.rs.helloworld)
-
-// Built-in header with graphics API's
-#include "rs_graphics.rsh"
-
-// gTouchX and gTouchY are variables that will be reflected for use
-// by the java API. We can use them to notify the script of touch events.
-int gTouchX;
-int gTouchY;
-
-// This is invoked automatically when the script is created
-void init() {
- gTouchX = 50.0f;
- gTouchY = 50.0f;
-}
-
-int root(int launchID) {
-
- // Clear the background color
- rsgClearColor(0.0f, 0.0f, 0.0f, 0.0f);
- // Tell the runtime what the font color should be
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- // Introuduce ourselves to the world by drawing a greeting
- // at the position user touched on the screen
- rsgDrawText("Hello World!", gTouchX, gTouchY);
-
- // Return value tells RS roughly how often to redraw
- // in this case 20 ms
- return 20;
-}
diff --git a/libs/rs/java/Samples/Android.mk b/libs/rs/java/Samples/Android.mk
deleted file mode 100644
index 65ae734..0000000
--- a/libs/rs/java/Samples/Android.mk
+++ /dev/null
@@ -1,31 +0,0 @@
-#
-# Copyright (C) 2008 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-ifneq ($(TARGET_SIMULATOR),true)
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE_TAGS := optional
-
-LOCAL_SRC_FILES := $(call all-java-files-under, src) $(call all-renderscript-files-under, src)
-#LOCAL_STATIC_JAVA_LIBRARIES := android.renderscript
-
-LOCAL_PACKAGE_NAME := Samples
-
-include $(BUILD_PACKAGE)
-
-endif
diff --git a/libs/rs/java/Samples/AndroidManifest.xml b/libs/rs/java/Samples/AndroidManifest.xml
deleted file mode 100644
index c08a264..0000000
--- a/libs/rs/java/Samples/AndroidManifest.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.android.samples">
- <uses-sdk android:minSdkVersion="11" />
- <application android:label="Samples"
- android:icon="@drawable/test_pattern">
- <activity android:name="RsList"
- android:label="RsList"
- android:theme="@android:style/Theme.Black.NoTitleBar">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
-
- <activity android:name="RsRenderStates"
- android:label="RsStates"
- android:theme="@android:style/Theme.Black.NoTitleBar">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
-</manifest>
diff --git a/libs/rs/java/Samples/_index.html b/libs/rs/java/Samples/_index.html
deleted file mode 100644
index 5872431..0000000
--- a/libs/rs/java/Samples/_index.html
+++ /dev/null
@@ -1 +0,0 @@
-<p>A set of samples that demonstrate how to use various features of the Renderscript APIs.</p>
\ No newline at end of file
diff --git a/libs/rs/java/Samples/res/drawable/checker.png b/libs/rs/java/Samples/res/drawable/checker.png
deleted file mode 100644
index b631e1e..0000000
--- a/libs/rs/java/Samples/res/drawable/checker.png
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/Samples/res/drawable/cubemap_test.png b/libs/rs/java/Samples/res/drawable/cubemap_test.png
deleted file mode 100644
index baf35d0..0000000
--- a/libs/rs/java/Samples/res/drawable/cubemap_test.png
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/Samples/res/drawable/data.png b/libs/rs/java/Samples/res/drawable/data.png
deleted file mode 100644
index 8e34714..0000000
--- a/libs/rs/java/Samples/res/drawable/data.png
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/Samples/res/drawable/leaf.png b/libs/rs/java/Samples/res/drawable/leaf.png
deleted file mode 100644
index 3cd3775..0000000
--- a/libs/rs/java/Samples/res/drawable/leaf.png
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/Samples/res/drawable/test_pattern.png b/libs/rs/java/Samples/res/drawable/test_pattern.png
deleted file mode 100644
index e7d1455..0000000
--- a/libs/rs/java/Samples/res/drawable/test_pattern.png
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/Samples/res/drawable/torusmap.png b/libs/rs/java/Samples/res/drawable/torusmap.png
deleted file mode 100644
index 1e08f3b..0000000
--- a/libs/rs/java/Samples/res/drawable/torusmap.png
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/Samples/res/raw/multitexf.glsl b/libs/rs/java/Samples/res/raw/multitexf.glsl
deleted file mode 100644
index e492a47..0000000
--- a/libs/rs/java/Samples/res/raw/multitexf.glsl
+++ /dev/null
@@ -1,13 +0,0 @@
-varying vec2 varTex0;
-
-void main() {
- vec2 t0 = varTex0.xy;
- lowp vec4 col0 = texture2D(UNI_Tex0, t0).rgba;
- lowp vec4 col1 = texture2D(UNI_Tex1, t0*4.0).rgba;
- lowp vec4 col2 = texture2D(UNI_Tex2, t0).rgba;
- col0.xyz = col0.xyz*col1.xyz*1.5;
- col0.xyz = mix(col0.xyz, col2.xyz, col2.w);
- col0.w = 0.5;
- gl_FragColor = col0;
-}
-
diff --git a/libs/rs/java/Samples/res/raw/shader2f.glsl b/libs/rs/java/Samples/res/raw/shader2f.glsl
deleted file mode 100644
index 5fc05f1..0000000
--- a/libs/rs/java/Samples/res/raw/shader2f.glsl
+++ /dev/null
@@ -1,29 +0,0 @@
-varying vec3 varWorldPos;
-varying vec3 varWorldNormal;
-varying vec2 varTex0;
-
-void main() {
-
- vec3 V = normalize(-varWorldPos.xyz);
- vec3 worldNorm = normalize(varWorldNormal);
-
- vec3 light0Vec = normalize(UNI_light0_Posision.xyz - varWorldPos);
- vec3 light0R = -reflect(light0Vec, worldNorm);
- float light0_Diffuse = clamp(dot(worldNorm, light0Vec), 0.0, 1.0) * UNI_light0_Diffuse;
- float light0Spec = clamp(dot(light0R, V), 0.001, 1.0);
- float light0_Specular = pow(light0Spec, UNI_light0_CosinePower) * UNI_light0_Specular;
-
- vec3 light1Vec = normalize(UNI_light1_Posision.xyz - varWorldPos);
- vec3 light1R = reflect(light1Vec, worldNorm);
- float light1_Diffuse = clamp(dot(worldNorm, light1Vec), 0.0, 1.0) * UNI_light1_Diffuse;
- float light1Spec = clamp(dot(light1R, V), 0.001, 1.0);
- float light1_Specular = pow(light1Spec, UNI_light1_CosinePower) * UNI_light1_Specular;
-
- vec2 t0 = varTex0.xy;
- lowp vec4 col = texture2D(UNI_Tex0, t0).rgba;
- col.xyz = col.xyz * (light0_Diffuse * UNI_light0_DiffuseColor.xyz + light1_Diffuse * UNI_light1_DiffuseColor.xyz);
- col.xyz += light0_Specular * UNI_light0_SpecularColor.xyz;
- col.xyz += light1_Specular * UNI_light1_SpecularColor.xyz;
- gl_FragColor = col;
-}
-
diff --git a/libs/rs/java/Samples/res/raw/shader2movev.glsl b/libs/rs/java/Samples/res/raw/shader2movev.glsl
deleted file mode 100644
index a2c807e..0000000
--- a/libs/rs/java/Samples/res/raw/shader2movev.glsl
+++ /dev/null
@@ -1,21 +0,0 @@
-varying vec3 varWorldPos;
-varying vec3 varWorldNormal;
-varying vec2 varTex0;
-
-// This is where actual shader code begins
-void main() {
- vec4 objPos = ATTRIB_position;
- vec3 oldPos = objPos.xyz;
- objPos.xyz += 0.1*sin(objPos.xyz*2.0 + UNI_time);
- objPos.xyz += 0.05*sin(objPos.xyz*4.0 + UNI_time*0.5);
- objPos.xyz += 0.02*sin(objPos.xyz*7.0 + UNI_time*0.75);
- vec4 worldPos = UNI_model * objPos;
- gl_Position = UNI_proj * worldPos;
-
- mat3 model3 = mat3(UNI_model[0].xyz, UNI_model[1].xyz, UNI_model[2].xyz);
- vec3 worldNorm = model3 * (ATTRIB_normal + oldPos - objPos.xyz);
-
- varWorldPos = worldPos.xyz;
- varWorldNormal = worldNorm;
- varTex0 = ATTRIB_texture0;
-}
diff --git a/libs/rs/java/Samples/res/raw/shader2v.glsl b/libs/rs/java/Samples/res/raw/shader2v.glsl
deleted file mode 100644
index e6885a3..0000000
--- a/libs/rs/java/Samples/res/raw/shader2v.glsl
+++ /dev/null
@@ -1,17 +0,0 @@
-varying vec3 varWorldPos;
-varying vec3 varWorldNormal;
-varying vec2 varTex0;
-
-// This is where actual shader code begins
-void main() {
- vec4 objPos = ATTRIB_position;
- vec4 worldPos = UNI_model * objPos;
- gl_Position = UNI_proj * worldPos;
-
- mat3 model3 = mat3(UNI_model[0].xyz, UNI_model[1].xyz, UNI_model[2].xyz);
- vec3 worldNorm = model3 * ATTRIB_normal;
-
- varWorldPos = worldPos.xyz;
- varWorldNormal = worldNorm;
- varTex0 = ATTRIB_texture0;
-}
diff --git a/libs/rs/java/Samples/res/raw/shaderarrayf.glsl b/libs/rs/java/Samples/res/raw/shaderarrayf.glsl
deleted file mode 100644
index 238ecad..0000000
--- a/libs/rs/java/Samples/res/raw/shaderarrayf.glsl
+++ /dev/null
@@ -1,16 +0,0 @@
-
-varying lowp float light0_Diffuse;
-varying lowp float light0_Specular;
-varying lowp float light1_Diffuse;
-varying lowp float light1_Specular;
-varying vec2 varTex0;
-
-void main() {
- vec2 t0 = varTex0.xy;
- lowp vec4 col = texture2D(UNI_Tex0, t0).rgba;
- col.xyz = col.xyz * (light0_Diffuse * UNI_light_DiffuseColor[0].xyz + light1_Diffuse * UNI_light_DiffuseColor[1].xyz);
- col.xyz += light0_Specular * UNI_light_SpecularColor[0].xyz;
- col.xyz += light1_Specular * UNI_light_SpecularColor[1].xyz;
- gl_FragColor = col;
-}
-
diff --git a/libs/rs/java/Samples/res/raw/shaderarrayv.glsl b/libs/rs/java/Samples/res/raw/shaderarrayv.glsl
deleted file mode 100644
index 7a1310a..0000000
--- a/libs/rs/java/Samples/res/raw/shaderarrayv.glsl
+++ /dev/null
@@ -1,32 +0,0 @@
-varying float light0_Diffuse;
-varying float light0_Specular;
-varying float light1_Diffuse;
-varying float light1_Specular;
-varying vec2 varTex0;
-
-// This is where actual shader code begins
-void main() {
- vec4 worldPos = UNI_model[0] * ATTRIB_position;
- worldPos = UNI_model[1] * worldPos;
- gl_Position = UNI_proj * worldPos;
-
- mat4 model0 = UNI_model[0];
- mat3 model3 = mat3(model0[0].xyz, model0[1].xyz, model0[2].xyz);
- vec3 worldNorm = model3 * ATTRIB_normal;
- vec3 V = normalize(-worldPos.xyz);
-
- vec3 light0Vec = normalize(UNI_light_Posision[0].xyz - worldPos.xyz);
- vec3 light0R = -reflect(light0Vec, worldNorm);
- light0_Diffuse = clamp(dot(worldNorm, light0Vec), 0.0, 1.0) * UNI_light_Diffuse[0];
- float light0Spec = clamp(dot(light0R, V), 0.001, 1.0);
- light0_Specular = pow(light0Spec, UNI_light_CosinePower[0]) * UNI_light_Specular[0];
-
- vec3 light1Vec = normalize(UNI_light_Posision[1].xyz - worldPos.xyz);
- vec3 light1R = reflect(light1Vec, worldNorm);
- light1_Diffuse = clamp(dot(worldNorm, light1Vec), 0.0, 1.0) * UNI_light_Diffuse[1];
- float light1Spec = clamp(dot(light1R, V), 0.001, 1.0);
- light1_Specular = pow(light1Spec, UNI_light_CosinePower[1]) * UNI_light_Specular[1];
-
- gl_PointSize = 1.0;
- varTex0 = ATTRIB_texture0;
-}
diff --git a/libs/rs/java/Samples/res/raw/shadercubef.glsl b/libs/rs/java/Samples/res/raw/shadercubef.glsl
deleted file mode 100644
index 15696a4..0000000
--- a/libs/rs/java/Samples/res/raw/shadercubef.glsl
+++ /dev/null
@@ -1,8 +0,0 @@
-
-varying vec3 worldNormal;
-
-void main() {
- lowp vec4 col = textureCube(UNI_Tex0, worldNormal);
- gl_FragColor = col;
-}
-
diff --git a/libs/rs/java/Samples/res/raw/shadercubev.glsl b/libs/rs/java/Samples/res/raw/shadercubev.glsl
deleted file mode 100644
index 70f5cd6..0000000
--- a/libs/rs/java/Samples/res/raw/shadercubev.glsl
+++ /dev/null
@@ -1,10 +0,0 @@
-varying vec3 worldNormal;
-
-// This is where actual shader code begins
-void main() {
- vec4 worldPos = UNI_model * ATTRIB_position;
- gl_Position = UNI_proj * worldPos;
-
- mat3 model3 = mat3(UNI_model[0].xyz, UNI_model[1].xyz, UNI_model[2].xyz);
- worldNormal = model3 * ATTRIB_normal;
-}
diff --git a/libs/rs/java/Samples/res/raw/shaderf.glsl b/libs/rs/java/Samples/res/raw/shaderf.glsl
deleted file mode 100644
index d56e203..0000000
--- a/libs/rs/java/Samples/res/raw/shaderf.glsl
+++ /dev/null
@@ -1,16 +0,0 @@
-
-varying lowp float light0_Diffuse;
-varying lowp float light0_Specular;
-varying lowp float light1_Diffuse;
-varying lowp float light1_Specular;
-varying vec2 varTex0;
-
-void main() {
- vec2 t0 = varTex0.xy;
- lowp vec4 col = texture2D(UNI_Tex0, t0).rgba;
- col.xyz = col.xyz * (light0_Diffuse * UNI_light0_DiffuseColor.xyz + light1_Diffuse * UNI_light1_DiffuseColor.xyz);
- col.xyz += light0_Specular * UNI_light0_SpecularColor.xyz;
- col.xyz += light1_Specular * UNI_light1_SpecularColor.xyz;
- gl_FragColor = col;
-}
-
diff --git a/libs/rs/java/Samples/res/raw/shaderv.glsl b/libs/rs/java/Samples/res/raw/shaderv.glsl
deleted file mode 100644
index f7d01de..0000000
--- a/libs/rs/java/Samples/res/raw/shaderv.glsl
+++ /dev/null
@@ -1,30 +0,0 @@
-varying float light0_Diffuse;
-varying float light0_Specular;
-varying float light1_Diffuse;
-varying float light1_Specular;
-varying vec2 varTex0;
-
-// This is where actual shader code begins
-void main() {
- vec4 worldPos = UNI_model * ATTRIB_position;
- gl_Position = UNI_proj * worldPos;
-
- mat3 model3 = mat3(UNI_model[0].xyz, UNI_model[1].xyz, UNI_model[2].xyz);
- vec3 worldNorm = model3 * ATTRIB_normal;
- vec3 V = normalize(-worldPos.xyz);
-
- vec3 light0Vec = normalize(UNI_light0_Posision.xyz - worldPos.xyz);
- vec3 light0R = -reflect(light0Vec, worldNorm);
- light0_Diffuse = clamp(dot(worldNorm, light0Vec), 0.0, 1.0) * UNI_light0_Diffuse;
- float light0Spec = clamp(dot(light0R, V), 0.001, 1.0);
- light0_Specular = pow(light0Spec, UNI_light0_CosinePower) * UNI_light0_Specular;
-
- vec3 light1Vec = normalize(UNI_light1_Posision.xyz - worldPos.xyz);
- vec3 light1R = reflect(light1Vec, worldNorm);
- light1_Diffuse = clamp(dot(worldNorm, light1Vec), 0.0, 1.0) * UNI_light1_Diffuse;
- float light1Spec = clamp(dot(light1R, V), 0.001, 1.0);
- light1_Specular = pow(light1Spec, UNI_light1_CosinePower) * UNI_light1_Specular;
-
- gl_PointSize = 1.0;
- varTex0 = ATTRIB_texture0;
-}
diff --git a/libs/rs/java/Samples/res/raw/torus.a3d b/libs/rs/java/Samples/res/raw/torus.a3d
deleted file mode 100644
index 0322b01..0000000
--- a/libs/rs/java/Samples/res/raw/torus.a3d
+++ /dev/null
Binary files differ
diff --git a/libs/rs/java/Samples/src/com/android/samples/RsList.java b/libs/rs/java/Samples/src/com/android/samples/RsList.java
deleted file mode 100644
index 2d7add0..0000000
--- a/libs/rs/java/Samples/src/com/android/samples/RsList.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.samples;
-
-import android.app.Activity;
-import android.os.Bundle;
-
-public class RsList extends Activity {
-
- private RsListView mView;
-
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
-
- // Create our Preview view and set it as the content of our
- // Activity
- mView = new RsListView(this);
- setContentView(mView);
- }
-
- @Override
- protected void onResume() {
- // Ideally a game should implement onResume() and onPause()
- // to take appropriate action when the activity loses focus
- super.onResume();
- mView.resume();
- }
-
- @Override
- protected void onPause() {
- // Ideally a game should implement onResume() and onPause()
- // to take appropriate action when the activity loses focus
- super.onPause();
- mView.pause();
- }
-
-}
-
diff --git a/libs/rs/java/Samples/src/com/android/samples/RsListRS.java b/libs/rs/java/Samples/src/com/android/samples/RsListRS.java
deleted file mode 100644
index 6ee545ac..0000000
--- a/libs/rs/java/Samples/src/com/android/samples/RsListRS.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.samples;
-
-import java.io.Writer;
-import java.util.Vector;
-
-import android.content.res.Resources;
-import android.renderscript.*;
-import android.renderscript.ProgramStore.DepthFunc;
-import android.util.Log;
-
-
-public class RsListRS {
-
- private final int STATE_LAST_FOCUS = 1;
-
- 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"
- };
-
- public RsListRS() {
- }
-
- public void init(RenderScriptGL rs, Resources res) {
- mRS = rs;
- mRes = res;
- initRS();
- }
-
- private Resources mRes;
- private RenderScriptGL mRS;
- private Font mItalic;
-
- ScriptField_ListAllocs_s mListAllocs;
-
- private ScriptC_rslist mScript;
-
- int mLastX;
- int mLastY;
-
- public void onActionDown(int x, int y) {
- mScript.set_gDY(0.0f);
-
- mLastX = x;
- mLastY = y;
- }
-
- public void onActionMove(int x, int y) {
- int dx = mLastX - x;
- int dy = mLastY - y;
-
- if (Math.abs(dy) <= 2) {
- dy = 0;
- }
-
- mScript.set_gDY(dy);
-
- mLastX = x;
- mLastY = y;
- }
-
- private void initRS() {
-
- mScript = new ScriptC_rslist(mRS, mRes, R.raw.rslist);
-
- mListAllocs = new ScriptField_ListAllocs_s(mRS, DATA_LIST.length);
- for (int i = 0; i < DATA_LIST.length; i ++) {
- ScriptField_ListAllocs_s.Item listElem = new ScriptField_ListAllocs_s.Item();
- listElem.text = Allocation.createFromString(mRS, DATA_LIST[i], Allocation.USAGE_SCRIPT);
- mListAllocs.set(listElem, i, false);
- }
-
- mListAllocs.copyAll();
-
- mScript.bind_gList(mListAllocs);
-
- mItalic = Font.create(mRS, mRes, "serif", Font.Style.BOLD_ITALIC, 8);
- mScript.set_gItalic(mItalic);
-
- mRS.bindRootScript(mScript);
- }
-}
-
-
-
diff --git a/libs/rs/java/Samples/src/com/android/samples/RsListView.java b/libs/rs/java/Samples/src/com/android/samples/RsListView.java
deleted file mode 100644
index b67bd48..0000000
--- a/libs/rs/java/Samples/src/com/android/samples/RsListView.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.samples;
-import android.renderscript.RSSurfaceView;
-import android.renderscript.RenderScriptGL;
-
-import android.content.Context;
-import android.view.MotionEvent;
-
-public class RsListView extends RSSurfaceView {
-
- public RsListView(Context context) {
- super(context);
- ensureRenderScript();
- }
-
- private RenderScriptGL mRS;
- private RsListRS mRender;
-
- private void ensureRenderScript() {
- if (mRS == null) {
- RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig();
- mRS = createRenderScriptGL(sc);
- mRender = new RsListRS();
- mRender.init(mRS, getResources());
- }
- }
-
- @Override
- protected void onAttachedToWindow() {
- super.onAttachedToWindow();
- ensureRenderScript();
- }
-
- @Override
- protected void onDetachedFromWindow() {
- mRender = null;
- if (mRS != null) {
- mRS = null;
- destroyRenderScriptGL();
- }
- }
-
- @Override
- public boolean onTouchEvent(MotionEvent ev)
- {
- boolean ret = false;
- int act = ev.getAction();
- if (act == MotionEvent.ACTION_DOWN) {
- mRender.onActionDown((int)ev.getX(), (int)ev.getY());
- ret = true;
- } else if (act == MotionEvent.ACTION_MOVE) {
- mRender.onActionMove((int)ev.getX(), (int)ev.getY());
- ret = true;
- }
-
- return ret;
- }
-}
-
-
diff --git a/libs/rs/java/Samples/src/com/android/samples/RsRenderStates.java b/libs/rs/java/Samples/src/com/android/samples/RsRenderStates.java
deleted file mode 100644
index ff8c2de..0000000
--- a/libs/rs/java/Samples/src/com/android/samples/RsRenderStates.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.samples;
-
-import android.app.Activity;
-import android.os.Bundle;
-
-public class RsRenderStates extends Activity {
-
- private RsRenderStatesView mView;
-
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
-
- // Create our Preview view and set it as the content of our
- // Activity
- mView = new RsRenderStatesView(this);
- setContentView(mView);
- }
-
- @Override
- protected void onResume() {
- // Ideally a game should implement onResume() and onPause()
- // to take appropriate action when the activity looses focus
- super.onResume();
- mView.resume();
- }
-
- @Override
- protected void onPause() {
- // Ideally a game should implement onResume() and onPause()
- // to take appropriate action when the activity looses focus
- super.onPause();
- mView.pause();
- }
-
-}
-
diff --git a/libs/rs/java/Samples/src/com/android/samples/RsRenderStatesRS.java b/libs/rs/java/Samples/src/com/android/samples/RsRenderStatesRS.java
deleted file mode 100644
index 49b65d6..0000000
--- a/libs/rs/java/Samples/src/com/android/samples/RsRenderStatesRS.java
+++ /dev/null
@@ -1,422 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.samples;
-
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.renderscript.*;
-import android.renderscript.Font.Style;
-import android.renderscript.Program.TextureType;
-import android.renderscript.ProgramStore.DepthFunc;
-import android.renderscript.ProgramStore.BlendSrcFunc;
-import android.renderscript.ProgramStore.BlendDstFunc;
-import android.renderscript.Sampler.Value;
-import android.util.Log;
-
-
-public class RsRenderStatesRS {
-
- int mWidth;
- int mHeight;
-
- public RsRenderStatesRS() {
- }
-
- public void init(RenderScriptGL rs, Resources res) {
- mRS = rs;
- mWidth = mRS.getWidth();
- mHeight = mRS.getHeight();
- mRes = res;
- mOptionsARGB.inScaled = false;
- mOptionsARGB.inPreferredConfig = Bitmap.Config.ARGB_8888;
- mMode = 0;
- mMaxModes = 0;
- initRS();
- }
-
- public void surfaceChanged() {
- mWidth = mRS.getWidth();
- mHeight = mRS.getHeight();
-
- Matrix4f proj = new Matrix4f();
- proj.loadOrthoWindow(mWidth, mHeight);
- mPVA.setProjection(proj);
- }
-
- private Resources mRes;
- private RenderScriptGL mRS;
-
- private Sampler mLinearClamp;
- private Sampler mLinearWrap;
- private Sampler mMipLinearWrap;
- private Sampler mNearestClamp;
- private Sampler mMipLinearAniso8;
- private Sampler mMipLinearAniso15;
-
- private ProgramStore mProgStoreBlendNoneDepth;
- private ProgramStore mProgStoreBlendNone;
- private ProgramStore mProgStoreBlendAlpha;
- private ProgramStore mProgStoreBlendAdd;
-
- private ProgramFragment mProgFragmentTexture;
- private ProgramFragment mProgFragmentColor;
-
- private ProgramVertex mProgVertex;
- private ProgramVertexFixedFunction.Constants mPVA;
-
- // Custom shaders
- private ProgramVertex mProgVertexCustom;
- private ProgramFragment mProgFragmentCustom;
- private ProgramFragment mProgFragmentMultitex;
- private ScriptField_VertexShaderConstants_s mVSConst;
- private ScriptField_VertexShaderConstants2_s mVSConst2;
- private ScriptField_FragentShaderConstants_s mFSConst;
- private ScriptField_FragentShaderConstants2_s mFSConst2;
-
- private ProgramVertex mProgVertexCustom2;
- private ProgramFragment mProgFragmentCustom2;
-
- private ProgramVertex mProgVertexCube;
- private ProgramFragment mProgFragmentCube;
-
- private ProgramRaster mCullBack;
- private ProgramRaster mCullFront;
- private ProgramRaster mCullNone;
-
- private Allocation mTexTorus;
- private Allocation mTexOpaque;
- private Allocation mTexTransparent;
- private Allocation mTexChecker;
- private Allocation mTexCube;
-
- private Mesh mMbyNMesh;
- private Mesh mTorus;
-
- Font mFontSans;
- Font mFontSerif;
- Font mFontSerifBold;
- Font mFontSerifItalic;
- Font mFontSerifBoldItalic;
- Font mFontMono;
- private Allocation mTextAlloc;
-
- private ScriptC_rsrenderstates mScript;
-
- private final BitmapFactory.Options mOptionsARGB = new BitmapFactory.Options();
-
- int mMode;
- int mMaxModes;
-
- public void onActionDown(int x, int y) {
- mMode ++;
- mMode = mMode % mMaxModes;
- mScript.set_gDisplayMode(mMode);
- }
-
- ProgramStore BLEND_ADD_DEPTH_NONE(RenderScript rs) {
- ProgramStore.Builder builder = new ProgramStore.Builder(rs);
- builder.setDepthFunc(ProgramStore.DepthFunc.ALWAYS);
- builder.setBlendFunc(BlendSrcFunc.ONE, BlendDstFunc.ONE);
- builder.setDitherEnabled(false);
- builder.setDepthMaskEnabled(false);
- return builder.create();
- }
-
- private Mesh getMbyNMesh(float width, float height, int wResolution, int hResolution) {
-
- Mesh.TriangleMeshBuilder tmb = new Mesh.TriangleMeshBuilder(mRS,
- 2, Mesh.TriangleMeshBuilder.TEXTURE_0);
-
- for (int y = 0; y <= hResolution; y++) {
- final float normalizedY = (float)y / hResolution;
- final float yOffset = (normalizedY - 0.5f) * height;
- for (int x = 0; x <= wResolution; x++) {
- float normalizedX = (float)x / wResolution;
- float xOffset = (normalizedX - 0.5f) * width;
- tmb.setTexture(normalizedX, normalizedY);
- tmb.addVertex(xOffset, yOffset);
- }
- }
-
- for (int y = 0; y < hResolution; y++) {
- final int curY = y * (wResolution + 1);
- final int belowY = (y + 1) * (wResolution + 1);
- for (int x = 0; x < wResolution; x++) {
- int curV = curY + x;
- int belowV = belowY + x;
- tmb.addTriangle(curV, belowV, curV + 1);
- tmb.addTriangle(belowV, belowV + 1, curV + 1);
- }
- }
-
- return tmb.create(true);
- }
-
- private void initProgramStore() {
- // Use stock the stock program store object
- mProgStoreBlendNoneDepth = ProgramStore.BLEND_NONE_DEPTH_TEST(mRS);
- mProgStoreBlendNone = ProgramStore.BLEND_NONE_DEPTH_NONE(mRS);
-
- // Create a custom program store
- ProgramStore.Builder builder = new ProgramStore.Builder(mRS);
- builder.setDepthFunc(ProgramStore.DepthFunc.ALWAYS);
- builder.setBlendFunc(ProgramStore.BlendSrcFunc.SRC_ALPHA,
- ProgramStore.BlendDstFunc.ONE_MINUS_SRC_ALPHA);
- builder.setDitherEnabled(false);
- builder.setDepthMaskEnabled(false);
- mProgStoreBlendAlpha = builder.create();
-
- mProgStoreBlendAdd = BLEND_ADD_DEPTH_NONE(mRS);
-
- mScript.set_gProgStoreBlendNoneDepth(mProgStoreBlendNoneDepth);
- mScript.set_gProgStoreBlendNone(mProgStoreBlendNone);
- mScript.set_gProgStoreBlendAlpha(mProgStoreBlendAlpha);
- mScript.set_gProgStoreBlendAdd(mProgStoreBlendAdd);
- }
-
- private void initProgramFragment() {
-
- ProgramFragmentFixedFunction.Builder texBuilder = new ProgramFragmentFixedFunction.Builder(mRS);
- texBuilder.setTexture(ProgramFragmentFixedFunction.Builder.EnvMode.REPLACE,
- ProgramFragmentFixedFunction.Builder.Format.RGBA, 0);
- mProgFragmentTexture = texBuilder.create();
- mProgFragmentTexture.bindSampler(mLinearClamp, 0);
-
- ProgramFragmentFixedFunction.Builder colBuilder = new ProgramFragmentFixedFunction.Builder(mRS);
- colBuilder.setVaryingColor(false);
- mProgFragmentColor = colBuilder.create();
-
- mScript.set_gProgFragmentColor(mProgFragmentColor);
- mScript.set_gProgFragmentTexture(mProgFragmentTexture);
- }
-
- private void initProgramVertex() {
- ProgramVertexFixedFunction.Builder pvb = new ProgramVertexFixedFunction.Builder(mRS);
- mProgVertex = pvb.create();
-
- mPVA = new ProgramVertexFixedFunction.Constants(mRS);
- ((ProgramVertexFixedFunction)mProgVertex).bindConstants(mPVA);
- Matrix4f proj = new Matrix4f();
- proj.loadOrthoWindow(mWidth, mHeight);
- mPVA.setProjection(proj);
-
- mScript.set_gProgVertex(mProgVertex);
- }
-
- private void initCustomShaders() {
- mVSConst = new ScriptField_VertexShaderConstants_s(mRS, 1);
- mVSConst2 = new ScriptField_VertexShaderConstants2_s(mRS, 1);
- mFSConst = new ScriptField_FragentShaderConstants_s(mRS, 1);
- mFSConst2 = new ScriptField_FragentShaderConstants2_s(mRS, 1);
-
- mScript.bind_gVSConstants(mVSConst);
- mScript.bind_gVSConstants2(mVSConst2);
- mScript.bind_gFSConstants(mFSConst);
- mScript.bind_gFSConstants2(mFSConst2);
-
- // Initialize the shader builder
- ProgramVertex.Builder pvbCustom = new ProgramVertex.Builder(mRS);
- // Specify the resource that contains the shader string
- pvbCustom.setShader(mRes, R.raw.shaderv);
- // Use a script field to spcify the input layout
- pvbCustom.addInput(ScriptField_VertexShaderInputs_s.createElement(mRS));
- // Define the constant input layout
- pvbCustom.addConstant(mVSConst.getAllocation().getType());
- mProgVertexCustom = pvbCustom.create();
- // Bind the source of constant data
- mProgVertexCustom.bindConstants(mVSConst.getAllocation(), 0);
-
- ProgramFragment.Builder pfbCustom = new ProgramFragment.Builder(mRS);
- // Specify the resource that contains the shader string
- pfbCustom.setShader(mRes, R.raw.shaderf);
- //Tell the builder how many textures we have
- pfbCustom.addTexture(Program.TextureType.TEXTURE_2D);
- // Define the constant input layout
- pfbCustom.addConstant(mFSConst.getAllocation().getType());
- mProgFragmentCustom = pfbCustom.create();
- // Bind the source of constant data
- mProgFragmentCustom.bindConstants(mFSConst.getAllocation(), 0);
-
- pvbCustom = new ProgramVertex.Builder(mRS);
- pvbCustom.setShader(mRes, R.raw.shaderarrayv);
- pvbCustom.addInput(ScriptField_VertexShaderInputs_s.createElement(mRS));
- pvbCustom.addConstant(mVSConst2.getAllocation().getType());
- mProgVertexCustom2 = pvbCustom.create();
- mProgVertexCustom2.bindConstants(mVSConst2.getAllocation(), 0);
-
- pfbCustom = new ProgramFragment.Builder(mRS);
- pfbCustom.setShader(mRes, R.raw.shaderarrayf);
- pfbCustom.addTexture(Program.TextureType.TEXTURE_2D);
- pfbCustom.addConstant(mFSConst2.getAllocation().getType());
- mProgFragmentCustom2 = pfbCustom.create();
- mProgFragmentCustom2.bindConstants(mFSConst2.getAllocation(), 0);
-
- // Cubemap test shaders
- pvbCustom = new ProgramVertex.Builder(mRS);
- pvbCustom.setShader(mRes, R.raw.shadercubev);
- pvbCustom.addInput(ScriptField_VertexShaderInputs_s.createElement(mRS));
- pvbCustom.addConstant(mVSConst.getAllocation().getType());
- mProgVertexCube = pvbCustom.create();
- mProgVertexCube.bindConstants(mVSConst.getAllocation(), 0);
-
- pfbCustom = new ProgramFragment.Builder(mRS);
- pfbCustom.setShader(mRes, R.raw.shadercubef);
- pfbCustom.addTexture(Program.TextureType.TEXTURE_CUBE);
- mProgFragmentCube = pfbCustom.create();
-
- pfbCustom = new ProgramFragment.Builder(mRS);
- pfbCustom.setShader(mRes, R.raw.multitexf);
- for (int texCount = 0; texCount < 3; texCount ++) {
- pfbCustom.addTexture(Program.TextureType.TEXTURE_2D);
- }
- mProgFragmentMultitex = pfbCustom.create();
-
- mScript.set_gProgVertexCustom(mProgVertexCustom);
- mScript.set_gProgFragmentCustom(mProgFragmentCustom);
- mScript.set_gProgVertexCustom2(mProgVertexCustom2);
- mScript.set_gProgFragmentCustom2(mProgFragmentCustom2);
- mScript.set_gProgVertexCube(mProgVertexCube);
- mScript.set_gProgFragmentCube(mProgFragmentCube);
- mScript.set_gProgFragmentMultitex(mProgFragmentMultitex);
- }
-
- private Allocation loadTextureRGB(int id) {
- return Allocation.createFromBitmapResource(mRS, mRes, id,
- Allocation.MipmapControl.MIPMAP_ON_SYNC_TO_TEXTURE,
- Allocation.USAGE_GRAPHICS_TEXTURE);
- }
-
- private Allocation loadTextureARGB(int id) {
- Bitmap b = BitmapFactory.decodeResource(mRes, id, mOptionsARGB);
- return Allocation.createFromBitmap(mRS, b,
- Allocation.MipmapControl.MIPMAP_ON_SYNC_TO_TEXTURE,
- Allocation.USAGE_GRAPHICS_TEXTURE);
- }
-
- private void loadImages() {
- mTexTorus = loadTextureRGB(R.drawable.torusmap);
- mTexOpaque = loadTextureRGB(R.drawable.data);
- mTexTransparent = loadTextureARGB(R.drawable.leaf);
- mTexChecker = loadTextureRGB(R.drawable.checker);
- Bitmap b = BitmapFactory.decodeResource(mRes, R.drawable.cubemap_test);
- mTexCube = Allocation.createCubemapFromBitmap(mRS, b);
-
- mScript.set_gTexTorus(mTexTorus);
- mScript.set_gTexOpaque(mTexOpaque);
- mScript.set_gTexTransparent(mTexTransparent);
- mScript.set_gTexChecker(mTexChecker);
- mScript.set_gTexCube(mTexCube);
- }
-
- private void initFonts() {
- // Sans font by family name
- mFontSans = Font.create(mRS, mRes, "sans-serif", Font.Style.NORMAL, 8);
- mFontSerif = Font.create(mRS, mRes, "serif", Font.Style.NORMAL, 8);
- // Create fonts by family and style
- mFontSerifBold = Font.create(mRS, mRes, "serif", Font.Style.BOLD, 8);
- mFontSerifItalic = Font.create(mRS, mRes, "serif", Font.Style.ITALIC, 8);
- mFontSerifBoldItalic = Font.create(mRS, mRes, "serif", Font.Style.BOLD_ITALIC, 8);
- mFontMono = Font.create(mRS, mRes, "mono", Font.Style.NORMAL, 8);
-
- mTextAlloc = Allocation.createFromString(mRS, "String from allocation", Allocation.USAGE_SCRIPT);
-
- mScript.set_gFontSans(mFontSans);
- mScript.set_gFontSerif(mFontSerif);
- mScript.set_gFontSerifBold(mFontSerifBold);
- mScript.set_gFontSerifItalic(mFontSerifItalic);
- mScript.set_gFontSerifBoldItalic(mFontSerifBoldItalic);
- mScript.set_gFontMono(mFontMono);
- mScript.set_gTextAlloc(mTextAlloc);
- }
-
- private void initMesh() {
- mMbyNMesh = getMbyNMesh(256, 256, 10, 10);
- mScript.set_gMbyNMesh(mMbyNMesh);
-
- FileA3D model = FileA3D.createFromResource(mRS, mRes, R.raw.torus);
- FileA3D.IndexEntry entry = model.getIndexEntry(0);
- if (entry == null || entry.getEntryType() != FileA3D.EntryType.MESH) {
- Log.e("rs", "could not load model");
- } else {
- mTorus = (Mesh)entry.getObject();
- mScript.set_gTorusMesh(mTorus);
- }
- }
-
- private void initSamplers() {
- Sampler.Builder bs = new Sampler.Builder(mRS);
- bs.setMinification(Sampler.Value.LINEAR);
- bs.setMagnification(Sampler.Value.LINEAR);
- bs.setWrapS(Sampler.Value.WRAP);
- bs.setWrapT(Sampler.Value.WRAP);
- mLinearWrap = bs.create();
-
- mLinearClamp = Sampler.CLAMP_LINEAR(mRS);
- mNearestClamp = Sampler.CLAMP_NEAREST(mRS);
- mMipLinearWrap = Sampler.WRAP_LINEAR_MIP_LINEAR(mRS);
-
- bs = new Sampler.Builder(mRS);
- bs.setMinification(Sampler.Value.LINEAR_MIP_LINEAR);
- bs.setMagnification(Sampler.Value.LINEAR);
- bs.setWrapS(Sampler.Value.WRAP);
- bs.setWrapT(Sampler.Value.WRAP);
- bs.setAnisotropy(8.0f);
- mMipLinearAniso8 = bs.create();
- bs.setAnisotropy(15.0f);
- mMipLinearAniso15 = bs.create();
-
- mScript.set_gLinearClamp(mLinearClamp);
- mScript.set_gLinearWrap(mLinearWrap);
- mScript.set_gMipLinearWrap(mMipLinearWrap);
- mScript.set_gMipLinearAniso8(mMipLinearAniso8);
- mScript.set_gMipLinearAniso15(mMipLinearAniso15);
- mScript.set_gNearestClamp(mNearestClamp);
- }
-
- private void initProgramRaster() {
- mCullBack = ProgramRaster.CULL_BACK(mRS);
- mCullFront = ProgramRaster.CULL_FRONT(mRS);
- mCullNone = ProgramRaster.CULL_NONE(mRS);
-
- mScript.set_gCullBack(mCullBack);
- mScript.set_gCullFront(mCullFront);
- mScript.set_gCullNone(mCullNone);
- }
-
- private void initRS() {
-
- mScript = new ScriptC_rsrenderstates(mRS, mRes, R.raw.rsrenderstates);
-
- mMaxModes = mScript.get_gMaxModes();
-
- initSamplers();
- initProgramStore();
- initProgramFragment();
- initProgramVertex();
- initFonts();
- loadImages();
- initMesh();
- initProgramRaster();
- initCustomShaders();
-
- mRS.bindRootScript(mScript);
- }
-}
-
-
-
diff --git a/libs/rs/java/Samples/src/com/android/samples/RsRenderStatesView.java b/libs/rs/java/Samples/src/com/android/samples/RsRenderStatesView.java
deleted file mode 100644
index 4d339dd..0000000
--- a/libs/rs/java/Samples/src/com/android/samples/RsRenderStatesView.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.samples;
-
-import android.renderscript.RSSurfaceView;
-import android.renderscript.RenderScriptGL;
-
-import android.content.Context;
-import android.view.MotionEvent;
-import android.view.SurfaceHolder;
-
-public class RsRenderStatesView extends RSSurfaceView {
-
- public RsRenderStatesView(Context context) {
- super(context);
- ensureRenderScript();
- }
-
- private RenderScriptGL mRS;
- private RsRenderStatesRS mRender;
-
- private void ensureRenderScript() {
- if (mRS == null) {
- RenderScriptGL.SurfaceConfig sc = new RenderScriptGL.SurfaceConfig();
- sc.setDepth(16, 24);
- mRS = createRenderScriptGL(sc);
- mRender = new RsRenderStatesRS();
- mRender.init(mRS, getResources());
- }
- }
-
- @Override
- protected void onAttachedToWindow() {
- super.onAttachedToWindow();
- ensureRenderScript();
- }
-
- @Override
- public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
- super.surfaceChanged(holder, format, w, h);
- mRender.surfaceChanged();
- }
-
- @Override
- protected void onDetachedFromWindow() {
- mRender = null;
- if (mRS != null) {
- mRS = null;
- destroyRenderScriptGL();
- }
- }
-
- @Override
- public boolean onTouchEvent(MotionEvent ev) {
- if (ev.getAction() == MotionEvent.ACTION_DOWN) {
- mRender.onActionDown((int)ev.getX(), (int)ev.getY());
- return true;
- }
-
- return false;
- }
-}
-
-
diff --git a/libs/rs/java/Samples/src/com/android/samples/rslist.rs b/libs/rs/java/Samples/src/com/android/samples/rslist.rs
deleted file mode 100644
index 52c870a..0000000
--- a/libs/rs/java/Samples/src/com/android/samples/rslist.rs
+++ /dev/null
@@ -1,70 +0,0 @@
-// Copyright (C) 2009 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#pragma version(1)
-
-#pragma rs java_package_name(com.android.samples)
-
-#include "rs_graphics.rsh"
-
-float gDY;
-
-rs_font gItalic;
-
-typedef struct ListAllocs_s {
- rs_allocation text;
-} ListAllocs;
-
-ListAllocs *gList;
-
-void init() {
- gDY = 0.0f;
-}
-
-int textPos = 0;
-
-int root(int launchID) {
-
- rsgClearColor(0.0f, 0.0f, 0.0f, 0.0f);
-
- textPos -= (int)gDY*2;
- gDY *= 0.95;
-
- rsgFontColor(0.9f, 0.9f, 0.9f, 1.0f);
- rsgBindFont(gItalic);
-
- rs_allocation listAlloc;
- rsSetObject(&listAlloc, rsGetAllocation(gList));
- int allocSize = rsAllocationGetDimX(listAlloc);
-
- int width = rsgGetWidth();
- int height = rsgGetHeight();
-
- int itemHeight = 80;
- int currentYPos = itemHeight + textPos;
-
- for (int i = 0; i < allocSize; i ++) {
- if (currentYPos - itemHeight > height) {
- break;
- }
-
- if (currentYPos > 0) {
- rsgDrawRect(0, currentYPos - 1, width, currentYPos, 0);
- rsgDrawText(gList[i].text, 30, currentYPos - 32);
- }
- currentYPos += itemHeight;
- }
-
- return 10;
-}
diff --git a/libs/rs/java/Samples/src/com/android/samples/rsrenderstates.rs b/libs/rs/java/Samples/src/com/android/samples/rsrenderstates.rs
deleted file mode 100644
index 9019533..0000000
--- a/libs/rs/java/Samples/src/com/android/samples/rsrenderstates.rs
+++ /dev/null
@@ -1,680 +0,0 @@
-// Copyright (C) 2009 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#pragma version(1)
-
-#pragma rs java_package_name(com.android.samples)
-
-#include "rs_graphics.rsh"
-#include "shader_def.rsh"
-
-const int gMaxModes = 11;
-
-rs_program_vertex gProgVertex;
-rs_program_fragment gProgFragmentColor;
-rs_program_fragment gProgFragmentTexture;
-
-rs_program_store gProgStoreBlendNoneDepth;
-rs_program_store gProgStoreBlendNone;
-rs_program_store gProgStoreBlendAlpha;
-rs_program_store gProgStoreBlendAdd;
-
-rs_allocation gTexOpaque;
-rs_allocation gTexTorus;
-rs_allocation gTexTransparent;
-rs_allocation gTexChecker;
-rs_allocation gTexCube;
-
-rs_mesh gMbyNMesh;
-rs_mesh gTorusMesh;
-
-rs_font gFontSans;
-rs_font gFontSerif;
-rs_font gFontSerifBold;
-rs_font gFontSerifItalic;
-rs_font gFontSerifBoldItalic;
-rs_font gFontMono;
-rs_allocation gTextAlloc;
-
-int gDisplayMode;
-
-rs_sampler gLinearClamp;
-rs_sampler gLinearWrap;
-rs_sampler gMipLinearWrap;
-rs_sampler gMipLinearAniso8;
-rs_sampler gMipLinearAniso15;
-rs_sampler gNearestClamp;
-
-rs_program_raster gCullBack;
-rs_program_raster gCullFront;
-rs_program_raster gCullNone;
-
-// Custom vertex shader compunents
-VertexShaderConstants *gVSConstants;
-VertexShaderConstants2 *gVSConstants2;
-FragentShaderConstants *gFSConstants;
-FragentShaderConstants2 *gFSConstants2;
-// Export these out to easily set the inputs to shader
-VertexShaderInputs *gVSInputs;
-// Custom shaders we use for lighting
-rs_program_vertex gProgVertexCustom;
-rs_program_fragment gProgFragmentCustom;
-rs_program_vertex gProgVertexCustom2;
-rs_program_fragment gProgFragmentCustom2;
-rs_program_vertex gProgVertexCube;
-rs_program_fragment gProgFragmentCube;
-rs_program_fragment gProgFragmentMultitex;
-
-float gDt = 0;
-
-void init() {
-}
-
-static void displayFontSamples() {
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- int yPos = 100;
- rsgBindFont(gFontSans);
- rsgDrawText("Sans font sample", 30, yPos);
- yPos += 30;
- rsgFontColor(0.5f, 0.9f, 0.5f, 1.0f);
- rsgBindFont(gFontSerif);
- rsgDrawText("Serif font sample", 30, yPos);
- yPos += 30;
- rsgFontColor(0.7f, 0.7f, 0.7f, 1.0f);
- rsgBindFont(gFontSerifBold);
- rsgDrawText("Serif Bold font sample", 30, yPos);
- yPos += 30;
- rsgFontColor(0.5f, 0.5f, 0.9f, 1.0f);
- rsgBindFont(gFontSerifItalic);
- rsgDrawText("Serif Italic font sample", 30, yPos);
- yPos += 30;
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontSerifBoldItalic);
- rsgDrawText("Serif Bold Italic font sample", 30, yPos);
- yPos += 30;
- rsgBindFont(gFontMono);
- rsgDrawText("Monospace font sample", 30, yPos);
- yPos += 50;
-
- // Now use text metrics to center the text
- uint width = rsgGetWidth();
- uint height = rsgGetHeight();
- int left = 0, right = 0, top = 0, bottom = 0;
-
- rsgFontColor(0.9f, 0.9f, 0.95f, 1.0f);
- rsgBindFont(gFontSerifBoldItalic);
-
- rsgMeasureText(gTextAlloc, &left, &right, &top, &bottom);
- int centeredPos = width / 2 - (right - left) / 2;
- rsgDrawText(gTextAlloc, centeredPos, yPos);
- yPos += 30;
-
- const char* text = "Centered Text Sample";
- rsgMeasureText(text, &left, &right, &top, &bottom);
- centeredPos = width / 2 - (right - left) / 2;
- rsgDrawText(text, centeredPos, yPos);
- yPos += 30;
-
- rsgBindFont(gFontSans);
- text = "More Centered Text Samples";
- rsgMeasureText(text, &left, &right, &top, &bottom);
- centeredPos = width / 2 - (right - left) / 2;
- rsgDrawText(text, centeredPos, yPos);
- yPos += 30;
-
- // Now draw bottom and top right aligned text
- text = "Top-right aligned text";
- rsgMeasureText(text, &left, &right, &top, &bottom);
- rsgDrawText(text, width - right, top);
-
- text = "Top-left";
- rsgMeasureText(text, &left, &right, &top, &bottom);
- rsgDrawText(text, -left, top);
-
- text = "Bottom-right aligned text";
- rsgMeasureText(text, &left, &right, &top, &bottom);
- rsgDrawText(text, width - right, height + bottom);
-
-}
-
-static void bindProgramVertexOrtho() {
- // Default vertex sahder
- rsgBindProgramVertex(gProgVertex);
- // Setup the projectioni matrix
- rs_matrix4x4 proj;
- rsMatrixLoadOrtho(&proj, 0, rsgGetWidth(), rsgGetHeight(), 0, -500, 500);
- rsgProgramVertexLoadProjectionMatrix(&proj);
-}
-
-static void displayShaderSamples() {
- bindProgramVertexOrtho();
- rs_matrix4x4 matrix;
- rsMatrixLoadIdentity(&matrix);
- rsgProgramVertexLoadModelMatrix(&matrix);
-
- // Fragment shader with texture
- rsgBindProgramStore(gProgStoreBlendNone);
- rsgBindProgramFragment(gProgFragmentTexture);
- rsgBindSampler(gProgFragmentTexture, 0, gLinearClamp);
- rsgBindTexture(gProgFragmentTexture, 0, gTexOpaque);
-
- float startX = 0, startY = 0;
- float width = 256, height = 256;
- rsgDrawQuadTexCoords(startX, startY, 0, 0, 0,
- startX, startY + height, 0, 0, 1,
- startX + width, startY + height, 0, 1, 1,
- startX + width, startY, 0, 1, 0);
-
- startX = 200; startY = 0;
- width = 128; height = 128;
- rsgDrawQuadTexCoords(startX, startY, 0, 0, 0,
- startX, startY + height, 0, 0, 1,
- startX + width, startY + height, 0, 1, 1,
- startX + width, startY, 0, 1, 0);
-
- rsgBindProgramStore(gProgStoreBlendAlpha);
- rsgBindTexture(gProgFragmentTexture, 0, gTexTransparent);
- startX = 0; startY = 200;
- width = 128; height = 128;
- rsgDrawQuadTexCoords(startX, startY, 0, 0, 0,
- startX, startY + height, 0, 0, 1,
- startX + width, startY + height, 0, 1, 1,
- startX + width, startY, 0, 1, 0);
-
- // Fragment program with simple color
- rsgBindProgramFragment(gProgFragmentColor);
- rsgProgramFragmentConstantColor(gProgFragmentColor, 0.9, 0.3, 0.3, 1);
- rsgDrawRect(200, 300, 350, 450, 0);
- rsgProgramFragmentConstantColor(gProgFragmentColor, 0.3, 0.9, 0.3, 1);
- rsgDrawRect(50, 400, 400, 600, 0);
-
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontMono);
- rsgDrawText("Texture shader", 10, 50);
- rsgDrawText("Alpha-blended texture shader", 10, 280);
- rsgDrawText("Flat color shader", 100, 450);
-}
-
-static void displayBlendingSamples() {
- int i;
-
- bindProgramVertexOrtho();
- rs_matrix4x4 matrix;
- rsMatrixLoadIdentity(&matrix);
- rsgProgramVertexLoadModelMatrix(&matrix);
-
- rsgBindProgramFragment(gProgFragmentColor);
-
- rsgBindProgramStore(gProgStoreBlendNone);
- for (i = 0; i < 3; i ++) {
- float iPlusOne = (float)(i + 1);
- rsgProgramFragmentConstantColor(gProgFragmentColor,
- 0.1f*iPlusOne, 0.2f*iPlusOne, 0.3f*iPlusOne, 1);
- float yPos = 150 * (float)i;
- rsgDrawRect(0, yPos, 200, yPos + 200, 0);
- }
-
- rsgBindProgramStore(gProgStoreBlendAlpha);
- for (i = 0; i < 3; i ++) {
- float iPlusOne = (float)(i + 1);
- rsgProgramFragmentConstantColor(gProgFragmentColor,
- 0.2f*iPlusOne, 0.3f*iPlusOne, 0.1f*iPlusOne, 0.5);
- float yPos = 150 * (float)i;
- rsgDrawRect(150, yPos, 350, yPos + 200, 0);
- }
-
- rsgBindProgramStore(gProgStoreBlendAdd);
- for (i = 0; i < 3; i ++) {
- float iPlusOne = (float)(i + 1);
- rsgProgramFragmentConstantColor(gProgFragmentColor,
- 0.3f*iPlusOne, 0.1f*iPlusOne, 0.2f*iPlusOne, 0.5);
- float yPos = 150 * (float)i;
- rsgDrawRect(300, yPos, 500, yPos + 200, 0);
- }
-
-
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontMono);
- rsgDrawText("No Blending", 10, 50);
- rsgDrawText("Alpha Blending", 160, 150);
- rsgDrawText("Additive Blending", 320, 250);
-
-}
-
-static void displayMeshSamples() {
-
- bindProgramVertexOrtho();
- rs_matrix4x4 matrix;
- rsMatrixLoadTranslate(&matrix, 128, 128, 0);
- rsgProgramVertexLoadModelMatrix(&matrix);
-
- // Fragment shader with texture
- rsgBindProgramStore(gProgStoreBlendNone);
- rsgBindProgramFragment(gProgFragmentTexture);
- rsgBindSampler(gProgFragmentTexture, 0, gLinearClamp);
- rsgBindTexture(gProgFragmentTexture, 0, gTexOpaque);
-
- rsgDrawMesh(gMbyNMesh);
-
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontMono);
- rsgDrawText("User gen 10 by 10 grid mesh", 10, 250);
-}
-
-static void displayTextureSamplers() {
-
- bindProgramVertexOrtho();
- rs_matrix4x4 matrix;
- rsMatrixLoadIdentity(&matrix);
- rsgProgramVertexLoadModelMatrix(&matrix);
-
- // Fragment shader with texture
- rsgBindProgramStore(gProgStoreBlendNone);
- rsgBindProgramFragment(gProgFragmentTexture);
- rsgBindTexture(gProgFragmentTexture, 0, gTexOpaque);
-
- // Linear clamp
- rsgBindSampler(gProgFragmentTexture, 0, gLinearClamp);
- float startX = 0, startY = 0;
- float width = 300, height = 300;
- rsgDrawQuadTexCoords(startX, startY, 0, 0, 0,
- startX, startY + height, 0, 0, 1.1,
- startX + width, startY + height, 0, 1.1, 1.1,
- startX + width, startY, 0, 1.1, 0);
-
- // Linear Wrap
- rsgBindSampler(gProgFragmentTexture, 0, gLinearWrap);
- startX = 0; startY = 300;
- width = 300; height = 300;
- rsgDrawQuadTexCoords(startX, startY, 0, 0, 0,
- startX, startY + height, 0, 0, 1.1,
- startX + width, startY + height, 0, 1.1, 1.1,
- startX + width, startY, 0, 1.1, 0);
-
- // Nearest
- rsgBindSampler(gProgFragmentTexture, 0, gNearestClamp);
- startX = 300; startY = 0;
- width = 300; height = 300;
- rsgDrawQuadTexCoords(startX, startY, 0, 0, 0,
- startX, startY + height, 0, 0, 1.1,
- startX + width, startY + height, 0, 1.1, 1.1,
- startX + width, startY, 0, 1.1, 0);
-
- rsgBindSampler(gProgFragmentTexture, 0, gMipLinearWrap);
- startX = 300; startY = 300;
- width = 300; height = 300;
- rsgDrawQuadTexCoords(startX, startY, 0, 0, 0,
- startX, startY + height, 0, 0, 1.5,
- startX + width, startY + height, 0, 1.5, 1.5,
- startX + width, startY, 0, 1.5, 0);
-
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontMono);
- rsgDrawText("Filtering: linear clamp", 10, 290);
- rsgDrawText("Filtering: linear wrap", 10, 590);
- rsgDrawText("Filtering: nearest clamp", 310, 290);
- rsgDrawText("Filtering: miplinear wrap", 310, 590);
-}
-
-static float gTorusRotation = 0;
-
-static void displayCullingSamples() {
- rsgBindProgramVertex(gProgVertex);
- // Setup the projectioni matrix with 60 degree field of view
- rs_matrix4x4 proj;
- float aspect = (float)rsgGetWidth() / (float)rsgGetHeight();
- rsMatrixLoadPerspective(&proj, 30.0f, aspect, 0.1f, 100.0f);
- rsgProgramVertexLoadProjectionMatrix(&proj);
-
- // Fragment shader with texture
- rsgBindProgramStore(gProgStoreBlendNoneDepth);
- rsgBindProgramFragment(gProgFragmentTexture);
- rsgBindSampler(gProgFragmentTexture, 0, gLinearClamp);
- rsgBindTexture(gProgFragmentTexture, 0, gTexTorus);
-
- // Aplly a rotation to our mesh
- gTorusRotation += 50.0f * gDt;
- if (gTorusRotation > 360.0f) {
- gTorusRotation -= 360.0f;
- }
-
- rs_matrix4x4 matrix;
- // Position our model on the screen
- rsMatrixLoadTranslate(&matrix, -2.0f, 0.0f, -10.0f);
- rsMatrixRotate(&matrix, gTorusRotation, 1.0f, 0.0f, 0.0f);
- rsgProgramVertexLoadModelMatrix(&matrix);
- // Use front face culling
- rsgBindProgramRaster(gCullFront);
- rsgDrawMesh(gTorusMesh);
-
- rsMatrixLoadTranslate(&matrix, 2.0f, 0.0f, -10.0f);
- rsMatrixRotate(&matrix, gTorusRotation, 1.0f, 0.0f, 0.0f);
- rsgProgramVertexLoadModelMatrix(&matrix);
- // Use back face culling
- rsgBindProgramRaster(gCullBack);
- rsgDrawMesh(gTorusMesh);
-
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontMono);
- rsgDrawText("Displaying mesh front/back face culling", 10, rsgGetHeight() - 10);
-}
-
-static float gLight0Rotation = 0;
-static float gLight1Rotation = 0;
-
-static void setupCustomShaderLights() {
- float4 light0Pos = {-5.0f, 5.0f, -10.0f, 1.0f};
- float4 light1Pos = {2.0f, 5.0f, 15.0f, 1.0f};
- float4 light0DiffCol = {0.9f, 0.7f, 0.7f, 1.0f};
- float4 light0SpecCol = {0.9f, 0.6f, 0.6f, 1.0f};
- float4 light1DiffCol = {0.5f, 0.5f, 0.9f, 1.0f};
- float4 light1SpecCol = {0.5f, 0.5f, 0.9f, 1.0f};
-
- gLight0Rotation += 50.0f * gDt;
- if (gLight0Rotation > 360.0f) {
- gLight0Rotation -= 360.0f;
- }
- gLight1Rotation -= 50.0f * gDt;
- if (gLight1Rotation > 360.0f) {
- gLight1Rotation -= 360.0f;
- }
-
- rs_matrix4x4 l0Mat;
- rsMatrixLoadRotate(&l0Mat, gLight0Rotation, 1.0f, 0.0f, 0.0f);
- light0Pos = rsMatrixMultiply(&l0Mat, light0Pos);
- rs_matrix4x4 l1Mat;
- rsMatrixLoadRotate(&l1Mat, gLight1Rotation, 0.0f, 0.0f, 1.0f);
- light1Pos = rsMatrixMultiply(&l1Mat, light1Pos);
-
- // Set light 0 properties
- gVSConstants->light0_Posision = light0Pos;
- gVSConstants->light0_Diffuse = 1.0f;
- gVSConstants->light0_Specular = 0.5f;
- gVSConstants->light0_CosinePower = 10.0f;
- // Set light 1 properties
- gVSConstants->light1_Posision = light1Pos;
- gVSConstants->light1_Diffuse = 1.0f;
- gVSConstants->light1_Specular = 0.7f;
- gVSConstants->light1_CosinePower = 25.0f;
- rsgAllocationSyncAll(rsGetAllocation(gVSConstants));
-
- gVSConstants2->light_Posision[0] = light0Pos;
- gVSConstants2->light_Diffuse[0] = 1.0f;
- gVSConstants2->light_Specular[0] = 0.5f;
- gVSConstants2->light_CosinePower[0] = 10.0f;
- gVSConstants2->light_Posision[1] = light1Pos;
- gVSConstants2->light_Diffuse[1] = 1.0f;
- gVSConstants2->light_Specular[1] = 0.7f;
- gVSConstants2->light_CosinePower[1] = 25.0f;
- rsgAllocationSyncAll(rsGetAllocation(gVSConstants2));
-
- // Update fragmetn shader constants
- // Set light 0 colors
- gFSConstants->light0_DiffuseColor = light0DiffCol;
- gFSConstants->light0_SpecularColor = light0SpecCol;
- // Set light 1 colors
- gFSConstants->light1_DiffuseColor = light1DiffCol;
- gFSConstants->light1_SpecularColor = light1SpecCol;
- rsgAllocationSyncAll(rsGetAllocation(gFSConstants));
-
- gFSConstants2->light_DiffuseColor[0] = light0DiffCol;
- gFSConstants2->light_SpecularColor[0] = light0SpecCol;
- // Set light 1 colors
- gFSConstants2->light_DiffuseColor[1] = light1DiffCol;
- gFSConstants2->light_SpecularColor[1] = light1SpecCol;
- rsgAllocationSyncAll(rsGetAllocation(gFSConstants2));
-}
-
-static void displayCustomShaderSamples() {
-
- // Update vertex shader constants
- // Load model matrix
- // Aplly a rotation to our mesh
- gTorusRotation += 50.0f * gDt;
- if (gTorusRotation > 360.0f) {
- gTorusRotation -= 360.0f;
- }
-
- // Position our model on the screen
- rsMatrixLoadTranslate(&gVSConstants->model, 0.0f, 0.0f, -10.0f);
- rsMatrixRotate(&gVSConstants->model, gTorusRotation, 1.0f, 0.0f, 0.0f);
- rsMatrixRotate(&gVSConstants->model, gTorusRotation, 0.0f, 0.0f, 1.0f);
- // Setup the projectioni matrix
- float aspect = (float)rsgGetWidth() / (float)rsgGetHeight();
- rsMatrixLoadPerspective(&gVSConstants->proj, 30.0f, aspect, 0.1f, 100.0f);
- setupCustomShaderLights();
-
- rsgBindProgramVertex(gProgVertexCustom);
-
- // Fragment shader with texture
- rsgBindProgramStore(gProgStoreBlendNoneDepth);
- rsgBindProgramFragment(gProgFragmentCustom);
- rsgBindSampler(gProgFragmentCustom, 0, gLinearClamp);
- rsgBindTexture(gProgFragmentCustom, 0, gTexTorus);
-
- // Use back face culling
- rsgBindProgramRaster(gCullBack);
- rsgDrawMesh(gTorusMesh);
-
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontMono);
- rsgDrawText("Custom shader sample", 10, rsgGetHeight() - 10);
-}
-
-static void displayCustomShaderSamples2() {
-
- // Update vertex shader constants
- // Load model matrix
- // Aplly a rotation to our mesh
- gTorusRotation += 50.0f * gDt;
- if (gTorusRotation > 360.0f) {
- gTorusRotation -= 360.0f;
- }
-
- // Position our model on the screen
- rsMatrixLoadTranslate(&gVSConstants2->model[1], 0.0f, 0.0f, -10.0f);
- rsMatrixLoadIdentity(&gVSConstants2->model[0]);
- rsMatrixRotate(&gVSConstants2->model[0], gTorusRotation, 1.0f, 0.0f, 0.0f);
- rsMatrixRotate(&gVSConstants2->model[0], gTorusRotation, 0.0f, 0.0f, 1.0f);
- // Setup the projectioni matrix
- float aspect = (float)rsgGetWidth() / (float)rsgGetHeight();
- rsMatrixLoadPerspective(&gVSConstants2->proj, 30.0f, aspect, 0.1f, 100.0f);
- setupCustomShaderLights();
-
- rsgBindProgramVertex(gProgVertexCustom2);
-
- // Fragment shader with texture
- rsgBindProgramStore(gProgStoreBlendNoneDepth);
- rsgBindProgramFragment(gProgFragmentCustom2);
- rsgBindSampler(gProgFragmentCustom2, 0, gLinearClamp);
- rsgBindTexture(gProgFragmentCustom2, 0, gTexTorus);
-
- // Use back face culling
- rsgBindProgramRaster(gCullBack);
- rsgDrawMesh(gTorusMesh);
-
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontMono);
- rsgDrawText("Custom shader sample with array uniforms", 10, rsgGetHeight() - 10);
-}
-
-static void displayCubemapShaderSample() {
- // Update vertex shader constants
- // Load model matrix
- // Aplly a rotation to our mesh
- gTorusRotation += 50.0f * gDt;
- if (gTorusRotation > 360.0f) {
- gTorusRotation -= 360.0f;
- }
-
- // Position our model on the screen
- // Position our model on the screen
- rsMatrixLoadTranslate(&gVSConstants->model, 0.0f, 0.0f, -10.0f);
- rsMatrixRotate(&gVSConstants->model, gTorusRotation, 1.0f, 0.0f, 0.0f);
- rsMatrixRotate(&gVSConstants->model, gTorusRotation, 0.0f, 0.0f, 1.0f);
- // Setup the projectioni matrix
- float aspect = (float)rsgGetWidth() / (float)rsgGetHeight();
- rsMatrixLoadPerspective(&gVSConstants->proj, 30.0f, aspect, 0.1f, 100.0f);
- rsgAllocationSyncAll(rsGetAllocation(gFSConstants));
-
- rsgBindProgramVertex(gProgVertexCube);
-
- // Fragment shader with texture
- rsgBindProgramStore(gProgStoreBlendNoneDepth);
- rsgBindProgramFragment(gProgFragmentCube);
- rsgBindSampler(gProgFragmentCube, 0, gLinearClamp);
- rsgBindTexture(gProgFragmentCube, 0, gTexCube);
-
- // Use back face culling
- rsgBindProgramRaster(gCullBack);
- rsgDrawMesh(gTorusMesh);
-
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontMono);
- rsgDrawText("Cubemap shader sample", 10, rsgGetHeight() - 10);
-}
-
-static void displayMultitextureSample() {
- bindProgramVertexOrtho();
- rs_matrix4x4 matrix;
- rsMatrixLoadIdentity(&matrix);
- rsgProgramVertexLoadModelMatrix(&matrix);
-
- // Fragment shader with texture
- rsgBindProgramStore(gProgStoreBlendNone);
- rsgBindProgramFragment(gProgFragmentMultitex);
- rsgBindSampler(gProgFragmentMultitex, 0, gLinearClamp);
- rsgBindSampler(gProgFragmentMultitex, 1, gLinearWrap);
- rsgBindSampler(gProgFragmentMultitex, 2, gLinearClamp);
- rsgBindTexture(gProgFragmentMultitex, 0, gTexChecker);
- rsgBindTexture(gProgFragmentMultitex, 1, gTexTorus);
- rsgBindTexture(gProgFragmentMultitex, 2, gTexTransparent);
-
- float startX = 0, startY = 0;
- float width = 256, height = 256;
- rsgDrawQuadTexCoords(startX, startY, 0, 0, 0,
- startX, startY + height, 0, 0, 1,
- startX + width, startY + height, 0, 1, 1,
- startX + width, startY, 0, 1, 0);
-
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontMono);
- rsgDrawText("Custom shader with multitexturing", 10, 280);
-}
-
-static float gAnisoTime = 0.0f;
-static uint anisoMode = 0;
-static void displayAnisoSample() {
-
- gAnisoTime += gDt;
-
- rsgBindProgramVertex(gProgVertex);
- float aspect = (float)rsgGetWidth() / (float)rsgGetHeight();
- rs_matrix4x4 proj;
- rsMatrixLoadPerspective(&proj, 30.0f, aspect, 0.1f, 100.0f);
- rsgProgramVertexLoadProjectionMatrix(&proj);
-
- rs_matrix4x4 matrix;
- // Fragment shader with texture
- rsgBindProgramStore(gProgStoreBlendNone);
- rsgBindProgramFragment(gProgFragmentTexture);
- rsMatrixLoadTranslate(&matrix, 0.0f, 0.0f, -10.0f);
- rsMatrixRotate(&matrix, -80, 1.0f, 0.0f, 0.0f);
- rsgProgramVertexLoadModelMatrix(&matrix);
-
- rsgBindProgramRaster(gCullNone);
-
- rsgBindTexture(gProgFragmentTexture, 0, gTexChecker);
-
- if (gAnisoTime >= 5.0f) {
- gAnisoTime = 0.0f;
- anisoMode ++;
- anisoMode = anisoMode % 3;
- }
-
- if (anisoMode == 0) {
- rsgBindSampler(gProgFragmentTexture, 0, gMipLinearAniso8);
- } else if (anisoMode == 1) {
- rsgBindSampler(gProgFragmentTexture, 0, gMipLinearAniso15);
- } else {
- rsgBindSampler(gProgFragmentTexture, 0, gMipLinearWrap);
- }
-
- float startX = -15;
- float startY = -15;
- float width = 30;
- float height = 30;
- rsgDrawQuadTexCoords(startX, startY, 0, 0, 0,
- startX, startY + height, 0, 0, 10,
- startX + width, startY + height, 0, 10, 10,
- startX + width, startY, 0, 10, 0);
-
- rsgBindProgramRaster(gCullBack);
-
- rsgFontColor(1.0f, 1.0f, 1.0f, 1.0f);
- rsgBindFont(gFontMono);
- if (anisoMode == 0) {
- rsgDrawText("Anisotropic filtering 8", 10, 40);
- } else if (anisoMode == 1) {
- rsgDrawText("Anisotropic filtering 15", 10, 40);
- } else {
- rsgDrawText("Miplinear filtering", 10, 40);
- }
-}
-
-int root(int launchID) {
-
- gDt = rsGetDt();
-
- rsgClearColor(0.2f, 0.2f, 0.2f, 0.0f);
- rsgClearDepth(1.0f);
-
- switch (gDisplayMode) {
- case 0:
- displayFontSamples();
- break;
- case 1:
- displayShaderSamples();
- break;
- case 2:
- displayBlendingSamples();
- break;
- case 3:
- displayMeshSamples();
- break;
- case 4:
- displayTextureSamplers();
- break;
- case 5:
- displayCullingSamples();
- break;
- case 6:
- displayCustomShaderSamples();
- break;
- case 7:
- displayMultitextureSample();
- break;
- case 8:
- displayAnisoSample();
- break;
- case 9:
- displayCustomShaderSamples2();
- break;
- case 10:
- displayCubemapShaderSample();
- break;
- }
-
- return 10;
-}
diff --git a/libs/rs/java/Samples/src/com/android/samples/shader_def.rsh b/libs/rs/java/Samples/src/com/android/samples/shader_def.rsh
deleted file mode 100644
index 1d804c6..0000000
--- a/libs/rs/java/Samples/src/com/android/samples/shader_def.rsh
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright (C) 2009 The Android Open Source Project
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-#pragma version(1)
-
-#pragma rs java_package_name(com.android.samples)
-
-typedef struct VertexShaderConstants_s {
- rs_matrix4x4 model;
- rs_matrix4x4 proj;
- float4 light0_Posision;
- float light0_Diffuse;
- float light0_Specular;
- float light0_CosinePower;
-
- float4 light1_Posision;
- float light1_Diffuse;
- float light1_Specular;
- float light1_CosinePower;
-} VertexShaderConstants;
-
-typedef struct VertexShaderConstants2_s {
- rs_matrix4x4 model[2];
- rs_matrix4x4 proj;
- float4 light_Posision[2];
- float light_Diffuse[2];
- float light_Specular[2];
- float light_CosinePower[2];
-} VertexShaderConstants2;
-
-typedef struct VertexShaderConstants3_s {
- rs_matrix4x4 model;
- rs_matrix4x4 proj;
- float time;
-} VertexShaderConstants3;
-
-
-typedef struct FragentShaderConstants_s {
- float4 light0_DiffuseColor;
- float4 light0_SpecularColor;
-
- float4 light1_DiffuseColor;
- float4 light1_SpecularColor;
-} FragentShaderConstants;
-
-typedef struct FragentShaderConstants2_s {
- float4 light_DiffuseColor[2];
- float4 light_SpecularColor[2];
-} FragentShaderConstants2;
-
-typedef struct FragentShaderConstants3_s {
- float4 light0_DiffuseColor;
- float4 light0_SpecularColor;
- float4 light0_Posision;
- float light0_Diffuse;
- float light0_Specular;
- float light0_CosinePower;
-
- float4 light1_DiffuseColor;
- float4 light1_SpecularColor;
- float4 light1_Posision;
- float light1_Diffuse;
- float light1_Specular;
- float light1_CosinePower;
-} FragentShaderConstants3;
-
-typedef struct VertexShaderInputs_s {
- float4 position;
- float3 normal;
- float2 texture0;
-} VertexShaderInputs;
-
diff --git a/libs/rs/java/_index.html b/libs/rs/java/_index.html
deleted file mode 100644
index 5872431..0000000
--- a/libs/rs/java/_index.html
+++ /dev/null
@@ -1 +0,0 @@
-<p>A set of samples that demonstrate how to use various features of the Renderscript APIs.</p>
\ No newline at end of file
diff --git a/libs/surfaceflinger_client/Surface.cpp b/libs/surfaceflinger_client/Surface.cpp
index 1e9bd74..68611d6 100644
--- a/libs/surfaceflinger_client/Surface.cpp
+++ b/libs/surfaceflinger_client/Surface.cpp
@@ -1040,7 +1040,7 @@
// e.g. if GraphicBuffer is used to wrap an android_native_buffer_t that
// was dequeued from an ANativeWindow.
for (size_t i = 0; i < mBuffers.size(); i++) {
- if (buffer->handle == mBuffers[i]->handle) {
+ if (mBuffers[i] != 0 && buffer->handle == mBuffers[i]->handle) {
idx = mBuffers[i]->getIndex();
break;
}
diff --git a/libs/rs/java/Fountain/Android.mk b/libs/usb/Android.mk
similarity index 73%
rename from libs/rs/java/Fountain/Android.mk
rename to libs/usb/Android.mk
index 71944b2..d0ef6f0 100644
--- a/libs/rs/java/Fountain/Android.mk
+++ b/libs/usb/Android.mk
@@ -14,18 +14,14 @@
# limitations under the License.
#
-ifneq ($(TARGET_SIMULATOR),true)
-
LOCAL_PATH := $(call my-dir)
+
include $(CLEAR_VARS)
+LOCAL_SRC_FILES := $(call all-java-files-under,src)
+
LOCAL_MODULE_TAGS := optional
-LOCAL_SRC_FILES := $(call all-java-files-under, src) $(call all-renderscript-files-under, src)
-#LOCAL_STATIC_JAVA_LIBRARIES := android.renderscript
+LOCAL_MODULE:= com.google.android.usb
-LOCAL_PACKAGE_NAME := Fountain
-
-include $(BUILD_PACKAGE)
-
-endif
+include $(BUILD_JAVA_LIBRARY)
diff --git a/libs/usb/src/com/google/android/usb/UsbAccessory.java b/libs/usb/src/com/google/android/usb/UsbAccessory.java
new file mode 100644
index 0000000..91095f3
--- /dev/null
+++ b/libs/usb/src/com/google/android/usb/UsbAccessory.java
@@ -0,0 +1,96 @@
+/*
+ * 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.google.android.usb;
+
+/**
+ * A class representing a USB accessory.
+ */
+public final class UsbAccessory {
+
+ private final String mManufacturer;
+ private final String mModel;
+ private final String mType;
+ private final String mVersion;
+
+ /* package */ UsbAccessory(android.hardware.UsbAccessory accessory) {
+ mManufacturer = accessory.getManufacturer();
+ mModel = accessory.getModel();
+ mType = accessory.getType();
+ mVersion = accessory.getVersion();
+ }
+
+ /**
+ * Returns the manufacturer of the accessory.
+ *
+ * @return the accessory manufacturer
+ */
+ public String getManufacturer() {
+ return mManufacturer;
+ }
+
+ /**
+ * Returns the model name of the accessory.
+ *
+ * @return the accessory model
+ */
+ public String getModel() {
+ return mModel;
+ }
+
+ /**
+ * Returns the type of the accessory.
+ *
+ * @return the accessory type
+ */
+ public String getType() {
+ return mType;
+ }
+
+ /**
+ * Returns the version of the accessory.
+ *
+ * @return the accessory version
+ */
+ public String getVersion() {
+ return mVersion;
+ }
+
+ private static boolean compare(String s1, String s2) {
+ if (s1 == null) return (s2 == null);
+ return s1.equals(s2);
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj instanceof UsbAccessory) {
+ UsbAccessory accessory = (UsbAccessory)obj;
+ return (compare(mManufacturer, accessory.getManufacturer()) &&
+ compare(mModel, accessory.getModel()) &&
+ compare(mType, accessory.getType()) &&
+ compare(mVersion, accessory.getVersion()));
+ }
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return "UsbAccessory[mManufacturer=" + mManufacturer +
+ ", mModel=" + mModel +
+ ", mType=" + mType +
+ ", mVersion=" + mVersion + "]";
+ }
+}
diff --git a/libs/usb/src/com/google/android/usb/UsbManager.java b/libs/usb/src/com/google/android/usb/UsbManager.java
new file mode 100644
index 0000000..1b9bff9
--- /dev/null
+++ b/libs/usb/src/com/google/android/usb/UsbManager.java
@@ -0,0 +1,127 @@
+/*
+ * 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.google.android.usb;
+
+import android.content.Context;
+import android.content.Intent;
+import android.hardware.IUsbManager;
+import android.os.IBinder;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Log;
+
+/**
+ * This class allows you to access the state of USB, both in host and device mode.
+ *
+ * <p>You can obtain an instance of this class by calling {@link #getInstance}
+ *
+ */
+public class UsbManager {
+ private static final String TAG = "UsbManager";
+
+ /**
+ * Broadcast Action: A broadcast for USB accessory attached event.
+ *
+ * This intent is sent when a USB accessory is attached.
+ * Call {@link #getAccessory(android.content.Intent)} to retrieve the
+ * {@link com.google.android.usb.UsbAccessory} for the attached accessory.
+ */
+ public static final String ACTION_USB_ACCESSORY_ATTACHED =
+ "android.hardware.action.USB_ACCESSORY_ATTACHED";
+
+ /**
+ * Broadcast Action: A broadcast for USB accessory detached event.
+ *
+ * This intent is sent when a USB accessory is detached.
+ * Call {@link #getAccessory(android.content.Intent)} to retrieve the
+ * {@link com.google.android.usb.UsbAccessory} for the attached accessory that was detached.
+ */
+ public static final String ACTION_USB_ACCESSORY_DETACHED =
+ "android.hardware.action.USB_ACCESSORY_DETACHED";
+
+ private final IUsbManager mService;
+
+ private UsbManager(IUsbManager service) {
+ mService = service;
+ }
+
+ /**
+ * Returns a new instance of this class.
+ *
+ * @return UsbManager instance.
+ */
+ public static UsbManager getInstance() {
+ IBinder b = ServiceManager.getService(Context.USB_SERVICE);
+ return new UsbManager(IUsbManager.Stub.asInterface(b));
+ }
+
+ /**
+ * Returns the {@link com.google.android.usb.UsbAccessory} for
+ * a {@link #ACTION_USB_ACCESSORY_ATTACHED} or {@link #ACTION_USB_ACCESSORY_ATTACHED}
+ * broadcast Intent
+ *
+ * @return UsbAccessory for the broadcast.
+ */
+ public static UsbAccessory getAccessory(Intent intent) {
+ android.hardware.UsbAccessory accessory =
+ intent.getParcelableExtra(android.hardware.UsbManager.EXTRA_ACCESSORY);
+ if (accessory == null) {
+ return null;
+ } else {
+ return new UsbAccessory(accessory);
+ }
+ }
+
+ /**
+ * Returns a list of currently attached USB accessories.
+ * (in the current implementation there can be at most one)
+ *
+ * @return list of USB accessories, or null if none are attached.
+ */
+ public UsbAccessory[] getAccessoryList() {
+ try {
+ android.hardware.UsbAccessory accessory = mService.getCurrentAccessory();
+ if (accessory == null) {
+ return null;
+ } else {
+ return new UsbAccessory[] { new UsbAccessory(accessory) };
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "RemoteException in getAccessoryList" , e);
+ return null;
+ }
+ }
+
+ /**
+ * Opens a file descriptor for reading and writing data to the USB accessory.
+ *
+ * @param accessory the USB accessory to open
+ * @return file descriptor, or null if the accessor could not be opened.
+ */
+ public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
+ try {
+ return mService.openAccessory(new android.hardware.UsbAccessory(
+ accessory.getManufacturer(),accessory.getModel(),
+ accessory.getType(), accessory.getVersion()));
+ } catch (RemoteException e) {
+ Log.e(TAG, "RemoteException in openAccessory" , e);
+ return null;
+ }
+ }
+}
diff --git a/libs/usb/tests/AccessoryChat/Android.mk b/libs/usb/tests/AccessoryChat/Android.mk
new file mode 100644
index 0000000..b854569
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/Android.mk
@@ -0,0 +1,15 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := tests
+
+LOCAL_SRC_FILES := $(call all-subdir-java-files)
+
+LOCAL_PACKAGE_NAME := AccessoryChatGB
+
+LOCAL_JAVA_LIBRARIES := com.google.android.usb
+
+# Force an old SDK version to make sure we aren't using newer UsbManager APIs
+LOCAL_SDK_VERSION := 8
+
+include $(BUILD_PACKAGE)
diff --git a/libs/usb/tests/AccessoryChat/AndroidManifest.xml b/libs/usb/tests/AccessoryChat/AndroidManifest.xml
new file mode 100644
index 0000000..b63999c
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/AndroidManifest.xml
@@ -0,0 +1,23 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.google.android.accessorychat">
+
+ <application>
+ <uses-library android:name="com.google.android.usb" />
+
+ <activity android:name="AccessoryChat" android:label="Accessory Chat GB">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+
+ <intent-filter>
+ <action android:name="android.hardware.action.USB_ACCESSORY_ATTACHED" />
+ </intent-filter>
+
+ <meta-data android:name="android.hardware.action.USB_ACCESSORY_ATTACHED"
+ android:resource="@xml/accessory_filter" />
+ </activity>
+ </application>
+ <uses-sdk android:minSdkVersion="8" />
+</manifest>
diff --git a/libs/usb/tests/AccessoryChat/README.txt b/libs/usb/tests/AccessoryChat/README.txt
new file mode 100644
index 0000000..d2ce11e
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/README.txt
@@ -0,0 +1,10 @@
+This is a test app for the USB accessory APIs. It consists of two parts:
+
+AccessoryChat - A Java app with a chat-like UI that sends and receives strings
+ via the UsbAccessory class.
+
+accessorychat - A C command-line program that communicates with AccessoryChat.
+ This program behaves as if it were a USB accessory.
+ It builds both for the host (Linux PC) and as an android
+ command line program, which will work if run as root on an
+ android device with USB host support
diff --git a/libs/usb/tests/AccessoryChat/accessorychat/Android.mk b/libs/usb/tests/AccessoryChat/accessorychat/Android.mk
new file mode 100644
index 0000000..300224a
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/accessorychat/Android.mk
@@ -0,0 +1,34 @@
+LOCAL_PATH:= $(call my-dir)
+
+# Build for Linux (desktop) host
+ifeq ($(HOST_OS),linux)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := accessorychat.c
+
+LOCAL_MODULE := accessorychat
+
+LOCAL_C_INCLUDES += bionic/libc/kernel/common
+LOCAL_STATIC_LIBRARIES := libusbhost libcutils
+LOCAL_LDLIBS += -lpthread
+LOCAL_CFLAGS := -g -O0
+
+include $(BUILD_HOST_EXECUTABLE)
+
+endif
+
+# Build for device
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_SRC_FILES := accessorychat.c
+
+LOCAL_MODULE := accessorychat
+
+LOCAL_SHARED_LIBRARIES := libusbhost libcutils
+
+include $(BUILD_EXECUTABLE)
diff --git a/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c b/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c
new file mode 100644
index 0000000..94cc0ce
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/accessorychat/accessorychat.c
@@ -0,0 +1,174 @@
+/*
+ * 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.
+ */
+
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <pthread.h>
+
+#include <usbhost/usbhost.h>
+#include <linux/usb/f_accessory.h>
+
+struct usb_device *sDevice = NULL;
+
+static void* read_thread(void* arg) {
+ int endpoint = (int)arg;
+ int ret = 0;
+
+ while (sDevice && ret >= 0) {
+ char buffer[16384];
+
+ ret = usb_device_bulk_transfer(sDevice, endpoint, buffer, sizeof(buffer), 1000);
+ if (ret < 0 && errno == ETIMEDOUT)
+ ret = 0;
+ if (ret > 0) {
+ fwrite(buffer, 1, ret, stdout);
+ printf("\n");
+ fflush(stdout);
+ }
+ }
+
+ return NULL;
+}
+
+static void* write_thread(void* arg) {
+ int endpoint = (int)arg;
+ int ret = 0;
+
+ while (ret >= 0) {
+ char buffer[16384];
+ char *line = fgets(buffer, sizeof(buffer), stdin);
+ if (!line || !sDevice)
+ break;
+ ret = usb_device_bulk_transfer(sDevice, endpoint, line, strlen(line), 1000);
+ }
+
+ return NULL;
+}
+
+static void send_string(struct usb_device *device, int index, const char* string) {
+ int ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
+ ACCESSORY_SEND_STRING, 0, index, (void *)string, strlen(string) + 1, 0);
+}
+
+static int usb_device_added(const char *devname, void* client_data) {
+ struct usb_descriptor_header* desc;
+ struct usb_descriptor_iter iter;
+ uint16_t vendorId, productId;
+ int ret;
+ pthread_t th;
+
+ struct usb_device *device = usb_device_open(devname);
+ if (!device) {
+ fprintf(stderr, "usb_device_open failed\n");
+ return 0;
+ }
+
+ vendorId = usb_device_get_vendor_id(device);
+ productId = usb_device_get_product_id(device);
+
+ if (vendorId == 0x18D1 || vendorId == 0x22B8) {
+ if (!sDevice && (productId == 0x2D00 || productId == 0x2D01)) {
+ struct usb_descriptor_header* desc;
+ struct usb_descriptor_iter iter;
+ struct usb_interface_descriptor *intf = NULL;
+ struct usb_endpoint_descriptor *ep1 = NULL;
+ struct usb_endpoint_descriptor *ep2 = NULL;
+
+ printf("Found android device in accessory mode\n");
+ sDevice = device;
+
+ usb_descriptor_iter_init(device, &iter);
+ while ((desc = usb_descriptor_iter_next(&iter)) != NULL && (!intf || !ep1 || !ep2)) {
+ if (desc->bDescriptorType == USB_DT_INTERFACE) {
+ intf = (struct usb_interface_descriptor *)desc;
+ } else if (desc->bDescriptorType == USB_DT_ENDPOINT) {
+ if (ep1)
+ ep2 = (struct usb_endpoint_descriptor *)desc;
+ else
+ ep1 = (struct usb_endpoint_descriptor *)desc;
+ }
+ }
+
+ if (!intf) {
+ fprintf(stderr, "interface not found\n");
+ exit(1);
+ }
+ if (!ep1 || !ep2) {
+ fprintf(stderr, "endpoints not found\n");
+ exit(1);
+ }
+
+ if (usb_device_claim_interface(device, intf->bInterfaceNumber)) {
+ fprintf(stderr, "usb_device_claim_interface failed errno: %d\n", errno);
+ exit(1);
+ }
+
+ if ((ep1->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) {
+ pthread_create(&th, NULL, read_thread, (void *)ep1->bEndpointAddress);
+ pthread_create(&th, NULL, write_thread, (void *)ep2->bEndpointAddress);
+ } else {
+ pthread_create(&th, NULL, read_thread, (void *)ep2->bEndpointAddress);
+ pthread_create(&th, NULL, write_thread, (void *)ep1->bEndpointAddress);
+ }
+ } else {
+ printf("Found possible android device - attempting to switch to accessory mode\n");
+
+ send_string(device, ACCESSORY_STRING_MANUFACTURER, "Google, Inc.");
+ send_string(device, ACCESSORY_STRING_MODEL, "AccessoryChat");
+ send_string(device, ACCESSORY_STRING_TYPE, "Sample Program");
+ send_string(device, ACCESSORY_STRING_VERSION, "1.0");
+
+ ret = usb_device_control_transfer(device, USB_DIR_OUT | USB_TYPE_VENDOR,
+ ACCESSORY_START, 0, 0, 0, 0, 0);
+ return 0;
+ }
+ }
+
+ if (device != sDevice)
+ usb_device_close(device);
+
+ return 0;
+}
+
+static int usb_device_removed(const char *devname, void* client_data) {
+ if (sDevice && !strcmp(usb_device_get_name(sDevice), devname)) {
+ usb_device_close(sDevice);
+ sDevice = NULL;
+ // exit when we are disconnected
+ return 1;
+ }
+ return 0;
+}
+
+
+int main(int argc, char* argv[]) {
+ struct usb_host_context* context = usb_host_init();
+ if (!context) {
+ fprintf(stderr, "usb_host_init failed");
+ return 1;
+ }
+
+ // this will never return so it is safe to pass thiz directly
+ usb_host_run(context, usb_device_added, usb_device_removed, NULL, NULL);
+ return 0;
+}
diff --git a/libs/usb/tests/AccessoryChat/res/layout/accessory_chat.xml b/libs/usb/tests/AccessoryChat/res/layout/accessory_chat.xml
new file mode 100644
index 0000000..596ecbf
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/res/layout/accessory_chat.xml
@@ -0,0 +1,47 @@
+<?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:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ >
+
+ <ScrollView android:id="@+id/scroll"
+ android:layout_width="match_parent"
+ android:layout_height="0px"
+ android:layout_weight="1"
+ >
+ <TextView android:id="@+id/log"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="25dp"
+ android:textSize="12sp"
+ android:textColor="#ffffffff"
+ />
+ </ScrollView>
+
+ <EditText android:id="@+id/message"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:capitalize="sentences"
+ android:autoText="true"
+ android:singleLine="true"
+ />
+
+</LinearLayout>
+
+
diff --git a/libs/usb/tests/AccessoryChat/res/xml/accessory_filter.xml b/libs/usb/tests/AccessoryChat/res/xml/accessory_filter.xml
new file mode 100644
index 0000000..588946f
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/res/xml/accessory_filter.xml
@@ -0,0 +1,18 @@
+<?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.
+-->
+<resources>
+ <usb-accessory manufacturer="Google, Inc." model="AccessoryChat" type="Sample Program" version="1.0" />
+</resources>
diff --git a/libs/usb/tests/AccessoryChat/src/com/google/android/accessorychat/AccessoryChat.java b/libs/usb/tests/AccessoryChat/src/com/google/android/accessorychat/AccessoryChat.java
new file mode 100644
index 0000000..0a5701c
--- /dev/null
+++ b/libs/usb/tests/AccessoryChat/src/com/google/android/accessorychat/AccessoryChat.java
@@ -0,0 +1,153 @@
+/*
+ * 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.google.android.accessorychat;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.os.ParcelFileDescriptor;
+import android.view.KeyEvent;
+import android.view.View;
+import android.view.inputmethod.EditorInfo;
+import android.util.Log;
+import android.widget.EditText;
+import android.widget.TextView;
+
+import com.google.android.usb.UsbAccessory;
+import com.google.android.usb.UsbManager;
+
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+public class AccessoryChat extends Activity implements Runnable, TextView.OnEditorActionListener {
+
+ private static final String TAG = "AccessoryChat";
+ TextView mLog;
+ EditText mEditText;
+ ParcelFileDescriptor mFileDescriptor;
+ FileInputStream mInputStream;
+ FileOutputStream mOutputStream;
+
+ private static final int MESSAGE_LOG = 1;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ setContentView(R.layout.accessory_chat);
+ mLog = (TextView)findViewById(R.id.log);
+ mEditText = (EditText)findViewById(R.id.message);
+ mEditText.setOnEditorActionListener(this);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+
+ Intent intent = getIntent();
+ Log.d(TAG, "intent: " + intent);
+ UsbManager manager = UsbManager.getInstance();
+ UsbAccessory[] accessories = manager.getAccessoryList();
+ UsbAccessory accessory = (accessories == null ? null : accessories[0]);
+ if (accessory != null) {
+ mFileDescriptor = manager.openAccessory(accessory);
+ if (mFileDescriptor != null) {
+ FileDescriptor fd = mFileDescriptor.getFileDescriptor();
+ mInputStream = new FileInputStream(fd);
+ mOutputStream = new FileOutputStream(fd);
+ Thread thread = new Thread(null, this, "AccessoryChat");
+ thread.start();
+ } else {
+ Log.d(TAG, "openAccessory fail");
+ }
+ } else {
+ Log.d(TAG, "mAccessory is null");
+ }
+ }
+
+ @Override
+ public void onPause() {
+ super.onPause();
+ if (mFileDescriptor != null) {
+ try {
+ mFileDescriptor.close();
+ } catch (IOException e) {
+ } finally {
+ mFileDescriptor = null;
+ }
+ }
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ }
+
+ public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
+ if (actionId == EditorInfo.IME_ACTION_DONE && mOutputStream != null) {
+ try {
+ mOutputStream.write(v.getText().toString().getBytes());
+ } catch (IOException e) {
+ Log.e(TAG, "write failed", e);
+ }
+ v.setText("");
+ return true;
+ }
+ Log.d(TAG, "onEditorAction " + actionId + " event: " + event);
+ return false;
+ }
+
+ public void run() {
+ int ret = 0;
+ byte[] buffer = new byte[16384];
+ while (ret >= 0) {
+ try {
+ ret = mInputStream.read(buffer);
+ } catch (IOException e) {
+ break;
+ }
+
+ if (ret > 0) {
+ Message m = Message.obtain(mHandler, MESSAGE_LOG);
+ String text = new String(buffer, 0, ret);
+ Log.d(TAG, "chat: " + text);
+ m.obj = text;
+ mHandler.sendMessage(m);
+ }
+ }
+ Log.d(TAG, "thread out");
+ }
+
+ Handler mHandler = new Handler() {
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case MESSAGE_LOG:
+ mLog.setText(mLog.getText() + "\n" + (String)msg.obj);
+ break;
+ }
+ }
+ };
+}
+
+
diff --git a/libs/utils/RefBase.cpp b/libs/utils/RefBase.cpp
index 0fd404d..bb6c125 100644
--- a/libs/utils/RefBase.cpp
+++ b/libs/utils/RefBase.cpp
@@ -99,20 +99,38 @@
#if DEBUG_REFS_FATAL_SANITY_CHECKS
LOG_ALWAYS_FATAL("Strong references remain!");
#else
- LOGE("Strong references remain!");
+ LOGE("Strong references remain:");
#endif
+ ref_entry* refs = mStrongRefs;
+ while (refs) {
+ char inc = refs->ref >= 0 ? '+' : '-';
+ LOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
+#if DEBUG_REFS_CALLSTACK_ENABLED
+ refs->stack.dump();
+#endif;
+ refs = refs->next;
+ }
}
if (!mRetain && mWeakRefs != NULL) {
dumpStack = true;
#if DEBUG_REFS_FATAL_SANITY_CHECKS
- LOG_ALWAYS_FATAL("Weak references remain!");
+ LOG_ALWAYS_FATAL("Weak references remain:");
#else
LOGE("Weak references remain!");
#endif
+ ref_entry* refs = mWeakRefs;
+ while (refs) {
+ char inc = refs->ref >= 0 ? '+' : '-';
+ LOGD("\t%c ID %p (ref %d):", inc, refs->id, refs->ref);
+#if DEBUG_REFS_CALLSTACK_ENABLED
+ refs->stack.dump();
+#endif;
+ refs = refs->next;
+ }
}
-
if (dumpStack) {
+ LOGE("above errors at:");
CallStack stack;
stack.update();
stack.dump();
@@ -228,7 +246,8 @@
if (mTrackEnabled) {
AutoMutex _l(mMutex);
- ref_entry* ref = *refs;
+ ref_entry* const head = *refs;
+ ref_entry* ref = head;
while (ref != NULL) {
if (ref->id == id) {
*refs = ref->next;
@@ -249,6 +268,13 @@
"(weakref_type %p) that doesn't exist!",
id, mBase, this);
+ ref = head;
+ while (ref) {
+ char inc = ref->ref >= 0 ? '+' : '-';
+ LOGD("\t%c ID %p (ref %d):", inc, ref->id, ref->ref);
+ ref = ref->next;
+ }
+
CallStack stack;
stack.update();
stack.dump();
diff --git a/media/java/android/media/videoeditor/MediaArtistNativeHelper.java b/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
index e0df257..53bbb0f 100644
--- a/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
+++ b/media/java/android/media/videoeditor/MediaArtistNativeHelper.java
@@ -3556,7 +3556,7 @@
case MediaProperties.ASPECT_RATIO_4_3:
if (height == MediaProperties.HEIGHT_480)
retValue = VideoFrameSize.VGA;
- if (height == MediaProperties.HEIGHT_720)
+ else if (height == MediaProperties.HEIGHT_720)
retValue = VideoFrameSize.S720p;
break;
case MediaProperties.ASPECT_RATIO_5_3:
@@ -3566,6 +3566,8 @@
case MediaProperties.ASPECT_RATIO_11_9:
if (height == MediaProperties.HEIGHT_144)
retValue = VideoFrameSize.QCIF;
+ else if (height == MediaProperties.HEIGHT_288)
+ retValue = VideoFrameSize.CIF;
break;
}
if (retValue == VideoFrameSize.SIZE_UNDEFINED) {
diff --git a/media/java/android/media/videoeditor/MediaProperties.java b/media/java/android/media/videoeditor/MediaProperties.java
index 0b7ec08..0225807 100755
--- a/media/java/android/media/videoeditor/MediaProperties.java
+++ b/media/java/android/media/videoeditor/MediaProperties.java
@@ -29,6 +29,7 @@
* Supported heights
*/
public static final int HEIGHT_144 = 144;
+ public static final int HEIGHT_288 = 288;
public static final int HEIGHT_360 = 360;
public static final int HEIGHT_480 = 480;
public static final int HEIGHT_720 = 720;
@@ -82,7 +83,8 @@
@SuppressWarnings({"unchecked"})
private static final Pair<Integer, Integer>[] ASPECT_RATIO_11_9_RESOLUTIONS =
new Pair[] {
- new Pair<Integer, Integer>(176, HEIGHT_144)
+ new Pair<Integer, Integer>(176, HEIGHT_144),
+ new Pair<Integer, Integer>(352, HEIGHT_288)
};
@SuppressWarnings({"unchecked"})
diff --git a/media/java/android/media/videoeditor/VideoEditorImpl.java b/media/java/android/media/videoeditor/VideoEditorImpl.java
index 1fb8c61..7e1f73a 100755
--- a/media/java/android/media/videoeditor/VideoEditorImpl.java
+++ b/media/java/android/media/videoeditor/VideoEditorImpl.java
@@ -389,6 +389,8 @@
switch (height) {
case MediaProperties.HEIGHT_144:
break;
+ case MediaProperties.HEIGHT_288:
+ break;
case MediaProperties.HEIGHT_360:
break;
case MediaProperties.HEIGHT_480:
diff --git a/media/libstagefright/ACodec.cpp b/media/libstagefright/ACodec.cpp
index b0ae3d8..2bbb320 100644
--- a/media/libstagefright/ACodec.cpp
+++ b/media/libstagefright/ACodec.cpp
@@ -459,16 +459,12 @@
return err;
}
- // XXX TODO: Do something so the ANativeWindow knows that we'll need to get
- // the same set of buffers.
-
LOGV("[%s] Allocating %lu buffers from a native window of size %lu on "
"output port",
mComponentName.c_str(), def.nBufferCountActual, def.nBufferSize);
// Dequeue buffers and send them to OMX
- OMX_U32 i;
- for (i = 0; i < def.nBufferCountActual; i++) {
+ for (OMX_U32 i = 0; i < def.nBufferCountActual; i++) {
android_native_buffer_t *buf;
err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf);
if (err != 0) {
@@ -477,23 +473,26 @@
}
sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(buf, false));
- IOMX::buffer_id bufferId;
- err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer,
- &bufferId);
- if (err != 0) {
- break;
- }
-
- LOGV("[%s] Registered graphic buffer with ID %p (pointer = %p)",
- mComponentName.c_str(),
- bufferId, graphicBuffer.get());
-
BufferInfo info;
- info.mBufferID = bufferId;
info.mStatus = BufferInfo::OWNED_BY_US;
info.mData = new ABuffer(0);
info.mGraphicBuffer = graphicBuffer;
mBuffers[kPortIndexOutput].push(info);
+
+ IOMX::buffer_id bufferId;
+ err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer,
+ &bufferId);
+ if (err != 0) {
+ LOGE("registering GraphicBuffer %lu with OMX IL component failed: "
+ "%d", i, err);
+ break;
+ }
+
+ mBuffers[kPortIndexOutput].editItemAt(i).mBufferID = bufferId;
+
+ LOGV("[%s] Registered graphic buffer with ID %p (pointer = %p)",
+ mComponentName.c_str(),
+ bufferId, graphicBuffer.get());
}
OMX_U32 cancelStart;
@@ -503,7 +502,7 @@
// If an error occurred while dequeuing we need to cancel any buffers
// that were dequeued.
cancelStart = 0;
- cancelEnd = i;
+ cancelEnd = mBuffers[kPortIndexOutput].size();
} else {
// Return the last two buffers to the native window.
// XXX TODO: The number of buffers the native window owns should
@@ -2286,4 +2285,3 @@
}
} // namespace android
-
diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp
index 5d502e7..00b1310 100644
--- a/media/libstagefright/OMXCodec.cpp
+++ b/media/libstagefright/OMXCodec.cpp
@@ -1769,15 +1769,11 @@
return err;
}
- // XXX TODO: Do something so the ANativeWindow knows that we'll need to get
- // the same set of buffers.
-
CODEC_LOGI("allocating %lu buffers from a native window of size %lu on "
"output port", def.nBufferCountActual, def.nBufferSize);
// Dequeue buffers and send them to OMX
- OMX_U32 i;
- for (i = 0; i < def.nBufferCountActual; i++) {
+ for (OMX_U32 i = 0; i < def.nBufferCountActual; i++) {
android_native_buffer_t* buf;
err = mNativeWindow->dequeueBuffer(mNativeWindow.get(), &buf);
if (err != 0) {
@@ -1786,36 +1782,37 @@
}
sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(buf, false));
- IOMX::buffer_id bufferId;
- err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer,
- &bufferId);
- if (err != 0) {
- break;
- }
-
- CODEC_LOGV("registered graphic buffer with ID %p (pointer = %p)",
- bufferId, graphicBuffer.get());
-
BufferInfo info;
info.mData = NULL;
info.mSize = def.nBufferSize;
- info.mBuffer = bufferId;
info.mStatus = OWNED_BY_US;
info.mMem = NULL;
info.mMediaBuffer = new MediaBuffer(graphicBuffer);
info.mMediaBuffer->setObserver(this);
-
mPortBuffers[kPortIndexOutput].push(info);
+
+ IOMX::buffer_id bufferId;
+ err = mOMX->useGraphicBuffer(mNode, kPortIndexOutput, graphicBuffer,
+ &bufferId);
+ if (err != 0) {
+ CODEC_LOGE("registering GraphicBuffer with OMX IL component "
+ "failed: %d", err);
+ break;
+ }
+
+ mPortBuffers[kPortIndexOutput].editItemAt(i).mBuffer = bufferId;
+
+ CODEC_LOGV("registered graphic buffer with ID %p (pointer = %p)",
+ bufferId, graphicBuffer.get());
}
OMX_U32 cancelStart;
OMX_U32 cancelEnd;
-
if (err != 0) {
// If an error occurred while dequeuing we need to cancel any buffers
// that were dequeued.
cancelStart = 0;
- cancelEnd = i;
+ cancelEnd = mPortBuffers[kPortIndexOutput].size();
} else {
// Return the last two buffers to the native window.
// XXX TODO: The number of buffers the native window owns should probably be
diff --git a/media/libstagefright/colorconversion/ColorConverter.cpp b/media/libstagefright/colorconversion/ColorConverter.cpp
index d518c97..3b92e5d 100644
--- a/media/libstagefright/colorconversion/ColorConverter.cpp
+++ b/media/libstagefright/colorconversion/ColorConverter.cpp
@@ -187,7 +187,7 @@
status_t ColorConverter::convertYUV420Planar(
const BitmapParams &src, const BitmapParams &dst) {
- if (!((dst.mWidth & 3) == 0
+ if (!((dst.mWidth & 1) == 0
&& (src.mCropLeft & 1) == 0
&& src.cropWidth() == dst.cropWidth()
&& src.cropHeight() == dst.cropHeight())) {
diff --git a/media/tests/CameraBrowser/AndroidManifest.xml b/media/tests/CameraBrowser/AndroidManifest.xml
index f167f4b..fccb3ca 100644
--- a/media/tests/CameraBrowser/AndroidManifest.xml
+++ b/media/tests/CameraBrowser/AndroidManifest.xml
@@ -2,7 +2,6 @@
package="com.android.camerabrowser">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
- <uses-permission android:name="android.permission.ACCESS_USB" />
<application android:label="@string/app_label"
android:name="com.android.camerabrowser.CameraBrowserApplication">
@@ -12,20 +11,15 @@
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
+ <intent-filter>
+ <action android:name="android.hardware.action.USB_DEVICE_ATTACHED" />
+ </intent-filter>
+ <meta-data android:name="android.hardware.action.USB_DEVICE_ATTACHED"
+ android:resource="@xml/device_filter" />
</activity>
<activity android:name="StorageBrowser" />
<activity android:name="ObjectBrowser" />
<activity android:name="ObjectViewer" />
-
-<!--
- <receiver android:name="UsbReceiver">
- <intent-filter>
- <action android:name="android.hardware.action.USB_DEVICE_ATTACHED" />
- </intent-filter>
- </receiver>
--->
</application>
-
-
</manifest>
diff --git a/media/tests/CameraBrowser/res/xml/device_filter.xml b/media/tests/CameraBrowser/res/xml/device_filter.xml
new file mode 100644
index 0000000..36cd13d
--- /dev/null
+++ b/media/tests/CameraBrowser/res/xml/device_filter.xml
@@ -0,0 +1,19 @@
+<?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.
+-->
+<resources>
+ <!-- filter for PTP devices -->
+ <usb-device class="6" subclass="1" protocol="1" />
+</resources>
diff --git a/media/tests/CameraBrowser/src/com/android/camerabrowser/UsbReceiver.java b/media/tests/CameraBrowser/src/com/android/camerabrowser/UsbReceiver.java
deleted file mode 100644
index 22d9443..0000000
--- a/media/tests/CameraBrowser/src/com/android/camerabrowser/UsbReceiver.java
+++ /dev/null
@@ -1,48 +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.camerabrowser;
-
-import android.content.Context;
-import android.content.Intent;
-import android.content.BroadcastReceiver;
-import android.hardware.UsbDevice;
-import android.hardware.UsbManager;
-import android.mtp.MtpClient;
-import android.os.Bundle;
-import android.os.Parcelable;
-import android.util.Log;
-
-public class UsbReceiver extends BroadcastReceiver
-{
- private static final String TAG = "UsbReceiver";
-
- @Override
- public void onReceive(Context context, Intent intent) {
- Log.d(TAG, "onReceive " + intent);
- if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(intent.getAction())) {
- UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
- if (MtpClient.isCamera(device)) {
- String deviceName = device.getDeviceName();
- Log.d(TAG, "Got camera: " + deviceName);
- intent = new Intent(context, StorageBrowser.class);
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent.putExtra("device", deviceName);
- context.startActivity(intent);
- }
- }
- }
-}
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkPerfTestRunner.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkPerfTestRunner.java
index 988b229..a6cf355 100755
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkPerfTestRunner.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaFrameworkPerfTestRunner.java
@@ -21,9 +21,10 @@
import com.android.mediaframeworktest.performance.VideoEditorPerformance;
import junit.framework.TestSuite;
+import android.os.Bundle;
import android.test.InstrumentationTestRunner;
import android.test.InstrumentationTestSuite;
-
+import android.util.Log;
/**
* Instrumentation Test Runner for all MediaPlayer tests.
@@ -36,19 +37,30 @@
public class MediaFrameworkPerfTestRunner extends InstrumentationTestRunner {
+ public static boolean mGetNativeHeapDump = false;
- @Override
- public TestSuite getAllTests() {
- TestSuite suite = new InstrumentationTestSuite(this);
- suite.addTestSuite(MediaPlayerPerformance.class);
- /*Video Editor performance Test cases*/
- suite.addTestSuite(VideoEditorPerformance.class);
- return suite;
- }
- @Override
- public ClassLoader getLoader() {
- return MediaFrameworkTestRunner.class.getClassLoader();
- }
+ @Override
+ public TestSuite getAllTests() {
+ TestSuite suite = new InstrumentationTestSuite(this);
+ suite.addTestSuite(MediaPlayerPerformance.class);
+ /* Video Editor performance Test cases */
+ suite.addTestSuite(VideoEditorPerformance.class);
+ return suite;
+ }
+
+ @Override
+ public ClassLoader getLoader() {
+ return MediaFrameworkTestRunner.class.getClassLoader();
+ }
+
+ @Override
+ public void onCreate(Bundle icicle) {
+ super.onCreate(icicle);
+ String get_heap_dump = (String) icicle.get("get_heap_dump");
+ if (get_heap_dump != null) {
+ mGetNativeHeapDump = true;
+ }
+ }
}
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaTestUtil.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaTestUtil.java
new file mode 100755
index 0000000..0183b5d
--- /dev/null
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/MediaTestUtil.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.mediaframeworktest;
+
+import java.io.FileOutputStream;
+
+import android.os.Debug;
+import android.os.Environment;
+
+/**
+ *
+ * Utilities for media framework test.
+ *
+ */
+public class MediaTestUtil {
+ private MediaTestUtil(){
+ }
+
+ private static final String STORAGE_PATH =
+ Environment.getExternalStorageDirectory().toString();
+
+ //Catpure the heapdump for memory leaksage analysis\
+ public static void getNativeHeapDump (String name) throws Exception {
+ System.gc();
+ System.runFinalization();
+ Thread.sleep(1000);
+ FileOutputStream o = new FileOutputStream(STORAGE_PATH + '/' +name + ".dump");
+ Debug.dumpNativeHeap(o.getFD());
+ o.close();
+ }
+}
\ No newline at end of file
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaRecorderTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaRecorderTest.java
index ce6db68..82df6690 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaRecorderTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/functional/MediaRecorderTest.java
@@ -28,7 +28,7 @@
import android.media.EncoderCapabilities;
import android.media.EncoderCapabilities.VideoEncoderCap;
import android.media.EncoderCapabilities.AudioEncoderCap;
-import android.test.ActivityInstrumentationTestCase;
+import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
@@ -42,7 +42,7 @@
/**
* Junit / Instrumentation test case for the media recorder api
*/
-public class MediaRecorderTest extends ActivityInstrumentationTestCase<MediaFrameworkTest> {
+public class MediaRecorderTest extends ActivityInstrumentationTestCase2<MediaFrameworkTest> {
private String TAG = "MediaRecorderTest";
private int mOutputDuration =0;
private int mOutputVideoWidth = 0;
@@ -62,9 +62,9 @@
}
protected void setUp() throws Exception {
- super.setUp();
- Log.v(TAG,"create the media recorder");
+ getActivity();
mRecorder = new MediaRecorder();
+ super.setUp();
}
private void recordVideo(int frameRate, int width, int height,
@@ -199,8 +199,6 @@
return false;
}
-
-
private void getOutputVideoProperty(String outputFilePath) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
@@ -215,8 +213,6 @@
Thread.sleep(1000);
mOutputVideoHeight = mediaPlayer.getVideoHeight();
mOutputVideoWidth = mediaPlayer.getVideoWidth();
- //mOutputVideoHeight = CodecTest.videoHeight(outputFilePath);
- //mOutputVideoWidth = CodecTest.videoWidth(outputFilePath);
mediaPlayer.release();
} catch (Exception e) {
Log.v(TAG, e.toString());
@@ -224,11 +220,6 @@
}
}
- private void removeFile(String filePath) {
- File fileRemove = new File(filePath);
- fileRemove.delete();
- }
-
private boolean validateVideo(String filePath, int width, int height) {
boolean validVideo = false;
getOutputVideoProperty(filePath);
@@ -237,72 +228,9 @@
validVideo = true;
}
Log.v(TAG, "width = " + mOutputVideoWidth + " height = " + mOutputVideoHeight + " Duration = " + mOutputDuration);
- //removeFile(filePath);
return validVideo;
}
-
-
- //Format: HVGA h263
- @Suppress
- public void testHVGAH263() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 480, 320, MediaRecorder.VideoEncoder.H263,
- MediaRecorder.OutputFormat.THREE_GPP, MediaNames.RECORDED_HVGA_H263, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_HVGA_H263, 480, 320);
- assertTrue("HVGAH263", videoRecordedResult);
- }
-
- //Format: QVGA h263
- @Suppress
- public void testQVGAH263() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 320, 240, MediaRecorder.VideoEncoder.H263,
- MediaRecorder.OutputFormat.THREE_GPP, MediaNames.RECORDED_QVGA_H263, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_QVGA_H263, 320, 240);
- assertTrue("QVGAH263", videoRecordedResult);
- }
-
- //Format: SQVGA h263
- @Suppress
- public void testSQVGAH263() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 240, 160, MediaRecorder.VideoEncoder.H263,
- MediaRecorder.OutputFormat.THREE_GPP, MediaNames.RECORDED_SQVGA_H263, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_SQVGA_H263, 240, 160);
- assertTrue("SQVGAH263", videoRecordedResult);
- }
-
- //Format: QCIF h263
- @LargeTest
- public void testQCIFH263() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 176, 144, MediaRecorder.VideoEncoder.H263,
- MediaRecorder.OutputFormat.THREE_GPP, MediaNames.RECORDED_QCIF_H263, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_QCIF_H263, 176, 144);
- assertTrue("QCIFH263", videoRecordedResult);
- }
-
- //Format: CIF h263
- @LargeTest
- public void testCIFH263() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 352, 288, MediaRecorder.VideoEncoder.H263,
- MediaRecorder.OutputFormat.THREE_GPP, MediaNames.RECORDED_CIF_H263, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_CIF_H263, 352, 288);
- assertTrue("CIFH263", videoRecordedResult);
- }
-
-
-
- @LargeTest
- public void testVideoOnly() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 176, 144, MediaRecorder.VideoEncoder.H263,
- MediaRecorder.OutputFormat.MPEG_4, MediaNames.RECORDED_VIDEO_3GP, true);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_VIDEO_3GP, 176, 144);
- assertTrue("QCIFH263 Video Only", videoRecordedResult);
- }
-
+
@LargeTest
/*
* This test case set the camera in portrait mode.
@@ -332,74 +260,6 @@
assertTrue("PortraitH263", videoRecordedResult);
}
- @Suppress
- public void testHVGAMP4() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 480, 320, MediaRecorder.VideoEncoder.MPEG_4_SP,
- MediaRecorder.OutputFormat.MPEG_4, MediaNames.RECORDED_HVGA_MP4, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_HVGA_MP4, 480, 320);
- assertTrue("HVGAMP4", videoRecordedResult);
- }
-
- @Suppress
- public void testQVGAMP4() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 320, 240, MediaRecorder.VideoEncoder.MPEG_4_SP,
- MediaRecorder.OutputFormat.MPEG_4, MediaNames.RECORDED_QVGA_MP4, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_QVGA_MP4, 320, 240);
- assertTrue("QVGAMP4", videoRecordedResult);
- }
-
- @Suppress
- public void testSQVGAMP4() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 240, 160, MediaRecorder.VideoEncoder.MPEG_4_SP,
- MediaRecorder.OutputFormat.MPEG_4, MediaNames.RECORDED_SQVGA_MP4, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_SQVGA_MP4, 240, 160);
- assertTrue("SQVGAMP4", videoRecordedResult);
- }
-
- //Format: QCIF MP4
- @LargeTest
- public void testQCIFMP4() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 176, 144, MediaRecorder.VideoEncoder.MPEG_4_SP,
- MediaRecorder.OutputFormat.MPEG_4, MediaNames.RECORDED_QCIF_MP4, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_QCIF_MP4, 176, 144);
- assertTrue("QCIFMP4", videoRecordedResult);
- }
-
-
- //Format: CIF MP4
- @LargeTest
- public void testCIFMP4() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 352, 288, MediaRecorder.VideoEncoder.MPEG_4_SP,
- MediaRecorder.OutputFormat.MPEG_4, MediaNames.RECORDED_CIF_MP4, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_CIF_MP4, 352, 288);
- assertTrue("CIFMP4", videoRecordedResult);
- }
-
-
- //Format: CIF MP4 output format 3gpp
- @LargeTest
- public void testCIFMP43GPP() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 352, 288, MediaRecorder.VideoEncoder.MPEG_4_SP,
- MediaRecorder.OutputFormat.THREE_GPP, MediaNames.RECORDED_VIDEO_3GP, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_VIDEO_3GP, 352, 288);
- assertTrue("CIFMP4 3GPP", videoRecordedResult);
- }
-
- @LargeTest
- public void testQCIFH2633GPP() throws Exception {
- boolean videoRecordedResult = false;
- recordVideo(15, 176, 144, MediaRecorder.VideoEncoder.H263,
- MediaRecorder.OutputFormat.THREE_GPP, MediaNames.RECORDED_VIDEO_3GP, false);
- videoRecordedResult = validateVideo(MediaNames.RECORDED_VIDEO_3GP, 176, 144);
- assertTrue("QCIFH263 3GPP", videoRecordedResult);
- }
-
@LargeTest
public void testInvalidVideoPath() throws Exception {
boolean isTestInvalidVideoPathSuccessful = false;
@@ -408,23 +268,6 @@
assertTrue("Invalid outputFile Path", isTestInvalidVideoPathSuccessful);
}
- @Suppress
- public void testInvalidVideoSize() throws Exception {
- boolean isTestInvalidVideoSizeSuccessful = false;
- isTestInvalidVideoSizeSuccessful = invalidRecordSetting(15, 800, 600, MediaRecorder.VideoEncoder.H263,
- MediaRecorder.OutputFormat.THREE_GPP, MediaNames.RECORDED_VIDEO_3GP, false);
- assertTrue("Invalid video Size", isTestInvalidVideoSizeSuccessful);
- }
-
- @Suppress
- @LargeTest
- public void testInvalidFrameRate() throws Exception {
- boolean isTestInvalidFrameRateSuccessful = false;
- isTestInvalidFrameRateSuccessful = invalidRecordSetting(50, 176, 144, MediaRecorder.VideoEncoder.H263,
- MediaRecorder.OutputFormat.THREE_GPP, MediaNames.RECORDED_VIDEO_3GP, false);
- assertTrue("Invalid FrameRate", isTestInvalidFrameRateSuccessful);
- }
-
@LargeTest
//test cases for the new codec
public void testDeviceSpecificCodec() throws Exception {
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java
index 0e3029b..34affa7 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/performance/MediaPlayerPerformance.java
@@ -17,7 +17,9 @@
package com.android.mediaframeworktest.performance;
import com.android.mediaframeworktest.MediaFrameworkTest;
+import com.android.mediaframeworktest.MediaFrameworkPerfTestRunner;
import com.android.mediaframeworktest.MediaNames;
+import com.android.mediaframeworktest.MediaTestUtil;
import android.database.sqlite.SQLiteDatabase;
import android.hardware.Camera;
@@ -27,7 +29,7 @@
import android.os.ConditionVariable;
import android.os.Looper;
import android.os.SystemClock;
-import android.test.ActivityInstrumentationTestCase;
+import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.Suppress;
import android.util.Log;
@@ -52,7 +54,7 @@
* Junit / Instrumentation - performance measurement for media player and
* recorder
*/
-public class MediaPlayerPerformance extends ActivityInstrumentationTestCase<MediaFrameworkTest> {
+public class MediaPlayerPerformance extends ActivityInstrumentationTestCase2<MediaFrameworkTest> {
private String TAG = "MediaPlayerPerformance";
@@ -87,6 +89,15 @@
protected void setUp() throws Exception {
super.setUp();
+ getActivity();
+ if (MediaFrameworkPerfTestRunner.mGetNativeHeapDump)
+ MediaTestUtil.getNativeHeapDump(this.getName() + "_before");
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ if (MediaFrameworkPerfTestRunner.mGetNativeHeapDump)
+ MediaTestUtil.getNativeHeapDump(this.getName() + "_after");
}
public void createDB() {
diff --git a/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_ime_default.png b/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_ime_default.png
index e4d5a32..7b54daf 100644
--- a/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_ime_default.png
+++ b/packages/SystemUI/res/drawable-mdpi/ic_sysbar_back_ime_default.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xlarge-mdpi/recents_thumbnail_bg.png b/packages/SystemUI/res/drawable-xlarge-mdpi/recents_thumbnail_bg.png
index 9f72549..87a67c9 100644
--- a/packages/SystemUI/res/drawable-xlarge-mdpi/recents_thumbnail_bg.png
+++ b/packages/SystemUI/res/drawable-xlarge-mdpi/recents_thumbnail_bg.png
Binary files differ
diff --git a/packages/SystemUI/res/drawable-xlarge-mdpi/recents_thumbnail_bg_press.png b/packages/SystemUI/res/drawable-xlarge-mdpi/recents_thumbnail_bg_press.png
new file mode 100644
index 0000000..7f86fb3
--- /dev/null
+++ b/packages/SystemUI/res/drawable-xlarge-mdpi/recents_thumbnail_bg_press.png
Binary files differ
diff --git a/packages/SystemUI/res/layout-xlarge/status_bar_recent_item.xml b/packages/SystemUI/res/layout-xlarge/status_bar_recent_item.xml
index d7e1633..bfa6c36a 100644
--- a/packages/SystemUI/res/layout-xlarge/status_bar_recent_item.xml
+++ b/packages/SystemUI/res/layout-xlarge/status_bar_recent_item.xml
@@ -22,14 +22,14 @@
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
- android:layout_width="156dip">
+ android:layout_width="@dimen/status_bar_recents_thumbnail_view_width">
<ImageView android:id="@+id/app_thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
- android:layout_marginLeft="105dip"
+ android:layout_marginLeft="@dimen/status_bar_recents_thumbnail_left_margin"
android:scaleType="center"
/>
@@ -40,8 +40,8 @@
android:layout_alignParentTop="true"
android:layout_marginLeft="123dip"
android:layout_marginTop="16dip"
- android:maxWidth="64dip"
- android:maxHeight="64dip"
+ android:maxWidth="@dimen/status_bar_recents_thumbnail_max_width"
+ android:maxHeight="@dimen/status_bar_recents_thumbnail_max_height"
android:adjustViewBounds="true"
/>
diff --git a/packages/SystemUI/res/layout-xlarge/status_bar_recent_panel.xml b/packages/SystemUI/res/layout-xlarge/status_bar_recent_panel.xml
index ecd2b6f..4be57a2 100644
--- a/packages/SystemUI/res/layout-xlarge/status_bar_recent_panel.xml
+++ b/packages/SystemUI/res/layout-xlarge/status_bar_recent_panel.xml
@@ -36,36 +36,35 @@
<LinearLayout android:id="@+id/recents_glow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:orientation="horizontal"
- android:layout_marginBottom="-28dip"
+ android:layout_marginBottom="-52dip"
android:layout_gravity="bottom"
- android:background="@drawable/recents_blue_glow">
+ android:background="@drawable/recents_blue_glow"
+ android:orientation="horizontal"
+ >
- <LinearLayout android:id="@+id/recents_container"
- android:layout_width="356dip"
+ <ListView android:id="@+id/recents_container"
+ android:layout_width="@dimen/status_bar_recents_width"
android:layout_height="wrap_content"
- android:orientation="vertical"
android:layout_marginRight="100dip"
+ android:divider="@null"
+ android:scrollingCache="true"
+ android:stackFromBottom="true"
+ android:fadingEdge="vertical"
+ android:scrollbars="none"
+ android:fadingEdgeLength="30dip"
+ android:listSelector="@drawable/recents_thumbnail_bg_press"
/>
</LinearLayout>
</FrameLayout>
- <!-- The outer FrameLayout is just used as an opaque background for the dismiss icon -->
- <FrameLayout
+ <View android:id="@+id/recents_dismiss_button"
android:layout_width="80px"
android:layout_height="@*android:dimen/status_bar_height"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
- android:background="#ff000000">
-
- <View android:id="@+id/recents_dismiss_button"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="@drawable/ic_sysbar_back_ime"
- />
-
- </FrameLayout>
+ android:background="@drawable/ic_sysbar_back_ime"
+ />
</com.android.systemui.statusbar.tablet.RecentAppsPanel>
diff --git a/packages/SystemUI/res/layout-xlarge/status_bar_recent_panel_footer.xml b/packages/SystemUI/res/layout-xlarge/status_bar_recent_panel_footer.xml
new file mode 100644
index 0000000..4d14d1f
--- /dev/null
+++ b/packages/SystemUI/res/layout-xlarge/status_bar_recent_panel_footer.xml
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/* apps/common/assets/default/default/skins/StatusBar.xml
+**
+** 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.
+*/
+-->
+
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/listview_footer_padding"
+ android:layout_height="24dip"
+ android:layout_width="match_parent">
+</FrameLayout>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index 93cf377..88cd43c 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -2,21 +2,34 @@
<!--
* Copyright (c) 2006, The Android Open Source Project
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * 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
+ * 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
+ * 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>
<!-- Margin at the edge of the screen to ignore touch events for in the windowshade. -->
<dimen name="status_bar_edge_ignore">5dp</dimen>
+
+ <!-- Recent Applications parameters -->
+ <!-- Width of a recent app view, including all content -->
+ <dimen name="status_bar_recents_thumbnail_view_width">156dp</dimen>
+ <!-- How far the thumbnail for a recent app appears from left edge -->
+ <dimen name="status_bar_recents_thumbnail_left_margin">110dp</dimen>
+ <!-- Upper width limit for application icon -->
+ <dimen name="status_bar_recents_thumbnail_max_width">64dp</dimen>
+ <!-- Upper height limit for application icon -->
+ <dimen name="status_bar_recents_thumbnail_max_height">64dp</dimen>
+ <!-- Width of scrollable area in recents -->
+ <dimen name="status_bar_recents_width">356dp</dimen>
+
</resources>
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 ad57b39..35ae118 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java
@@ -39,6 +39,7 @@
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
+import android.os.SystemProperties;
import android.provider.Settings;
import android.provider.Telephony;
import android.telephony.PhoneStateListener;
@@ -92,7 +93,7 @@
boolean mWifiEnabled, mWifiConnected;
int mWifiLevel;
String mWifiSsid;
- int mWifiIconId;
+ int mWifiIconId = 0;
// bluetooth
private boolean mBluetoothTethered = false;
@@ -130,6 +131,9 @@
public NetworkController(Context context) {
mContext = context;
+ // set up the default wifi icon, used when no radios have ever appeared
+ updateWifiIcons();
+
// telephony
mPhone = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
mPhone.listen(mPhoneStateListener,
@@ -272,6 +276,10 @@
}
mDataState = state;
mDataNetType = networkType;
+ if (state < 0) {
+ // device without a data connection
+ mSignalStrength = null;
+ }
updateDataNetType();
updateDataIcon();
refreshViews();
@@ -330,6 +338,11 @@
}
}
+ private boolean hasMobileDataFeature() {
+ // XXX: HAX: replace when a more reliable method is available
+ return (! "wifi-only".equals(SystemProperties.get("ro.carrier")));
+ }
+
private final void updateTelephonySignalStrength() {
// Display signal strength while in "emergency calls only" mode
if (mServiceState == null || (!hasService() && !mServiceState.isEmergencyOnly())) {
@@ -708,11 +721,13 @@
dataTypeIconId = 0;
} else {
label = context.getString(R.string.status_bar_settings_signal_meter_disconnected);
- combinedSignalIconId = mDataSignalIconId;
+ // On devices without mobile radios, we want to show the wifi icon
+ combinedSignalIconId =
+ hasMobileDataFeature() ? mDataSignalIconId : mWifiIconId;
dataTypeIconId = 0;
}
- if (false) {
+ if (DEBUG) {
Slog.d(TAG, "refreshViews combinedSignalIconId=0x"
+ Integer.toHexString(combinedSignalIconId)
+ "/" + getResourceName(combinedSignalIconId)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/WifiIcons.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/WifiIcons.java
index 0787289..8d72eba 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/WifiIcons.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/WifiIcons.java
@@ -20,11 +20,13 @@
class WifiIcons {
static final int[][] WIFI_SIGNAL_STRENGTH = {
- { R.drawable.stat_sys_wifi_signal_1,
+ { R.drawable.stat_sys_wifi_signal_0,
+ R.drawable.stat_sys_wifi_signal_1,
R.drawable.stat_sys_wifi_signal_2,
R.drawable.stat_sys_wifi_signal_3,
R.drawable.stat_sys_wifi_signal_4 },
- { R.drawable.stat_sys_wifi_signal_1_fully,
+ { R.drawable.stat_sys_wifi_signal_0,
+ R.drawable.stat_sys_wifi_signal_1_fully,
R.drawable.stat_sys_wifi_signal_2_fully,
R.drawable.stat_sys_wifi_signal_3_fully,
R.drawable.stat_sys_wifi_signal_4_fully }
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 e0d558f..ebe1a7c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/RecentAppsPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/RecentAppsPanel.java
@@ -40,37 +40,43 @@
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
+import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Slog;
+import android.view.LayoutInflater;
import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.animation.DecelerateInterpolator;
+import android.view.ViewGroup;
+import android.widget.AdapterView;
+import android.widget.AdapterView.OnItemClickListener;
+import android.widget.BaseAdapter;
import android.widget.ImageView;
-import android.widget.LinearLayout;
+import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.systemui.R;
-public class RecentAppsPanel extends RelativeLayout implements StatusBarPanel, OnClickListener {
+public class RecentAppsPanel extends RelativeLayout implements StatusBarPanel, OnItemClickListener {
private static final int GLOW_PADDING = 15;
private static final String TAG = "RecentAppsPanel";
private static final boolean DEBUG = TabletStatusBar.DEBUG;
- private static final int DISPLAY_TASKS_PORTRAIT = 7; // Limited by max binder transaction size
- private static final int DISPLAY_TASKS_LANDSCAPE = 5; // number of recent tasks to display
- private static final int MAX_TASKS = DISPLAY_TASKS_PORTRAIT + 1; // allow extra for non-apps
+ private static final int DISPLAY_TASKS = 20;
+ private static final int MAX_TASKS = DISPLAY_TASKS + 1; // allow extra for non-apps
+ private static final int BOTTOM_OFFSET = 28; // TODO: Get from dimens.xml
private TabletStatusBar mBar;
private ArrayList<ActivityDescription> mActivityDescriptions;
private int mIconDpi;
private View mRecentsScrim;
private View mRecentsGlowView;
- private LinearLayout mRecentsContainer;
+ private ListView mRecentsContainer;
private Bitmap mGlowBitmap;
private boolean mShowing;
private Choreographer mChoreo;
private View mRecentsDismissButton;
+ private ActvityDescriptionAdapter mListAdapter;
+ protected int mLastVisibleItem;
static class ActivityDescription {
int id;
@@ -98,6 +104,63 @@
}
};
+ private static class ViewHolder {
+ private ImageView thumbnailView;
+ private ImageView iconView;
+ private TextView labelView;
+ private TextView descriptionView;
+ private ActivityDescription activityDescription;
+ }
+
+ private class ActvityDescriptionAdapter extends BaseAdapter {
+ private LayoutInflater mInflater;
+
+ public ActvityDescriptionAdapter(Context context) {
+ mInflater = LayoutInflater.from(context);
+ }
+
+ public int getCount() {
+ return mActivityDescriptions != null ? mActivityDescriptions.size() : 0;
+ }
+
+ public Object getItem(int position) {
+ return position; // we only need the index
+ }
+
+ public long getItemId(int position) {
+ return position; // we just need something unique for this position
+ }
+
+ public View getView(int position, View convertView, ViewGroup parent) {
+ ViewHolder holder;
+ if (convertView == null) {
+ convertView = mInflater.inflate(R.layout.status_bar_recent_item, null);
+ holder = new ViewHolder();
+ holder.thumbnailView = (ImageView) convertView.findViewById(R.id.app_thumbnail);
+ holder.iconView = (ImageView) convertView.findViewById(R.id.app_icon);
+ holder.labelView = (TextView) convertView.findViewById(R.id.app_label);
+ holder.descriptionView = (TextView) convertView.findViewById(R.id.app_description);
+ convertView.setTag(holder);
+ } else {
+ holder = (ViewHolder) convertView.getTag();
+ }
+
+ // activityId is reverse since most recent appears at the bottom...
+ final int activityId = mActivityDescriptions.size() - position - 1;
+
+ final ActivityDescription activityDescription = mActivityDescriptions.get(activityId);
+ final Bitmap thumb = activityDescription.thumbnail;
+ holder.thumbnailView.setImageBitmap(compositeBitmap(mGlowBitmap, thumb));
+ holder.iconView.setImageDrawable(activityDescription.icon);
+ holder.labelView.setText(activityDescription.label);
+ holder.descriptionView.setText(activityDescription.description);
+ holder.thumbnailView.setTag(activityDescription);
+ holder.activityDescription = activityDescription;
+
+ return convertView;
+ }
+ }
+
public boolean isInContentArea(int x, int y) {
// use mRecentsContainer's exact bounds to determine horizontal position
final int l = mRecentsContainer.getLeft();
@@ -267,9 +330,41 @@
}
@Override
+ protected void onSizeChanged(int w, int h, int oldw, int oldh) {
+ super.onSizeChanged(w, h, oldw, oldh);
+ // Keep track of the last visible item in the list so we can restore it
+ // to the bottom when the orientation changes.
+ int childCount = mRecentsContainer.getChildCount();
+ if (childCount > 0) {
+ mLastVisibleItem = mRecentsContainer.getFirstVisiblePosition() + childCount - 1;
+ View view = mRecentsContainer.getChildAt(childCount - 1);
+ final int distanceFromBottom = mRecentsContainer.getHeight() - view.getTop();
+ //final int distanceFromBottom = view.getHeight() + BOTTOM_OFFSET;
+
+ // This has to happen post-layout, so run it "in the future"
+ post(new Runnable() {
+ public void run() {
+ mRecentsContainer.setSelectionFromTop(mLastVisibleItem,
+ mRecentsContainer.getHeight() - distanceFromBottom);
+ }
+ });
+ }
+ }
+
+ @Override
protected void onFinishInflate() {
super.onFinishInflate();
- mRecentsContainer = (LinearLayout) findViewById(R.id.recents_container);
+ LayoutInflater inflater = (LayoutInflater)
+ mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+
+ mRecentsContainer = (ListView) findViewById(R.id.recents_container);
+ View footer = inflater.inflate(R.layout.status_bar_recent_panel_footer,
+ mRecentsContainer, false);
+ mRecentsContainer.setScrollbarFadingEnabled(true);
+ mRecentsContainer.addFooterView(footer);
+ mRecentsContainer.setAdapter(mListAdapter = new ActvityDescriptionAdapter(mContext));
+ mRecentsContainer.setOnItemClickListener(this);
+
mRecentsGlowView = findViewById(R.id.recents_glow);
mRecentsScrim = (View) findViewById(R.id.recents_bg_protect);
mChoreo = new Choreographer(this, mRecentsScrim, mRecentsGlowView);
@@ -287,20 +382,16 @@
}
@Override
- protected void onConfigurationChanged(Configuration newConfig) {
- super.onConfigurationChanged(newConfig);
- // we show more in portrait mode, so update UI if orientation changes
- updateUiElements(newConfig, false);
- }
-
- @Override
protected void onVisibilityChanged(View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (DEBUG) Log.v(TAG, "onVisibilityChanged(" + changedView + ", " + visibility + ")");
if (visibility == View.VISIBLE && changedView == this) {
refreshApplicationList();
- mRecentsContainer.setScrollbarFadingEnabled(true);
- mRecentsContainer.scrollTo(0, 0);
+ post(new Runnable() {
+ public void run() {
+ mRecentsContainer.setSelection(mActivityDescriptions.size() - 1);
+ }
+ });
}
}
@@ -402,11 +493,12 @@
private void refreshApplicationList() {
mActivityDescriptions = getRecentTasks();
+ mListAdapter.notifyDataSetInvalidated();
if (mActivityDescriptions.size() > 0) {
- updateUiElements(getResources().getConfiguration(), true);
+ mLastVisibleItem = mActivityDescriptions.size() - 1; // scroll to bottom after reloading
+ updateUiElements(getResources().getConfiguration());
} else {
// Immediately hide this panel
- mShowing = false;
hide(false);
}
}
@@ -426,44 +518,29 @@
canvas.drawBitmap(thumbnail,
new Rect(0, 0, srcWidth-1, srcHeight-1),
new RectF(GLOW_PADDING,
- GLOW_PADDING - 4.0f,
- outBitmap.getWidth() - GLOW_PADDING + 2.0f,
- outBitmap.getHeight() - GLOW_PADDING + 3.0f), paint);
+ GLOW_PADDING - 7.0f,
+ outBitmap.getWidth() - GLOW_PADDING + 3.0f,
+ outBitmap.getHeight() - GLOW_PADDING + 7.0f), paint);
}
return outBitmap;
}
- private void updateUiElements(Configuration config, boolean animate) {
- mRecentsContainer.removeAllViews();
+ private void updateUiElements(Configuration config) {
+ final int items = mActivityDescriptions.size();
- final int first = 0;
- final boolean isPortrait = config.orientation == Configuration.ORIENTATION_PORTRAIT;
- final int taskCount = isPortrait ? DISPLAY_TASKS_PORTRAIT : DISPLAY_TASKS_LANDSCAPE;
- final int last = Math.min(mActivityDescriptions.size(), taskCount) - 1;
- for (int i = last; i >= first; i--) {
- ActivityDescription activityDescription = mActivityDescriptions.get(i);
- View view = View.inflate(mContext, R.layout.status_bar_recent_item, null);
- ImageView appThumbnail = (ImageView) view.findViewById(R.id.app_thumbnail);
- ImageView appIcon = (ImageView) view.findViewById(R.id.app_icon);
- TextView appLabel = (TextView) view.findViewById(R.id.app_label);
- TextView appDesc = (TextView) view.findViewById(R.id.app_description);
- final Bitmap thumb = activityDescription.thumbnail;
- appThumbnail.setImageBitmap(compositeBitmap(mGlowBitmap, thumb));
- appIcon.setImageDrawable(activityDescription.icon);
- appLabel.setText(activityDescription.label);
- appDesc.setText(activityDescription.description);
- appThumbnail.setOnClickListener(this);
- appThumbnail.setTag(activityDescription);
- mRecentsContainer.addView(view);
- }
-
- int views = mRecentsContainer.getChildCount();
- mRecentsContainer.setVisibility(views > 0 ? View.VISIBLE : View.GONE);
- mRecentsGlowView.setVisibility(views > 0 ? View.VISIBLE : View.GONE);
+ mRecentsContainer.setVisibility(items > 0 ? View.VISIBLE : View.GONE);
+ mRecentsGlowView.setVisibility(items > 0 ? View.VISIBLE : View.GONE);
}
- public void onClick(View v) {
- ActivityDescription ad = (ActivityDescription)v.getTag();
+ private void hide(boolean animate) {
+ if (!animate) {
+ setVisibility(View.GONE);
+ }
+ mBar.animateCollapse();
+ }
+
+ public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
+ ActivityDescription ad = ((ViewHolder) view.getTag()).activityDescription;
final ActivityManager am = (ActivityManager)
getContext().getSystemService(Context.ACTIVITY_SERVICE);
if (ad.id >= 0) {
@@ -478,11 +555,4 @@
}
hide(true);
}
-
- private void hide(boolean animate) {
- setVisibility(View.GONE);
- if (animate) {
- mBar.animateCollapse();
- }
- }
}
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 233d601..f0408a2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/tablet/TabletStatusBar.java
@@ -267,6 +267,8 @@
lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
lp.setTitle("RecentsPanel");
lp.windowAnimations = R.style.Animation_RecentPanel;
+ lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
+ | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
WindowManagerImpl.getDefault().addView(mRecentsPanel, lp);
mRecentsPanel.setBar(this);
@@ -509,7 +511,7 @@
final int peekIndex = m.arg1;
if (peekIndex < N) {
//Slog.d(TAG, "loading peek: " + peekIndex);
- NotificationData.Entry entry =
+ NotificationData.Entry entry =
mNotificationDNDMode
? mNotificationDNDDummyEntry
: mNotificationData.get(N-1-peekIndex);
@@ -555,7 +557,7 @@
final int N = mNotificationData.size();
if (mNotificationPeekIndex >= 0 && mNotificationPeekIndex < N) {
- NotificationData.Entry entry =
+ NotificationData.Entry entry =
mNotificationDNDMode
? mNotificationDNDDummyEntry
: mNotificationData.get(N-1-mNotificationPeekIndex);
@@ -584,6 +586,8 @@
case MSG_OPEN_RECENTS_PANEL:
if (DEBUG) Slog.d(TAG, "opening recents panel");
if (mRecentsPanel != null) {
+ disable(StatusBarManager.DISABLE_NAVIGATION
+ | StatusBarManager.DISABLE_BACK);
mRecentsPanel.setVisibility(View.VISIBLE);
mRecentsPanel.show(true, true);
}
@@ -591,6 +595,7 @@
case MSG_CLOSE_RECENTS_PANEL:
if (DEBUG) Slog.d(TAG, "closing recents panel");
if (mRecentsPanel != null && mRecentsPanel.isShowing()) {
+ disable(StatusBarManager.DISABLE_NONE);
mRecentsPanel.show(false, true);
}
break;
@@ -701,7 +706,7 @@
&& oldContentView.getLayoutId() == contentView.getLayoutId();
ViewGroup rowParent = (ViewGroup) oldEntry.row.getParent();
boolean orderUnchanged = notification.notification.when==oldNotification.notification.when
- && notification.priority == oldNotification.priority;
+ && notification.priority == oldNotification.priority;
// priority now encompasses isOngoing()
boolean isLastAnyway = rowParent.indexOfChild(oldEntry.row) == rowParent.getChildCount()-1;
if (contentsUnchanged && (orderUnchanged || isLastAnyway)) {
diff --git a/policy/src/com/android/internal/policy/impl/PhoneWindow.java b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
index b746c37..d342d669 100644
--- a/policy/src/com/android/internal/policy/impl/PhoneWindow.java
+++ b/policy/src/com/android/internal/policy/impl/PhoneWindow.java
@@ -1601,6 +1601,7 @@
private ActionMode mActionMode;
private ActionBarContextView mActionModeView;
private PopupWindow mActionModePopup;
+ private Runnable mShowActionModePopup;
public DecorView(Context context, int featureId) {
super(context);
@@ -1976,6 +1977,12 @@
final int height = TypedValue.complexToDimensionPixelSize(heightValue.data,
mContext.getResources().getDisplayMetrics());
mActionModePopup.setHeight(height);
+ mShowActionModePopup = new Runnable() {
+ public void run() {
+ mActionModePopup.showAtLocation(PhoneWindow.DecorView.this,
+ Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
+ }
+ };
} else {
ViewStub stub = (ViewStub) findViewById(
com.android.internal.R.id.action_mode_bar_stub);
@@ -1994,8 +2001,7 @@
mActionModeView.setVisibility(View.VISIBLE);
mActionMode = mode;
if (mActionModePopup != null) {
- mActionModePopup.showAtLocation(this,
- Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
+ post(mShowActionModePopup);
}
} else {
mActionMode = null;
@@ -2183,6 +2189,14 @@
}
mActionButtonPopup = null;
}
+
+ if (mActionModePopup != null) {
+ removeCallbacks(mShowActionModePopup);
+ if (mActionModePopup.isShowing()) {
+ mActionModePopup.dismiss();
+ }
+ mActionModePopup = null;
+ }
}
@Override
@@ -2246,6 +2260,7 @@
public void onDestroyActionMode(ActionMode mode) {
mWrapped.onDestroyActionMode(mode);
if (mActionModePopup != null) {
+ removeCallbacks(mShowActionModePopup);
mActionModePopup.dismiss();
} else if (mActionModeView != null) {
mActionModeView.setVisibility(GONE);
diff --git a/services/java/com/android/server/AppWidgetService.java b/services/java/com/android/server/AppWidgetService.java
index afa8d69..f28e2b1 100644
--- a/services/java/com/android/server/AppWidgetService.java
+++ b/services/java/com/android/server/AppWidgetService.java
@@ -1029,7 +1029,7 @@
com.android.internal.R.styleable.AppWidgetProviderInfo_previewImage, 0);
info.autoAdvanceViewId = sa.getResourceId(
com.android.internal.R.styleable.AppWidgetProviderInfo_autoAdvanceViewId, -1);
- info.resizableMode = sa.getInt(
+ info.resizeMode = sa.getInt(
com.android.internal.R.styleable.AppWidgetProviderInfo_resizeMode,
AppWidgetProviderInfo.RESIZE_NONE);
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 52c47e1..d160963 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -17,6 +17,7 @@
package com.android.server;
import com.android.server.am.ActivityManagerService;
+import com.android.server.usb.UsbService;
import com.android.server.wm.WindowManagerService;
import com.android.internal.app.ShutdownThread;
import com.android.internal.os.BinderInternal;
diff --git a/services/java/com/android/server/usb/UsbDeviceSettingsManager.java b/services/java/com/android/server/usb/UsbDeviceSettingsManager.java
new file mode 100644
index 0000000..21eb7dc
--- /dev/null
+++ b/services/java/com/android/server/usb/UsbDeviceSettingsManager.java
@@ -0,0 +1,861 @@
+/*
+ * 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.usb;
+
+import android.content.ActivityNotFoundException;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.ResolveInfo;
+import android.content.res.XmlResourceParser;
+import android.hardware.UsbAccessory;
+import android.hardware.UsbDevice;
+import android.hardware.UsbInterface;
+import android.hardware.UsbManager;
+import android.os.Binder;
+import android.os.FileUtils;
+import android.os.Process;
+import android.util.Log;
+import android.util.SparseArray;
+import android.util.Xml;
+
+import com.android.internal.content.PackageMonitor;
+import com.android.internal.util.FastXmlSerializer;
+import com.android.internal.util.XmlUtils;
+
+import org.xmlpull.v1.XmlPullParser;
+import org.xmlpull.v1.XmlPullParserException;
+import org.xmlpull.v1.XmlSerializer;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+class UsbDeviceSettingsManager {
+
+ private static final String TAG = "UsbDeviceSettingsManager";
+ private static final File sSettingsFile = new File("/data/system/usb_device_manager.xml");
+
+ private final Context mContext;
+
+ // maps UID to user approved USB devices
+ final SparseArray<ArrayList<DeviceFilter>> mDevicePermissionMap =
+ new SparseArray<ArrayList<DeviceFilter>>();
+ // maps UID to user approved USB accessories
+ final SparseArray<ArrayList<AccessoryFilter>> mAccessoryPermissionMap =
+ new SparseArray<ArrayList<AccessoryFilter>>();
+ // Maps DeviceFilter to user preferred application package
+ final HashMap<DeviceFilter, String> mDevicePreferenceMap =
+ new HashMap<DeviceFilter, String>();
+ // Maps DeviceFilter to user preferred application package
+ final HashMap<AccessoryFilter, String> mAccessoryPreferenceMap =
+ new HashMap<AccessoryFilter, String>();
+
+ // This class is used to describe a USB device.
+ // When used in HashMaps all values must be specified,
+ // but wildcards can be used for any of the fields in
+ // the package meta-data.
+ private static class DeviceFilter {
+ // USB Vendor ID (or -1 for unspecified)
+ public final int mVendorId;
+ // USB Product ID (or -1 for unspecified)
+ public final int mProductId;
+ // USB device or interface class (or -1 for unspecified)
+ public final int mClass;
+ // USB device subclass (or -1 for unspecified)
+ public final int mSubclass;
+ // USB device protocol (or -1 for unspecified)
+ public final int mProtocol;
+
+ public DeviceFilter(int vid, int pid, int clasz, int subclass, int protocol) {
+ mVendorId = vid;
+ mProductId = pid;
+ mClass = clasz;
+ mSubclass = subclass;
+ mProtocol = protocol;
+ }
+
+ public DeviceFilter(UsbDevice device) {
+ mVendorId = device.getVendorId();
+ mProductId = device.getProductId();
+ mClass = device.getDeviceClass();
+ mSubclass = device.getDeviceSubclass();
+ mProtocol = device.getDeviceProtocol();
+ }
+
+ public static DeviceFilter read(XmlPullParser parser)
+ throws XmlPullParserException, IOException {
+ int vendorId = -1;
+ int productId = -1;
+ int deviceClass = -1;
+ int deviceSubclass = -1;
+ int deviceProtocol = -1;
+
+ int count = parser.getAttributeCount();
+ for (int i = 0; i < count; i++) {
+ String name = parser.getAttributeName(i);
+ // All attribute values are ints
+ int value = Integer.parseInt(parser.getAttributeValue(i));
+
+ if ("vendor-id".equals(name)) {
+ vendorId = value;
+ } else if ("product-id".equals(name)) {
+ productId = value;
+ } else if ("class".equals(name)) {
+ deviceClass = value;
+ } else if ("subclass".equals(name)) {
+ deviceSubclass = value;
+ } else if ("protocol".equals(name)) {
+ deviceProtocol = value;
+ }
+ }
+ return new DeviceFilter(vendorId, productId,
+ deviceClass, deviceSubclass, deviceProtocol);
+ }
+
+ public void write(XmlSerializer serializer) throws IOException {
+ serializer.startTag(null, "usb-device");
+ if (mVendorId != -1) {
+ serializer.attribute(null, "vendor-id", Integer.toString(mVendorId));
+ }
+ if (mProductId != -1) {
+ serializer.attribute(null, "product-id", Integer.toString(mProductId));
+ }
+ if (mClass != -1) {
+ serializer.attribute(null, "class", Integer.toString(mClass));
+ }
+ if (mSubclass != -1) {
+ serializer.attribute(null, "subclass", Integer.toString(mSubclass));
+ }
+ if (mProtocol != -1) {
+ serializer.attribute(null, "protocol", Integer.toString(mProtocol));
+ }
+ serializer.endTag(null, "usb-device");
+ }
+
+ private boolean matches(int clasz, int subclass, int protocol) {
+ return ((mClass == -1 || clasz == mClass) &&
+ (mSubclass == -1 || subclass == mSubclass) &&
+ (mProtocol == -1 || protocol == mProtocol));
+ }
+
+ public boolean matches(UsbDevice device) {
+ if (mVendorId != -1 && device.getVendorId() != mVendorId) return false;
+ if (mProductId != -1 && device.getProductId() != mProductId) return false;
+
+ // check device class/subclass/protocol
+ if (matches(device.getDeviceClass(), device.getDeviceSubclass(),
+ device.getDeviceProtocol())) return true;
+
+ // if device doesn't match, check the interfaces
+ int count = device.getInterfaceCount();
+ for (int i = 0; i < count; i++) {
+ UsbInterface intf = device.getInterface(i);
+ if (matches(intf.getInterfaceClass(), intf.getInterfaceSubclass(),
+ intf.getInterfaceProtocol())) return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ // can't compare if we have wildcard strings
+ if (mVendorId == -1 || mProductId == -1 ||
+ mClass == -1 || mSubclass == -1 || mProtocol == -1) {
+ return false;
+ }
+ if (obj instanceof DeviceFilter) {
+ DeviceFilter filter = (DeviceFilter)obj;
+ return (filter.mVendorId == mVendorId &&
+ filter.mProductId == mProductId &&
+ filter.mClass == mClass &&
+ filter.mSubclass == mSubclass &&
+ filter.mProtocol == mProtocol);
+ }
+ if (obj instanceof UsbDevice) {
+ UsbDevice device = (UsbDevice)obj;
+ return (device.getVendorId() == mVendorId &&
+ device.getProductId() == mProductId &&
+ device.getDeviceClass() == mClass &&
+ device.getDeviceSubclass() == mSubclass &&
+ device.getDeviceProtocol() == mProtocol);
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return (((mVendorId << 16) | mProductId) ^
+ ((mClass << 16) | (mSubclass << 8) | mProtocol));
+ }
+
+ @Override
+ public String toString() {
+ return "DeviceFilter[mVendorId=" + mVendorId + ",mProductId=" + mProductId +
+ ",mClass=" + mClass + ",mSubclass=" + mSubclass +
+ ",mProtocol=" + mProtocol + "]";
+ }
+ }
+
+ // This class is used to describe a USB accessory.
+ // When used in HashMaps all values must be specified,
+ // but wildcards can be used for any of the fields in
+ // the package meta-data.
+ private static class AccessoryFilter {
+ // USB accessory manufacturer (or null for unspecified)
+ public final String mManufacturer;
+ // USB accessory model (or null for unspecified)
+ public final String mModel;
+ // USB accessory type (or null for unspecified)
+ public final String mType;
+ // USB accessory version (or null for unspecified)
+ public final String mVersion;
+
+ public AccessoryFilter(String manufacturer, String model, String type, String version) {
+ mManufacturer = manufacturer;
+ mModel = model;
+ mType = type;
+ mVersion = version;
+ }
+
+ public AccessoryFilter(UsbAccessory accessory) {
+ mManufacturer = accessory.getManufacturer();
+ mModel = accessory.getModel();
+ mType = accessory.getType();
+ mVersion = accessory.getVersion();
+ }
+
+ public static AccessoryFilter read(XmlPullParser parser)
+ throws XmlPullParserException, IOException {
+ String manufacturer = null;
+ String model = null;
+ String type = null;
+ String version = null;
+
+ int count = parser.getAttributeCount();
+ for (int i = 0; i < count; i++) {
+ String name = parser.getAttributeName(i);
+ String value = parser.getAttributeValue(i);
+
+ if ("manufacturer".equals(name)) {
+ manufacturer = value;
+ } else if ("model".equals(name)) {
+ model = value;
+ } else if ("type".equals(name)) {
+ type = value;
+ } else if ("version".equals(name)) {
+ version = value;
+ }
+ }
+ return new AccessoryFilter(manufacturer, model, type, version);
+ }
+
+ public void write(XmlSerializer serializer)throws IOException {
+ serializer.startTag(null, "usb-accessory");
+ if (mManufacturer != null) {
+ serializer.attribute(null, "manufacturer", mManufacturer);
+ }
+ if (mModel != null) {
+ serializer.attribute(null, "model", mModel);
+ }
+ if (mType != null) {
+ serializer.attribute(null, "type", mType);
+ }
+ if (mVersion != null) {
+ serializer.attribute(null, "version", mVersion);
+ }
+ serializer.endTag(null, "usb-accessory");
+ }
+
+ public boolean matches(UsbAccessory acc) {
+ if (mManufacturer != null && !acc.getManufacturer().equals(mManufacturer)) return false;
+ if (mModel != null && !acc.getModel().equals(mModel)) return false;
+ if (mType != null && !acc.getType().equals(mType)) return false;
+ if (mVersion != null && !acc.getVersion().equals(mVersion)) return false;
+ return true;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ // can't compare if we have wildcard strings
+ if (mManufacturer == null || mModel == null || mType == null || mVersion == null) {
+ return false;
+ }
+ if (obj instanceof AccessoryFilter) {
+ AccessoryFilter filter = (AccessoryFilter)obj;
+ return (mManufacturer.equals(filter.mManufacturer) &&
+ mModel.equals(filter.mModel) &&
+ mType.equals(filter.mType) &&
+ mVersion.equals(filter.mVersion));
+ }
+ if (obj instanceof UsbAccessory) {
+ UsbAccessory accessory = (UsbAccessory)obj;
+ return (mManufacturer.equals(accessory.getManufacturer()) &&
+ mModel.equals(accessory.getModel()) &&
+ mType.equals(accessory.getType()) &&
+ mVersion.equals(accessory.getVersion()));
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return ((mManufacturer == null ? 0 : mManufacturer.hashCode()) ^
+ (mModel == null ? 0 : mModel.hashCode()) ^
+ (mType == null ? 0 : mType.hashCode()) ^
+ (mVersion == null ? 0 : mVersion.hashCode()));
+ }
+
+ @Override
+ public String toString() {
+ return "AccessoryFilter[mManufacturer=\"" + mManufacturer +
+ "\", mModel=\"" + mModel +
+ "\", mType=\"" + mType +
+ "\", mVersion=\"" + mVersion + "\"]";
+ }
+ }
+
+ private class MyPackageMonitor extends PackageMonitor {
+ public void onPackageRemoved(String packageName, int uid) {
+ // clear all activity preferences for the package
+ if (clearPackageDefaults(packageName)) {
+ writeSettings();
+ }
+ }
+
+ public void onUidRemoved(int uid) {
+ // clear all permissions for the UID
+ if (clearUidDefaults(uid)) {
+ writeSettings();
+ }
+ }
+ }
+ MyPackageMonitor mPackageMonitor = new MyPackageMonitor();
+
+ public UsbDeviceSettingsManager(Context context) {
+ mContext = context;
+ readSettings();
+ mPackageMonitor.register(context, true);
+ }
+
+ private void readDevicePermission(XmlPullParser parser)
+ throws XmlPullParserException, IOException {
+ int uid = -1;
+ ArrayList<DeviceFilter> filters = new ArrayList<DeviceFilter>();
+ int count = parser.getAttributeCount();
+ for (int i = 0; i < count; i++) {
+ if ("uid".equals(parser.getAttributeName(i))) {
+ uid = Integer.parseInt(parser.getAttributeValue(i));
+ break;
+ }
+ }
+ XmlUtils.nextElement(parser);
+ while ("usb-device".equals(parser.getName())) {
+ filters.add(DeviceFilter.read(parser));
+ XmlUtils.nextElement(parser);
+ }
+ mDevicePermissionMap.put(uid, filters);
+ }
+
+ private void readAccessoryPermission(XmlPullParser parser)
+ throws XmlPullParserException, IOException {
+ int uid = -1;
+ ArrayList<AccessoryFilter> filters = new ArrayList<AccessoryFilter>();
+ int count = parser.getAttributeCount();
+ for (int i = 0; i < count; i++) {
+ if ("uid".equals(parser.getAttributeName(i))) {
+ uid = Integer.parseInt(parser.getAttributeValue(i));
+ break;
+ }
+ }
+ XmlUtils.nextElement(parser);
+ while ("usb-accessory".equals(parser.getName())) {
+ filters.add(AccessoryFilter.read(parser));
+ XmlUtils.nextElement(parser);
+ }
+ mAccessoryPermissionMap.put(uid, filters);
+ }
+
+ private void readPreference(XmlPullParser parser)
+ throws XmlPullParserException, IOException {
+ String packageName = null;
+ int count = parser.getAttributeCount();
+ for (int i = 0; i < count; i++) {
+ if ("package".equals(parser.getAttributeName(i))) {
+ packageName = parser.getAttributeValue(i);
+ break;
+ }
+ }
+ XmlUtils.nextElement(parser);
+ if ("usb-device".equals(parser.getName())) {
+ DeviceFilter filter = DeviceFilter.read(parser);
+ mDevicePreferenceMap.put(filter, packageName);
+ } else if ("usb-accessory".equals(parser.getName())) {
+ AccessoryFilter filter = AccessoryFilter.read(parser);
+ mAccessoryPreferenceMap.put(filter, packageName);
+ }
+ XmlUtils.nextElement(parser);
+ }
+
+ private void readSettings() {
+ FileInputStream stream = null;
+ try {
+ stream = new FileInputStream(sSettingsFile);
+ XmlPullParser parser = Xml.newPullParser();
+ parser.setInput(stream, null);
+
+ XmlUtils.nextElement(parser);
+ while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
+ String tagName = parser.getName();
+ if ("device-permission".equals(tagName)) {
+ readDevicePermission(parser);
+ } else if ("accessory-permission".equals(tagName)) {
+ readAccessoryPermission(parser);
+ } else if ("preference".equals(tagName)) {
+ readPreference(parser);
+ } else {
+ XmlUtils.nextElement(parser);
+ }
+ }
+ } catch (FileNotFoundException e) {
+ Log.w(TAG, "settings file not found");
+ } catch (Exception e) {
+ Log.e(TAG, "error reading settings file, deleting to start fresh", e);
+ sSettingsFile.delete();
+ } finally {
+ if (stream != null) {
+ try {
+ stream.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+ }
+
+ private void writeSettings() {
+ FileOutputStream fos = null;
+ try {
+ FileOutputStream fstr = new FileOutputStream(sSettingsFile);
+ Log.d(TAG, "writing settings to " + fstr);
+ BufferedOutputStream str = new BufferedOutputStream(fstr);
+ FastXmlSerializer serializer = new FastXmlSerializer();
+ serializer.setOutput(str, "utf-8");
+ serializer.startDocument(null, true);
+ serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
+ serializer.startTag(null, "settings");
+
+ int count = mDevicePermissionMap.size();
+ for (int i = 0; i < count; i++) {
+ int uid = mDevicePermissionMap.keyAt(i);
+ ArrayList<DeviceFilter> filters = mDevicePermissionMap.valueAt(i);
+ serializer.startTag(null, "device-permission");
+ serializer.attribute(null, "uid", Integer.toString(uid));
+ int filterCount = filters.size();
+ for (int j = 0; j < filterCount; j++) {
+ filters.get(j).write(serializer);
+ }
+ serializer.endTag(null, "device-permission");
+ }
+
+ count = mAccessoryPermissionMap.size();
+ for (int i = 0; i < count; i++) {
+ int uid = mAccessoryPermissionMap.keyAt(i);
+ ArrayList<AccessoryFilter> filters = mAccessoryPermissionMap.valueAt(i);
+ serializer.startTag(null, "accessory-permission");
+ serializer.attribute(null, "uid", Integer.toString(uid));
+ int filterCount = filters.size();
+ for (int j = 0; j < filterCount; j++) {
+ filters.get(j).write(serializer);
+ }
+ serializer.endTag(null, "accessory-permission");
+ }
+
+ for (DeviceFilter filter : mDevicePreferenceMap.keySet()) {
+ serializer.startTag(null, "preference");
+ serializer.attribute(null, "package", mDevicePreferenceMap.get(filter));
+ filter.write(serializer);
+ serializer.endTag(null, "preference");
+ }
+
+ for (AccessoryFilter filter : mAccessoryPreferenceMap.keySet()) {
+ serializer.startTag(null, "preference");
+ serializer.attribute(null, "package", mAccessoryPreferenceMap.get(filter));
+ filter.write(serializer);
+ serializer.endTag(null, "preference");
+ }
+
+ serializer.endTag(null, "settings");
+ serializer.endDocument();
+
+ str.flush();
+ FileUtils.sync(fstr);
+ str.close();
+ } catch (Exception e) {
+ Log.e(TAG, "error writing settings file, deleting to start fresh", e);
+ sSettingsFile.delete();
+ }
+ }
+
+ // Checks to see if a package matches a device or accessory.
+ // Only one of device and accessory should be non-null.
+ private boolean packageMatches(ResolveInfo info, String metaDataName,
+ UsbDevice device, UsbAccessory accessory) {
+ ActivityInfo ai = info.activityInfo;
+ PackageManager pm = mContext.getPackageManager();
+
+ XmlResourceParser parser = null;
+ try {
+ parser = ai.loadXmlMetaData(pm, metaDataName);
+ if (parser == null) {
+ Log.w(TAG, "no meta-data for " + info);
+ return false;
+ }
+
+ XmlUtils.nextElement(parser);
+ while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
+ String tagName = parser.getName();
+ if (device != null && "usb-device".equals(tagName)) {
+ DeviceFilter filter = DeviceFilter.read(parser);
+ if (filter.matches(device)) {
+ return true;
+ }
+ }
+ else if (accessory != null && "usb-accessory".equals(tagName)) {
+ AccessoryFilter filter = AccessoryFilter.read(parser);
+ if (filter.matches(accessory)) {
+ return true;
+ }
+ }
+ XmlUtils.nextElement(parser);
+ }
+ } catch (Exception e) {
+ Log.w(TAG, "Unable to load component info " + info.toString(), e);
+ } finally {
+ if (parser != null) parser.close();
+ }
+ return false;
+ }
+
+ private final ArrayList<ResolveInfo> getDeviceMatches(UsbDevice device, Intent intent) {
+ ArrayList<ResolveInfo> matches = new ArrayList<ResolveInfo>();
+ PackageManager pm = mContext.getPackageManager();
+ List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent,
+ PackageManager.GET_META_DATA);
+ int count = resolveInfos.size();
+ for (int i = 0; i < count; i++) {
+ ResolveInfo resolveInfo = resolveInfos.get(i);
+ if (packageMatches(resolveInfo, intent.getAction(), device, null)) {
+ matches.add(resolveInfo);
+ }
+ }
+ return matches;
+ }
+
+ private final ArrayList<ResolveInfo> getAccessoryMatches(UsbAccessory accessory, Intent intent) {
+ ArrayList<ResolveInfo> matches = new ArrayList<ResolveInfo>();
+ PackageManager pm = mContext.getPackageManager();
+ List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent,
+ PackageManager.GET_META_DATA);
+ int count = resolveInfos.size();
+ for (int i = 0; i < count; i++) {
+ ResolveInfo resolveInfo = resolveInfos.get(i);
+ if (packageMatches(resolveInfo, intent.getAction(), null, accessory)) {
+ matches.add(resolveInfo);
+ }
+ }
+ return matches;
+ }
+
+ public void deviceAttached(UsbDevice device) {
+ Intent deviceIntent = new Intent(UsbManager.ACTION_USB_DEVICE_ATTACHED);
+ deviceIntent.putExtra(UsbManager.EXTRA_DEVICE, device);
+ deviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ ArrayList<ResolveInfo> matches = getDeviceMatches(device, deviceIntent);
+ // Launch our default activity directly, if we have one.
+ // Otherwise we will start the UsbResolverActivity to allow the user to choose.
+ String defaultPackage = mDevicePreferenceMap.get(new DeviceFilter(device));
+ if (defaultPackage != null) {
+ int count = matches.size();
+ for (int i = 0; i < count; i++) {
+ ResolveInfo rInfo = matches.get(i);
+ if (rInfo.activityInfo != null &&
+ defaultPackage.equals(rInfo.activityInfo.packageName)) {
+ try {
+ deviceIntent.setComponent(new ComponentName(
+ defaultPackage, rInfo.activityInfo.name));
+ mContext.startActivity(deviceIntent);
+ } catch (ActivityNotFoundException e) {
+ Log.e(TAG, "startActivity failed", e);
+ }
+ return;
+ }
+ }
+ }
+
+ Intent intent = new Intent(mContext, UsbResolverActivity.class);
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ intent.putExtra(Intent.EXTRA_INTENT, deviceIntent);
+ intent.putParcelableArrayListExtra(UsbResolverActivity.EXTRA_RESOLVE_INFOS,
+ matches);
+ try {
+ mContext.startActivity(intent);
+ } catch (ActivityNotFoundException e) {
+ Log.w(TAG, "unable to start UsbResolverActivity");
+ }
+ }
+
+ public void deviceDetached(UsbDevice device) {
+ Intent intent = new Intent(UsbManager.ACTION_USB_DEVICE_DETACHED);
+ intent.putExtra(UsbManager.EXTRA_DEVICE, device);
+ Log.d(TAG, "usbDeviceRemoved, sending " + intent);
+ mContext.sendBroadcast(intent);
+ }
+
+ public void accessoryAttached(UsbAccessory accessory) {
+ Intent accessoryIntent = new Intent(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
+ accessoryIntent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
+ accessoryIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ ArrayList<ResolveInfo> matches = getAccessoryMatches(accessory, accessoryIntent);
+ // Launch our default activity directly, if we have one.
+ // Otherwise we will start the UsbResolverActivity to allow the user to choose.
+ String defaultPackage = mAccessoryPreferenceMap.get(new AccessoryFilter(accessory));
+ if (defaultPackage != null) {
+ int count = matches.size();
+ for (int i = 0; i < count; i++) {
+ ResolveInfo rInfo = matches.get(i);
+ if (rInfo.activityInfo != null &&
+ defaultPackage.equals(rInfo.activityInfo.packageName)) {
+ try {
+ accessoryIntent.setComponent(new ComponentName(
+ defaultPackage, rInfo.activityInfo.name));
+ mContext.startActivity(accessoryIntent);
+ } catch (ActivityNotFoundException e) {
+ Log.e(TAG, "startActivity failed", e);
+ }
+ return;
+ }
+ }
+ }
+
+ Intent intent = new Intent(mContext, UsbResolverActivity.class);
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ intent.putExtra(Intent.EXTRA_INTENT, accessoryIntent);
+ intent.putParcelableArrayListExtra(UsbResolverActivity.EXTRA_RESOLVE_INFOS,
+ matches);
+ try {
+ mContext.startActivity(intent);
+ } catch (ActivityNotFoundException e) {
+ Log.w(TAG, "unable to start UsbResolverActivity");
+ }
+ }
+
+ public void accessoryDetached(UsbAccessory accessory) {
+ Intent intent = new Intent(
+ UsbManager.ACTION_USB_ACCESSORY_DETACHED);
+ intent.putExtra(UsbManager.EXTRA_ACCESSORY, accessory);
+ mContext.sendBroadcast(intent);
+ }
+
+ public void checkPermission(UsbDevice device) {
+ if (device == null) return;
+ ArrayList<DeviceFilter> filterList = mDevicePermissionMap.get(Binder.getCallingUid());
+ if (filterList != null) {
+ int count = filterList.size();
+ for (int i = 0; i < count; i++) {
+ DeviceFilter filter = filterList.get(i);
+ if (filter.equals(device)) {
+ // permission allowed
+ return;
+ }
+ }
+ }
+ throw new SecurityException("User has not given permission to device " + device);
+ }
+
+ public void checkPermission(UsbAccessory accessory) {
+ if (accessory == null) return;
+ ArrayList<AccessoryFilter> filterList = mAccessoryPermissionMap.get(Binder.getCallingUid());
+ if (filterList != null) {
+ int count = filterList.size();
+ for (int i = 0; i < count; i++) {
+ AccessoryFilter filter = filterList.get(i);
+ if (filter.equals(accessory)) {
+ // permission allowed
+ return;
+ }
+ }
+ }
+ throw new SecurityException("User has not given permission to accessory " + accessory);
+ }
+
+ public void setDevicePackage(UsbDevice device, String packageName) {
+ DeviceFilter filter = new DeviceFilter(device);
+ if (packageName == null) {
+ mDevicePreferenceMap.remove(filter);
+ } else {
+ mDevicePreferenceMap.put(filter, packageName);
+ }
+ // FIXME - only if changed
+ writeSettings();
+ }
+
+ public void setAccessoryPackage(UsbAccessory accessory, String packageName) {
+ AccessoryFilter filter = new AccessoryFilter(accessory);
+ if (packageName == null) {
+ mAccessoryPreferenceMap.remove(filter);
+ } else {
+ mAccessoryPreferenceMap.put(filter, packageName);
+ }
+ // FIXME - only if changed
+ writeSettings();
+ }
+
+ public void grantDevicePermission(UsbDevice device, int uid) {
+ ArrayList<DeviceFilter> filterList = mDevicePermissionMap.get(uid);
+ if (filterList == null) {
+ filterList = new ArrayList<DeviceFilter>();
+ mDevicePermissionMap.put(uid, filterList);
+ } else {
+ int count = filterList.size();
+ for (int i = 0; i < count; i++) {
+ if (filterList.get(i).equals(device)) return;
+ }
+ }
+ filterList.add(new DeviceFilter(device));
+ writeSettings();
+ }
+
+ public void grantAccessoryPermission(UsbAccessory accessory, int uid) {
+ ArrayList<AccessoryFilter> filterList = mAccessoryPermissionMap.get(uid);
+ if (filterList == null) {
+ filterList = new ArrayList<AccessoryFilter>();
+ mAccessoryPermissionMap.put(uid, filterList);
+ } else {
+ int count = filterList.size();
+ for (int i = 0; i < count; i++) {
+ if (filterList.get(i).equals(accessory)) return;
+ }
+ }
+ filterList.add(new AccessoryFilter(accessory));
+ writeSettings();
+ }
+
+ public boolean hasDefaults(String packageName, int uid) {
+ if (mDevicePermissionMap.get(uid) != null) return true;
+ if (mAccessoryPermissionMap.get(uid) != null) return true;
+ if (mDevicePreferenceMap.values().contains(packageName)) return true;
+ if (mAccessoryPreferenceMap.values().contains(packageName)) return true;
+ return false;
+ }
+
+ public void clearDefaults(String packageName, int uid) {
+ boolean packageCleared = clearPackageDefaults(packageName);
+ boolean uidCleared = clearUidDefaults(uid);
+ if (packageCleared || uidCleared) {
+ writeSettings();
+ }
+ }
+
+ private boolean clearUidDefaults(int uid) {
+ boolean cleared = false;
+ int index = mDevicePermissionMap.indexOfKey(uid);
+ if (index >= 0) {
+ mDevicePermissionMap.removeAt(index);
+ cleared = true;
+ }
+ index = mAccessoryPermissionMap.indexOfKey(uid);
+ if (index >= 0) {
+ mAccessoryPermissionMap.removeAt(index);
+ cleared = true;
+ }
+ return cleared;
+ }
+
+ private boolean clearPackageDefaults(String packageName) {
+ boolean cleared = false;
+ if (mDevicePreferenceMap.containsValue(packageName)) {
+ // make a copy of the key set to avoid ConcurrentModificationException
+ Object[] keys = mDevicePreferenceMap.keySet().toArray();
+ for (int i = 0; i < keys.length; i++) {
+ Object key = keys[i];
+ if (packageName.equals(mDevicePreferenceMap.get(key))) {
+ mDevicePreferenceMap.remove(key);
+ cleared = true;
+ }
+ }
+ }
+ if (mAccessoryPreferenceMap.containsValue(packageName)) {
+ // make a copy of the key set to avoid ConcurrentModificationException
+ Object[] keys = mAccessoryPreferenceMap.keySet().toArray();
+ for (int i = 0; i < keys.length; i++) {
+ Object key = keys[i];
+ if (packageName.equals(mAccessoryPreferenceMap.get(key))) {
+ mAccessoryPreferenceMap.remove(key);
+ cleared = true;
+ }
+ }
+ }
+ return cleared;
+ }
+
+ public void dump(FileDescriptor fd, PrintWriter pw) {
+ pw.println(" Device permissions:");
+ int count = mDevicePermissionMap.size();
+ for (int i = 0; i < count; i++) {
+ int uid = mDevicePermissionMap.keyAt(i);
+ pw.println(" " + "uid " + uid + ":");
+ ArrayList<DeviceFilter> filters = mDevicePermissionMap.valueAt(i);
+ for (DeviceFilter filter : filters) {
+ pw.println(" " + filter);
+ }
+ }
+ pw.println(" Accessory permissions:");
+ count = mAccessoryPermissionMap.size();
+ for (int i = 0; i < count; i++) {
+ int uid = mAccessoryPermissionMap.keyAt(i);
+ pw.println(" " + "uid " + uid + ":");
+ ArrayList<AccessoryFilter> filters = mAccessoryPermissionMap.valueAt(i);
+ for (AccessoryFilter filter : filters) {
+ pw.println(" " + filter);
+ }
+ }
+ pw.println(" Device preferences:");
+ for (DeviceFilter filter : mDevicePreferenceMap.keySet()) {
+ pw.println(" " + filter + ": " + mDevicePreferenceMap.get(filter));
+ }
+ pw.println(" Accessory preferences:");
+ for (AccessoryFilter filter : mAccessoryPreferenceMap.keySet()) {
+ pw.println(" " + filter + ": " + mAccessoryPreferenceMap.get(filter));
+ }
+ }
+}
diff --git a/services/java/com/android/server/usb/UsbResolverActivity.java b/services/java/com/android/server/usb/UsbResolverActivity.java
new file mode 100644
index 0000000..1bb3c21
--- /dev/null
+++ b/services/java/com/android/server/usb/UsbResolverActivity.java
@@ -0,0 +1,102 @@
+/*
+ * 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.usb;
+
+import com.android.internal.app.ResolverActivity;
+
+import android.content.ActivityNotFoundException;
+import android.content.Intent;
+import android.content.pm.ResolveInfo;
+import android.hardware.IUsbManager;
+import android.hardware.UsbAccessory;
+import android.hardware.UsbDevice;
+import android.hardware.UsbManager;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.Parcelable;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.util.Log;
+
+import java.util.ArrayList;
+
+/* Activity for choosing an application for a USB device or accessory */
+public class UsbResolverActivity extends ResolverActivity {
+ public static final String TAG = "UsbResolverActivity";
+ public static final String EXTRA_RESOLVE_INFOS = "rlist";
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ Intent intent = getIntent();
+ Parcelable targetParcelable = intent.getParcelableExtra(Intent.EXTRA_INTENT);
+ if (!(targetParcelable instanceof Intent)) {
+ Log.w("UsbResolverActivity", "Target is not an intent: " + targetParcelable);
+ finish();
+ return;
+ }
+ Intent target = (Intent)targetParcelable;
+ ArrayList<ResolveInfo> rList = intent.getParcelableArrayListExtra(EXTRA_RESOLVE_INFOS);
+ Log.d(TAG, "rList.size() " + rList.size());
+ CharSequence title = getResources().getText(com.android.internal.R.string.chooseUsbActivity);
+ super.onCreate(savedInstanceState, target, title, null, rList,
+ true, /* Set alwaysUseOption to true to enable "always use this app" checkbox. */
+ true /* Set alwaysChoose to display activity when only one choice is available.
+ This is necessary because this activity is needed for the user to allow
+ the application permission to access the device */
+ );
+ }
+
+ protected void onIntentSelected(ResolveInfo ri, Intent intent, boolean alwaysCheck) {
+ try {
+ IBinder b = ServiceManager.getService(USB_SERVICE);
+ IUsbManager service = IUsbManager.Stub.asInterface(b);
+ int uid = ri.activityInfo.applicationInfo.uid;
+ String action = intent.getAction();
+
+ if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
+ UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
+ // grant permission for the device
+ service.grantDevicePermission(device, uid);
+ // set or clear default setting
+ if (alwaysCheck) {
+ service.setDevicePackage(device, ri.activityInfo.packageName);
+ } else {
+ service.setDevicePackage(device, null);
+ }
+ } else if (UsbManager.ACTION_USB_ACCESSORY_ATTACHED.equals(action)) {
+ UsbAccessory accessory = (UsbAccessory)intent.getParcelableExtra(
+ UsbManager.EXTRA_ACCESSORY);
+ // grant permission for the accessory
+ service.grantAccessoryPermission(accessory, uid);
+ // set or clear default setting
+ if (alwaysCheck) {
+ service.setAccessoryPackage(accessory, ri.activityInfo.packageName);
+ } else {
+ service.setAccessoryPackage(accessory, null);
+ }
+ }
+
+ try {
+ startActivity(intent);
+ } catch (ActivityNotFoundException e) {
+ Log.e(TAG, "startActivity failed", e);
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "onIntentSelected failed", e);
+ }
+ }
+}
diff --git a/services/java/com/android/server/UsbService.java b/services/java/com/android/server/usb/UsbService.java
similarity index 77%
rename from services/java/com/android/server/UsbService.java
rename to services/java/com/android/server/usb/UsbService.java
index 2f84713..a093d95 100644
--- a/services/java/com/android/server/UsbService.java
+++ b/services/java/com/android/server/usb/UsbService.java
@@ -14,11 +14,12 @@
* limitations under the License.
*/
-package com.android.server;
+package com.android.server.usb;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
+import android.content.pm.PackageManager;
import android.hardware.IUsbManager;
import android.hardware.UsbAccessory;
import android.hardware.UsbConstants;
@@ -27,6 +28,7 @@
import android.hardware.UsbInterface;
import android.hardware.UsbManager;
import android.net.Uri;
+import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
@@ -38,10 +40,13 @@
import android.util.Slog;
import java.io.File;
+import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileReader;
+import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
/**
* UsbService monitors for changes to USB state.
@@ -50,7 +55,7 @@
* Accessory mode is a special case of USB device mode, where the android device is
* connected to a USB host that supports the android accessory protocol.
*/
-class UsbService extends IUsbManager.Stub {
+public class UsbService extends IUsbManager.Stub {
private static final String TAG = UsbService.class.getSimpleName();
private static final boolean LOG = false;
@@ -102,13 +107,16 @@
private final Context mContext;
private final Object mLock = new Object();
+ private final UsbDeviceSettingsManager mDeviceManager;
+ private final boolean mHasUsbHost;
+ private final boolean mHasUsbAccessory;
/*
* Handles USB function enable/disable events (device mode)
*/
private final void functionEnabledLocked(String function, boolean enabled) {
boolean enteringAccessoryMode =
- (enabled && UsbManager.USB_FUNCTION_ACCESSORY.equals(function));
+ (mHasUsbAccessory && enabled && UsbManager.USB_FUNCTION_ACCESSORY.equals(function));
if (enteringAccessoryMode) {
// keep a list of functions to reenable after exiting accessory mode
@@ -139,11 +147,9 @@
if (enteringAccessoryMode) {
String[] strings = nativeGetAccessoryStrings();
if (strings != null) {
- Log.d(TAG, "entering USB accessory mode");
mCurrentAccessory = new UsbAccessory(strings);
- Intent intent = new Intent(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
- intent.putExtra(UsbManager.EXTRA_ACCESSORY, mCurrentAccessory);
- mContext.sendBroadcast(intent);
+ Log.d(TAG, "entering USB accessory mode: " + mCurrentAccessory);
+ mDeviceManager.accessoryAttached(mCurrentAccessory);
} else {
Log.e(TAG, "nativeGetAccessoryStrings failed");
}
@@ -170,7 +176,7 @@
mConnected = intState;
// trigger an Intent broadcast
if (mSystemReady) {
- // debounce disconnects
+ // debounce disconnects to avoid problems bringing up USB tethering
update(mConnected == 0);
}
} else if ("usb_configuration".equals(name)) {
@@ -202,6 +208,11 @@
public UsbService(Context context) {
mContext = context;
+ mDeviceManager = new UsbDeviceSettingsManager(context);
+ PackageManager pm = mContext.getPackageManager();
+ mHasUsbHost = pm.hasSystemFeature(PackageManager.FEATURE_USB_HOST);
+ mHasUsbAccessory = pm.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY);
+
mHostBlacklist = context.getResources().getStringArray(
com.android.internal.R.array.config_usbHostBlacklist);
@@ -345,11 +356,7 @@
UsbDevice device = new UsbDevice(deviceName, vendorID, productID,
deviceClass, deviceSubclass, deviceProtocol, interfaces);
mDevices.put(deviceName, device);
-
- Intent intent = new Intent(UsbManager.ACTION_USB_DEVICE_ATTACHED);
- intent.putExtra(UsbManager.EXTRA_DEVICE, device);
- Log.d(TAG, "usbDeviceAdded, sending " + intent);
- mContext.sendBroadcast(intent);
+ mDeviceManager.deviceAttached(device);
}
}
@@ -358,10 +365,7 @@
synchronized (mLock) {
UsbDevice device = mDevices.remove(deviceName);
if (device != null) {
- Intent intent = new Intent(UsbManager.ACTION_USB_DEVICE_DETACHED);
- intent.putExtra(UsbManager.EXTRA_DEVICE, device);
- Log.d(TAG, "usbDeviceRemoved, sending " + intent);
- mContext.sendBroadcast(intent);
+ mDeviceManager.deviceDetached(device);
}
}
}
@@ -377,10 +381,9 @@
new Thread(null, runnable, "UsbService host thread").start();
}
- void systemReady() {
+ public void systemReady() {
synchronized (mLock) {
- if (mContext.getResources().getBoolean(
- com.android.internal.R.bool.config_hasUsbHostSupport)) {
+ if (mHasUsbHost) {
// start monitoring for connected USB devices
initHostSupport();
}
@@ -402,7 +405,6 @@
/* Returns a list of all currently attached USB devices (host mdoe) */
public void getDeviceList(Bundle devices) {
- mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_USB, null);
synchronized (mLock) {
for (String name : mDevices.keySet()) {
devices.putParcelable(name, mDevices.get(name));
@@ -412,28 +414,85 @@
/* Opens the specified USB device (host mode) */
public ParcelFileDescriptor openDevice(String deviceName) {
- if (isBlackListed(deviceName)) {
- throw new SecurityException("USB device is on a restricted bus");
+ synchronized (mLock) {
+ if (isBlackListed(deviceName)) {
+ throw new SecurityException("USB device is on a restricted bus");
+ }
+ UsbDevice device = mDevices.get(deviceName);
+ if (device == null) {
+ // if it is not in mDevices, it either does not exist or is blacklisted
+ throw new IllegalArgumentException(
+ "device " + deviceName + " does not exist or is restricted");
+ }
+ mDeviceManager.checkPermission(device);
+ return nativeOpenDevice(deviceName);
}
- mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_USB, null);
- if (mDevices.get(deviceName) == null) {
- // if it is not in mDevices, it either does not exist or is blacklisted
- throw new IllegalArgumentException(
- "device " + deviceName + " does not exist or is restricted");
- }
- return nativeOpenDevice(deviceName);
}
/* returns the currently attached USB accessory (device mode) */
public UsbAccessory getCurrentAccessory() {
- mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_USB, null);
- return mCurrentAccessory;
+ synchronized (mLock) {
+ mDeviceManager.checkPermission(mCurrentAccessory);
+ return mCurrentAccessory;
+ }
}
/* opens the currently attached USB accessory (device mode) */
- public ParcelFileDescriptor openAccessory() {
- mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_USB, null);
- return nativeOpenAccessory();
+ public ParcelFileDescriptor openAccessory(UsbAccessory accessory) {
+ synchronized (mLock) {
+ if (mCurrentAccessory == null) {
+ throw new IllegalArgumentException("no accessory attached");
+ }
+ if (!mCurrentAccessory.equals(accessory)) {
+ Log.e(TAG, accessory.toString() + " does not match current accessory "
+ + mCurrentAccessory);
+ throw new IllegalArgumentException("accessory not attached");
+ }
+ mDeviceManager.checkPermission(mCurrentAccessory);
+ return nativeOpenAccessory();
+ }
+ }
+
+ public void setDevicePackage(UsbDevice device, String packageName) {
+ synchronized (mLock) {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+ mDeviceManager.setDevicePackage(device, packageName);
+ }
+ }
+
+ public void setAccessoryPackage(UsbAccessory accessory, String packageName) {
+ synchronized (mLock) {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+ mDeviceManager.setAccessoryPackage(accessory, packageName);
+ }
+ }
+
+ public void grantDevicePermission(UsbDevice device, int uid) {
+ synchronized (mLock) {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+ mDeviceManager.grantDevicePermission(device, uid);
+ }
+ }
+
+ public void grantAccessoryPermission(UsbAccessory accessory, int uid) {
+ synchronized (mLock) {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+ mDeviceManager.grantAccessoryPermission(accessory, uid);
+ }
+ }
+
+ public boolean hasDefaults(String packageName, int uid) {
+ synchronized (mLock) {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+ return mDeviceManager.hasDefaults(packageName, uid);
+ }
+ }
+
+ public void clearDefaults(String packageName, int uid) {
+ synchronized (mLock) {
+ mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USB, null);
+ mDeviceManager.clearDefaults(packageName, uid);
+ }
}
/*
@@ -470,10 +529,7 @@
}
mAccessoryRestoreFunctions.clear();
- Intent intent = new Intent(
- UsbManager.ACTION_USB_ACCESSORY_DETACHED);
- intent.putExtra(UsbManager.EXTRA_ACCESSORY, mCurrentAccessory);
- mContext.sendBroadcast(intent);
+ mDeviceManager.accessoryDetached(mCurrentAccessory);
mCurrentAccessory = null;
// this will cause an immediate reset of the USB bus,
@@ -513,6 +569,42 @@
}
};
+ @Override
+ public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+ if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
+ != PackageManager.PERMISSION_GRANTED) {
+ pw.println("Permission Denial: can't dump UsbManager from from pid="
+ + Binder.getCallingPid()
+ + ", uid=" + Binder.getCallingUid());
+ return;
+ }
+
+ synchronized (mLock) {
+ pw.println("USB Manager State:");
+
+ pw.println(" USB Device State:");
+ pw.print(" Enabled Functions: ");
+ for (int i = 0; i < mEnabledFunctions.size(); i++) {
+ pw.print(mEnabledFunctions.get(i) + " ");
+ }
+ pw.println("");
+ pw.print(" Disabled Functions: ");
+ for (int i = 0; i < mDisabledFunctions.size(); i++) {
+ pw.print(mDisabledFunctions.get(i) + " ");
+ }
+ pw.println("");
+ pw.println(" mConnected: " + mConnected + ", mConfiguration: " + mConfiguration);
+
+ pw.println(" USB Host State:");
+ for (String name : mDevices.keySet()) {
+ pw.println(" " + name + ": " + mDevices.get(name));
+ }
+ pw.println(" mCurrentAccessory: " + mCurrentAccessory);
+
+ mDeviceManager.dump(fd, pw);
+ }
+ }
+
// host support
private native void monitorUsbHostBus();
private native ParcelFileDescriptor nativeOpenDevice(String deviceName);
diff --git a/services/java/com/android/server/wm/WindowManagerService.java b/services/java/com/android/server/wm/WindowManagerService.java
index b7cc324..e3218c8 100644
--- a/services/java/com/android/server/wm/WindowManagerService.java
+++ b/services/java/com/android/server/wm/WindowManagerService.java
@@ -5812,8 +5812,7 @@
mDisplay = wm.getDefaultDisplay();
mInitialDisplayWidth = mDisplay.getWidth();
mInitialDisplayHeight = mDisplay.getHeight();
- mInputManager.setDisplaySize(0, Display.unmapDisplaySize(mInitialDisplayWidth),
- Display.unmapDisplaySize(mInitialDisplayHeight));
+ mInputManager.setDisplaySize(0, mDisplay.getRealWidth(), mDisplay.getRealHeight());
}
try {
diff --git a/services/jni/com_android_server_UsbService.cpp b/services/jni/com_android_server_UsbService.cpp
index 192daaf..3c49e54 100644
--- a/services/jni/com_android_server_UsbService.cpp
+++ b/services/jni/com_android_server_UsbService.cpp
@@ -177,7 +177,6 @@
buffer[0] = 0;
int length = ioctl(fd, cmd, buffer);
- LOGD("ioctl returned %d", length);
if (buffer[0]) {
jstring obj = env->NewStringUTF(buffer);
env->SetObjectArrayElement(strArray, index, obj);
@@ -236,9 +235,9 @@
int register_android_server_UsbService(JNIEnv *env)
{
- jclass clazz = env->FindClass("com/android/server/UsbService");
+ jclass clazz = env->FindClass("com/android/server/usb/UsbService");
if (clazz == NULL) {
- LOGE("Can't find com/android/server/UsbService");
+ LOGE("Can't find com/android/server/usb/UsbService");
return -1;
}
method_usbDeviceAdded = env->GetMethodID(clazz, "usbDeviceAdded", "(Ljava/lang/String;IIIII[I[I)V");
@@ -267,7 +266,7 @@
LOG_FATAL_IF(gParcelFileDescriptorOffsets.mConstructor == NULL,
"Unable to find constructor for android.os.ParcelFileDescriptor");
- return jniRegisterNativeMethods(env, "com/android/server/UsbService",
+ return jniRegisterNativeMethods(env, "com/android/server/usb/UsbService",
method_table, NELEM(method_table));
}
diff --git a/test-runner/src/android/test/SingleLaunchActivityTestCase.java b/test-runner/src/android/test/SingleLaunchActivityTestCase.java
index b63b3ce..79c554a 100644
--- a/test-runner/src/android/test/SingleLaunchActivityTestCase.java
+++ b/test-runner/src/android/test/SingleLaunchActivityTestCase.java
@@ -75,7 +75,7 @@
protected void tearDown() throws Exception {
// If it is the last test case, call finish on the activity.
sTestCaseCounter --;
- if (sTestCaseCounter == 1) {
+ if (sTestCaseCounter == 0) {
sActivity.finish();
}
super.tearDown();
diff --git a/tools/aapt/NOTICE b/tools/aapt/NOTICE
new file mode 100644
index 0000000..c5b1efa
--- /dev/null
+++ b/tools/aapt/NOTICE
@@ -0,0 +1,190 @@
+
+ Copyright (c) 2005-2008, The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+
+ 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.
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
diff --git a/tools/aidl/NOTICE b/tools/aidl/NOTICE
new file mode 100644
index 0000000..c5b1efa
--- /dev/null
+++ b/tools/aidl/NOTICE
@@ -0,0 +1,190 @@
+
+ Copyright (c) 2005-2008, The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+
+ 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.
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
diff --git a/wifi/java/android/net/wifi/WifiStateMachine.java b/wifi/java/android/net/wifi/WifiStateMachine.java
index 676218e..f9d2772 100644
--- a/wifi/java/android/net/wifi/WifiStateMachine.java
+++ b/wifi/java/android/net/wifi/WifiStateMachine.java
@@ -2785,11 +2785,30 @@
class DisconnectedState extends HierarchicalState {
private boolean mAlarmEnabled = false;
+ private long mScanIntervalMs;
+
+ private void setScanAlarm(boolean enabled) {
+ if (enabled == mAlarmEnabled) return;
+ if (enabled) {
+ mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
+ System.currentTimeMillis() + mScanIntervalMs,
+ mScanIntervalMs,
+ mScanIntent);
+
+ mAlarmEnabled = true;
+ } else {
+ mAlarmManager.cancel(mScanIntent);
+ mAlarmEnabled = false;
+ }
+ }
+
@Override
public void enter() {
if (DBG) Log.d(TAG, getName() + "\n");
EventLog.writeEvent(EVENTLOG_WIFI_STATE_CHANGED, getName());
+ mScanIntervalMs = Settings.Secure.getLong(mContext.getContentResolver(),
+ Settings.Secure.WIFI_SCAN_INTERVAL_MS, DEFAULT_SCAN_INTERVAL_MS);
/*
* We initiate background scanning if it is enabled, otherwise we
* initiate an infrequent scan that wakes up the device to ensure
@@ -2806,12 +2825,7 @@
WifiNative.enableBackgroundScan(true);
}
} else {
- long scanMs = Settings.Secure.getLong(mContext.getContentResolver(),
- Settings.Secure.WIFI_SCAN_INTERVAL_MS, DEFAULT_SCAN_INTERVAL_MS);
-
- mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
- System.currentTimeMillis() + scanMs, scanMs, mScanIntent);
- mAlarmEnabled = true;
+ setScanAlarm(true);
}
}
@Override
@@ -2829,7 +2843,13 @@
break;
case CMD_ENABLE_BACKGROUND_SCAN:
mEnableBackgroundScan = (message.arg1 == 1);
- WifiNative.enableBackgroundScan(mEnableBackgroundScan);
+ if (mEnableBackgroundScan) {
+ WifiNative.enableBackgroundScan(true);
+ setScanAlarm(false);
+ } else {
+ WifiNative.enableBackgroundScan(false);
+ setScanAlarm(true);
+ }
break;
/* Ignore network disconnect */
case NETWORK_DISCONNECTION_EVENT:
@@ -2866,10 +2886,7 @@
if (mEnableBackgroundScan) {
WifiNative.enableBackgroundScan(false);
}
- if (mAlarmEnabled) {
- mAlarmManager.cancel(mScanIntent);
- mAlarmEnabled = false;
- }
+ setScanAlarm(false);
}
}