Merge "Minor code cleanups in vector."
diff --git a/api/current.txt b/api/current.txt
index 86339f2..634b050 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -2256,7 +2256,6 @@
method public abstract void setCustomView(android.view.View);
method public abstract void setCustomView(android.view.View, android.app.ActionBar.LayoutParams);
method public abstract void setCustomView(int);
- method public abstract void setDisplayDisableHomeEnabled(boolean);
method public abstract void setDisplayHomeAsUpEnabled(boolean);
method public abstract void setDisplayOptions(int);
method public abstract void setDisplayOptions(int, int);
@@ -2264,6 +2263,7 @@
method public abstract void setDisplayShowHomeEnabled(boolean);
method public abstract void setDisplayShowTitleEnabled(boolean);
method public abstract void setDisplayUseLogoEnabled(boolean);
+ method public abstract void setHomeButtonEnabled(boolean);
method public abstract void setIcon(int);
method public abstract void setIcon(android.graphics.drawable.Drawable);
method public abstract void setListNavigationCallbacks(android.widget.SpinnerAdapter, android.app.ActionBar.OnNavigationListener);
@@ -2276,7 +2276,6 @@
method public abstract void setTitle(java.lang.CharSequence);
method public abstract void setTitle(int);
method public abstract void show();
- field public static final int DISPLAY_DISABLE_HOME = 32; // 0x20
field public static final int DISPLAY_HOME_AS_UP = 4; // 0x4
field public static final int DISPLAY_SHOW_CUSTOM = 16; // 0x10
field public static final int DISPLAY_SHOW_HOME = 2; // 0x2
@@ -8938,6 +8937,8 @@
method public java.lang.String flatten();
method public java.lang.String get(java.lang.String);
method public java.lang.String getAntibanding();
+ method public boolean getAutoExposureLock();
+ method public boolean getAutoWhiteBalanceLock();
method public java.lang.String getColorEffect();
method public int getExposureCompensation();
method public float getExposureCompensationStep();
@@ -8983,6 +8984,8 @@
method public java.lang.String getWhiteBalance();
method public int getZoom();
method public java.util.List<java.lang.Integer> getZoomRatios();
+ method public boolean isAutoExposureLockSupported();
+ method public boolean isAutoWhiteBalanceLockSupported();
method public boolean isSmoothZoomSupported();
method public boolean isZoomSupported();
method public void remove(java.lang.String);
@@ -8990,6 +8993,8 @@
method public void set(java.lang.String, java.lang.String);
method public void set(java.lang.String, int);
method public void setAntibanding(java.lang.String);
+ method public void setAutoExposureLock(boolean);
+ method public void setAutoWhiteBalanceLock(boolean);
method public void setColorEffect(java.lang.String);
method public void setExposureCompensation(int);
method public void setFlashMode(java.lang.String);
@@ -11958,6 +11963,8 @@
public final class NdefRecord implements android.os.Parcelable {
ctor public NdefRecord(short, byte[], byte[], byte[]);
ctor public NdefRecord(byte[]) throws android.nfc.FormatException;
+ method public static android.nfc.NdefRecord createUri(android.net.Uri);
+ method public static android.nfc.NdefRecord createUri(java.lang.String);
method public int describeContents();
method public byte[] getId();
method public byte[] getPayload();
@@ -22073,6 +22080,7 @@
method public void buildDrawingCache();
method public void buildDrawingCache(boolean);
method public void buildLayer();
+ method protected boolean canResolveLayoutDirection();
method public boolean canScrollHorizontally(int);
method public boolean canScrollVertically(int);
method public void cancelLongPress();
@@ -25274,6 +25282,10 @@
method public void setRowCount(int);
method public void setRowOrderPreserved(boolean);
method public void setUseDefaultMargins(boolean);
+ method public static android.widget.GridLayout.Spec spec(int, int, android.widget.GridLayout.Alignment, int);
+ method public static android.widget.GridLayout.Spec spec(int, android.widget.GridLayout.Alignment, int);
+ method public static android.widget.GridLayout.Spec spec(int, int, android.widget.GridLayout.Alignment);
+ method public static android.widget.GridLayout.Spec spec(int, android.widget.GridLayout.Alignment);
field public static final int ALIGN_BOUNDS = 0; // 0x0
field public static final int ALIGN_MARGINS = 1; // 0x1
field public static final android.widget.GridLayout.Alignment BASELINE;
@@ -25292,23 +25304,19 @@
public static abstract class GridLayout.Alignment {
}
- public static class GridLayout.Group {
- ctor public GridLayout.Group(int, int, android.widget.GridLayout.Alignment);
- ctor public GridLayout.Group(int, android.widget.GridLayout.Alignment);
- field public final android.widget.GridLayout.Alignment alignment;
- field public int flexibility;
- }
-
public static class GridLayout.LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
- ctor public GridLayout.LayoutParams(android.widget.GridLayout.Group, android.widget.GridLayout.Group);
+ ctor public GridLayout.LayoutParams(android.widget.GridLayout.Spec, android.widget.GridLayout.Spec);
ctor public GridLayout.LayoutParams();
ctor public GridLayout.LayoutParams(android.view.ViewGroup.LayoutParams);
ctor public GridLayout.LayoutParams(android.view.ViewGroup.MarginLayoutParams);
ctor public GridLayout.LayoutParams(android.widget.GridLayout.LayoutParams);
ctor public GridLayout.LayoutParams(android.content.Context, android.util.AttributeSet);
method public void setGravity(int);
- field public android.widget.GridLayout.Group columnGroup;
- field public android.widget.GridLayout.Group rowGroup;
+ field public android.widget.GridLayout.Spec columnSpec;
+ field public android.widget.GridLayout.Spec rowSpec;
+ }
+
+ public static class GridLayout.Spec {
}
public class GridView extends android.widget.AbsListView {
diff --git a/cmds/ip-up-vpn/ip-up-vpn.c b/cmds/ip-up-vpn/ip-up-vpn.c
index bbf6b14e..e9ee95d 100644
--- a/cmds/ip-up-vpn/ip-up-vpn.c
+++ b/cmds/ip-up-vpn/ip-up-vpn.c
@@ -17,19 +17,135 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <errno.h>
-#include <cutils/properties.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <linux/if.h>
+#include <linux/route.h>
+#define LOG_TAG "ip-up-vpn"
+#include <cutils/log.h>
+
+#define DIR "/data/misc/vpn/"
+
+static const char *env(const char *name) {
+ const char *value = getenv(name);
+ return value ? value : "";
+}
+
+static int set_address(struct sockaddr *sa, const char *address) {
+ sa->sa_family = AF_INET;
+ return inet_pton(AF_INET, address, &((struct sockaddr_in *)sa)->sin_addr);
+}
+
+/*
+ * The primary goal is to create a file with VPN parameters. Currently they
+ * are interface, addresses, routes, DNS servers, and search domains. Each
+ * parameter occupies one line in the file, and it can be an empty string or
+ * space-separated values. The order and the format must be consistent with
+ * com.android.server.connectivity.Vpn. Here is an example.
+ *
+ * ppp0
+ * 192.168.1.100/24
+ * 0.0.0.0/0
+ * 192.168.1.1 192.168.1.2
+ * example.org
+ *
+ * The secondary goal is to unify the outcome of VPN. The current baseline
+ * is to have an interface configured with the given address and netmask
+ * and maybe add a host route to protect the tunnel. PPP-based VPN already
+ * does this, but others might not. Routes, DNS servers, and search domains
+ * are handled by the framework since they can be overridden by the users.
+ */
int main(int argc, char **argv)
{
- if (argc > 1 && strlen(argv[1]) > 0) {
- char dns[PROPERTY_VALUE_MAX];
- char *dns1 = getenv("DNS1");
- char *dns2 = getenv("DNS2");
+ FILE *state = fopen(DIR ".tmp", "wb");
+ if (!state) {
+ LOGE("Cannot create state: %s", strerror(errno));
+ return 1;
+ }
- snprintf(dns, sizeof(dns), "%s %s", dns1 ? dns1 : "", dns2 ? dns2 : "");
- property_set("vpn.dns", dns);
- property_set("vpn.via", argv[1]);
+ if (argc >= 6) {
+ /* Invoked by pppd. */
+ fprintf(state, "%s\n", argv[1]);
+ fprintf(state, "%s/32\n", argv[4]);
+ fprintf(state, "0.0.0.0/0\n");
+ fprintf(state, "%s %s\n", env("DNS1"), env("DNS2"));
+ fprintf(state, "\n");
+ } else if (argc == 2) {
+ /* Invoked by racoon. */
+ const char *interface = env("INTERFACE");
+ const char *address = env("INTERNAL_ADDR4");
+ const char *routes = env("SPLIT_INCLUDE_CIDR");
+
+ int s = socket(AF_INET, SOCK_DGRAM, 0);
+ struct rtentry rt;
+ struct ifreq ifr;
+
+ memset(&rt, 0, sizeof(rt));
+ memset(&ifr, 0, sizeof(ifr));
+
+ /* Remove the old host route. There could be more than one. */
+ rt.rt_flags |= RTF_UP | RTF_HOST;
+ if (set_address(&rt.rt_dst, env("REMOTE_ADDR"))) {
+ while (!ioctl(s, SIOCDELRT, &rt));
+ }
+ if (errno != ESRCH) {
+ LOGE("Cannot remove host route: %s", strerror(errno));
+ return 1;
+ }
+
+ /* Create a new host route. */
+ rt.rt_flags |= RTF_GATEWAY;
+ if (!set_address(&rt.rt_gateway, argv[1]) ||
+ (ioctl(s, SIOCADDRT, &rt) && errno != EEXIST)) {
+ LOGE("Cannot create host route: %s", strerror(errno));
+ return 1;
+ }
+
+ /* Bring up the interface. */
+ ifr.ifr_flags = IFF_UP;
+ strncpy(ifr.ifr_name, interface, IFNAMSIZ);
+ if (ioctl(s, SIOCSIFFLAGS, &ifr)) {
+ LOGE("Cannot bring up %s: %s", interface, strerror(errno));
+ return 1;
+ }
+
+ /* Set the address. */
+ if (!set_address(&ifr.ifr_addr, address) ||
+ ioctl(s, SIOCSIFADDR, &ifr)) {
+ LOGE("Cannot set address: %s", strerror(errno));
+ return 1;
+ }
+
+ /* Set the netmask. */
+ if (!set_address(&ifr.ifr_netmask, env("INTERNAL_NETMASK4")) ||
+ ioctl(s, SIOCSIFNETMASK, &ifr)) {
+ LOGE("Cannot set netmask: %s", strerror(errno));
+ return 1;
+ }
+
+ /* TODO: Send few packets to trigger phase 2? */
+
+ fprintf(state, "%s\n", interface);
+ fprintf(state, "%s/%s\n", address, env("INTERNAL_CIDR4"));
+ fprintf(state, "%s\n", routes[0] ? routes : "0.0.0.0/0");
+ fprintf(state, "%s\n", env("INTERNAL_DNS4_LIST"));
+ fprintf(state, "%s\n", env("DEFAULT_DOMAIN"));
+ } else {
+ LOGE("Cannot parse parameters");
+ return 1;
+ }
+
+ fclose(state);
+ if (chmod(DIR ".tmp", 0444) || rename(DIR ".tmp", DIR "state")) {
+ LOGE("Cannot write state: %s", strerror(errno));
+ return 1;
}
return 0;
}
diff --git a/cmds/stagefright/stagefright.cpp b/cmds/stagefright/stagefright.cpp
index 1a5b7f3..dd1c275 100644
--- a/cmds/stagefright/stagefright.cpp
+++ b/cmds/stagefright/stagefright.cpp
@@ -793,7 +793,9 @@
MEDIA_MIMETYPE_VIDEO_AVC, MEDIA_MIMETYPE_VIDEO_MPEG4,
MEDIA_MIMETYPE_VIDEO_H263, MEDIA_MIMETYPE_AUDIO_AAC,
MEDIA_MIMETYPE_AUDIO_AMR_NB, MEDIA_MIMETYPE_AUDIO_AMR_WB,
- MEDIA_MIMETYPE_AUDIO_MPEG
+ MEDIA_MIMETYPE_AUDIO_MPEG, MEDIA_MIMETYPE_AUDIO_G711_MLAW,
+ MEDIA_MIMETYPE_AUDIO_G711_ALAW, MEDIA_MIMETYPE_AUDIO_VORBIS,
+ MEDIA_MIMETYPE_VIDEO_VPX
};
for (size_t k = 0; k < sizeof(kMimeTypes) / sizeof(kMimeTypes[0]);
diff --git a/core/java/android/app/ActionBar.java b/core/java/android/app/ActionBar.java
index 3ec5edb..36940c2 100644
--- a/core/java/android/app/ActionBar.java
+++ b/core/java/android/app/ActionBar.java
@@ -81,6 +81,9 @@
* Set this flag if selecting the 'home' button in the action bar to return
* up by a single level in your UI rather than back to the top level or front page.
*
+ * <p>Setting this option will implicitly enable interaction with the home/up
+ * button. See {@link #setHomeButtonEnabled(boolean)}.
+ *
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
@@ -107,18 +110,6 @@
public static final int DISPLAY_SHOW_CUSTOM = 0x10;
/**
- * Disable the 'home' element. This may be combined with
- * {@link #DISPLAY_SHOW_HOME} to create a non-focusable/non-clickable
- * 'home' element. Useful for a level of your app's navigation hierarchy
- * where clicking 'home' doesn't do anything.
- *
- * @see #setDisplayOptions(int)
- * @see #setDisplayOptions(int, int)
- * @see #setDisplayDisableHomeEnabled(boolean)
- */
- public static final int DISPLAY_DISABLE_HOME = 0x20;
-
- /**
* Set the action bar into custom navigation mode, supplying a view
* for custom navigation.
*
@@ -405,21 +396,6 @@
public abstract void setDisplayShowCustomEnabled(boolean showCustom);
/**
- * Set whether the 'home' affordance on the action bar should be disabled.
- * If set, the 'home' element will not be focusable or clickable, useful if
- * the user is at the top level of the app's navigation hierarchy.
- *
- * <p>To set several display options at once, see the setDisplayOptions methods.
- *
- * @param disableHome true to disable the 'home' element.
- *
- * @see #setDisplayOptions(int)
- * @see #setDisplayOptions(int, int)
- * @see #DISPLAY_DISABLE_HOME
- */
- public abstract void setDisplayDisableHomeEnabled(boolean disableHome);
-
- /**
* Set the ActionBar's background.
*
* @param d Background drawable
@@ -632,6 +608,22 @@
public abstract void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener);
/**
+ * Enable or disable the "home" button in the corner of the action bar. (Note that this
+ * is the application home/up affordance on the action bar, not the systemwide home
+ * button.)
+ *
+ * <p>This defaults to true for packages targeting < API 14. For packages targeting
+ * API 14 or greater, the application should call this method to enable interaction
+ * with the home/up affordance.
+ *
+ * <p>Setting the {@link #DISPLAY_HOME_AS_UP} display option will automatically enable
+ * the home button.
+ *
+ * @param enabled true to enable the home button, false to disable the home button.
+ */
+ public abstract void setHomeButtonEnabled(boolean enabled);
+
+ /**
* Listener interface for ActionBar navigation events.
*/
public interface OnNavigationListener {
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index ee04729..8994b17 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -932,6 +932,10 @@
ucd.info = info;
queueOrSendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
}
+
+ public void scheduleTrimMemory(int level) {
+ queueOrSendMessage(H.TRIM_MEMORY, level);
+ }
}
private final class H extends Handler {
@@ -975,6 +979,7 @@
public static final int SLEEPING = 137;
public static final int SET_CORE_SETTINGS = 138;
public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
+ public static final int TRIM_MEMORY = 140;
String codeToString(int code) {
if (DEBUG_MESSAGES) {
switch (code) {
@@ -1018,6 +1023,7 @@
case SLEEPING: return "SLEEPING";
case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
+ case TRIM_MEMORY: return "TRIM_MEMORY";
}
}
return "(unknown)";
@@ -1158,6 +1164,8 @@
break;
case UPDATE_PACKAGE_COMPATIBILITY_INFO:
handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
+ case TRIM_MEMORY:
+ handleTrimMemory(msg.arg1);
}
if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what);
}
@@ -3529,6 +3537,9 @@
BinderInternal.forceGc("mem");
}
+ final void handleTrimMemory(int level) {
+ }
+
private final void handleBindApplication(AppBindData data) {
mBoundApplication = data;
mConfiguration = new Configuration(data.config);
diff --git a/core/java/android/app/ApplicationThreadNative.java b/core/java/android/app/ApplicationThreadNative.java
index dc0f529..16181e0 100644
--- a/core/java/android/app/ApplicationThreadNative.java
+++ b/core/java/android/app/ApplicationThreadNative.java
@@ -478,6 +478,13 @@
updatePackageCompatibilityInfo(pkg, compat);
return true;
}
+
+ case SCHEDULE_TRIM_MEMORY_TRANSACTION: {
+ data.enforceInterface(IApplicationThread.descriptor);
+ int level = data.readInt();
+ scheduleTrimMemory(level);
+ return true;
+ }
}
return super.onTransact(code, data, reply, flags);
@@ -989,4 +996,12 @@
mRemote.transact(UPDATE_PACKAGE_COMPATIBILITY_INFO_TRANSACTION, data, null,
IBinder.FLAG_ONEWAY);
}
+
+ public void scheduleTrimMemory(int level) throws RemoteException {
+ Parcel data = Parcel.obtain();
+ data.writeInterfaceToken(IApplicationThread.descriptor);
+ data.writeInt(level);
+ mRemote.transact(SCHEDULE_TRIM_MEMORY_TRANSACTION, data, null,
+ IBinder.FLAG_ONEWAY);
+ }
}
diff --git a/core/java/android/app/IApplicationThread.java b/core/java/android/app/IApplicationThread.java
index 05a68a8..94c2c86 100644
--- a/core/java/android/app/IApplicationThread.java
+++ b/core/java/android/app/IApplicationThread.java
@@ -119,6 +119,7 @@
throws RemoteException;
void setCoreSettings(Bundle coreSettings) throws RemoteException;
void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) throws RemoteException;
+ void scheduleTrimMemory(int level) throws RemoteException;
String descriptor = "android.app.IApplicationThread";
@@ -162,4 +163,5 @@
int SET_HTTP_PROXY_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+38;
int SET_CORE_SETTINGS_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+39;
int UPDATE_PACKAGE_COMPATIBILITY_INFO_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+40;
+ int SCHEDULE_TRIM_MEMORY_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+41;
}
diff --git a/core/java/android/content/ComponentCallbacks.java b/core/java/android/content/ComponentCallbacks.java
index dad60b0..92b98fd 100644
--- a/core/java/android/content/ComponentCallbacks.java
+++ b/core/java/android/content/ComponentCallbacks.java
@@ -51,4 +51,16 @@
* The system will perform a gc for you after returning from this method.
*/
void onLowMemory();
+
+ /** @hide */
+ static final int TRIM_MEMORY_COMPLETE = 80;
+
+ /** @hide */
+ static final int TRIM_MEMORY_MODERATE = 60;
+
+ /** @hide */
+ static final int TRIM_MEMORY_BACKGROUND = 40;
+
+ /** @hide */
+ static final int TRIM_MEMORY_INVISIBLE = 20;
}
diff --git a/core/java/android/hardware/Camera.java b/core/java/android/hardware/Camera.java
index 8a42693..7d67e11 100644
--- a/core/java/android/hardware/Camera.java
+++ b/core/java/android/hardware/Camera.java
@@ -720,8 +720,20 @@
* onAutoFocus will be called immediately with a fake value of
* <code>success</code> set to <code>true</code>.
*
+ * The auto-focus routine may lock auto-exposure and auto-white balance
+ * after it completes. To check for the state of these locks, use the
+ * {@link android.hardware.Camera.Parameters#getAutoExposureLock()} and
+ * {@link android.hardware.Camera.Parameters#getAutoWhiteBalanceLock()}
+ * methods. If such locking is undesirable, use
+ * {@link android.hardware.Camera.Parameters#setAutoExposureLock(boolean)}
+ * and
+ * {@link android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean)}
+ * to release the locks.
+ *
* @param success true if focus was successful, false if otherwise
* @param camera the Camera service object
+ * @see android.hardware.Camera.Parameters#setAutoExposureLock(boolean)
+ * @see android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean)
*/
void onAutoFocus(boolean success, Camera camera);
};
@@ -747,8 +759,21 @@
* {@link android.hardware.Camera.Parameters#FLASH_MODE_OFF}, flash may be
* fired during auto-focus, depending on the driver and camera hardware.<p>
*
+ * The auto-focus routine may lock auto-exposure and auto-white balance
+ * after it completes. To check for the state of these locks, use the
+ * {@link android.hardware.Camera.Parameters#getAutoExposureLock()} and
+ * {@link android.hardware.Camera.Parameters#getAutoWhiteBalanceLock()}
+ * methods after the {@link AutoFocusCallback#onAutoFocus(boolean, Camera)}
+ * callback is invoked. If such locking is undesirable, use
+ * {@link android.hardware.Camera.Parameters#setAutoExposureLock(boolean)}
+ * and
+ * {@link android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean)}
+ * to release the locks.
+ *
* @param cb the callback to run
* @see #cancelAutoFocus()
+ * @see android.hardware.Camera.Parameters#setAutoExposureLock(boolean)
+ * @see android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean)
*/
public final void autoFocus(AutoFocusCallback cb)
{
@@ -763,7 +788,13 @@
* this function will return the focus position to the default.
* If the camera does not support auto-focus, this is a no-op.
*
+ * Canceling auto-focus will return the auto-exposure lock and auto-white
+ * balance lock to their state before {@link #autoFocus(AutoFocusCallback)}
+ * was called.
+ *
* @see #autoFocus(Camera.AutoFocusCallback)
+ * @see android.hardware.Camera.Parameters#setAutoExposureLock(boolean)
+ * @see android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean)
*/
public final void cancelAutoFocus()
{
@@ -2562,8 +2593,6 @@
* routine is free to run normally.
*
* @see #getAutoExposureLock()
- *
- * @hide
*/
public void setAutoExposureLock(boolean toggle) {
set(KEY_AUTO_EXPOSURE_LOCK, toggle ? TRUE : FALSE);
@@ -2583,7 +2612,6 @@
*
* @see #setAutoExposureLock(boolean)
*
- * @hide
*/
public boolean getAutoExposureLock() {
String str = get(KEY_AUTO_EXPOSURE_LOCK);
@@ -2598,7 +2626,6 @@
* @return true if auto-exposure lock is supported.
* @see #setAutoExposureLock(boolean)
*
- * @hide
*/
public boolean isAutoExposureLockSupported() {
String str = get(KEY_AUTO_EXPOSURE_LOCK_SUPPORTED);
@@ -2645,8 +2672,6 @@
* auto-white balance routine is free to run normally.
*
* @see #getAutoWhiteBalanceLock()
- *
- * @hide
*/
public void setAutoWhiteBalanceLock(boolean toggle) {
set(KEY_AUTO_WHITEBALANCE_LOCK, toggle ? TRUE : FALSE);
@@ -2668,7 +2693,6 @@
*
* @see #setAutoWhiteBalanceLock(boolean)
*
- * @hide
*/
public boolean getAutoWhiteBalanceLock() {
String str = get(KEY_AUTO_WHITEBALANCE_LOCK);
@@ -2683,7 +2707,6 @@
* @return true if auto-white balance lock is supported.
* @see #setAutoWhiteBalanceLock(boolean)
*
- * @hide
*/
public boolean isAutoWhiteBalanceLockSupported() {
String str = get(KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED);
diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl
index d6f5643..d95fc8d 100644
--- a/core/java/android/net/IConnectivityManager.aidl
+++ b/core/java/android/net/IConnectivityManager.aidl
@@ -100,7 +100,7 @@
void setDataDependency(int networkType, boolean met);
- void protectVpn(in ParcelFileDescriptor socket);
+ boolean protectVpn(in ParcelFileDescriptor socket);
boolean prepareVpn(String oldPackage, String newPackage);
diff --git a/core/java/android/net/LinkProperties.java b/core/java/android/net/LinkProperties.java
index 19894a0..f2f0e82 100644
--- a/core/java/android/net/LinkProperties.java
+++ b/core/java/android/net/LinkProperties.java
@@ -52,11 +52,26 @@
public class LinkProperties implements Parcelable {
String mIfaceName;
- private Collection<LinkAddress> mLinkAddresses;
- private Collection<InetAddress> mDnses;
- private Collection<RouteInfo> mRoutes;
+ private Collection<LinkAddress> mLinkAddresses = new ArrayList<LinkAddress>();
+ private Collection<InetAddress> mDnses = new ArrayList<InetAddress>();
+ private Collection<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
private ProxyProperties mHttpProxy;
+ public static class CompareAddressesResult {
+ public ArrayList<LinkAddress> removed = new ArrayList<LinkAddress>();
+ public ArrayList<LinkAddress> added = new ArrayList<LinkAddress>();
+
+ @Override
+ public String toString() {
+ String retVal = "removedAddresses=[";
+ for (LinkAddress addr : removed) retVal += addr.toString() + ",";
+ retVal += "] addedAddresses=[";
+ for (LinkAddress addr : added) retVal += addr.toString() + ",";
+ retVal += "]";
+ return retVal;
+ }
+ }
+
public LinkProperties() {
clear();
}
@@ -121,9 +136,9 @@
public void clear() {
mIfaceName = null;
- mLinkAddresses = new ArrayList<LinkAddress>();
- mDnses = new ArrayList<InetAddress>();
- mRoutes = new ArrayList<RouteInfo>();
+ mLinkAddresses.clear();
+ mDnses.clear();
+ mRoutes.clear();
mHttpProxy = null;
}
@@ -155,6 +170,63 @@
return ifaceName + linkAddresses + routes + dns + proxy;
}
+ /**
+ * Compares this {@code LinkProperties} interface name against the target
+ *
+ * @param target LinkProperties to compare.
+ * @return {@code true} if both are identical, {@code false} otherwise.
+ */
+ public boolean isIdenticalInterfaceName(LinkProperties target) {
+ return TextUtils.equals(getInterfaceName(), target.getInterfaceName());
+ }
+
+ /**
+ * Compares this {@code LinkProperties} interface name against the target
+ *
+ * @param target LinkProperties to compare.
+ * @return {@code true} if both are identical, {@code false} otherwise.
+ */
+ public boolean isIdenticalAddresses(LinkProperties target) {
+ Collection<InetAddress> targetAddresses = target.getAddresses();
+ Collection<InetAddress> sourceAddresses = getAddresses();
+ return (sourceAddresses.size() == targetAddresses.size()) ?
+ sourceAddresses.containsAll(targetAddresses) : false;
+ }
+
+ /**
+ * Compares this {@code LinkProperties} DNS addresses against the target
+ *
+ * @param target LinkProperties to compare.
+ * @return {@code true} if both are identical, {@code false} otherwise.
+ */
+ public boolean isIdenticalDnses(LinkProperties target) {
+ Collection<InetAddress> targetDnses = target.getDnses();
+ return (mDnses.size() == targetDnses.size()) ?
+ mDnses.containsAll(targetDnses) : false;
+ }
+
+ /**
+ * Compares this {@code LinkProperties} Routes against the target
+ *
+ * @param target LinkProperties to compare.
+ * @return {@code true} if both are identical, {@code false} otherwise.
+ */
+ public boolean isIdenticalRoutes(LinkProperties target) {
+ Collection<RouteInfo> targetRoutes = target.getRoutes();
+ return (mRoutes.size() == targetRoutes.size()) ?
+ mRoutes.containsAll(targetRoutes) : false;
+ }
+
+ /**
+ * Compares this {@code LinkProperties} HttpProxy against the target
+ *
+ * @param target LinkProperties to compare.
+ * @return {@code true} if both are identical, {@code false} otherwise.
+ */
+ public boolean isIdenticalHttpProxy(LinkProperties target) {
+ return getHttpProxy() == null ? target.getHttpProxy() == null :
+ getHttpProxy().equals(target.getHttpProxy());
+ }
@Override
/**
@@ -176,30 +248,41 @@
if (!(obj instanceof LinkProperties)) return false;
- boolean sameAddresses;
- boolean sameDnses;
- boolean sameRoutes;
-
LinkProperties target = (LinkProperties) obj;
- Collection<InetAddress> targetAddresses = target.getAddresses();
- Collection<InetAddress> sourceAddresses = getAddresses();
- sameAddresses = (sourceAddresses.size() == targetAddresses.size()) ?
- sourceAddresses.containsAll(targetAddresses) : false;
+ return isIdenticalInterfaceName(target) &&
+ isIdenticalAddresses(target) &&
+ isIdenticalDnses(target) &&
+ isIdenticalRoutes(target) &&
+ isIdenticalHttpProxy(target);
+ }
- Collection<InetAddress> targetDnses = target.getDnses();
- sameDnses = (mDnses.size() == targetDnses.size()) ?
- mDnses.containsAll(targetDnses) : false;
-
- Collection<RouteInfo> targetRoutes = target.getRoutes();
- sameRoutes = (mRoutes.size() == targetRoutes.size()) ?
- mRoutes.containsAll(targetRoutes) : false;
-
- return
- sameAddresses && sameDnses && sameRoutes
- && TextUtils.equals(getInterfaceName(), target.getInterfaceName())
- && (getHttpProxy() == null ? target.getHttpProxy() == null :
- getHttpProxy().equals(target.getHttpProxy()));
+ /**
+ * Return two lists, a list of addresses that would be removed from
+ * mLinkAddresses and a list of addresses that would be added to
+ * mLinkAddress which would then result in target and mLinkAddresses
+ * being the same list.
+ *
+ * @param target is a new list of addresses
+ * @return the removed and added lists.
+ */
+ public CompareAddressesResult compareAddresses(LinkProperties target) {
+ /*
+ * Duplicate the LinkAddresses into removed, we will be removing
+ * address which are common between mLinkAddresses and target
+ * leaving the addresses that are different. And address which
+ * are in target but not in mLinkAddresses are placed in the
+ * addedAddresses.
+ */
+ CompareAddressesResult result = new CompareAddressesResult();
+ result.removed = new ArrayList<LinkAddress>(mLinkAddresses);
+ result.added.clear();
+ for (LinkAddress newAddress : target.getLinkAddresses()) {
+ if (! result.removed.remove(newAddress)) {
+ result.added.add(newAddress);
+ }
+ }
+ return result;
}
@Override
diff --git a/core/java/android/nfc/NdefRecord.java b/core/java/android/nfc/NdefRecord.java
index 0eb8cd8..b668f30 100644
--- a/core/java/android/nfc/NdefRecord.java
+++ b/core/java/android/nfc/NdefRecord.java
@@ -334,8 +334,6 @@
/**
* Creates an NDEF record of well known type URI.
- * TODO: Make a public API
- * @hide
*/
public static NdefRecord createUri(Uri uri) {
return createUri(uri.toString());
@@ -343,8 +341,6 @@
/**
* Creates an NDEF record of well known type URI.
- * TODO: Make a public API
- * @hide
*/
public static NdefRecord createUri(String uriString) {
byte prefix = 0x0;
diff --git a/core/java/android/os/Process.java b/core/java/android/os/Process.java
index 5b1f563..3362575 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -86,6 +86,12 @@
public static final int WIFI_UID = 1010;
/**
+ * Defines the UID/GID for the mediaserver process.
+ * @hide
+ */
+ public static final int MEDIA_UID = 1013;
+
+ /**
* Defines the GID for the group that allows write access to the SD card.
* @hide
*/
diff --git a/core/java/android/server/BluetoothEventLoop.java b/core/java/android/server/BluetoothEventLoop.java
index 63c420a..f345a6a 100644
--- a/core/java/android/server/BluetoothEventLoop.java
+++ b/core/java/android/server/BluetoothEventLoop.java
@@ -660,7 +660,6 @@
case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE:
case BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES:
case BluetoothClass.Device.AUDIO_VIDEO_PORTABLE_AUDIO:
- case BluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO:
case BluetoothClass.Device.AUDIO_VIDEO_HIFI_AUDIO:
if (mBluetoothService.attemptAutoPair(address)) return;
}
diff --git a/core/java/android/speech/tts/TextToSpeech.java b/core/java/android/speech/tts/TextToSpeech.java
index 8e4725f..32ca226 100755
--- a/core/java/android/speech/tts/TextToSpeech.java
+++ b/core/java/android/speech/tts/TextToSpeech.java
@@ -181,7 +181,7 @@
*
* @hide
* @deprecated No longer in use, the default engine is determined by
- * the sort order defined in {@link EngineInfoComparator}. Note that
+ * the sort order defined in {@link TtsEngines}. Note that
* this doesn't "break" anything because there is no guarantee that
* the engine specified below is installed on a given build, let
* alone be the default.
@@ -504,36 +504,39 @@
}
private int initTts() {
- String defaultEngine = getDefaultEngine();
- String engine = defaultEngine;
- if (mEnginesHelper.isEngineInstalled(mRequestedEngine)) {
- engine = mRequestedEngine;
+ // Step 1: Try connecting to the engine that was requested.
+ if (mRequestedEngine != null && mEnginesHelper.isEngineInstalled(mRequestedEngine)) {
+ if (connectToEngine(mRequestedEngine)) {
+ mCurrentEngine = mRequestedEngine;
+ return SUCCESS;
+ }
}
- // Try requested engine
- if (connectToEngine(engine)) {
- mCurrentEngine = engine;
- return SUCCESS;
- }
-
- // Fall back to user's default engine if different from the already tested one
- if (!engine.equals(defaultEngine)) {
+ // Step 2: Try connecting to the user's default engine.
+ final String defaultEngine = getDefaultEngine();
+ if (defaultEngine != null && !defaultEngine.equals(mRequestedEngine)) {
if (connectToEngine(defaultEngine)) {
- mCurrentEngine = engine;
+ mCurrentEngine = defaultEngine;
return SUCCESS;
}
}
+ // Step 3: Try connecting to the highest ranked engine in the
+ // system.
final String highestRanked = mEnginesHelper.getHighestRankedEngineName();
- // Fall back to the hardcoded default if different from the two above
- if (!defaultEngine.equals(highestRanked)
- && !engine.equals(highestRanked)) {
+ if (highestRanked != null && !highestRanked.equals(mRequestedEngine) &&
+ !highestRanked.equals(defaultEngine)) {
if (connectToEngine(highestRanked)) {
- mCurrentEngine = engine;
+ mCurrentEngine = highestRanked;
return SUCCESS;
}
}
+ // NOTE: The API currently does not allow the caller to query whether
+ // they are actually connected to any engine. This might fail for various
+ // reasons like if the user disables all her TTS engines.
+
+ mCurrentEngine = null;
dispatchOnInit(ERROR);
return ERROR;
}
@@ -963,7 +966,7 @@
/**
* Synthesizes the given text to a file using the specified parameters.
*
- * @param text Thetext that should be synthesized
+ * @param text The text that should be synthesized
* @param params Parameters for the request. Can be null.
* Supported parameter names:
* {@link Engine#KEY_PARAM_UTTERANCE_ID}.
@@ -1073,7 +1076,9 @@
*
* @deprecated This doesn't inform callers when the TTS engine has been
* initialized. {@link #TextToSpeech(Context, OnInitListener, String)}
- * can be used with the appropriate engine name.
+ * can be used with the appropriate engine name. Also, there is no
+ * guarantee that the engine specified will be loaded. If it isn't
+ * installed or disabled, the user / system wide defaults will apply.
*
* @param enginePackageName The package name for the synthesis engine (e.g. "com.svox.pico")
*
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 74dc100..8cd683e 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -9066,11 +9066,20 @@
// Set resolved depending on layout direction
switch (getLayoutDirection()) {
case LAYOUT_DIRECTION_INHERIT:
+ // We cannot do the resolution if there is no parent
+ if (mParent == null) return;
+
// If this is root view, no need to look at parent's layout dir.
- if (mParent != null &&
- mParent instanceof ViewGroup &&
- ((ViewGroup) mParent).getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
- mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
+ if (mParent instanceof ViewGroup) {
+ ViewGroup viewGroup = ((ViewGroup) mParent);
+
+ // Check if the parent view group can resolve
+ if (! viewGroup.canResolveLayoutDirection()) {
+ return;
+ }
+ if (viewGroup.getResolvedLayoutDirection() == LAYOUT_DIRECTION_RTL) {
+ mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED_RTL;
+ }
}
break;
case LAYOUT_DIRECTION_RTL:
@@ -9132,6 +9141,15 @@
recomputePadding();
}
+ protected boolean canResolveLayoutDirection() {
+ switch (getLayoutDirection()) {
+ case LAYOUT_DIRECTION_INHERIT:
+ return (mParent != null);
+ default:
+ return true;
+ }
+ }
+
/**
* Reset the resolved layout direction.
*
diff --git a/core/java/android/webkit/CallbackProxy.java b/core/java/android/webkit/CallbackProxy.java
index 0294e3f..88583df 100644
--- a/core/java/android/webkit/CallbackProxy.java
+++ b/core/java/android/webkit/CallbackProxy.java
@@ -120,6 +120,7 @@
private static final int AUTO_LOGIN = 140;
private static final int CLIENT_CERT_REQUEST = 141;
private static final int SEARCHBOX_IS_SUPPORTED_CALLBACK = 142;
+ private static final int SEARCHBOX_DISPATCH_COMPLETE_CALLBACK= 143;
// Message triggered by the client to resume execution
private static final int NOTIFY = 200;
@@ -821,6 +822,13 @@
searchBox.handleIsSupportedCallback(supported);
break;
}
+ case SEARCHBOX_DISPATCH_COMPLETE_CALLBACK: {
+ SearchBoxImpl searchBox = (SearchBoxImpl) mWebView.getSearchBox();
+ Boolean success = (Boolean) msg.obj;
+ searchBox.handleDispatchCompleteCallback(msg.getData().getString("function"),
+ msg.getData().getInt("id"), success);
+ break;
+ }
}
}
@@ -1641,4 +1649,13 @@
msg.obj = new Boolean(isSupported);
sendMessage(msg);
}
+
+ void onSearchboxDispatchCompleteCallback(String function, int id, boolean success) {
+ Message msg = obtainMessage(SEARCHBOX_DISPATCH_COMPLETE_CALLBACK);
+ msg.obj = Boolean.valueOf(success);
+ msg.getData().putString("function", function);
+ msg.getData().putInt("id", id);
+
+ sendMessage(msg);
+ }
}
diff --git a/core/java/android/webkit/SearchBox.java b/core/java/android/webkit/SearchBox.java
index 5075302..6512c4b 100644
--- a/core/java/android/webkit/SearchBox.java
+++ b/core/java/android/webkit/SearchBox.java
@@ -68,11 +68,15 @@
* Notify the search page of any changes to the searchbox. Such as
* a change in the typed query (onchange), the user commiting a given query
* (onsubmit), or a change in size of a suggestions dropdown (onresize).
+ *
+ * @param listener an optional listener to notify of the success of the operation,
+ * indicating if the javascript function existed and could be called or not.
+ * It will be called on the UI thread.
*/
- void onchange();
- void onsubmit();
- void onresize();
- void oncancel();
+ void onchange(SearchBoxListener listener);
+ void onsubmit(SearchBoxListener listener);
+ void onresize(SearchBoxListener listener);
+ void oncancel(SearchBoxListener listener);
/**
* Add and remove listeners to the given Searchbox. Listeners are notified
@@ -91,8 +95,12 @@
* Listeners (if any) will be called on the thread that created the
* webview.
*/
- interface SearchBoxListener {
- void onSuggestionsReceived(String query, List<String> suggestions);
+ public abstract class SearchBoxListener {
+ public void onSuggestionsReceived(String query, List<String> suggestions) {}
+ public void onChangeComplete(boolean called) {}
+ public void onSubmitComplete(boolean called) {}
+ public void onResizeComplete(boolean called) {}
+ public void onCancelComplete(boolean called) {}
}
interface IsSupportedCallback {
diff --git a/core/java/android/webkit/SearchBoxImpl.java b/core/java/android/webkit/SearchBoxImpl.java
index 61fb2ce..9942d25 100644
--- a/core/java/android/webkit/SearchBoxImpl.java
+++ b/core/java/android/webkit/SearchBoxImpl.java
@@ -16,10 +16,12 @@
package android.webkit;
+import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebViewCore.EventHub;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
@@ -69,7 +71,7 @@
private static final String SET_VERBATIM_SCRIPT
= "if (window.chrome && window.chrome.searchBox) {"
- + " window.chrome.searchBox.verbatim = %s;"
+ + " window.chrome.searchBox.verbatim = %1$s;"
+ "}";
private static final String SET_SELECTION_SCRIPT
@@ -89,13 +91,21 @@
+ "}";
private static final String DISPATCH_EVENT_SCRIPT
- = "if (window.chrome && window.chrome.searchBox &&"
- + " window.chrome.searchBox.on%1$s) { window.chrome.searchBox.on%1$s(); }";
+ = "if (window.chrome && window.chrome.searchBox && window.chrome.searchBox.on%1$s) {"
+ + " window.chrome.searchBox.on%1$s();"
+ + " window.searchBoxJavaBridge_.dispatchCompleteCallback('%1$s', %2$d, true);"
+ + "} else {"
+ + " window.searchBoxJavaBridge_.dispatchCompleteCallback('%1$s', %2$d, false);"
+ + "}";
+
+ private static final String EVENT_CHANGE = "change";
+ private static final String EVENT_SUBMIT = "submit";
+ private static final String EVENT_RESIZE = "resize";
+ private static final String EVENT_CANCEL = "cancel";
private static final String IS_SUPPORTED_SCRIPT
= "if (window.searchBoxJavaBridge_) {"
- + " if (window.chrome && window.chrome.searchBox && "
- + " window.chrome.searchBox.onsubmit) {"
+ + " if (window.chrome && window.chrome.sv) {"
+ " window.searchBoxJavaBridge_.isSupportedCallback(true);"
+ " } else {"
+ " window.searchBoxJavaBridge_.isSupportedCallback(false);"
@@ -105,11 +115,14 @@
private final WebViewCore mWebViewCore;
private final CallbackProxy mCallbackProxy;
private IsSupportedCallback mSupportedCallback;
+ private int mNextEventId = 1;
+ private final HashMap<Integer, SearchBoxListener> mEventCallbacks;
SearchBoxImpl(WebViewCore webViewCore, CallbackProxy callbackProxy) {
mListeners = new ArrayList<SearchBoxListener>();
mWebViewCore = webViewCore;
mCallbackProxy = callbackProxy;
+ mEventCallbacks = new HashMap<Integer, SearchBoxListener>();
}
@Override
@@ -141,27 +154,36 @@
}
@Override
- public void onchange() {
- dispatchEvent("change");
+ public void onchange(SearchBoxListener callback) {
+ dispatchEvent(EVENT_CHANGE, callback);
}
@Override
- public void onsubmit() {
- dispatchEvent("submit");
+ public void onsubmit(SearchBoxListener callback) {
+ dispatchEvent(EVENT_SUBMIT, callback);
}
@Override
- public void onresize() {
- dispatchEvent("resize");
+ public void onresize(SearchBoxListener callback) {
+ dispatchEvent(EVENT_RESIZE, callback);
}
@Override
- public void oncancel() {
- dispatchEvent("cancel");
+ public void oncancel(SearchBoxListener callback) {
+ dispatchEvent(EVENT_CANCEL, callback);
}
- private void dispatchEvent(String eventName) {
- final String js = String.format(DISPATCH_EVENT_SCRIPT, eventName);
+ private void dispatchEvent(String eventName, SearchBoxListener callback) {
+ int eventId;
+ if (callback != null) {
+ synchronized(this) {
+ eventId = mNextEventId++;
+ mEventCallbacks.put(eventId, callback);
+ }
+ } else {
+ eventId = 0;
+ }
+ final String js = String.format(DISPATCH_EVENT_SCRIPT, eventName, eventId);
dispatchJs(js);
}
@@ -202,9 +224,35 @@
}
}
+ // Called by Javascript through the Java bridge.
+ public void dispatchCompleteCallback(String function, int id, boolean successful) {
+ mCallbackProxy.onSearchboxDispatchCompleteCallback(function, id, successful);
+ }
+
+ public void handleDispatchCompleteCallback(String function, int id, boolean successful) {
+ if (id != 0) {
+ SearchBoxListener listener;
+ synchronized(this) {
+ listener = mEventCallbacks.get(id);
+ mEventCallbacks.remove(id);
+ }
+ if (listener != null) {
+ if (TextUtils.equals(EVENT_CHANGE, function)) {
+ listener.onChangeComplete(successful);
+ } else if (TextUtils.equals(EVENT_SUBMIT, function)) {
+ listener.onSubmitComplete(successful);
+ } else if (TextUtils.equals(EVENT_RESIZE, function)) {
+ listener.onResizeComplete(successful);
+ } else if (TextUtils.equals(EVENT_CANCEL, function)) {
+ listener.onCancelComplete(successful);
+ }
+ }
+ }
+ }
+
// This is used as a hackish alternative to javascript escaping.
// There appears to be no such functionality in the core framework.
- private String jsonSerialize(String query) {
+ private static String jsonSerialize(String query) {
JSONStringer stringer = new JSONStringer();
try {
stringer.array().value(query).endArray();
diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java
index c652e55..5414b79 100644
--- a/core/java/android/webkit/WebViewCore.java
+++ b/core/java/android/webkit/WebViewCore.java
@@ -248,7 +248,7 @@
/* Get the BrowserFrame component. This is used for subwindow creation and
* is called only from BrowserFrame in the WebCore thread. */
- /* package */ BrowserFrame getBrowserFrame() {
+ /* package */ synchronized BrowserFrame getBrowserFrame() {
return mBrowserFrame;
}
diff --git a/core/java/android/widget/GridLayout.java b/core/java/android/widget/GridLayout.java
index c2759e5..b9eb5ff 100644
--- a/core/java/android/widget/GridLayout.java
+++ b/core/java/android/widget/GridLayout.java
@@ -53,12 +53,12 @@
* container and grid index {@code N} is fixed to its trailing edge
* (after padding is taken into account).
*
- * <h4>Row and Column Groups</h4>
+ * <h4>Row and Column Specs</h4>
*
* Children occupy one or more contiguous cells, as defined
- * by their {@link GridLayout.LayoutParams#rowGroup rowGroup} and
- * {@link GridLayout.LayoutParams#columnGroup columnGroup} layout parameters.
- * Each group specifies the set of rows or columns that are to be
+ * by their {@link GridLayout.LayoutParams#rowSpec rowSpec} and
+ * {@link GridLayout.LayoutParams#columnSpec columnSpec} layout parameters.
+ * Each spec defines the set of rows or columns that are to be
* occupied; and how children should be aligned within the resulting group of cells.
* Although cells do not normally overlap in a GridLayout, GridLayout does
* not prevent children being defined to occupy the same cell or group of cells.
@@ -92,7 +92,7 @@
*
* <h4>Excess Space Distribution</h4>
*
- * A child's ability to stretch is controlled using the {@link Group#flexibility flexibility}
+ * A child's ability to stretch is controlled using the flexibility
* properties of its row and column groups.
* <p>
* <p>
@@ -167,8 +167,7 @@
// Misc constants
private static final String TAG = GridLayout.class.getName();
- private static final boolean DEBUG = false;
- private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;
+ static final boolean DEBUG = false;
private static final int PRF = 1;
// Defaults
@@ -178,8 +177,9 @@
private static final boolean DEFAULT_USE_DEFAULT_MARGINS = false;
private static final boolean DEFAULT_ORDER_PRESERVED = false;
private static final int DEFAULT_ALIGNMENT_MODE = ALIGN_MARGINS;
- // todo remove this
- private static final int DEFAULT_CONTAINER_MARGIN = 20;
+ private static final int DEFAULT_CONTAINER_MARGIN = 0;
+ private static final int DEFAULT_MARGIN = 8;
+ private static final int DEFAULT_CONTAINER_PADDING = 16;
private static final int MAX_SIZE = 100000;
// TypedArray indices
@@ -278,12 +278,12 @@
/**
* Returns the current number of rows. This is either the last value that was set
* with {@link #setRowCount(int)} or, if no such value was set, the maximum
- * value of each the upper bounds defined in {@link LayoutParams#rowGroup}.
+ * value of each the upper bounds defined in {@link LayoutParams#rowSpec}.
*
* @return the current number of rows
*
* @see #setRowCount(int)
- * @see LayoutParams#rowGroup
+ * @see LayoutParams#rowSpec
*
* @attr ref android.R.styleable#GridLayout_rowCount
*/
@@ -299,7 +299,7 @@
* @param rowCount the number of rows
*
* @see #getRowCount()
- * @see LayoutParams#rowGroup
+ * @see LayoutParams#rowSpec
*
* @attr ref android.R.styleable#GridLayout_rowCount
*/
@@ -310,12 +310,12 @@
/**
* Returns the current number of columns. This is either the last value that was set
* with {@link #setColumnCount(int)} or, if no such value was set, the maximum
- * value of each the upper bounds defined in {@link LayoutParams#columnGroup}.
+ * value of each the upper bounds defined in {@link LayoutParams#columnSpec}.
*
* @return the current number of columns
*
* @see #setColumnCount(int)
- * @see LayoutParams#columnGroup
+ * @see LayoutParams#columnSpec
*
* @attr ref android.R.styleable#GridLayout_columnCount
*/
@@ -331,7 +331,7 @@
* @param columnCount the number of columns.
*
* @see #getColumnCount()
- * @see LayoutParams#columnGroup
+ * @see LayoutParams#columnSpec
*
* @attr ref android.R.styleable#GridLayout_columnCount
*/
@@ -381,6 +381,10 @@
*/
public void setUseDefaultMargins(boolean useDefaultMargins) {
mUseDefaultMargins = useDefaultMargins;
+ if (useDefaultMargins) {
+ int padding = DEFAULT_CONTAINER_PADDING;
+ setPadding(padding, padding, padding, padding);
+ }
requestLayout();
}
@@ -518,6 +522,14 @@
return result;
}
+ private static int sum(int[] a) {
+ int result = 0;
+ for (int i = 0, N = a.length; i < N; i++) {
+ result += a[i];
+ }
+ return result;
+ }
+
private static <T> T[] append(T[] a, T[] b) {
T[] result = (T[]) Array.newInstance(a.getClass().getComponentType(), a.length + b.length);
System.arraycopy(a, 0, result, 0, a.length);
@@ -526,16 +538,10 @@
}
private int getDefaultMargin(View c, boolean horizontal, boolean leading) {
- // In the absence of any other information, calculate a default gap such
- // that, in a grid of identical components, the heights and the vertical
- // gaps are in the proportion of the golden ratio.
- // To effect this with equal margins at each edge, set each of the
- // four margin values to half this amount.
- return (int) (c.getMeasuredHeight() / GOLDEN_RATIO / 2);
+ return DEFAULT_MARGIN;
}
private int getDefaultMargin(View c, boolean isAtEdge, boolean horizontal, boolean leading) {
- // todo remove DEFAULT_CONTAINER_MARGIN. Use padding? Seek advice on Themes/Styles, etc.
return isAtEdge ? DEFAULT_CONTAINER_MARGIN : getDefaultMargin(c, horizontal, leading);
}
@@ -543,9 +549,9 @@
if (!mUseDefaultMargins) {
return 0;
}
- Group group = horizontal ? p.columnGroup : p.rowGroup;
+ Spec spec = horizontal ? p.columnSpec : p.rowSpec;
Axis axis = horizontal ? mHorizontalAxis : mVerticalAxis;
- Interval span = group.span;
+ Interval span = spec.span;
boolean isAtEdge = leading ? (span.min == 0) : (span.max == axis.getCount());
return getDefaultMargin(c, isAtEdge, horizontal, leading);
@@ -593,12 +599,12 @@
if (isGone(c)) continue;
LayoutParams lp = getLayoutParams1(c);
- final Group colGroup = lp.columnGroup;
- final Interval cols = colGroup.span;
+ final Spec colSpec = lp.columnSpec;
+ final Interval cols = colSpec.span;
final int colSpan = cols.size();
- final Group rowGroup = lp.rowGroup;
- final Interval rows = rowGroup.span;
+ final Spec rowSpec = lp.rowSpec;
+ final Interval rows = rowSpec.span;
final int rowSpan = rows.size();
if (horizontal) {
@@ -623,8 +629,8 @@
maxSize = max(maxSize, colSpan);
}
- lp.setColumnGroupSpan(new Interval(col, col + colSpan));
- lp.setRowGroupSpan(new Interval(row, row + rowSpan));
+ lp.setColumnSpecSpan(new Interval(col, col + colSpan));
+ lp.setRowSpecSpan(new Interval(row, row + rowSpan));
if (horizontal) {
col = col + colSpan;
@@ -737,7 +743,7 @@
}
// Draw margins
- paint.setColor(Color.YELLOW);
+ paint.setColor(Color.MAGENTA);
for (int i = 0; i < getChildCount(); i++) {
View c = getChildAt(i);
drawRectangle(canvas,
@@ -872,11 +878,11 @@
View c = getChildAt(i);
if (isGone(c)) continue;
LayoutParams lp = getLayoutParams(c);
- Group columnGroup = lp.columnGroup;
- Group rowGroup = lp.rowGroup;
+ Spec columnSpec = lp.columnSpec;
+ Spec rowSpec = lp.rowSpec;
- Interval colSpan = columnGroup.span;
- Interval rowSpan = rowGroup.span;
+ Interval colSpan = columnSpec.span;
+ Interval rowSpan = rowSpec.span;
int x1 = mHorizontalAxis.getLocationIncludingMargin(true, colSpan.min);
int y1 = mVerticalAxis.getLocationIncludingMargin(true, rowSpan.min);
@@ -890,8 +896,8 @@
int pWidth = getMeasurement(c, true);
int pHeight = getMeasurement(c, false);
- Alignment hAlign = columnGroup.alignment;
- Alignment vAlign = rowGroup.alignment;
+ Alignment hAlign = columnSpec.alignment;
+ Alignment vAlign = rowSpec.alignment;
int dx, dy;
@@ -961,7 +967,7 @@
public boolean countValid = false;
public boolean countWasExplicitySet = false;
- PackedMap<Group, Bounds> groupBounds;
+ PackedMap<Spec, Bounds> groupBounds;
public boolean groupBoundsValid = false;
PackedMap<Interval, MutableInt> forwardLinks;
@@ -998,9 +1004,9 @@
View c = getChildAt(i);
if (isGone(c)) continue;
LayoutParams params = getLayoutParams(c);
- Group g = horizontal ? params.columnGroup : params.rowGroup;
- count = max(count, g.span.min);
- count = max(count, g.span.max);
+ Spec spec = horizontal ? params.columnSpec : params.rowSpec;
+ count = max(count, spec.span.min);
+ count = max(count, spec.span.max);
}
return count == -1 ? UNDEFINED : count;
}
@@ -1027,17 +1033,17 @@
invalidateStructure();
}
- private PackedMap<Group, Bounds> createGroupBounds() {
- Assoc<Group, Bounds> assoc = Assoc.of(Group.class, Bounds.class);
+ private PackedMap<Spec, Bounds> createGroupBounds() {
+ Assoc<Spec, Bounds> assoc = Assoc.of(Spec.class, Bounds.class);
for (int i = 0, N = getChildCount(); i < N; i++) {
View c = getChildAt(i);
if (isGone(c)) {
- assoc.put(Group.GONE, Bounds.GONE);
+ assoc.put(Spec.GONE, Bounds.GONE);
} else {
LayoutParams lp = getLayoutParams(c);
- Group group = horizontal ? lp.columnGroup : lp.rowGroup;
- Bounds bounds = group.alignment.getBounds();
- assoc.put(group, bounds);
+ Spec spec = horizontal ? lp.columnSpec : lp.rowSpec;
+ Bounds bounds = spec.alignment.getBounds();
+ assoc.put(spec, bounds);
}
}
return assoc.pack();
@@ -1052,12 +1058,12 @@
View c = getChildAt(i);
if (isGone(c)) continue;
LayoutParams lp = getLayoutParams(c);
- Group g = horizontal ? lp.columnGroup : lp.rowGroup;
- groupBounds.getValue(i).include(c, g, GridLayout.this, this);
+ Spec spec = horizontal ? lp.columnSpec : lp.rowSpec;
+ groupBounds.getValue(i).include(c, spec, GridLayout.this, this);
}
}
- private PackedMap<Group, Bounds> getGroupBounds() {
+ private PackedMap<Spec, Bounds> getGroupBounds() {
if (groupBounds == null) {
groupBounds = createGroupBounds();
}
@@ -1071,7 +1077,7 @@
// Add values computed by alignment - taking the max of all alignments in each span
private PackedMap<Interval, MutableInt> createLinks(boolean min) {
Assoc<Interval, MutableInt> result = Assoc.of(Interval.class, MutableInt.class);
- Group[] keys = getGroupBounds().keys;
+ Spec[] keys = getGroupBounds().keys;
for (int i = 0, N = keys.length; i < N; i++) {
Interval span = min ? keys[i].span : keys[i].span.inverse();
result.put(span, new MutableInt());
@@ -1092,8 +1098,7 @@
MutableInt valueHolder = links.getValue(i);
if (min) {
valueHolder.value = max(valueHolder.value, size);
- }
- else {
+ } else {
valueHolder.value = -max(-valueHolder.value, size);
}
}
@@ -1236,8 +1241,8 @@
View c = getChildAt(i);
if (isGone(c)) continue;
LayoutParams lp = getLayoutParams(c);
- Group g = horizontal ? lp.columnGroup : lp.rowGroup;
- Interval span = g.span;
+ Spec spec = horizontal ? lp.columnSpec : lp.rowSpec;
+ Interval span = spec.span;
leadingEdgeCount[span.min]++;
trailingEdgeCount[span.max]++;
}
@@ -1436,8 +1441,8 @@
View c = getChildAt(i);
if (isGone(c)) continue;
LayoutParams lp = getLayoutParams(c);
- Group g = horizontal ? lp.columnGroup : lp.rowGroup;
- Interval span = g.span;
+ Spec spec = horizontal ? lp.columnSpec : lp.rowSpec;
+ Interval span = spec.span;
int index = leading ? span.min : span.max;
margins[index] = max(margins[index], getMargin(c, horizontal, leading));
}
@@ -1514,6 +1519,12 @@
}
private void setParentConstraints(int min, int max) {
+ if (mAlignmentMode != ALIGN_MARGINS) {
+ int margins = sum(getLeadingMargins()) + sum(getTrailingMargins());
+ min -= margins;
+ max -= margins;
+ }
+
parentMin.value = min;
parentMax.value = -max;
locationsValid = false;
@@ -1529,7 +1540,7 @@
int size = MeasureSpec.getSize(measureSpec);
switch (mode) {
case MeasureSpec.UNSPECIFIED: {
- return getMeasure(0, MAX_SIZE);
+ return getMeasure(0, MAX_SIZE);
}
case MeasureSpec.EXACTLY: {
return getMeasure(size, size);
@@ -1584,14 +1595,14 @@
* GridLayout supports both row and column spanning and arbitrary forms of alignment within
* each cell group. The fundamental parameters associated with each cell group are
* gathered into their vertical and horizontal components and stored
- * in the {@link #rowGroup} and {@link #columnGroup} layout parameters.
- * {@link Group Groups} are immutable structures and may be shared between the layout
+ * in the {@link #rowSpec} and {@link #columnSpec} layout parameters.
+ * {@link android.widget.GridLayout.Spec Specs} are immutable structures and may be shared between the layout
* parameters of different children.
* <p>
- * The row and column groups contain the leading and trailing indices along each axis
+ * The row and column specs contain the leading and trailing indices along each axis
* and together specify the four grid indices that delimit the cells of this cell group.
* <p>
- * The {@link Group#alignment alignment} fields of the row and column groups together specify
+ * The alignment properties of the row and column specs together specify
* both aspects of alignment within the cell group. It is also possible to specify a child's
* alignment within its cell group by using the {@link GridLayout.LayoutParams#setGravity(int)}
* method.
@@ -1620,10 +1631,10 @@
* {@link GridLayout#setUseDefaultMargins(boolean) useDefaultMargins} is
* {@code false}; otherwise {@link #UNDEFINED}, to
* indicate that a default value should be computed on demand. </li>
- * <li>{@link #rowGroup}{@code .span} = {@code [0, 1]} </li>
- * <li>{@link #rowGroup}{@code .alignment} = {@link #BASELINE} </li>
- * <li>{@link #columnGroup}{@code .span} = {@code [0, 1]} </li>
- * <li>{@link #columnGroup}{@code .alignment} = {@link #LEFT} </li>
+ * <li>{@link #rowSpec}{@code .span} = {@code [0, 1]} </li>
+ * <li>{@link #rowSpec}{@code .alignment} = {@link #BASELINE} </li>
+ * <li>{@link #columnSpec}{@code .span} = {@code [0, 1]} </li>
+ * <li>{@link #columnSpec}{@code .alignment} = {@link #LEFT} </li>
* </ul>
*
* @attr ref android.R.styleable#GridLayout_Layout_layout_row
@@ -1678,48 +1689,48 @@
// Instance variables
/**
- * The group that specifies the vertical characteristics of the cell group
+ * The spec that specifies the vertical characteristics of the cell group
* described by these layout parameters.
*/
- public Group rowGroup;
+ public Spec rowSpec;
/**
- * The group that specifies the horizontal characteristics of the cell group
+ * The spec that specifies the horizontal characteristics of the cell group
* described by these layout parameters.
*/
- public Group columnGroup;
+ public Spec columnSpec;
// Constructors
private LayoutParams(
int width, int height,
int left, int top, int right, int bottom,
- Group rowGroup, Group columnGroup) {
+ Spec rowSpec, Spec columnSpec) {
super(width, height);
setMargins(left, top, right, bottom);
- this.rowGroup = rowGroup;
- this.columnGroup = columnGroup;
+ this.rowSpec = rowSpec;
+ this.columnSpec = columnSpec;
}
/**
- * Constructs a new LayoutParams instance for this <code>rowGroup</code>
- * and <code>columnGroup</code>. All other fields are initialized with
+ * Constructs a new LayoutParams instance for this <code>rowSpec</code>
+ * and <code>columnSpec</code>. All other fields are initialized with
* default values as defined in {@link LayoutParams}.
*
- * @param rowGroup the rowGroup
- * @param columnGroup the columnGroup
+ * @param rowSpec the rowSpec
+ * @param columnSpec the columnSpec
*/
- public LayoutParams(Group rowGroup, Group columnGroup) {
+ public LayoutParams(Spec rowSpec, Spec columnSpec) {
this(DEFAULT_WIDTH, DEFAULT_HEIGHT,
DEFAULT_MARGIN, DEFAULT_MARGIN, DEFAULT_MARGIN, DEFAULT_MARGIN,
- rowGroup, columnGroup);
+ rowSpec, columnSpec);
}
/**
* Constructs a new LayoutParams with default values as defined in {@link LayoutParams}.
*/
public LayoutParams() {
- this(new Group(DEFAULT_SPAN, DEFAULT_ROW_ALIGNMENT),
- new Group(DEFAULT_SPAN, DEFAULT_COLUMN_ALIGNMENT));
+ this(new Spec(DEFAULT_SPAN, DEFAULT_ROW_ALIGNMENT, Spec.DEFAULT_FLEXIBILITY),
+ new Spec(DEFAULT_SPAN, DEFAULT_COLUMN_ALIGNMENT, Spec.DEFAULT_FLEXIBILITY));
}
// Copying constructors
@@ -1743,8 +1754,8 @@
*/
public LayoutParams(LayoutParams that) {
super(that);
- this.columnGroup = new Group(that.columnGroup);
- this.rowGroup = new Group(that.rowGroup);
+ this.columnSpec = new Spec(that.columnSpec);
+ this.rowSpec = new Spec(that.rowSpec);
}
// AttributeSet constructors
@@ -1836,14 +1847,14 @@
int column = a.getInt(COLUMN, DEFAULT_COLUMN);
int columnSpan = a.getInt(COLUMN_SPAN, DEFAULT_SPAN_SIZE);
Interval hSpan = new Interval(column, column + columnSpan);
- int hFlexibility = a.getInt(COLUMN_FLEXIBILITY, Group.DEFAULT_FLEXIBILITY);
- this.columnGroup = new Group(hSpan, getColAlignment(gravity, width), hFlexibility);
+ int hFlexibility = a.getInt(COLUMN_FLEXIBILITY, Spec.DEFAULT_FLEXIBILITY);
+ this.columnSpec = new Spec(hSpan, getColAlignment(gravity, width), hFlexibility);
int row = a.getInt(ROW, DEFAULT_ROW);
int rowSpan = a.getInt(ROW_SPAN, DEFAULT_SPAN_SIZE);
Interval vSpan = new Interval(row, row + rowSpan);
- int vFlexibility = a.getInt(ROW_FLEXIBILITY, Group.DEFAULT_FLEXIBILITY);
- this.rowGroup = new Group(vSpan, getRowAlignment(gravity, height), vFlexibility);
+ int vFlexibility = a.getInt(ROW_FLEXIBILITY, Spec.DEFAULT_FLEXIBILITY);
+ this.rowSpec = new Spec(vSpan, getRowAlignment(gravity, height), vFlexibility);
} finally {
a.recycle();
}
@@ -1858,8 +1869,8 @@
* @attr ref android.R.styleable#GridLayout_Layout_layout_gravity
*/
public void setGravity(int gravity) {
- columnGroup = columnGroup.copyWriteAlignment(getColAlignment(gravity, width));
- rowGroup = rowGroup.copyWriteAlignment(getRowAlignment(gravity, height));
+ columnSpec = columnSpec.copyWriteAlignment(getColAlignment(gravity, width));
+ rowSpec = rowSpec.copyWriteAlignment(getRowAlignment(gravity, height));
}
@Override
@@ -1868,12 +1879,12 @@
this.height = attributes.getLayoutDimension(heightAttr, DEFAULT_HEIGHT);
}
- private void setRowGroupSpan(Interval span) {
- rowGroup = rowGroup.copyWriteSpan(span);
+ private void setRowSpecSpan(Interval span) {
+ rowSpec = rowSpec.copyWriteSpan(span);
}
- private void setColumnGroupSpan(Interval span) {
- columnGroup = columnGroup.copyWriteSpan(span);
+ private void setColumnSpecSpan(Interval span) {
+ columnSpec = columnSpec.copyWriteSpan(span);
}
}
@@ -2019,14 +2030,14 @@
}
/*
- For each Group (with a given alignment) we need to store the amount of space required
+ For each group (with a given alignment) we need to store the amount of space required
before the alignment point and the amount of space required after it. One side of this
calculation is always 0 for LEADING and TRAILING alignments but we don't make use of this.
For CENTER and BASELINE alignments both sides are needed and in the BASELINE case no
simple optimisations are possible.
The general algorithm therefore is to create a Map (actually a PackedMap) from
- Group to Bounds and to loop through all Views in the group taking the maximum
+ group to Bounds and to loop through all Views in the group taking the maximum
of the values for each View.
*/
private static class Bounds {
@@ -2067,11 +2078,11 @@
return before - alignment.getAlignmentValue(c, size);
}
- protected void include(View c, Group group, GridLayout gridLayout, Axis axis) {
- this.flexibility &= group.flexibility;
+ protected void include(View c, Spec spec, GridLayout gridLayout, Axis axis) {
+ this.flexibility &= spec.flexibility;
int size = gridLayout.getMeasurementIncludingMargin(c, axis.horizontal);
// todo test this works correctly when the returned value is UNDEFINED
- int before = group.alignment.getAlignmentValue(c, size);
+ int before = spec.alignment.getAlignmentValue(c, size);
include(before, size - before);
}
@@ -2176,16 +2187,13 @@
}
/**
- * A group specifies either the horizontal or vertical characteristics of a group of
+ * A spec defines either the horizontal or vertical characteristics of a group of
* cells.
- * <p>
- * Groups are immutable and so may be shared between views with the same
- * {@code span} and {@code alignment}.
*/
- public static class Group {
+ public static class Spec {
private static final int DEFAULT_FLEXIBILITY = UNDEFINED_FLEXIBILITY;
- private static final Group GONE = new Group(Interval.GONE, Alignment.GONE);
+ private static final Spec GONE = new Spec(Interval.GONE, Alignment.GONE);
/**
* The grid indices of the leading and trailing edges of this cell group for the
@@ -2200,7 +2208,7 @@
* For row groups, this specifies the vertical alignment.
* For column groups, this specifies the horizontal alignment.
*/
- public final Alignment alignment;
+ final Alignment alignment;
/**
* The flexibility field tells GridLayout how to derive minimum and maximum size
@@ -2212,82 +2220,48 @@
*
* @see GridLayout#CAN_STRETCH
*/
- public int flexibility = DEFAULT_FLEXIBILITY;
+ final int flexibility;
- /**
- * Construct a new Group, {@code group}, where:
- * <ul>
- * <li> {@code group.span = span} </li>
- * <li> {@code group.alignment = alignment} </li>
- * </ul>
- *
- * @param span the span
- * @param alignment the alignment
- */
- private Group(Interval span, Alignment alignment) {
- this.span = span;
- this.alignment = alignment;
- }
-
- private Group(Interval span, Alignment alignment, int flexibility) {
+ private Spec(Interval span, Alignment alignment, int flexibility) {
this.span = span;
this.alignment = alignment;
this.flexibility = flexibility;
}
+ private Spec(Interval span, Alignment alignment) {
+ this(span, alignment, DEFAULT_FLEXIBILITY);
+ }
+
/* Copying constructor */
- private Group(Group that) {
- this.span = that.span;
- this.alignment = that.alignment;
- this.flexibility = that.flexibility;
+ private Spec(Spec that) {
+ this(that.span, that.alignment, that.flexibility);
+ }
+
+ Spec(int start, int size, Alignment alignment, int flexibility) {
+ this(new Interval(start, start + size), alignment, flexibility);
+ }
+
+ private Spec copyWriteSpan(Interval span) {
+ return new Spec(span, alignment, flexibility);
+ }
+
+ private Spec copyWriteAlignment(Alignment alignment) {
+ return new Spec(span, alignment, flexibility);
+ }
+
+ private Spec copyWriteFlexibility(int flexibility) {
+ return new Spec(span, alignment, flexibility);
}
/**
- * Construct a new Group, {@code group}, where:
- * <ul>
- * <li> {@code group.span = [start, start + size]} </li>
- * <li> {@code group.alignment = alignment} </li>
- * </ul>
- *
- * @param start the start
- * @param size the size
- * @param alignment the alignment
- */
- public Group(int start, int size, Alignment alignment) {
- this(new Interval(start, start + size), alignment);
- }
-
- /**
- * Construct a new Group, {@code group}, where:
- * <ul>
- * <li> {@code group.span = [start, start + 1]} </li>
- * <li> {@code group.alignment = alignment} </li>
- * </ul>
- *
- * @param start the start index
- * @param alignment the alignment
- */
- public Group(int start, Alignment alignment) {
- this(start, 1, alignment);
- }
-
- private Group copyWriteSpan(Interval span) {
- return new Group(span, alignment, flexibility);
- }
-
- private Group copyWriteAlignment(Alignment alignment) {
- return new Group(span, alignment, flexibility);
- }
-
- /**
- * Returns {@code true} if the {@link #getClass class}, {@link #alignment} and {@code span}
- * properties of this Group and the supplied parameter are pairwise equal,
+ * Returns {@code true} if the {@code class}, {@code alignment} and {@code span}
+ * properties of this Spec and the supplied parameter are pairwise equal,
* {@code false} otherwise.
*
- * @param that the object to compare this group with
+ * @param that the object to compare this spec with
*
* @return {@code true} if the specified object is equal to this
- * {@code Group}; {@code false} otherwise
+ * {@code Spec}; {@code false} otherwise
*/
@Override
public boolean equals(Object that) {
@@ -2298,12 +2272,12 @@
return false;
}
- Group group = (Group) that;
+ Spec spec = (Spec) that;
- if (!alignment.equals(group.alignment)) {
+ if (!alignment.equals(spec.alignment)) {
return false;
}
- if (!span.equals(group.span)) {
+ if (!span.equals(spec.span)) {
return false;
}
@@ -2319,12 +2293,93 @@
}
/**
+ * Temporary backward compatibility class for Launcher - to avoid
+ * dependent multi-project commit. This class will be deleted after
+ * AppsCustomizePagedView is updated to new API.
+ *
+ * @hide
+ */
+ @Deprecated
+ public static class Group extends Spec {
+ /**
+ * @deprecated Please replace with {@link #spec(int, int, Alignment)}
+ * @hide
+ */
+ @Deprecated
+ public Group(int start, int size, Alignment alignment) {
+ super(start, size, alignment, UNDEFINED_FLEXIBILITY);
+ }
+ }
+
+ /**
+ * Return a Spec, {@code spec}, where:
+ * <ul>
+ * <li> {@code spec.span = [start, start + size]} </li>
+ * <li> {@code spec.alignment = alignment} </li>
+ * <li> {@code spec.flexibility = flexibility} </li>
+ * </ul>
+ *
+ * @param start the start
+ * @param size the size
+ * @param alignment the alignment
+ * @param flexibility the flexibility
+ */
+ public static Spec spec(int start, int size, Alignment alignment, int flexibility) {
+ return new Spec(start, size, alignment, flexibility);
+ }
+
+ /**
+ * Return a Spec, {@code spec}, where:
+ * <ul>
+ * <li> {@code spec.span = [start, start + 1]} </li>
+ * <li> {@code spec.alignment = alignment} </li>
+ * <li> {@code spec.flexibility = flexibility} </li>
+ * </ul>
+ *
+ * @param start the start
+ * @param alignment the alignment
+ * @param flexibility the flexibility
+ */
+ public static Spec spec(int start, Alignment alignment, int flexibility) {
+ return spec(start, 1, alignment, flexibility);
+ }
+
+ /**
+ * Return a Spec, {@code spec}, where:
+ * <ul>
+ * <li> {@code spec.span = [start, start + size]} </li>
+ * <li> {@code spec.alignment = alignment} </li>
+ * </ul>
+ *
+ * @param start the start
+ * @param size the size
+ * @param alignment the alignment
+ */
+ public static Spec spec(int start, int size, Alignment alignment) {
+ return spec(start, size, alignment, Spec.DEFAULT_FLEXIBILITY);
+ }
+
+ /**
+ * Return a Spec, {@code spec}, where:
+ * <ul>
+ * <li> {@code spec.span = [start, start + 1]} </li>
+ * <li> {@code spec.alignment = alignment} </li>
+ * </ul>
+ *
+ * @param start the start index
+ * @param alignment the alignment
+ */
+ public static Spec spec(int start, Alignment alignment) {
+ return spec(start, 1, alignment);
+ }
+
+ /**
* Alignments specify where a view should be placed within a cell group and
* what size it should be.
* <p>
- * The {@link LayoutParams} class contains a {@link LayoutParams#rowGroup rowGroup}
- * and a {@link LayoutParams#columnGroup columnGroup} each of which contains an
- * {@link Group#alignment alignment}. Overall placement of the view in the cell
+ * The {@link LayoutParams} class contains a {@link LayoutParams#rowSpec rowSpec}
+ * and a {@link LayoutParams#columnSpec columnSpec} each of which contains an
+ * {@code alignment}. Overall placement of the view in the cell
* group is specified by the two alignments which act along each axis independently.
* <p>
* The GridLayout class defines the most common alignments used in general layout:
@@ -2425,8 +2480,8 @@
/**
* Indicates that a view should be <em>centered</em> with the other views in its cell group.
- * This constant may be used in both {@link LayoutParams#rowGroup rowGroups} and {@link
- * LayoutParams#columnGroup columnGroups}.
+ * This constant may be used in both {@link LayoutParams#rowSpec rowSpecs} and {@link
+ * LayoutParams#columnSpec columnSpecs}.
*/
public static final Alignment CENTER = new Alignment() {
public int getAlignmentValue(View view, int viewSize) {
@@ -2437,7 +2492,7 @@
/**
* Indicates that a view should be aligned with the <em>baselines</em>
* of the other views in its cell group.
- * This constant may only be used as an alignment in {@link LayoutParams#rowGroup rowGroups}.
+ * This constant may only be used as an alignment in {@link LayoutParams#rowSpec rowSpecs}.
*
* @see View#getBaseline()
*/
@@ -2488,8 +2543,8 @@
/**
* Indicates that a view should expanded to fit the boundaries of its cell group.
- * This constant may be used in both {@link LayoutParams#rowGroup rowGroups} and
- * {@link LayoutParams#columnGroup columnGroups}.
+ * This constant may be used in both {@link LayoutParams#rowSpec rowSpecs} and
+ * {@link LayoutParams#columnSpec columnSpecs}.
*/
public static final Alignment FILL = new Alignment() {
public int getAlignmentValue(View view, int viewSize) {
@@ -2513,42 +2568,30 @@
/**
* Indicates that a view requests precisely the size specified by its layout parameters.
*
- * @see Group#flexibility
- *
- * @hide
+ * @see Spec#flexibility
*/
- public static final int FIXED = 0;
+ private static final int NONE = 0;
/**
* Indicates that a view's size should lie between its minimum and the size specified by
* its layout parameters.
*
- * @see Group#flexibility
- *
- * @hide
+ * @see Spec#flexibility
*/
- public static final int CAN_SHRINK = 1;
+ private static final int CAN_SHRINK = 1;
/**
* Indicates that a view's size should be greater than or equal to the size specified by
* its layout parameters.
*
- * @see Group#flexibility
+ * @see Spec#flexibility
*/
public static final int CAN_STRETCH = 2;
/**
- * Indicates that a view will ignore its measurement, and can take any size that is greater
- * than its minimum.
- *
- * @see Group#flexibility
- */
- private static final int CAN_SHRINK_OR_STRETCH = CAN_SHRINK | CAN_STRETCH;
-
- /**
* A default value for flexibility.
*
- * @see Group#flexibility
+ * @see Spec#flexibility
*/
private static final int UNDEFINED_FLEXIBILITY = UNDEFINED | CAN_SHRINK | CAN_STRETCH;
diff --git a/core/java/android/widget/RemoteViewsAdapter.java b/core/java/android/widget/RemoteViewsAdapter.java
index 4c47d37..867ebb4 100644
--- a/core/java/android/widget/RemoteViewsAdapter.java
+++ b/core/java/android/widget/RemoteViewsAdapter.java
@@ -53,6 +53,10 @@
// This ensures that we don't stay continually bound to the service and that it can be destroyed
// if we need the memory elsewhere in the system.
private static final int sUnbindServiceDelay = 5000;
+
+ // Default height for the default loading view, in case we cannot get inflate the first view
+ private static final int sDefaultLoadingViewHeight = 50;
+
// Type defs for controlling different messages across the main and worker message queues
private static final int sDefaultMessageType = 0;
private static final int sUnbindServiceMessageType = 1;
@@ -386,21 +390,39 @@
// Create a new loading view
synchronized (mCache) {
+ boolean customLoadingViewAvailable = false;
+
if (mUserLoadingView != null) {
- // A user-specified loading view
- View loadingView = mUserLoadingView.apply(parent.getContext(), parent);
- loadingView.setTagInternal(com.android.internal.R.id.rowTypeId, new Integer(0));
- layout.addView(loadingView);
- } else {
+ // Try to inflate user-specified loading view
+ try {
+ View loadingView = mUserLoadingView.apply(parent.getContext(), parent);
+ loadingView.setTagInternal(com.android.internal.R.id.rowTypeId,
+ new Integer(0));
+ layout.addView(loadingView);
+ customLoadingViewAvailable = true;
+ } catch (Exception e) {
+ Log.w(TAG, "Error inflating custom loading view, using default loading" +
+ "view instead", e);
+ }
+ }
+ if (!customLoadingViewAvailable) {
// A default loading view
// Use the size of the first row as a guide for the size of the loading view
if (mFirstViewHeight < 0) {
- View firstView = mFirstView.apply(parent.getContext(), parent);
- firstView.measure(
- MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
- MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
- mFirstViewHeight = firstView.getMeasuredHeight();
- mFirstView = null;
+ try {
+ View firstView = mFirstView.apply(parent.getContext(), parent);
+ firstView.measure(
+ MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
+ MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
+ mFirstViewHeight = firstView.getMeasuredHeight();
+ mFirstView = null;
+ } catch (Exception e) {
+ float density = mContext.getResources().getDisplayMetrics().density;
+ mFirstViewHeight = (int)
+ Math.round(sDefaultLoadingViewHeight * density);
+ mFirstView = null;
+ Log.w(TAG, "Error inflating first RemoteViews" + e);
+ }
}
// Compose the loading view text
@@ -937,24 +959,40 @@
indexMetaData.isRequested = true;
int typeId = indexMetaData.typeId;
- // Reuse the convert view where possible
- if (layout != null) {
- if (convertViewTypeId == typeId) {
- rv.reapply(context, convertViewChild);
- return layout;
+ try {
+ // Reuse the convert view where possible
+ if (layout != null) {
+ if (convertViewTypeId == typeId) {
+ rv.reapply(context, convertViewChild);
+ return layout;
+ }
+ layout.removeAllViews();
+ } else {
+ layout = new RemoteViewsFrameLayout(context);
}
- layout.removeAllViews();
- } else {
- layout = new RemoteViewsFrameLayout(context);
+
+ // Otherwise, create a new view to be returned
+ View newView = rv.apply(context, parent);
+ newView.setTagInternal(com.android.internal.R.id.rowTypeId,
+ new Integer(typeId));
+ layout.addView(newView);
+ return layout;
+
+ } catch (Exception e){
+ // We have to make sure that we successfully inflated the RemoteViews, if not
+ // we return the loading view instead.
+ Log.w(TAG, "Error inflating RemoteViews at position: " + position + ", using" +
+ "loading view instead" + e);
+
+ RemoteViewsFrameLayout loadingView = null;
+ final RemoteViewsMetaData metaData = mCache.getMetaData();
+ synchronized (metaData) {
+ loadingView = metaData.createLoadingView(position, convertView, parent);
+ }
+ return loadingView;
+ } finally {
+ if (hasNewItems) loadNextIndexInBackground();
}
-
- // Otherwise, create a new view to be returned
- View newView = rv.apply(context, parent);
- newView.setTagInternal(com.android.internal.R.id.rowTypeId, new Integer(typeId));
- layout.addView(newView);
- if (hasNewItems) loadNextIndexInBackground();
-
- return layout;
} else {
// If the cache does not have the RemoteViews at this position, then create a
// loading view and queue the actual position to be loaded in the background
diff --git a/core/java/com/android/internal/app/ActionBarImpl.java b/core/java/com/android/internal/app/ActionBarImpl.java
index 519acf5..243c605 100644
--- a/core/java/com/android/internal/app/ActionBarImpl.java
+++ b/core/java/com/android/internal/app/ActionBarImpl.java
@@ -36,6 +36,7 @@
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
+import android.os.Build;
import android.os.Handler;
import android.view.ActionMode;
import android.view.LayoutInflater;
@@ -155,6 +156,13 @@
CONTEXT_DISPLAY_SPLIT : CONTEXT_DISPLAY_NORMAL;
mContentHeight = mActionView.getContentHeight();
+
+ // Older apps get the home button interaction enabled by default.
+ // Newer apps need to enable it explicitly.
+ if (mContext.getApplicationInfo().targetSdkVersion <
+ Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
+ setHomeButtonEnabled(true);
+ }
}
public void onConfigurationChanged(Configuration newConfig) {
@@ -266,8 +274,8 @@
}
@Override
- public void setDisplayDisableHomeEnabled(boolean disableHome) {
- setDisplayOptions(disableHome ? DISPLAY_DISABLE_HOME : 0, DISPLAY_DISABLE_HOME);
+ public void setHomeButtonEnabled(boolean enable) {
+ mActionView.setHomeButtonEnabled(enable);
}
@Override
diff --git a/core/java/com/android/internal/widget/ActionBarView.java b/core/java/com/android/internal/widget/ActionBarView.java
index 595753a..58043c9 100644
--- a/core/java/com/android/internal/widget/ActionBarView.java
+++ b/core/java/com/android/internal/widget/ActionBarView.java
@@ -434,22 +434,40 @@
}
}
+ public void setHomeButtonEnabled(boolean enable) {
+ mHomeLayout.setEnabled(enable);
+ // Make sure the home button has an accurate content description for accessibility.
+ if (!enable) {
+ mHomeLayout.setContentDescription(null);
+ } else if ((mDisplayOptions & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
+ mHomeLayout.setContentDescription(mContext.getResources().getText(
+ R.string.action_bar_up_description));
+ } else {
+ mHomeLayout.setContentDescription(mContext.getResources().getText(
+ R.string.action_bar_home_description));
+ }
+ }
+
public void setDisplayOptions(int options) {
final int flagsChanged = options ^ mDisplayOptions;
mDisplayOptions = options;
- if ((flagsChanged & ActionBar.DISPLAY_DISABLE_HOME) != 0) {
- final boolean disableHome = (options & ActionBar.DISPLAY_DISABLE_HOME) != 0;
- mHomeLayout.setEnabled(!disableHome);
- }
-
if ((flagsChanged & DISPLAY_RELAYOUT_MASK) != 0) {
final boolean showHome = (options & ActionBar.DISPLAY_SHOW_HOME) != 0;
final int vis = showHome ? VISIBLE : GONE;
mHomeLayout.setVisibility(vis);
if ((flagsChanged & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
- mHomeLayout.setUp((options & ActionBar.DISPLAY_HOME_AS_UP) != 0);
+ final boolean setUp = (options & ActionBar.DISPLAY_HOME_AS_UP) != 0;
+ mHomeLayout.setUp(setUp);
+
+ // Showing home as up implicitly enables interaction with it.
+ // In honeycomb it was always enabled, so make this transition
+ // a bit easier for developers in the common case.
+ // (It would be silly to show it as up without responding to it.)
+ if (setUp) {
+ setHomeButtonEnabled(true);
+ }
}
if ((flagsChanged & ActionBar.DISPLAY_USE_LOGO) != 0) {
@@ -487,7 +505,7 @@
}
// Make sure the home button has an accurate content description for accessibility.
- if ((options & ActionBar.DISPLAY_DISABLE_HOME) != 0) {
+ if (!mHomeLayout.isEnabled()) {
mHomeLayout.setContentDescription(null);
} else if ((options & ActionBar.DISPLAY_HOME_AS_UP) != 0) {
mHomeLayout.setContentDescription(mContext.getResources().getText(
diff --git a/core/jni/android/graphics/BitmapFactory.cpp b/core/jni/android/graphics/BitmapFactory.cpp
index 258ffa5..ea35006 100644
--- a/core/jni/android/graphics/BitmapFactory.cpp
+++ b/core/jni/android/graphics/BitmapFactory.cpp
@@ -116,7 +116,7 @@
bool forcePurgeable = false) {
int sampleSize = 1;
SkImageDecoder::Mode mode = SkImageDecoder::kDecodePixels_Mode;
- SkBitmap::Config prefConfig = SkBitmap::kNo_Config;
+ SkBitmap::Config prefConfig = SkBitmap::kARGB_8888_Config;
bool doDither = true;
bool isMutable = false;
bool isPurgeable = forcePurgeable ||
diff --git a/core/res/res/values/arrays.xml b/core/res/res/values/arrays.xml
index 0f04a67..bcf1991 100644
--- a/core/res/res/values/arrays.xml
+++ b/core/res/res/values/arrays.xml
@@ -22,6 +22,15 @@
<!-- Do not translate. These are all of the drawable resources that should be preloaded by
the zygote process before it starts forking application processes. -->
<array name="preloaded_drawables">
+ <item>@drawable/spinner_black_16</item>
+ <item>@drawable/spinner_black_20</item>
+ <item>@drawable/spinner_black_48</item>
+ <item>@drawable/spinner_black_76</item>
+ <item>@drawable/spinner_white_16</item>
+ <item>@drawable/spinner_white_48</item>
+ <item>@drawable/spinner_white_76</item>
+ <item>@drawable/toast_frame</item>
+ <item>@drawable/toast_frame_holo</item>
<item>@drawable/btn_check_on_selected</item>
<item>@drawable/btn_check_on_pressed_holo_light</item>
<item>@drawable/btn_check_on_pressed_holo_dark</item>
@@ -109,6 +118,11 @@
<item>@drawable/btn_default_disabled_holo_dark</item>
<item>@drawable/btn_default_disabled_focused_holo_light</item>
<item>@drawable/btn_default_disabled_focused_holo_dark</item>
+ <item>@drawable/btn_dropdown_disabled</item>
+ <item>@drawable/btn_dropdown_disabled_focused</item>
+ <item>@drawable/btn_dropdown_normal</item>
+ <item>@drawable/btn_dropdown_pressed</item>
+ <item>@drawable/btn_dropdown_selected</item>
<item>@drawable/btn_toggle_on_pressed_holo_light</item>
<item>@drawable/btn_toggle_on_pressed_holo_dark</item>
<item>@drawable/btn_toggle_on_normal_holo_light</item>
@@ -141,6 +155,10 @@
<item>@drawable/edit_text_holo_light</item>
<item>@drawable/edit_text_holo_dark</item>
<item>@drawable/edit_text</item>
+ <item>@drawable/expander_close_holo_dark</item>
+ <item>@drawable/expander_close_holo_light</item>
+ <item>@drawable/expander_ic_maximized</item>
+ <item>@drawable/expander_ic_minimized</item>
<item>@drawable/expander_group</item>
<item>@drawable/expander_group_holo_dark</item>
<item>@drawable/expander_group_holo_light</item>
@@ -157,6 +175,8 @@
<item>@drawable/menu_background_fill_parent_width</item>
<item>@drawable/menu_submenu_background</item>
<item>@drawable/menu_selector</item>
+ <item>@drawable/overscroll_edge</item>
+ <item>@drawable/overscroll_glow</item>
<item>@drawable/panel_background</item>
<item>@drawable/popup_bottom_bright</item>
<item>@drawable/popup_bottom_dark</item>
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index cfc5041..9613712 100755
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -3349,7 +3349,7 @@
<!-- The row span: the difference between the bottom and top
boundaries delimiting the group of cells occupied by this view.
The default is one.
- See {@link android.widget.GridLayout.Group}. -->
+ See {@link android.widget.GridLayout.Spec}. -->
<attr name="layout_rowSpan" format="integer" min="1" />
<!-- The column boundary delimiting the left of the group of cells
occupied by this view. -->
@@ -3357,23 +3357,21 @@
<!-- The column span: the difference between the right and left
boundaries delimiting the group of cells occupied by this view.
The default is one.
- See {@link android.widget.GridLayout.Group}. -->
+ See {@link android.widget.GridLayout.Spec}. -->
<attr name="layout_columnSpan" format="integer" min="1" />
<!-- Gravity specifies how a component should be placed in its group of cells.
The default is LEFT | BASELINE.
See {@link android.widget.GridLayout.LayoutParams#setGravity(int)}. -->
<attr name="layout_gravity" />
<!-- A value specifying how much deficit or excess width this component can accomodate.
- The default is FIXED.
- See {@link android.widget.GridLayout.Group#flexibility}.-->
+ The default is FIXED. -->
<attr name="layout_columnFlexibility" >
<!-- If possible, width should be greater than or equal to the specified width.
See {@link android.widget.GridLayout#CAN_STRETCH}. -->
<enum name="canStretch" value="2" />
</attr>
<!-- A value specifying how much deficit or excess height this component can accomodate.
- The default is FIXED.
- See {@link android.widget.GridLayout.Group#flexibility}.-->
+ The default is FIXED. -->
<attr name="layout_rowFlexibility" >
<!-- If possible, height should be greater than or equal to the specified height.
See {@link android.widget.GridLayout#CAN_STRETCH}. -->
diff --git a/include/media/IOMX.h b/include/media/IOMX.h
index 3c65147..02ad703 100644
--- a/include/media/IOMX.h
+++ b/include/media/IOMX.h
@@ -184,6 +184,11 @@
uint32_t flags = 0);
};
+struct CodecProfileLevel {
+ OMX_U32 mProfile;
+ OMX_U32 mLevel;
+};
+
} // namespace android
#endif // ANDROID_IOMX_H_
diff --git a/include/media/stagefright/OMXCodec.h b/include/media/stagefright/OMXCodec.h
index 7f3c497..a042ddb 100644
--- a/include/media/stagefright/OMXCodec.h
+++ b/include/media/stagefright/OMXCodec.h
@@ -336,11 +336,6 @@
OMXCodec &operator=(const OMXCodec &);
};
-struct CodecProfileLevel {
- OMX_U32 mProfile;
- OMX_U32 mLevel;
-};
-
struct CodecCapabilities {
String8 mComponentName;
Vector<CodecProfileLevel> mProfileLevels;
diff --git a/include/media/stagefright/ShoutcastSource.h b/include/media/stagefright/ShoutcastSource.h
deleted file mode 100644
index bc67156..0000000
--- a/include/media/stagefright/ShoutcastSource.h
+++ /dev/null
@@ -1,61 +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.
- */
-
-#ifndef SHOUTCAST_SOURCE_H_
-
-#define SHOUTCAST_SOURCE_H_
-
-#include <sys/types.h>
-
-#include <media/stagefright/MediaSource.h>
-
-namespace android {
-
-class HTTPStream;
-class MediaBufferGroup;
-
-class ShoutcastSource : public MediaSource {
-public:
- // Assumes ownership of "http".
- ShoutcastSource(HTTPStream *http);
-
- virtual status_t start(MetaData *params = NULL);
- virtual status_t stop();
-
- virtual sp<MetaData> getFormat();
-
- virtual status_t read(
- MediaBuffer **buffer, const ReadOptions *options = NULL);
-
-protected:
- virtual ~ShoutcastSource();
-
-private:
- HTTPStream *mHttp;
- size_t mMetaDataOffset;
- size_t mBytesUntilMetaData;
-
- MediaBufferGroup *mGroup;
- bool mStarted;
-
- ShoutcastSource(const ShoutcastSource &);
- ShoutcastSource &operator= (const ShoutcastSource &);
-};
-
-} // namespace android
-
-#endif // SHOUTCAST_SOURCE_H_
-
diff --git a/media/java/android/media/AudioTrack.java b/media/java/android/media/AudioTrack.java
index b97c3c4..b20a6e9 100644
--- a/media/java/android/media/AudioTrack.java
+++ b/media/java/android/media/AudioTrack.java
@@ -32,24 +32,25 @@
* It allows to stream PCM audio buffers to the audio hardware for playback. This is
* achieved by "pushing" the data to the AudioTrack object using one of the
* {@link #write(byte[], int, int)} and {@link #write(short[], int, int)} methods.
- *
+ *
* <p>An AudioTrack instance can operate under two modes: static or streaming.<br>
* In Streaming mode, the application writes a continuous stream of data to the AudioTrack, using
- * one of the write() methods. These are blocking and return when the data has been transferred
- * from the Java layer to the native layer and queued for playback. The streaming mode
- * is most useful when playing blocks of audio data that for instance are:
+ * one of the {@code write()} methods. These are blocking and return when the data has been
+ * transferred from the Java layer to the native layer and queued for playback. The streaming
+ * mode is most useful when playing blocks of audio data that for instance are:
+ *
* <ul>
* <li>too big to fit in memory because of the duration of the sound to play,</li>
* <li>too big to fit in memory because of the characteristics of the audio data
* (high sampling rate, bits per sample ...)</li>
* <li>received or generated while previously queued audio is playing.</li>
* </ul>
+ *
* The static mode is to be chosen when dealing with short sounds that fit in memory and
- * that need to be played with the smallest latency possible. AudioTrack instances in static mode
- * can play the sound without the need to transfer the audio data from Java to native layer
- * each time the sound is to be played. The static mode will therefore be preferred for UI and
- * game sounds that are played often, and with the smallest overhead possible.
- *
+ * that need to be played with the smallest latency possible. The static mode will
+ * therefore be preferred for UI and game sounds that are played often, and with the
+ * smallest overhead possible.
+ *
* <p>Upon creation, an AudioTrack object initializes its associated audio buffer.
* The size of this buffer, specified during the construction, determines how long an AudioTrack
* can play before running out of data.<br>
@@ -816,6 +817,7 @@
//--------------------
/**
* Starts playing an AudioTrack.
+ *
* @throws IllegalStateException
*/
public void play()
@@ -832,6 +834,7 @@
/**
* Stops playing the audio data.
+ *
* @throws IllegalStateException
*/
public void stop()
@@ -848,7 +851,10 @@
}
/**
- * Pauses the playback of the audio data.
+ * Pauses the playback of the audio data. Data that has not been played
+ * back will not be discarded. Subsequent calls to {@link #play} will play
+ * this data back.
+ *
* @throws IllegalStateException
*/
public void pause()
@@ -871,9 +877,9 @@
//--------------------
/**
- * Flushes the audio data currently queued for playback.
+ * Flushes the audio data currently queued for playback. Any data that has
+ * not been played back will be discarded.
*/
-
public void flush() {
if (mState == STATE_INITIALIZED) {
// flush the data in native layer
@@ -883,9 +889,14 @@
}
/**
- * Writes the audio data to the audio hardware for playback.
+ * Writes the audio data to the audio hardware for playback. Will block until
+ * all data has been written to the audio mixer.
+ * Note that the actual playback of this data might occur after this function
+ * returns. This function is thread safe with respect to {@link #stop} calls,
+ * in which case all of the specified data might not be written to the mixer.
+ *
* @param audioData the array that holds the data to play.
- * @param offsetInBytes the offset expressed in bytes in audioData where the data to play
+ * @param offsetInBytes the offset expressed in bytes in audioData where the data to play
* starts.
* @param sizeInBytes the number of bytes to read in audioData after the offset.
* @return the number of bytes that were written or {@link #ERROR_INVALID_OPERATION}
@@ -914,7 +925,12 @@
/**
- * Writes the audio data to the audio hardware for playback.
+ * Writes the audio data to the audio hardware for playback. Will block until
+ * all data has been written to the audio mixer.
+ * Note that the actual playback of this data might occur after this function
+ * returns. This function is thread safe with respect to {@link #stop} calls,
+ * in which case all of the specified data might not be written to the mixer.
+ *
* @param audioData the array that holds the data to play.
* @param offsetInShorts the offset expressed in shorts in audioData where the data to play
* starts.
@@ -988,7 +1004,7 @@
/**
* Sets the send level of the audio track to the attached auxiliary effect
- * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0.
+ * {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0.
* <p>By default the send level is 0, so even if an effect is attached to the player
* this method must be called for the effect to be applied.
* <p>Note that the passed level value is a raw scalar. UI controls should be scaled
diff --git a/media/libstagefright/Android.mk b/media/libstagefright/Android.mk
index 0b998b9..e17e1e8 100644
--- a/media/libstagefright/Android.mk
+++ b/media/libstagefright/Android.mk
@@ -22,7 +22,6 @@
FileSource.cpp \
FLACExtractor.cpp \
HTTPBase.cpp \
- HTTPStream.cpp \
JPEGSource.cpp \
MP3Extractor.cpp \
MPEG2TSWriter.cpp \
@@ -36,13 +35,11 @@
MediaSourceSplitter.cpp \
MetaData.cpp \
NuCachedSource2.cpp \
- NuHTTPDataSource.cpp \
OMXClient.cpp \
OMXCodec.cpp \
OggExtractor.cpp \
SampleIterator.cpp \
SampleTable.cpp \
- ShoutcastSource.cpp \
StagefrightMediaScanner.cpp \
StagefrightMetadataRetriever.cpp \
ThrottledSource.cpp \
diff --git a/media/libstagefright/AwesomePlayer.cpp b/media/libstagefright/AwesomePlayer.cpp
index 77c25d1..0098537 100644
--- a/media/libstagefright/AwesomePlayer.cpp
+++ b/media/libstagefright/AwesomePlayer.cpp
@@ -453,7 +453,6 @@
}
void AwesomePlayer::reset() {
- LOGI("reset");
Mutex::Autolock autoLock(mLock);
reset_l();
}
@@ -467,10 +466,8 @@
Playback::STOP, 0);
mDecryptHandle = NULL;
mDrmManagerClient = NULL;
- LOGI("DRM manager client stopped");
}
-
if (mFlags & PLAYING) {
uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder;
if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) {
@@ -503,7 +500,6 @@
mPreparedCondition.wait(mLock);
}
- LOGI("cancel player events");
cancelPlayerEvents();
mWVMExtractor.clear();
@@ -890,7 +886,11 @@
CHECK(!(mFlags & AUDIO_RUNNING));
if (mVideoSource == NULL) {
- status_t err = startAudioPlayer_l();
+ // We don't want to post an error notification at this point,
+ // the error returned from MediaPlayer::start() will suffice.
+
+ status_t err = startAudioPlayer_l(
+ false /* sendErrorNotification */);
if (err != OK) {
delete mAudioPlayer;
@@ -940,7 +940,7 @@
return OK;
}
-status_t AwesomePlayer::startAudioPlayer_l() {
+status_t AwesomePlayer::startAudioPlayer_l(bool sendErrorNotification) {
CHECK(!(mFlags & AUDIO_RUNNING));
if (mAudioSource == NULL || mAudioPlayer == NULL) {
@@ -958,7 +958,10 @@
true /* sourceAlreadyStarted */);
if (err != OK) {
- notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
+ if (sendErrorNotification) {
+ notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err);
+ }
+
return err;
}
@@ -1684,7 +1687,7 @@
if (mAudioPlayer != NULL && !(mFlags & (AUDIO_RUNNING | SEEK_PREVIEW))) {
status_t err = startAudioPlayer_l();
if (err != OK) {
- LOGE("Startung the audio player failed w/ err %d", err);
+ LOGE("Starting the audio player failed w/ err %d", err);
return;
}
}
diff --git a/media/libstagefright/HTTPBase.cpp b/media/libstagefright/HTTPBase.cpp
index 0d24551..f9d8501 100644
--- a/media/libstagefright/HTTPBase.cpp
+++ b/media/libstagefright/HTTPBase.cpp
@@ -24,10 +24,11 @@
#include "include/ChromiumHTTPDataSource.h"
#endif
-#include "include/NuHTTPDataSource.h"
-
+#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/foundation/ALooper.h>
+
#include <cutils/properties.h>
+#include <cutils/qtaguid.h>
namespace android {
@@ -44,14 +45,12 @@
// static
sp<HTTPBase> HTTPBase::Create(uint32_t flags) {
#if CHROMIUM_AVAILABLE
- char value[PROPERTY_VALUE_MAX];
- if (!property_get("media.stagefright.use-chromium", value, NULL)
- || (strcasecmp("false", value) && strcmp("0", value))) {
return new ChromiumHTTPDataSource(flags);
- } else
#endif
{
- return new NuHTTPDataSource(flags);
+ TRESPASS();
+
+ return NULL;
}
}
@@ -135,4 +134,10 @@
return true;
}
+// static
+void HTTPBase::RegisterSocketUser(int s, uid_t uid) {
+ static const uint32_t kTag = 0xdeadbeef;
+ set_qtaguid(s, kTag, uid);
+}
+
} // namespace android
diff --git a/media/libstagefright/HTTPStream.cpp b/media/libstagefright/HTTPStream.cpp
deleted file mode 100644
index d526ebd..0000000
--- a/media/libstagefright/HTTPStream.cpp
+++ /dev/null
@@ -1,623 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "HTTPStream"
-#include <utils/Log.h>
-
-#include "include/HTTPStream.h"
-
-#include <sys/socket.h>
-
-#include <arpa/inet.h>
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <netdb.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <media/stagefright/foundation/ADebug.h>
-
-#include <openssl/ssl.h>
-
-namespace android {
-
-// static
-const char *HTTPStream::kStatusKey = ":status:"; // MUST be lowercase.
-
-HTTPStream::HTTPStream()
- : mState(READY),
- mUIDValid(false),
- mSocket(-1),
- mSSLContext(NULL),
- mSSL(NULL) {
-}
-
-HTTPStream::~HTTPStream() {
- disconnect();
-
- if (mSSLContext != NULL) {
- SSL_CTX_free((SSL_CTX *)mSSLContext);
- mSSLContext = NULL;
- }
-}
-
-void HTTPStream::setUID(uid_t uid) {
- mUIDValid = true;
- mUID = uid;
-}
-
-static bool MakeSocketBlocking(int s, bool blocking) {
- // Make socket non-blocking.
- int flags = fcntl(s, F_GETFL, 0);
- if (flags == -1) {
- return false;
- }
-
- if (blocking) {
- flags &= ~O_NONBLOCK;
- } else {
- flags |= O_NONBLOCK;
- }
-
- return fcntl(s, F_SETFL, flags) != -1;
-}
-
-static status_t MyConnect(
- int s, const struct sockaddr *addr, socklen_t addrlen) {
- status_t result = UNKNOWN_ERROR;
-
- MakeSocketBlocking(s, false);
-
- if (connect(s, addr, addrlen) == 0) {
- result = OK;
- } else if (errno != EINPROGRESS) {
- result = -errno;
- } else {
- for (;;) {
- fd_set rs, ws;
- FD_ZERO(&rs);
- FD_ZERO(&ws);
- FD_SET(s, &rs);
- FD_SET(s, &ws);
-
- struct timeval tv;
- tv.tv_sec = 0;
- tv.tv_usec = 100000ll;
-
- int nfds = ::select(s + 1, &rs, &ws, NULL, &tv);
-
- if (nfds < 0) {
- if (errno == EINTR) {
- continue;
- }
-
- result = -errno;
- break;
- }
-
- if (FD_ISSET(s, &ws) && !FD_ISSET(s, &rs)) {
- result = OK;
- break;
- }
-
- if (FD_ISSET(s, &rs) || FD_ISSET(s, &ws)) {
- // Get the pending error.
- int error = 0;
- socklen_t errorLen = sizeof(error);
- if (getsockopt(s, SOL_SOCKET, SO_ERROR, &error, &errorLen) == -1) {
- // Couldn't get the real error, so report why not.
- result = -errno;
- } else {
- result = -error;
- }
- break;
- }
-
- // Timeout expired. Try again.
- }
- }
-
- MakeSocketBlocking(s, true);
-
- return result;
-}
-
-// Apparently under out linux closing a socket descriptor from one thread
-// will not unblock a pending send/recv on that socket on another thread.
-static ssize_t MySendReceive(
- int s, void *data, size_t size, int flags, bool sendData) {
- ssize_t result = 0;
-
- if (s < 0) {
- return -1;
- }
- while (size > 0) {
- fd_set rs, ws, es;
- FD_ZERO(&rs);
- FD_ZERO(&ws);
- FD_ZERO(&es);
- FD_SET(s, sendData ? &ws : &rs);
- FD_SET(s, &es);
-
- struct timeval tv;
- tv.tv_sec = 0;
- tv.tv_usec = 100000ll;
-
- int nfds = ::select(
- s + 1,
- sendData ? NULL : &rs,
- sendData ? &ws : NULL,
- &es,
- &tv);
-
- if (nfds < 0) {
- if (errno == EINTR) {
- continue;
- }
-
- result = -errno;
- break;
- } else if (nfds == 0) {
- // timeout
-
- continue;
- }
-
- CHECK_EQ(nfds, 1);
-
- ssize_t nbytes =
- sendData ? send(s, data, size, flags) : recv(s, data, size, flags);
-
- if (nbytes < 0) {
- if (errno == EINTR) {
- continue;
- }
-
- result = -errno;
- break;
- } else if (nbytes == 0) {
- result = 0;
- break;
- }
-
- data = (uint8_t *)data + nbytes;
- size -= nbytes;
-
- result = nbytes;
- break;
- }
-
- return result;
-}
-
-static ssize_t MySend(int s, const void *data, size_t size, int flags) {
- return MySendReceive(
- s, const_cast<void *>(data), size, flags, true /* sendData */);
-}
-
-static ssize_t MyReceive(int s, void *data, size_t size, int flags) {
- return MySendReceive(s, data, size, flags, false /* sendData */);
-}
-
-status_t HTTPStream::connect(const char *server, int port, bool https) {
- if (port < 0) {
- port = https ? 443 : 80;
- }
-
- Mutex::Autolock autoLock(mLock);
-
- status_t err = OK;
-
- if (mState == CONNECTED) {
- return ERROR_ALREADY_CONNECTED;
- }
-
- if (port < 0 || port > (int) USHRT_MAX) {
- return UNKNOWN_ERROR;
- }
-
- char service[sizeof("65536")];
- sprintf(service, "%d", port);
- struct addrinfo hints, *ai;
- memset(&hints, 0, sizeof(hints));
- hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
- hints.ai_socktype = SOCK_STREAM;
-
- int ret = getaddrinfo(server, service, &hints, &ai);
- if (ret) {
- return ERROR_UNKNOWN_HOST;
- }
-
- CHECK_EQ(mSocket, -1);
-
- mState = CONNECTING;
- status_t res = -1;
- struct addrinfo *tmp;
- for (tmp = ai; tmp; tmp = tmp->ai_next) {
- mSocket = socket(tmp->ai_family, tmp->ai_socktype, tmp->ai_protocol);
- if (mSocket < 0) {
- continue;
- }
-
- if (mUIDValid) {
- RegisterSocketUser(mSocket, mUID);
- }
-
- setReceiveTimeout(30); // Time out reads after 30 secs by default.
-
- int s = mSocket;
-
- mLock.unlock();
-
- res = MyConnect(s, tmp->ai_addr, tmp->ai_addrlen);
-
- mLock.lock();
-
- if (mState != CONNECTING) {
- close(s);
- freeaddrinfo(ai);
- return UNKNOWN_ERROR;
- }
-
- if (res == OK) {
- break;
- }
-
- close(s);
- }
-
- freeaddrinfo(ai);
-
- if (res != OK) {
- close(mSocket);
- mSocket = -1;
-
- mState = READY;
- return res;
- }
-
- if (https) {
- CHECK(mSSL == NULL);
-
- if (mSSLContext == NULL) {
- SSL_library_init();
-
- mSSLContext = SSL_CTX_new(TLSv1_client_method());
-
- if (mSSLContext == NULL) {
- LOGE("failed to create SSL context");
- mState = READY;
- return ERROR_IO;
- }
- }
-
- mSSL = SSL_new((SSL_CTX *)mSSLContext);
-
- if (mSSL == NULL) {
- LOGE("failed to create SSL session");
-
- mState = READY;
- return ERROR_IO;
- }
-
- int res = SSL_set_fd((SSL *)mSSL, mSocket);
-
- if (res == 1) {
- res = SSL_connect((SSL *)mSSL);
- }
-
- if (res != 1) {
- SSL_free((SSL *)mSSL);
- mSSL = NULL;
-
- LOGE("failed to connect over SSL");
- mState = READY;
-
- return ERROR_IO;
- }
- }
-
- mState = CONNECTED;
-
- return OK;
-}
-
-status_t HTTPStream::disconnect() {
- Mutex::Autolock autoLock(mLock);
-
- if (mState != CONNECTED && mState != CONNECTING) {
- return ERROR_NOT_CONNECTED;
- }
-
- if (mSSL != NULL) {
- SSL_shutdown((SSL *)mSSL);
-
- SSL_free((SSL *)mSSL);
- mSSL = NULL;
- }
-
- CHECK(mSocket >= 0);
- close(mSocket);
- mSocket = -1;
-
- mState = READY;
-
- return OK;
-}
-
-status_t HTTPStream::send(const char *data, size_t size) {
- if (mState != CONNECTED) {
- return ERROR_NOT_CONNECTED;
- }
-
- while (size > 0) {
- ssize_t n;
- if (mSSL != NULL) {
- n = SSL_write((SSL *)mSSL, data, size);
-
- if (n < 0) {
- n = -SSL_get_error((SSL *)mSSL, n);
- }
- } else {
- n = MySend(mSocket, data, size, 0);
- }
-
- if (n < 0) {
- disconnect();
-
- return n;
- } else if (n == 0) {
- disconnect();
-
- return ERROR_CONNECTION_LOST;
- }
-
- size -= (size_t)n;
- data += (size_t)n;
- }
-
- return OK;
-}
-
-status_t HTTPStream::send(const char *data) {
- return send(data, strlen(data));
-}
-
-// A certain application spawns a local webserver that sends invalid responses,
-// specifically it terminates header line with only a newline instead of the
-// CRLF (carriage-return followed by newline) required by the HTTP specs.
-// The workaround accepts both behaviours but could potentially break
-// legitimate responses that use a single newline to "fold" headers, which is
-// why it's not yet on by default.
-#define WORKAROUND_FOR_MISSING_CR 1
-
-status_t HTTPStream::receive_line(char *line, size_t size) {
- if (mState != CONNECTED) {
- return ERROR_NOT_CONNECTED;
- }
-
- bool saw_CR = false;
- size_t length = 0;
-
- for (;;) {
- char c;
- ssize_t n;
- if (mSSL != NULL) {
- n = SSL_read((SSL *)mSSL, &c, 1);
-
- if (n < 0) {
- n = -SSL_get_error((SSL *)mSSL, n);
- }
- } else {
- n = MyReceive(mSocket, &c, 1, 0);
- }
-
- if (n < 0) {
- disconnect();
-
- return ERROR_IO;
- } else if (n == 0) {
- disconnect();
-
- return ERROR_CONNECTION_LOST;
- }
-
-#if WORKAROUND_FOR_MISSING_CR
- if (c == '\n') {
- // We have a complete line.
-
- line[saw_CR ? length - 1 : length] = '\0';
- return OK;
- }
-#else
- if (saw_CR && c == '\n') {
- // We have a complete line.
-
- line[length - 1] = '\0';
- return OK;
- }
-#endif
-
- saw_CR = (c == '\r');
-
- if (length + 1 >= size) {
- return ERROR_MALFORMED;
- }
- line[length++] = c;
- }
-}
-
-status_t HTTPStream::receive_header(int *http_status) {
- *http_status = -1;
- mHeaders.clear();
-
- char line[2048];
- status_t err = receive_line(line, sizeof(line));
- if (err != OK) {
- return err;
- }
-
- mHeaders.add(AString(kStatusKey), AString(line));
-
- char *spacePos = strchr(line, ' ');
- if (spacePos == NULL) {
- // Malformed response?
- return UNKNOWN_ERROR;
- }
-
- char *status_start = spacePos + 1;
- char *status_end = status_start;
- while (isdigit(*status_end)) {
- ++status_end;
- }
-
- if (status_end == status_start) {
- // Malformed response, status missing?
- return UNKNOWN_ERROR;
- }
-
- memmove(line, status_start, status_end - status_start);
- line[status_end - status_start] = '\0';
-
- long tmp = strtol(line, NULL, 10);
- if (tmp < 0 || tmp > 999) {
- return UNKNOWN_ERROR;
- }
-
- *http_status = (int)tmp;
-
- for (;;) {
- err = receive_line(line, sizeof(line));
- if (err != OK) {
- return err;
- }
-
- if (*line == '\0') {
- // Empty line signals the end of the header.
- break;
- }
-
- // puts(line);
-
- char *colonPos = strchr(line, ':');
- if (colonPos == NULL) {
- AString key = line;
- key.tolower();
-
- mHeaders.add(key, AString());
- } else {
- char *end_of_key = colonPos;
- while (end_of_key > line && isspace(end_of_key[-1])) {
- --end_of_key;
- }
-
- char *start_of_value = colonPos + 1;
- while (isspace(*start_of_value)) {
- ++start_of_value;
- }
-
- *end_of_key = '\0';
-
- AString key = line;
- key.tolower();
-
- mHeaders.add(key, AString(start_of_value));
- }
- }
-
- return OK;
-}
-
-ssize_t HTTPStream::receive(void *data, size_t size) {
- size_t total = 0;
- while (total < size) {
- ssize_t n;
- if (mSSL != NULL) {
- n = SSL_read((SSL *)mSSL, (char *)data + total, size - total);
-
- if (n < 0) {
- n = -SSL_get_error((SSL *)mSSL, n);
- }
- } else {
- n = MyReceive(mSocket, (char *)data + total, size - total, 0);
- }
-
- if (n < 0) {
- LOGE("recv failed, errno = %d (%s)", (int)n, strerror(-n));
-
- disconnect();
- return (ssize_t)ERROR_IO;
- } else if (n == 0) {
- disconnect();
-
- LOGE("recv failed, server is gone, total received: %d bytes",
- total);
-
- return total == 0 ? (ssize_t)ERROR_CONNECTION_LOST : total;
- }
-
- total += (size_t)n;
- }
-
- return (ssize_t)total;
-}
-
-bool HTTPStream::find_header_value(const AString &key, AString *value) const {
- AString key_lower = key;
- key_lower.tolower();
-
- ssize_t index = mHeaders.indexOfKey(key_lower);
- if (index < 0) {
- value->clear();
- return false;
- }
-
- *value = mHeaders.valueAt(index);
-
- return true;
-}
-
-void HTTPStream::setReceiveTimeout(int seconds) {
- if (seconds < 0) {
- // Disable the timeout.
- seconds = 0;
- }
-
- struct timeval tv;
- tv.tv_usec = 0;
- tv.tv_sec = seconds;
- CHECK_EQ(0, setsockopt(mSocket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)));
-}
-
-// static
-void HTTPStream::RegisterSocketUser(int s, uid_t uid) {
- // Lower bits MUST be 0.
- static const uint64_t kTag = 0xdeadbeef00000000ll;
-
- AString line = StringPrintf("t %d %llu %d", s, kTag, uid);
-
- int fd = open("/proc/net/xt_qtaguid/ctrl", O_WRONLY);
- write(fd, line.c_str(), line.size());
- close(fd);
- fd = -1;
-}
-
-} // namespace android
-
diff --git a/media/libstagefright/NuHTTPDataSource.cpp b/media/libstagefright/NuHTTPDataSource.cpp
deleted file mode 100644
index 2949767..0000000
--- a/media/libstagefright/NuHTTPDataSource.cpp
+++ /dev/null
@@ -1,560 +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.
- */
-
-//#define LOG_NDEBUG 0
-#define LOG_TAG "NuHTTPDataSource"
-#include <utils/Log.h>
-
-#include "include/NuHTTPDataSource.h"
-
-#include <cutils/properties.h>
-#include <media/stagefright/foundation/ALooper.h>
-#include <media/stagefright/MediaDebug.h>
-#include <media/stagefright/MediaErrors.h>
-
-namespace android {
-
-static bool ParseSingleUnsignedLong(
- const char *from, unsigned long *x) {
- char *end;
- *x = strtoul(from, &end, 10);
-
- if (end == from || *end != '\0') {
- return false;
- }
-
- return true;
-}
-
-static bool ParseURL(
- const char *url, String8 *host, unsigned *port,
- String8 *path, bool *https) {
- host->setTo("");
- *port = 0;
- path->setTo("");
-
- size_t hostStart;
- if (!strncasecmp("http://", url, 7)) {
- hostStart = 7;
- *https = false;
- } else if (!strncasecmp("https://", url, 8)) {
- hostStart = 8;
- *https = true;
- } else {
- return false;
- }
-
- const char *slashPos = strchr(&url[hostStart], '/');
-
- if (slashPos == NULL) {
- host->setTo(&url[hostStart]);
- path->setTo("/");
- } else {
- host->setTo(&url[hostStart], slashPos - &url[hostStart]);
- path->setTo(slashPos);
- }
-
- const char *colonPos = strchr(host->string(), ':');
-
- if (colonPos != NULL) {
- unsigned long x;
- if (!ParseSingleUnsignedLong(colonPos + 1, &x) || x >= 65536) {
- return false;
- }
-
- *port = x;
-
- size_t colonOffset = colonPos - host->string();
- String8 tmp(host->string(), colonOffset);
- *host = tmp;
- } else {
- *port = (*https) ? 443 : 80;
- }
-
- return true;
-}
-
-NuHTTPDataSource::NuHTTPDataSource(uint32_t flags)
- : mFlags(flags),
- mState(DISCONNECTED),
- mPort(0),
- mHTTPS(false),
- mOffset(0),
- mContentLength(0),
- mContentLengthValid(false),
- mHasChunkedTransferEncoding(false),
- mChunkDataBytesLeft(0),
- mDecryptHandle(NULL),
- mDrmManagerClient(NULL) {
-}
-
-NuHTTPDataSource::~NuHTTPDataSource() {
- if (mDecryptHandle != NULL) {
- // To release mDecryptHandle
- CHECK(mDrmManagerClient);
- mDrmManagerClient->closeDecryptSession(mDecryptHandle);
- mDecryptHandle = NULL;
- }
-
- if (mDrmManagerClient != NULL) {
- delete mDrmManagerClient;
- mDrmManagerClient = NULL;
- }
-}
-
-status_t NuHTTPDataSource::connect(
- const char *uri,
- const KeyedVector<String8, String8> *overrides,
- off64_t offset) {
- String8 headers;
- MakeFullHeaders(overrides, &headers);
-
- return connect(uri, headers, offset);
-}
-
-status_t NuHTTPDataSource::connect(
- const char *uri,
- const String8 &headers,
- off64_t offset) {
- String8 host, path;
- unsigned port;
-
- mUri = uri;
- mContentType = String8("application/octet-stream");
-
- bool https;
- if (!ParseURL(uri, &host, &port, &path, &https)) {
- return ERROR_MALFORMED;
- }
-
- uid_t uid;
- if (getUID(&uid)) {
- mHTTP.setUID(uid);
- }
-
- return connect(host, port, path, https, headers, offset);
-}
-
-static bool IsRedirectStatusCode(int httpStatus) {
- return httpStatus == 301 || httpStatus == 302
- || httpStatus == 303 || httpStatus == 307;
-}
-
-status_t NuHTTPDataSource::connect(
- const char *host, unsigned port, const char *path,
- bool https,
- const String8 &headers,
- off64_t offset) {
- if (!(mFlags & kFlagIncognito)) {
- LOGI("connect to %s:%u%s @%lld", host, port, path, offset);
- } else {
- LOGI("connect to <URL suppressed> @%lld", offset);
- }
-
- bool needsToReconnect = true;
-
- if (mState == CONNECTED && host == mHost && port == mPort
- && https == mHTTPS && offset == mOffset) {
- if (mContentLengthValid && mOffset == mContentLength) {
- LOGI("Didn't have to reconnect, old one's still good.");
- needsToReconnect = false;
- }
- }
-
- mHost = host;
- mPort = port;
- mPath = path;
- mHTTPS = https;
- mHeaders = headers;
-
- status_t err = OK;
-
- mState = CONNECTING;
-
- if (needsToReconnect) {
- mHTTP.disconnect();
- err = mHTTP.connect(host, port, https);
- }
-
- if (err != OK) {
- mState = DISCONNECTED;
- } else if (mState != CONNECTING) {
- err = UNKNOWN_ERROR;
- } else {
- mState = CONNECTED;
-
- mOffset = offset;
- mContentLength = 0;
- mContentLengthValid = false;
-
- String8 request("GET ");
- request.append(mPath);
- request.append(" HTTP/1.1\r\n");
- request.append("Host: ");
- request.append(mHost);
- if (mPort != 80) {
- request.append(StringPrintf(":%u", mPort).c_str());
- }
- request.append("\r\n");
-
- if (offset != 0) {
- char rangeHeader[128];
- sprintf(rangeHeader, "Range: bytes=%lld-\r\n", offset);
- request.append(rangeHeader);
- }
-
- request.append(mHeaders);
- request.append("\r\n");
-
- int httpStatus;
- if ((err = mHTTP.send(request.string(), request.size())) != OK
- || (err = mHTTP.receive_header(&httpStatus)) != OK) {
- mHTTP.disconnect();
- mState = DISCONNECTED;
- return err;
- }
-
- if (IsRedirectStatusCode(httpStatus)) {
- AString value;
- CHECK(mHTTP.find_header_value("Location", &value));
-
- mState = DISCONNECTED;
-
- mHTTP.disconnect();
-
- return connect(value.c_str(), headers, offset);
- }
-
- if (httpStatus < 200 || httpStatus >= 300) {
- mState = DISCONNECTED;
- mHTTP.disconnect();
-
- return ERROR_IO;
- }
-
- mHasChunkedTransferEncoding = false;
-
- {
- AString value;
- if (mHTTP.find_header_value("Transfer-Encoding", &value)) {
- // We don't currently support any transfer encodings but
- // chunked.
-
- if (!strcasecmp(value.c_str(), "chunked")) {
- LOGI("Chunked transfer encoding applied.");
- mHasChunkedTransferEncoding = true;
- mChunkDataBytesLeft = 0;
- } else {
- mState = DISCONNECTED;
- mHTTP.disconnect();
-
- LOGE("We don't support '%s' transfer encoding.", value.c_str());
-
- return ERROR_UNSUPPORTED;
- }
- }
- }
-
- {
- AString value;
- if (mHTTP.find_header_value("Content-Type", &value)) {
- mContentType = String8(value.c_str());
- } else {
- mContentType = String8("application/octet-stream");
- }
- }
-
- applyTimeoutResponse();
-
- if (offset == 0) {
- AString value;
- unsigned long x;
- if (mHTTP.find_header_value(AString("Content-Length"), &value)
- && ParseSingleUnsignedLong(value.c_str(), &x)) {
- mContentLength = (off64_t)x;
- mContentLengthValid = true;
- } else {
- LOGW("Server did not give us the content length!");
- }
- } else {
- if (httpStatus != 206 /* Partial Content */) {
- // We requested a range but the server didn't support that.
- LOGE("We requested a range but the server didn't "
- "support that.");
- return ERROR_UNSUPPORTED;
- }
-
- AString value;
- unsigned long x;
- if (mHTTP.find_header_value(AString("Content-Range"), &value)) {
- const char *slashPos = strchr(value.c_str(), '/');
- if (slashPos != NULL
- && ParseSingleUnsignedLong(slashPos + 1, &x)) {
- mContentLength = x;
- mContentLengthValid = true;
- }
- }
- }
- }
-
- return err;
-}
-
-void NuHTTPDataSource::disconnect() {
- if (mState == CONNECTING || mState == CONNECTED) {
- mHTTP.disconnect();
- }
- mState = DISCONNECTED;
-}
-
-status_t NuHTTPDataSource::initCheck() const {
- return mState == CONNECTED ? OK : NO_INIT;
-}
-
-ssize_t NuHTTPDataSource::internalRead(void *data, size_t size) {
- if (!mHasChunkedTransferEncoding) {
- return mHTTP.receive(data, size);
- }
-
- if (mChunkDataBytesLeft < 0) {
- return 0;
- } else if (mChunkDataBytesLeft == 0) {
- char line[1024];
- status_t err = mHTTP.receive_line(line, sizeof(line));
-
- if (err != OK) {
- return err;
- }
-
- LOGV("line = '%s'", line);
-
- char *end;
- unsigned long n = strtoul(line, &end, 16);
-
- if (end == line || (*end != ';' && *end != '\0')) {
- LOGE("malformed HTTP chunk '%s'", line);
- return ERROR_MALFORMED;
- }
-
- mChunkDataBytesLeft = n;
- LOGV("chunk data size = %lu", n);
-
- if (mChunkDataBytesLeft == 0) {
- mChunkDataBytesLeft = -1;
- return 0;
- }
-
- // fall through
- }
-
- if (size > (size_t)mChunkDataBytesLeft) {
- size = mChunkDataBytesLeft;
- }
-
- ssize_t n = mHTTP.receive(data, size);
-
- if (n < 0) {
- return n;
- }
-
- mChunkDataBytesLeft -= (size_t)n;
-
- if (mChunkDataBytesLeft == 0) {
- char line[1024];
- status_t err = mHTTP.receive_line(line, sizeof(line));
-
- if (err != OK) {
- return err;
- }
-
- if (line[0] != '\0') {
- LOGE("missing HTTP chunk terminator.");
- return ERROR_MALFORMED;
- }
- }
-
- return n;
-}
-
-ssize_t NuHTTPDataSource::readAt(off64_t offset, void *data, size_t size) {
- LOGV("readAt offset %ld, size %d", offset, size);
-
- Mutex::Autolock autoLock(mLock);
-
- if (offset != mOffset) {
- String8 host = mHost;
- String8 path = mPath;
- String8 headers = mHeaders;
- status_t err = connect(host, mPort, path, mHTTPS, headers, offset);
-
- if (err != OK) {
- return err;
- }
- }
-
- if (mContentLengthValid) {
- size_t avail =
- (offset >= mContentLength) ? 0 : mContentLength - offset;
-
- if (size > avail) {
- size = avail;
- }
- }
-
- size_t numBytesRead = 0;
- while (numBytesRead < size) {
- int64_t startTimeUs = ALooper::GetNowUs();
-
- ssize_t n =
- internalRead((uint8_t *)data + numBytesRead, size - numBytesRead);
-
- if (n < 0) {
- if (numBytesRead == 0 || mContentLengthValid) {
- return n;
- }
-
- // If there was an error we want to at least return the data
- // we've already successfully read. The next call to read will
- // then return the error.
- n = 0;
- }
-
- int64_t delayUs = ALooper::GetNowUs() - startTimeUs;
- addBandwidthMeasurement(n, delayUs);
-
- numBytesRead += (size_t)n;
-
- if (n == 0) {
- if (mContentLengthValid) {
- // We know the content length and made sure not to read beyond
- // it and yet the server closed the connection on us.
- return ERROR_IO;
- }
-
- break;
- }
- }
-
- mOffset += numBytesRead;
-
- return numBytesRead;
-}
-
-status_t NuHTTPDataSource::getSize(off64_t *size) {
- *size = 0;
-
- if (mState != CONNECTED) {
- return ERROR_IO;
- }
-
- if (mContentLengthValid) {
- *size = mContentLength;
- return OK;
- }
-
- return ERROR_UNSUPPORTED;
-}
-
-uint32_t NuHTTPDataSource::flags() {
- return kWantsPrefetching | kIsHTTPBasedSource;
-}
-
-// static
-void NuHTTPDataSource::MakeFullHeaders(
- const KeyedVector<String8, String8> *overrides, String8 *headers) {
- headers->setTo("");
-
- headers->append("User-Agent: stagefright/1.1 (Linux;Android ");
-
-#if (PROPERTY_VALUE_MAX < 8)
-#error "PROPERTY_VALUE_MAX must be at least 8"
-#endif
-
- char value[PROPERTY_VALUE_MAX];
- property_get("ro.build.version.release", value, "Unknown");
- headers->append(value);
- headers->append(")\r\n");
-
- if (overrides == NULL) {
- return;
- }
-
- for (size_t i = 0; i < overrides->size(); ++i) {
- String8 line;
- line.append(overrides->keyAt(i));
- line.append(": ");
- line.append(overrides->valueAt(i));
- line.append("\r\n");
-
- headers->append(line);
- }
-}
-
-void NuHTTPDataSource::applyTimeoutResponse() {
- AString timeout;
- if (mHTTP.find_header_value("X-SocketTimeout", &timeout)) {
- const char *s = timeout.c_str();
- char *end;
- long tmp = strtol(s, &end, 10);
- if (end == s || *end != '\0') {
- LOGW("Illegal X-SocketTimeout value given.");
- return;
- }
-
- LOGI("overriding default timeout, new timeout is %ld seconds", tmp);
- mHTTP.setReceiveTimeout(tmp);
- }
-}
-
-sp<DecryptHandle> NuHTTPDataSource::DrmInitialization() {
- if (mDrmManagerClient == NULL) {
- mDrmManagerClient = new DrmManagerClient();
- }
-
- if (mDrmManagerClient == NULL) {
- return NULL;
- }
-
- if (mDecryptHandle == NULL) {
- /* Note if redirect occurs, mUri is the redirect uri instead of the
- * original one
- */
- mDecryptHandle = mDrmManagerClient->openDecryptSession(mUri);
- }
-
- if (mDecryptHandle == NULL) {
- delete mDrmManagerClient;
- mDrmManagerClient = NULL;
- }
-
- return mDecryptHandle;
-}
-
-void NuHTTPDataSource::getDrmInfo(sp<DecryptHandle> &handle, DrmManagerClient **client) {
- handle = mDecryptHandle;
-
- *client = mDrmManagerClient;
-}
-
-String8 NuHTTPDataSource::getUri() {
- return mUri;
-}
-
-String8 NuHTTPDataSource::getMIMEType() const {
- return mContentType;
-}
-
-} // namespace android
diff --git a/media/libstagefright/OMXCodec.cpp b/media/libstagefright/OMXCodec.cpp
index b7b0dc0f..5cab60e 100755
--- a/media/libstagefright/OMXCodec.cpp
+++ b/media/libstagefright/OMXCodec.cpp
@@ -3539,7 +3539,7 @@
}
status_t OMXCodec::stop() {
- CODEC_LOGI("stop mState=%d", mState);
+ CODEC_LOGV("stop mState=%d", mState);
Mutex::Autolock autoLock(mLock);
@@ -3601,7 +3601,6 @@
mLeftOverBuffer = NULL;
}
- CODEC_LOGI("stopping video source");
mSource->stop();
CODEC_LOGI("stopped in state %d", mState);
diff --git a/media/libstagefright/ShoutcastSource.cpp b/media/libstagefright/ShoutcastSource.cpp
deleted file mode 100644
index 783f2d0..0000000
--- a/media/libstagefright/ShoutcastSource.cpp
+++ /dev/null
@@ -1,157 +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.
- */
-
-#include "include/HTTPStream.h"
-
-#include <stdlib.h>
-
-#include <media/stagefright/MediaBuffer.h>
-#include <media/stagefright/MediaBufferGroup.h>
-#include <media/stagefright/MediaDebug.h>
-#include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MetaData.h>
-#include <media/stagefright/ShoutcastSource.h>
-
-namespace android {
-
-ShoutcastSource::ShoutcastSource(HTTPStream *http)
- : mHttp(http),
- mMetaDataOffset(0),
- mBytesUntilMetaData(0),
- mGroup(NULL),
- mStarted(false) {
- AString metaint;
- if (mHttp->find_header_value("icy-metaint", &metaint)) {
- char *end;
- const char *start = metaint.c_str();
- mMetaDataOffset = strtol(start, &end, 10);
- CHECK(end > start && *end == '\0');
- CHECK(mMetaDataOffset > 0);
-
- mBytesUntilMetaData = mMetaDataOffset;
- }
-}
-
-ShoutcastSource::~ShoutcastSource() {
- if (mStarted) {
- stop();
- }
-
- delete mHttp;
- mHttp = NULL;
-}
-
-status_t ShoutcastSource::start(MetaData *) {
- CHECK(!mStarted);
-
- mGroup = new MediaBufferGroup;
- mGroup->add_buffer(new MediaBuffer(4096)); // XXX
-
- mStarted = true;
-
- return OK;
-}
-
-status_t ShoutcastSource::stop() {
- CHECK(mStarted);
-
- delete mGroup;
- mGroup = NULL;
-
- mStarted = false;
-
- return OK;
-}
-
-sp<MetaData> ShoutcastSource::getFormat() {
- sp<MetaData> meta = new MetaData;
- meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_MPEG);
- meta->setInt32(kKeySampleRate, 44100);
- meta->setInt32(kKeyChannelCount, 2); // XXX
-
- return meta;
-}
-
-status_t ShoutcastSource::read(
- MediaBuffer **out, const ReadOptions *options) {
- CHECK(mStarted);
-
- *out = NULL;
-
- int64_t seekTimeUs;
- ReadOptions::SeekMode mode;
- if (options && options->getSeekTo(&seekTimeUs, &mode)) {
- return ERROR_UNSUPPORTED;
- }
-
- MediaBuffer *buffer;
- status_t err = mGroup->acquire_buffer(&buffer);
- if (err != OK) {
- return err;
- }
-
- *out = buffer;
-
- size_t num_bytes = buffer->size();
- if (mMetaDataOffset > 0 && num_bytes > mBytesUntilMetaData) {
- num_bytes = mBytesUntilMetaData;
- }
-
- ssize_t n = mHttp->receive(buffer->data(), num_bytes);
-
- if (n <= 0) {
- return (status_t)n;
- }
-
- buffer->set_range(0, n);
-
- mBytesUntilMetaData -= (size_t)n;
-
- if (mBytesUntilMetaData == 0) {
- unsigned char num_16_byte_blocks = 0;
- n = mHttp->receive((char *)&num_16_byte_blocks, 1);
- CHECK_EQ(n, 1);
-
- char meta[255 * 16];
- size_t meta_size = num_16_byte_blocks * 16;
- size_t meta_length = 0;
- while (meta_length < meta_size) {
- n = mHttp->receive(&meta[meta_length], meta_size - meta_length);
- if (n <= 0) {
- return (status_t)n;
- }
-
- meta_length += (size_t) n;
- }
-
- while (meta_length > 0 && meta[meta_length - 1] == '\0') {
- --meta_length;
- }
-
- if (meta_length > 0) {
- // Technically we should probably attach this meta data to the
- // next buffer. XXX
- buffer->meta_data()->setData('shou', 'shou', meta, meta_length);
- }
-
- mBytesUntilMetaData = mMetaDataOffset;
- }
-
- return OK;
-}
-
-} // namespace android
-
diff --git a/media/libstagefright/codecs/avc/dec/SoftAVC.cpp b/media/libstagefright/codecs/avc/dec/SoftAVC.cpp
index 9f141ac..6a476f6 100644
--- a/media/libstagefright/codecs/avc/dec/SoftAVC.cpp
+++ b/media/libstagefright/codecs/avc/dec/SoftAVC.cpp
@@ -23,6 +23,7 @@
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/MediaErrors.h>
+#include <media/IOMX.h>
#include "avcdec_api.h"
#include "avcdec_int.h"
@@ -31,6 +32,13 @@
static const char kStartCode[4] = { 0x00, 0x00, 0x00, 0x01 };
+static const CodecProfileLevel kProfileLevels[] = {
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel1 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel1b },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel11 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel12 },
+};
+
template<class T>
static void InitOMXParams(T *params) {
params->nSize = sizeof(T);
@@ -181,6 +189,28 @@
return OMX_ErrorNone;
}
+ case OMX_IndexParamVideoProfileLevelQuerySupported:
+ {
+ OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevel =
+ (OMX_VIDEO_PARAM_PROFILELEVELTYPE *) params;
+
+ if (profileLevel->nPortIndex != 0) { // Input port only
+ LOGE("Invalid port index: %ld", profileLevel->nPortIndex);
+ return OMX_ErrorUnsupportedIndex;
+ }
+
+ size_t index = profileLevel->nProfileIndex;
+ size_t nProfileLevels =
+ sizeof(kProfileLevels) / sizeof(kProfileLevels[0]);
+ if (index >= nProfileLevels) {
+ return OMX_ErrorNoMore;
+ }
+
+ profileLevel->eProfile = kProfileLevels[index].mProfile;
+ profileLevel->eLevel = kProfileLevels[index].mLevel;
+ return OMX_ErrorNone;
+ }
+
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
diff --git a/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp b/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp
index cffbfb5..ddced5f 100644
--- a/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp
+++ b/media/libstagefright/codecs/m4v_h263/dec/SoftMPEG4.cpp
@@ -23,11 +23,31 @@
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/MediaErrors.h>
+#include <media/IOMX.h>
#include "mp4dec_api.h"
namespace android {
+static const CodecProfileLevel kM4VProfileLevels[] = {
+ { OMX_VIDEO_MPEG4ProfileSimple, OMX_VIDEO_MPEG4Level0 },
+ { OMX_VIDEO_MPEG4ProfileSimple, OMX_VIDEO_MPEG4Level0b },
+ { OMX_VIDEO_MPEG4ProfileSimple, OMX_VIDEO_MPEG4Level1 },
+ { OMX_VIDEO_MPEG4ProfileSimple, OMX_VIDEO_MPEG4Level2 },
+ { OMX_VIDEO_MPEG4ProfileSimple, OMX_VIDEO_MPEG4Level3 },
+};
+
+static const CodecProfileLevel kH263ProfileLevels[] = {
+ { OMX_VIDEO_H263ProfileBaseline, OMX_VIDEO_H263Level10 },
+ { OMX_VIDEO_H263ProfileBaseline, OMX_VIDEO_H263Level20 },
+ { OMX_VIDEO_H263ProfileBaseline, OMX_VIDEO_H263Level30 },
+ { OMX_VIDEO_H263ProfileBaseline, OMX_VIDEO_H263Level45 },
+ { OMX_VIDEO_H263ProfileISWV2, OMX_VIDEO_H263Level10 },
+ { OMX_VIDEO_H263ProfileISWV2, OMX_VIDEO_H263Level20 },
+ { OMX_VIDEO_H263ProfileISWV2, OMX_VIDEO_H263Level30 },
+ { OMX_VIDEO_H263ProfileISWV2, OMX_VIDEO_H263Level45 },
+};
+
template<class T>
static void InitOMXParams(T *params) {
params->nSize = sizeof(T);
@@ -181,6 +201,39 @@
return OMX_ErrorNone;
}
+ case OMX_IndexParamVideoProfileLevelQuerySupported:
+ {
+ OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevel =
+ (OMX_VIDEO_PARAM_PROFILELEVELTYPE *) params;
+
+ if (profileLevel->nPortIndex != 0) { // Input port only
+ LOGE("Invalid port index: %ld", profileLevel->nPortIndex);
+ return OMX_ErrorUnsupportedIndex;
+ }
+
+ size_t index = profileLevel->nProfileIndex;
+ if (mMode == MODE_H263) {
+ size_t nProfileLevels =
+ sizeof(kH263ProfileLevels) / sizeof(kH263ProfileLevels[0]);
+ if (index >= nProfileLevels) {
+ return OMX_ErrorNoMore;
+ }
+
+ profileLevel->eProfile = kH263ProfileLevels[index].mProfile;
+ profileLevel->eLevel = kH263ProfileLevels[index].mLevel;
+ } else {
+ size_t nProfileLevels =
+ sizeof(kM4VProfileLevels) / sizeof(kM4VProfileLevels[0]);
+ if (index >= nProfileLevels) {
+ return OMX_ErrorNoMore;
+ }
+
+ profileLevel->eProfile = kM4VProfileLevels[index].mProfile;
+ profileLevel->eLevel = kM4VProfileLevels[index].mLevel;
+ }
+ return OMX_ErrorNone;
+ }
+
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
diff --git a/media/libstagefright/codecs/on2/h264dec/SoftAVC.cpp b/media/libstagefright/codecs/on2/h264dec/SoftAVC.cpp
index ec7bd1c..740c957 100644
--- a/media/libstagefright/codecs/on2/h264dec/SoftAVC.cpp
+++ b/media/libstagefright/codecs/on2/h264dec/SoftAVC.cpp
@@ -23,10 +23,30 @@
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/MediaDefs.h>
#include <media/stagefright/MediaErrors.h>
+#include <media/IOMX.h>
namespace android {
+static const CodecProfileLevel kProfileLevels[] = {
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel1 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel1b },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel11 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel12 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel13 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel2 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel21 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel22 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel3 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel31 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel32 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel4 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel41 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel42 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel5 },
+ { OMX_VIDEO_AVCProfileBaseline, OMX_VIDEO_AVCLevel51 },
+};
+
template<class T>
static void InitOMXParams(T *params) {
params->nSize = sizeof(T);
@@ -177,6 +197,28 @@
return OMX_ErrorNone;
}
+ case OMX_IndexParamVideoProfileLevelQuerySupported:
+ {
+ OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevel =
+ (OMX_VIDEO_PARAM_PROFILELEVELTYPE *) params;
+
+ if (profileLevel->nPortIndex != kInputPortIndex) {
+ LOGE("Invalid port index: %ld", profileLevel->nPortIndex);
+ return OMX_ErrorUnsupportedIndex;
+ }
+
+ size_t index = profileLevel->nProfileIndex;
+ size_t nProfileLevels =
+ sizeof(kProfileLevels) / sizeof(kProfileLevels[0]);
+ if (index >= nProfileLevels) {
+ return OMX_ErrorNoMore;
+ }
+
+ profileLevel->eProfile = kProfileLevels[index].mProfile;
+ profileLevel->eLevel = kProfileLevels[index].mLevel;
+ return OMX_ErrorNone;
+ }
+
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
diff --git a/media/libstagefright/include/AwesomePlayer.h b/media/libstagefright/include/AwesomePlayer.h
index e069b4d..95f2ae8 100644
--- a/media/libstagefright/include/AwesomePlayer.h
+++ b/media/libstagefright/include/AwesomePlayer.h
@@ -291,7 +291,7 @@
void finishSeekIfNecessary(int64_t videoTimeUs);
void ensureCacheIsFetching_l();
- status_t startAudioPlayer_l();
+ status_t startAudioPlayer_l(bool sendErrorNotification = true);
void postAudioSeekComplete_l();
void shutdownVideoDecoder_l();
diff --git a/media/libstagefright/include/HTTPBase.h b/media/libstagefright/include/HTTPBase.h
index 2e25dd9..0e9af69 100644
--- a/media/libstagefright/include/HTTPBase.h
+++ b/media/libstagefright/include/HTTPBase.h
@@ -53,6 +53,8 @@
static sp<HTTPBase> Create(uint32_t flags = 0);
+ static void RegisterSocketUser(int s, uid_t uid);
+
protected:
void addBandwidthMeasurement(size_t numBytes, int64_t delayUs);
diff --git a/media/libstagefright/include/HTTPStream.h b/media/libstagefright/include/HTTPStream.h
deleted file mode 100644
index 88ba9d6..0000000
--- a/media/libstagefright/include/HTTPStream.h
+++ /dev/null
@@ -1,91 +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.
- */
-
-#ifndef HTTP_STREAM_H_
-
-#define HTTP_STREAM_H_
-
-#include <sys/types.h>
-
-#include <media/stagefright/foundation/AString.h>
-#include <media/stagefright/MediaErrors.h>
-#include <utils/KeyedVector.h>
-#include <utils/threads.h>
-
-namespace android {
-
-class HTTPStream {
-public:
- HTTPStream();
- ~HTTPStream();
-
- void setUID(uid_t uid);
-
- status_t connect(const char *server, int port = -1, bool https = false);
- status_t disconnect();
-
- status_t send(const char *data, size_t size);
-
- // Assumes data is a '\0' terminated string.
- status_t send(const char *data);
-
- // Receive up to "size" bytes of data.
- ssize_t receive(void *data, size_t size);
-
- status_t receive_header(int *http_status);
-
- // The header key used to retrieve the status line.
- static const char *kStatusKey;
-
- bool find_header_value(
- const AString &key, AString *value) const;
-
- // Pass a negative value to disable the timeout.
- void setReceiveTimeout(int seconds);
-
- // Receive a line of data terminated by CRLF, line will be '\0' terminated
- // _excluding_ the termianting CRLF.
- status_t receive_line(char *line, size_t size);
-
- static void RegisterSocketUser(int s, uid_t uid);
-
-private:
- enum State {
- READY,
- CONNECTING,
- CONNECTED
- };
-
- State mState;
- Mutex mLock;
-
- bool mUIDValid;
- uid_t mUID;
-
- int mSocket;
-
- KeyedVector<AString, AString> mHeaders;
-
- void *mSSLContext;
- void *mSSL;
-
- HTTPStream(const HTTPStream &);
- HTTPStream &operator=(const HTTPStream &);
-};
-
-} // namespace android
-
-#endif // HTTP_STREAM_H_
diff --git a/media/libstagefright/include/NuHTTPDataSource.h b/media/libstagefright/include/NuHTTPDataSource.h
deleted file mode 100644
index c265b3a..0000000
--- a/media/libstagefright/include/NuHTTPDataSource.h
+++ /dev/null
@@ -1,114 +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.
- */
-
-#ifndef NU_HTTP_DATA_SOURCE_H_
-
-#define NU_HTTP_DATA_SOURCE_H_
-
-#include <utils/List.h>
-#include <utils/String8.h>
-#include <utils/threads.h>
-
-#include "HTTPStream.h"
-#include "include/HTTPBase.h"
-
-namespace android {
-
-struct NuHTTPDataSource : public HTTPBase {
- NuHTTPDataSource(uint32_t flags = 0);
-
- virtual status_t connect(
- const char *uri,
- const KeyedVector<String8, String8> *headers = NULL,
- off64_t offset = 0);
-
- virtual void disconnect();
-
- virtual status_t initCheck() const;
-
- virtual ssize_t readAt(off64_t offset, void *data, size_t size);
- virtual status_t getSize(off64_t *size);
- virtual uint32_t flags();
-
- virtual sp<DecryptHandle> DrmInitialization();
- virtual void getDrmInfo(sp<DecryptHandle> &handle, DrmManagerClient **client);
- virtual String8 getUri();
-
- virtual String8 getMIMEType() const;
-
-protected:
- virtual ~NuHTTPDataSource();
-
-private:
- enum State {
- DISCONNECTED,
- CONNECTING,
- CONNECTED
- };
-
- Mutex mLock;
-
- uint32_t mFlags;
-
- State mState;
-
- String8 mHost;
- unsigned mPort;
- String8 mPath;
- bool mHTTPS;
- String8 mHeaders;
- String8 mUri;
-
- HTTPStream mHTTP;
- off64_t mOffset;
- off64_t mContentLength;
- bool mContentLengthValid;
- bool mHasChunkedTransferEncoding;
-
- String8 mContentType;
-
- // The number of data bytes in the current chunk before any subsequent
- // chunk header (or -1 if no more chunks).
- ssize_t mChunkDataBytesLeft;
-
- sp<DecryptHandle> mDecryptHandle;
- DrmManagerClient *mDrmManagerClient;
-
- status_t connect(
- const char *uri, const String8 &headers, off64_t offset);
-
- status_t connect(
- const char *host, unsigned port, const char *path,
- bool https,
- const String8 &headers,
- off64_t offset);
-
- // Read up to "size" bytes of data, respect transfer encoding.
- ssize_t internalRead(void *data, size_t size);
-
- void applyTimeoutResponse();
-
- static void MakeFullHeaders(
- const KeyedVector<String8, String8> *overrides,
- String8 *headers);
-
- NuHTTPDataSource(const NuHTTPDataSource &);
- NuHTTPDataSource &operator=(const NuHTTPDataSource &);
-};
-
-} // namespace android
-
-#endif // NU_HTTP_DATA_SOURCE_H_
diff --git a/media/libstagefright/include/OMX.h b/media/libstagefright/include/OMX.h
index ec3e5fa..d54b1c1 100644
--- a/media/libstagefright/include/OMX.h
+++ b/media/libstagefright/include/OMX.h
@@ -121,6 +121,7 @@
virtual ~OMX();
private:
+ struct CallbackDispatcherThread;
struct CallbackDispatcher;
Mutex mLock;
diff --git a/media/libstagefright/omx/OMX.cpp b/media/libstagefright/omx/OMX.cpp
index d23aa3a..25f30d6 100644
--- a/media/libstagefright/omx/OMX.cpp
+++ b/media/libstagefright/omx/OMX.cpp
@@ -20,8 +20,6 @@
#include <dlfcn.h>
-#include <sys/prctl.h>
-
#include "../include/OMX.h"
#include "../include/OMXNodeInstance.h"
@@ -38,11 +36,32 @@
////////////////////////////////////////////////////////////////////////////////
+// This provides the underlying Thread used by CallbackDispatcher.
+// Note that deriving CallbackDispatcher from Thread does not work.
+
+struct OMX::CallbackDispatcherThread : public Thread {
+ CallbackDispatcherThread(CallbackDispatcher *dispatcher)
+ : mDispatcher(dispatcher) {
+ }
+
+private:
+ CallbackDispatcher *mDispatcher;
+
+ bool threadLoop();
+
+ CallbackDispatcherThread(const CallbackDispatcherThread &);
+ CallbackDispatcherThread &operator=(const CallbackDispatcherThread &);
+};
+
+////////////////////////////////////////////////////////////////////////////////
+
struct OMX::CallbackDispatcher : public RefBase {
CallbackDispatcher(OMXNodeInstance *owner);
void post(const omx_message &msg);
+ bool loop();
+
protected:
virtual ~CallbackDispatcher();
@@ -54,13 +73,10 @@
Condition mQueueChanged;
List<omx_message> mQueue;
- pthread_t mThread;
+ sp<CallbackDispatcherThread> mThread;
void dispatch(const omx_message &msg);
- static void *ThreadWrapper(void *me);
- void threadEntry();
-
CallbackDispatcher(const CallbackDispatcher &);
CallbackDispatcher &operator=(const CallbackDispatcher &);
};
@@ -68,13 +84,8 @@
OMX::CallbackDispatcher::CallbackDispatcher(OMXNodeInstance *owner)
: mOwner(owner),
mDone(false) {
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
-
- pthread_create(&mThread, &attr, ThreadWrapper, this);
-
- pthread_attr_destroy(&attr);
+ mThread = new CallbackDispatcherThread(this);
+ mThread->run("OMXCallbackDisp", ANDROID_PRIORITY_AUDIO);
}
OMX::CallbackDispatcher::~CallbackDispatcher() {
@@ -86,10 +97,8 @@
}
// Don't call join on myself
- CHECK(mThread != pthread_self());
-
- void *dummy;
- pthread_join(mThread, &dummy);
+ status_t status = mThread->join();
+ CHECK(status == NO_ERROR);
}
void OMX::CallbackDispatcher::post(const omx_message &msg) {
@@ -107,17 +116,7 @@
mOwner->onMessage(msg);
}
-// static
-void *OMX::CallbackDispatcher::ThreadWrapper(void *me) {
- static_cast<CallbackDispatcher *>(me)->threadEntry();
-
- return NULL;
-}
-
-void OMX::CallbackDispatcher::threadEntry() {
- androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
- prctl(PR_SET_NAME, (unsigned long)"OMXCallbackDisp", 0, 0, 0);
-
+bool OMX::CallbackDispatcher::loop() {
for (;;) {
omx_message msg;
@@ -137,6 +136,14 @@
dispatch(msg);
}
+
+ return false;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+bool OMX::CallbackDispatcherThread::threadLoop() {
+ return mDispatcher->loop();
}
////////////////////////////////////////////////////////////////////////////////
diff --git a/media/libstagefright/rtsp/ARTSPConnection.cpp b/media/libstagefright/rtsp/ARTSPConnection.cpp
index 072d6b2..b398c9d 100644
--- a/media/libstagefright/rtsp/ARTSPConnection.cpp
+++ b/media/libstagefright/rtsp/ARTSPConnection.cpp
@@ -34,7 +34,7 @@
#include <openssl/md5.h>
#include <sys/socket.h>
-#include "HTTPStream.h"
+#include "HTTPBase.h"
namespace android {
@@ -251,7 +251,7 @@
mSocket = socket(AF_INET, SOCK_STREAM, 0);
if (mUIDValid) {
- HTTPStream::RegisterSocketUser(mSocket, mUID);
+ HTTPBase::RegisterSocketUser(mSocket, mUID);
}
MakeSocketBlocking(mSocket, false);
diff --git a/media/libstagefright/rtsp/MyHandler.h b/media/libstagefright/rtsp/MyHandler.h
index 3188959..71d68f6 100644
--- a/media/libstagefright/rtsp/MyHandler.h
+++ b/media/libstagefright/rtsp/MyHandler.h
@@ -40,7 +40,7 @@
#include <sys/socket.h>
#include <netdb.h>
-#include "HTTPStream.h"
+#include "HTTPBase.h"
// If no access units are received within 5 secs, assume that the rtp
// stream has ended and signal end of stream.
@@ -1181,8 +1181,8 @@
&info->mRTPSocket, &info->mRTCPSocket, &rtpPort);
if (mUIDValid) {
- HTTPStream::RegisterSocketUser(info->mRTPSocket, mUID);
- HTTPStream::RegisterSocketUser(info->mRTCPSocket, mUID);
+ HTTPBase::RegisterSocketUser(info->mRTPSocket, mUID);
+ HTTPBase::RegisterSocketUser(info->mRTCPSocket, mUID);
}
request.append("Transport: RTP/AVP/UDP;unicast;client_port=");
diff --git a/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java b/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java
index 8ba235b..935f4ad 100644
--- a/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java
+++ b/policy/src/com/android/internal/policy/impl/KeyguardViewMediator.java
@@ -689,13 +689,11 @@
switch (simState) {
case ABSENT:
- case PERM_DISABLED:
// only force lock screen in case of missing sim if user hasn't
// gone through setup wizard
if (!mUpdateMonitor.isDeviceProvisioned()) {
if (!isShowing()) {
- if (DEBUG) Log.d(TAG, "INTENT_VALUE_ICC_ABSENT "
- + "or PERM_DISABLED and keygaurd isn't showing,"
+ if (DEBUG) Log.d(TAG, "ICC_ABSENT isn't showing,"
+ " we need to show the keyguard since the "
+ "device isn't provisioned yet.");
doKeyguard();
@@ -713,7 +711,17 @@
} else {
resetStateLocked();
}
-
+ break;
+ case PERM_DISABLED:
+ if (!isShowing()) {
+ if (DEBUG) Log.d(TAG, "PERM_DISABLED and "
+ + "keygaurd isn't showing.");
+ doKeyguard();
+ } else {
+ if (DEBUG) Log.d(TAG, "PERM_DISABLED, resetStateLocked to"
+ + "show permanently disabled message in lockscreen.");
+ resetStateLocked();
+ }
break;
case READY:
if (isShowing()) {
diff --git a/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java b/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
index 75e799c..e177565 100644
--- a/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
+++ b/policy/src/com/android/internal/policy/impl/PasswordUnlockScreen.java
@@ -75,6 +75,7 @@
private StatusView mStatusView;
private final boolean mUseSystemIME = true; // TODO: Make configurable
+ private boolean mResuming; // used to prevent poking the wakelock during onResume()
// To avoid accidental lockout due to events while the device in in the pocket, ignore
// any passwords with length less than or equal to this length.
@@ -185,7 +186,9 @@
}
public void afterTextChanged(Editable s) {
- mCallback.pokeWakelock();
+ if (!mResuming) {
+ mCallback.pokeWakelock();
+ }
}
});
}
@@ -208,6 +211,7 @@
/** {@inheritDoc} */
public void onResume() {
+ mResuming = true;
// reset status
mStatusView.resetStatusInfo(mUpdateMonitor, mLockPatternUtils);
@@ -222,6 +226,7 @@
if (deadline != 0) {
handleAttemptLockout(deadline);
}
+ mResuming = false;
}
/** {@inheritDoc} */
diff --git a/services/java/com/android/server/ConnectivityService.java b/services/java/com/android/server/ConnectivityService.java
index 41450d2..bf5deb7 100644
--- a/services/java/com/android/server/ConnectivityService.java
+++ b/services/java/com/android/server/ConnectivityService.java
@@ -33,7 +33,9 @@
import android.net.IConnectivityManager;
import android.net.INetworkPolicyListener;
import android.net.INetworkPolicyManager;
+import android.net.LinkAddress;
import android.net.LinkProperties;
+import android.net.LinkProperties.CompareAddressesResult;
import android.net.MobileDataStateTracker;
import android.net.NetworkConfig;
import android.net.NetworkInfo;
@@ -76,6 +78,8 @@
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
+import java.net.Inet4Address;
+import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
@@ -92,6 +96,7 @@
public class ConnectivityService extends IConnectivityManager.Stub {
private static final boolean DBG = true;
+ private static final boolean VDBG = true;
private static final String TAG = "ConnectivityService";
private static final boolean LOGD_RULES = false;
@@ -126,6 +131,11 @@
private NetworkStateTracker mNetTrackers[];
/**
+ * The link properties that define the current links
+ */
+ private LinkProperties mCurrentLinkProperties[];
+
+ /**
* A per Net list of the PID's that requested access to the net
* used both as a refcount and for per-PID DNS selection
*/
@@ -332,6 +342,7 @@
mNetTrackers = new NetworkStateTracker[
ConnectivityManager.MAX_NETWORK_TYPE+1];
+ mCurrentLinkProperties = new LinkProperties[ConnectivityManager.MAX_NETWORK_TYPE+1];
mNetworkPreference = getPersistedNetworkPreference();
@@ -468,6 +479,7 @@
mNetConfigs[netType].radio);
continue;
}
+ mCurrentLinkProperties[netType] = mNetTrackers[netType].getLinkProperties();
}
IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
@@ -1563,6 +1575,8 @@
* right routing table entries exist.
*/
private void handleConnectivityChange(int netType, boolean doReset) {
+ int resetMask = doReset ? NetworkUtils.RESET_ALL_ADDRESSES : 0;
+
/*
* If a non-default network is enabled, add the host routes that
* will allow it's DNS servers to be accessed.
@@ -1570,6 +1584,45 @@
handleDnsConfigurationChange(netType);
if (mNetTrackers[netType].getNetworkInfo().isConnected()) {
+ LinkProperties newLp = mNetTrackers[netType].getLinkProperties();
+ LinkProperties curLp = mCurrentLinkProperties[netType];
+ mCurrentLinkProperties[netType] = newLp;
+ if (VDBG) {
+ log("handleConnectivityChange: changed linkProperty[" + netType + "]:" +
+ " doReset=" + doReset + " resetMask=" + resetMask +
+ "\n curLp=" + curLp +
+ "\n newLp=" + newLp);
+ }
+
+ if (curLp.isIdenticalInterfaceName(newLp)) {
+ CompareAddressesResult car = curLp.compareAddresses(newLp);
+ if ((car.removed.size() != 0) || (car.added.size() != 0)) {
+ for (LinkAddress linkAddr : car.removed) {
+ if (linkAddr.getAddress() instanceof Inet4Address) {
+ resetMask |= NetworkUtils.RESET_IPV4_ADDRESSES;
+ }
+ if (linkAddr.getAddress() instanceof Inet6Address) {
+ resetMask |= NetworkUtils.RESET_IPV6_ADDRESSES;
+ }
+ }
+ if (DBG) {
+ log("handleConnectivityChange: addresses changed" +
+ " linkProperty[" + netType + "]:" + " resetMask=" + resetMask +
+ "\n car=" + car);
+ }
+ } else {
+ if (DBG) {
+ log("handleConnectivityChange: address are the same reset per doReset" +
+ " linkProperty[" + netType + "]:" +
+ " resetMask=" + resetMask);
+ }
+ }
+ } else {
+ resetMask = NetworkUtils.RESET_ALL_ADDRESSES;
+ log("handleConnectivityChange: interface not not equivalent reset both" +
+ " linkProperty[" + netType + "]:" +
+ " resetMask=" + resetMask);
+ }
if (mNetConfigs[netType].isDefault()) {
handleApplyDefaultProxy(netType);
addDefaultRoute(mNetTrackers[netType]);
@@ -1597,15 +1650,13 @@
}
}
- if (doReset) {
+ if (doReset || resetMask != 0) {
LinkProperties linkProperties = mNetTrackers[netType].getLinkProperties();
if (linkProperties != null) {
String iface = linkProperties.getInterfaceName();
if (TextUtils.isEmpty(iface) == false) {
- if (DBG) {
- log("resetConnections(" + iface + ", NetworkUtils.RESET_ALL_ADDRESSES)");
- }
- NetworkUtils.resetConnections(iface, NetworkUtils.RESET_ALL_ADDRESSES);
+ if (DBG) log("resetConnections(" + iface + ", " + resetMask + ")");
+ NetworkUtils.resetConnections(iface, resetMask);
}
}
}
@@ -2477,8 +2528,23 @@
* @hide
*/
@Override
- public void protectVpn(ParcelFileDescriptor socket) {
- mVpn.protect(socket, getDefaultInterface());
+ public boolean protectVpn(ParcelFileDescriptor socket) {
+ try {
+ int type = mActiveDefaultNetwork;
+ if (ConnectivityManager.isNetworkTypeValid(type)) {
+ mVpn.protect(socket, mNetTrackers[type].getLinkProperties().getInterfaceName());
+ return true;
+ }
+ } catch (Exception e) {
+ // ignore
+ } finally {
+ try {
+ socket.close();
+ } catch (Exception e) {
+ // ignore
+ }
+ }
+ return false;
}
/**
@@ -2526,19 +2592,6 @@
return mVpn.getLegacyVpnInfo();
}
- private String getDefaultInterface() {
- if (ConnectivityManager.isNetworkTypeValid(mActiveDefaultNetwork)) {
- NetworkStateTracker tracker = mNetTrackers[mActiveDefaultNetwork];
- if (tracker != null) {
- LinkProperties properties = tracker.getLinkProperties();
- if (properties != null) {
- return properties.getInterfaceName();
- }
- }
- }
- throw new IllegalStateException("No default interface");
- }
-
/**
* Callback for VPN subsystem. Currently VPN is not adapted to the service
* through NetworkStateTracker since it works differently. For example, it
diff --git a/services/java/com/android/server/LoadAverageService.java b/services/java/com/android/server/LoadAverageService.java
index da9fc99..e05b570 100644
--- a/services/java/com/android/server/LoadAverageService.java
+++ b/services/java/com/android/server/LoadAverageService.java
@@ -28,7 +28,6 @@
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
-import android.view.WindowManagerImpl;
public class LoadAverageService extends Service {
private View mView;
@@ -91,32 +90,46 @@
setPadding(4, 4, 4, 4);
//setBackgroundResource(com.android.internal.R.drawable.load_average_background);
+ // Need to scale text size by density... but we won't do it
+ // linearly, because with higher dps it is nice to squeeze the
+ // text a bit to fit more of it. And with lower dps, trying to
+ // go much smaller will result in unreadable text.
+ int textSize = 10;
+ float density = c.getResources().getDisplayMetrics().density;
+ if (density < 1) {
+ textSize = 9;
+ } else {
+ textSize = (int)(10*density);
+ if (textSize < 10) {
+ textSize = 10;
+ }
+ }
mLoadPaint = new Paint();
mLoadPaint.setAntiAlias(true);
- mLoadPaint.setTextSize(10);
+ mLoadPaint.setTextSize(textSize);
mLoadPaint.setARGB(255, 255, 255, 255);
mAddedPaint = new Paint();
mAddedPaint.setAntiAlias(true);
- mAddedPaint.setTextSize(10);
+ mAddedPaint.setTextSize(textSize);
mAddedPaint.setARGB(255, 128, 255, 128);
mRemovedPaint = new Paint();
mRemovedPaint.setAntiAlias(true);
mRemovedPaint.setStrikeThruText(true);
- mRemovedPaint.setTextSize(10);
+ mRemovedPaint.setTextSize(textSize);
mRemovedPaint.setARGB(255, 255, 128, 128);
mShadowPaint = new Paint();
mShadowPaint.setAntiAlias(true);
- mShadowPaint.setTextSize(10);
+ mShadowPaint.setTextSize(textSize);
//mShadowPaint.setFakeBoldText(true);
mShadowPaint.setARGB(192, 0, 0, 0);
mLoadPaint.setShadowLayer(4, 0, 0, 0xff000000);
mShadow2Paint = new Paint();
mShadow2Paint.setAntiAlias(true);
- mShadow2Paint.setTextSize(10);
+ mShadow2Paint.setTextSize(textSize);
//mShadow2Paint.setFakeBoldText(true);
mShadow2Paint.setARGB(192, 0, 0, 0);
mLoadPaint.setShadowLayer(2, 0, 0, 0xff000000);
@@ -153,14 +166,16 @@
}
@Override
- protected void onMeasure(int widthMeasureSpect, int heightMeasureSpec) {
- setMeasuredDimension(mNeededWidth, mNeededHeight);
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ setMeasuredDimension(resolveSize(mNeededWidth, widthMeasureSpec),
+ resolveSize(mNeededHeight, heightMeasureSpec));
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
- final int W = getWidth();
+ final int W = mNeededWidth;
+ final int RIGHT = getWidth()-1;
final Stats stats = mStats;
final int userTime = stats.getLastUserTime();
@@ -178,7 +193,7 @@
int systemW = (systemTime*W)/totalTime;
int irqW = ((iowaitTime+irqTime+softIrqTime)*W)/totalTime;
- int x = W - mPaddingRight;
+ int x = RIGHT - mPaddingRight;
int top = mPaddingTop + 2;
int bottom = mPaddingTop + mFH - 2;
@@ -196,15 +211,15 @@
}
int y = mPaddingTop - (int)mAscent;
- canvas.drawText(stats.mLoadText, W-mPaddingRight-stats.mLoadWidth-1,
+ canvas.drawText(stats.mLoadText, RIGHT-mPaddingRight-stats.mLoadWidth-1,
y-1, mShadowPaint);
- canvas.drawText(stats.mLoadText, W-mPaddingRight-stats.mLoadWidth-1,
+ canvas.drawText(stats.mLoadText, RIGHT-mPaddingRight-stats.mLoadWidth-1,
y+1, mShadowPaint);
- canvas.drawText(stats.mLoadText, W-mPaddingRight-stats.mLoadWidth+1,
+ canvas.drawText(stats.mLoadText, RIGHT-mPaddingRight-stats.mLoadWidth+1,
y-1, mShadow2Paint);
- canvas.drawText(stats.mLoadText, W-mPaddingRight-stats.mLoadWidth+1,
+ canvas.drawText(stats.mLoadText, RIGHT-mPaddingRight-stats.mLoadWidth+1,
y+1, mShadow2Paint);
- canvas.drawText(stats.mLoadText, W-mPaddingRight-stats.mLoadWidth,
+ canvas.drawText(stats.mLoadText, RIGHT-mPaddingRight-stats.mLoadWidth,
y, mLoadPaint);
int N = stats.countWorkingStats();
@@ -216,7 +231,7 @@
userW = (st.rel_utime*W)/totalTime;
systemW = (st.rel_stime*W)/totalTime;
- x = W - mPaddingRight;
+ x = RIGHT - mPaddingRight;
if (systemW > 0) {
canvas.drawRect(x-systemW, top, x, bottom, mSystemPaint);
x -= systemW;
@@ -226,18 +241,18 @@
x -= userW;
}
- canvas.drawText(st.name, W-mPaddingRight-st.nameWidth-1,
+ canvas.drawText(st.name, RIGHT-mPaddingRight-st.nameWidth-1,
y-1, mShadowPaint);
- canvas.drawText(st.name, W-mPaddingRight-st.nameWidth-1,
+ canvas.drawText(st.name, RIGHT-mPaddingRight-st.nameWidth-1,
y+1, mShadowPaint);
- canvas.drawText(st.name, W-mPaddingRight-st.nameWidth+1,
+ canvas.drawText(st.name, RIGHT-mPaddingRight-st.nameWidth+1,
y-1, mShadow2Paint);
- canvas.drawText(st.name, W-mPaddingRight-st.nameWidth+1,
+ canvas.drawText(st.name, RIGHT-mPaddingRight-st.nameWidth+1,
y+1, mShadow2Paint);
Paint p = mLoadPaint;
if (st.added) p = mAddedPaint;
if (st.removed) p = mRemovedPaint;
- canvas.drawText(st.name, W-mPaddingRight-st.nameWidth, y, p);
+ canvas.drawText(st.name, RIGHT-mPaddingRight-st.nameWidth, y, p);
}
}
@@ -270,7 +285,7 @@
super.onCreate();
mView = new LoadView(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
- WindowManager.LayoutParams.WRAP_CONTENT,
+ WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
diff --git a/services/java/com/android/server/am/ActivityManagerService.java b/services/java/com/android/server/am/ActivityManagerService.java
index 8501163..fd93bcf 100644
--- a/services/java/com/android/server/am/ActivityManagerService.java
+++ b/services/java/com/android/server/am/ActivityManagerService.java
@@ -45,7 +45,6 @@
import android.app.IProcessObserver;
import android.app.IServiceConnection;
import android.app.IThumbnailReceiver;
-import android.app.IThumbnailRetriever;
import android.app.Instrumentation;
import android.app.Notification;
import android.app.NotificationManager;
@@ -54,6 +53,7 @@
import android.app.backup.IBackupManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
+import android.content.ComponentCallbacks;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
@@ -181,22 +181,8 @@
// The flags that are set for all calls we make to the package manager.
static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
- private static final String SYSTEM_SECURE = "ro.secure";
private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
- // This is the maximum number of application processes we would like
- // to have running. Due to the asynchronous nature of things, we can
- // temporarily go beyond this limit.
- static final int MAX_PROCESSES = 2;
-
- // Set to false to leave processes running indefinitely, relying on
- // the kernel killing them as resources are required.
- static final boolean ENFORCE_PROCESS_LIMIT = false;
-
- // This is the maximum number of activities that we would like to have
- // running at a given time.
- static final int MAX_ACTIVITIES = 20;
-
// Maximum number of recent tasks that we can remember.
static final int MAX_RECENT_TASKS = 20;
@@ -914,7 +900,8 @@
*/
boolean mBooted = false;
- int mProcessLimit = 0;
+ int mProcessLimit = MAX_HIDDEN_APPS;
+ int mProcessLimitOverride = -1;
WindowManagerService mWindowManager;
@@ -2291,11 +2278,10 @@
}
synchronized (this) {
- int index = mMainStack.indexOfTokenLocked(callingActivity);
- if (index < 0) {
+ ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
+ if (r == null) {
return false;
}
- ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
if (r.app == null || r.app.thread == null) {
// The caller is not running... d'oh!
return false;
@@ -2442,11 +2428,10 @@
public void setRequestedOrientation(IBinder token,
int requestedOrientation) {
synchronized (this) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index < 0) {
+ ActivityRecord r = mMainStack.isInStackLocked(token);
+ if (r == null) {
return;
}
- ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
final long origId = Binder.clearCallingIdentity();
mWindowManager.setAppOrientation(r, requestedOrientation);
Configuration config = mWindowManager.updateOrientationFromAppTokens(
@@ -2464,11 +2449,10 @@
public int getRequestedOrientation(IBinder token) {
synchronized (this) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index < 0) {
+ ActivityRecord r = mMainStack.isInStackLocked(token);
+ if (r == null) {
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
}
- ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
return mWindowManager.getAppOrientation(r);
}
}
@@ -2609,11 +2593,10 @@
public final void finishSubActivity(IBinder token, String resultWho,
int requestCode) {
synchronized(this) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index < 0) {
+ ActivityRecord self = mMainStack.isInStackLocked(token);
+ if (self == null) {
return;
}
- ActivityRecord self = (ActivityRecord)mMainStack.mHistory.get(index);
final long origId = Binder.clearCallingIdentity();
@@ -2652,11 +2635,10 @@
public void overridePendingTransition(IBinder token, String packageName,
int enterAnim, int exitAnim) {
synchronized(this) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index < 0) {
+ ActivityRecord self = mMainStack.isInStackLocked(token);
+ if (self == null) {
return;
}
- ActivityRecord self = (ActivityRecord)mMainStack.mHistory.get(index);
final long origId = Binder.clearCallingIdentity();
@@ -2735,8 +2717,7 @@
}
}
- r.stack.cleanUpActivityLocked(r, true);
- r.state = ActivityState.STOPPED;
+ r.stack.cleanUpActivityLocked(r, true, true);
}
atTop = false;
}
@@ -3920,20 +3901,9 @@
final long origId = Binder.clearCallingIdentity();
synchronized (this) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index >= 0) {
- r = (ActivityRecord)mMainStack.mHistory.get(index);
- r.icicle = icicle;
- r.haveState = true;
- r.updateThumbnail(thumbnail, description);
- r.stopped = true;
- r.state = ActivityState.STOPPED;
- if (!r.finishing) {
- if (r.configDestroy) {
- r.stack.destroyActivityLocked(r, true);
- r.stack.resumeTopActivityLocked(null);
- }
- }
+ r = mMainStack.isInStackLocked(token);
+ if (r != null) {
+ r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
}
}
@@ -3966,35 +3936,30 @@
}
private ActivityRecord getCallingRecordLocked(IBinder token) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index >= 0) {
- ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
- if (r != null) {
- return r.resultTo;
- }
+ ActivityRecord r = mMainStack.isInStackLocked(token);
+ if (r == null) {
+ return null;
}
- return null;
+ return r.resultTo;
}
public ComponentName getActivityClassForToken(IBinder token) {
synchronized(this) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index >= 0) {
- ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
- return r.intent.getComponent();
+ ActivityRecord r = mMainStack.isInStackLocked(token);
+ if (r == null) {
+ return null;
}
- return null;
+ return r.intent.getComponent();
}
}
public String getPackageForToken(IBinder token) {
synchronized(this) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index >= 0) {
- ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
- return r.packageName;
+ ActivityRecord r = mMainStack.isInStackLocked(token);
+ if (r == null) {
+ return null;
}
- return null;
+ return r.packageName;
}
}
@@ -4057,11 +4022,10 @@
int requestCode, Intent[] intents, String[] resolvedTypes, int flags) {
ActivityRecord activity = null;
if (type == INTENT_SENDER_ACTIVITY_RESULT) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index < 0) {
+ activity = mMainStack.isInStackLocked(token);
+ if (activity == null) {
return null;
}
- activity = (ActivityRecord)mMainStack.mHistory.get(index);
if (activity.finishing) {
return null;
}
@@ -4183,11 +4147,17 @@
public void setProcessLimit(int max) {
enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
"setProcessLimit()");
- mProcessLimit = max;
+ synchronized (this) {
+ mProcessLimit = max < 0 ? MAX_HIDDEN_APPS : max;
+ mProcessLimitOverride = max;
+ }
+ trimApplications();
}
public int getProcessLimit() {
- return mProcessLimit;
+ synchronized (this) {
+ return mProcessLimitOverride;
+ }
}
void foregroundTokenDied(ForegroundToken token) {
@@ -5451,11 +5421,10 @@
synchronized(this) {
if (r == null) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index < 0) {
+ r = mMainStack.isInStackLocked(token);
+ if (r == null) {
return;
}
- r = (ActivityRecord)mMainStack.mHistory.get(index);
}
if (thumbnail == null && r.thumbHolder != null) {
thumbnail = r.thumbHolder.lastThumbnail;
@@ -6169,9 +6138,8 @@
final long origId = Binder.clearCallingIdentity();
synchronized (this) {
- int index = mMainStack.indexOfTokenLocked(token);
- if (index >= 0) {
- r = (ActivityRecord)mMainStack.mHistory.get(index);
+ r = mMainStack.isInStackLocked(token);
+ if (r != null) {
mMainStack.activitySleptLocked(r);
}
}
@@ -6322,22 +6290,20 @@
public void setImmersive(IBinder token, boolean immersive) {
synchronized(this) {
- int index = (token != null) ? mMainStack.indexOfTokenLocked(token) : -1;
- if (index < 0) {
+ ActivityRecord r = mMainStack.isInStackLocked(token);
+ if (r == null) {
throw new IllegalArgumentException();
}
- ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
r.immersive = immersive;
}
}
public boolean isImmersive(IBinder token) {
synchronized (this) {
- int index = (token != null) ? mMainStack.indexOfTokenLocked(token) : -1;
- if (index < 0) {
+ ActivityRecord r = mMainStack.isInStackLocked(token);
+ if (r == null) {
throw new IllegalArgumentException();
}
- ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(index);
return r.immersive;
}
}
@@ -8800,9 +8766,10 @@
} else {
foreground = " ";
}
- pw.println(String.format("%s%s #%2d: adj=%s/%s%s %s (%s)",
+ pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
prefix, (r.persistent ? persistentLabel : normalLabel),
- N-i, oomAdj, schedGroup, foreground, r.toShortString(), r.adjType));
+ N-i, oomAdj, schedGroup, foreground, r.trimMemoryLevel,
+ r.toShortString(), r.adjType));
if (r.adjSource != null || r.adjTarget != null) {
pw.print(prefix);
pw.print(" ");
@@ -10337,12 +10304,11 @@
ActivityRecord activity = null;
if (token != null) {
- int aindex = mMainStack.indexOfTokenLocked(token);
- if (aindex < 0) {
+ activity = mMainStack.isInStackLocked(token);
+ if (activity == null) {
Slog.w(TAG, "Binding with unknown activity: " + token);
return 0;
}
- activity = (ActivityRecord)mMainStack.mHistory.get(aindex);
}
int clientLabel = 0;
@@ -11556,8 +11522,8 @@
return false;
}
int state = r.state;
- r.state = r.IDLE;
- if (state == r.IDLE) {
+ r.state = BroadcastRecord.IDLE;
+ if (state == BroadcastRecord.IDLE) {
if (explicit) {
Slog.w(TAG, "finishReceiver called but state is IDLE");
}
@@ -12941,7 +12907,7 @@
ProcessRecord proc = mProcessesToGc.get(0);
Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
- long when = mProcessesToGc.get(0).lastRequestedGc + GC_MIN_INTERVAL;
+ long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
long now = SystemClock.uptimeMillis();
if (when < (now+GC_TIMEOUT)) {
when = now + GC_TIMEOUT;
@@ -13084,16 +13050,14 @@
}
}
- private final boolean updateOomAdjLocked(
+ private final void updateOomAdjLocked(
ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP) {
app.hiddenAdj = hiddenAdj;
if (app.thread == null) {
- return true;
+ return;
}
- boolean success = true;
-
final boolean wasKeeping = app.keeping;
int adj = computeOomAdjLocked(app, hiddenAdj, TOP_APP, false);
@@ -13129,10 +13093,10 @@
if (Process.setOomAdj(app.pid, adj)) {
if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
TAG, "Set app " + app.processName +
- " oom adj to " + adj);
+ " oom adj to " + adj + " because " + app.adjType);
app.setAdj = adj;
} else {
- success = false;
+ Slog.w(TAG, "Failed setting oom adj of " + app + " to " + adj);
}
}
if (app.setSchedGroup != app.curSchedGroup) {
@@ -13158,8 +13122,7 @@
} finally {
Binder.restoreCallingIdentity(oldId);
}
- }
- if (false) {
+ } else {
if (app.thread != null) {
try {
app.thread.setSchedulingGroup(app.curSchedGroup);
@@ -13169,8 +13132,6 @@
}
}
}
-
- return success;
}
private final ActivityRecord resumedAppLocked() {
@@ -13184,30 +13145,26 @@
return resumedActivity;
}
- private final boolean updateOomAdjLocked(ProcessRecord app) {
+ private final void updateOomAdjLocked(ProcessRecord app) {
final ActivityRecord TOP_ACT = resumedAppLocked();
final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
int curAdj = app.curAdj;
- final boolean wasHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
- && app.curAdj <= HIDDEN_APP_MAX_ADJ;
+ final boolean wasHidden = curAdj >= HIDDEN_APP_MIN_ADJ
+ && curAdj <= HIDDEN_APP_MAX_ADJ;
mAdjSeq++;
- final boolean res = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP);
- if (res) {
- final boolean nowHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
- && app.curAdj <= HIDDEN_APP_MAX_ADJ;
- if (nowHidden != wasHidden) {
- // Changed to/from hidden state, so apps after it in the LRU
- // list may also be changed.
- updateOomAdjLocked();
- }
+ updateOomAdjLocked(app, app.hiddenAdj, TOP_APP);
+ final boolean nowHidden = app.curAdj >= HIDDEN_APP_MIN_ADJ
+ && app.curAdj <= HIDDEN_APP_MAX_ADJ;
+ if (nowHidden != wasHidden) {
+ // Changed to/from hidden state, so apps after it in the LRU
+ // list may also be changed.
+ updateOomAdjLocked();
}
- return res;
}
- final boolean updateOomAdjLocked() {
- boolean didOomAdj = true;
+ final void updateOomAdjLocked() {
final ActivityRecord TOP_ACT = resumedAppLocked();
final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
@@ -13229,45 +13186,104 @@
int step = 0;
int numHidden = 0;
- // First try updating the OOM adjustment for each of the
+ // First update the OOM adjustment for each of the
// application processes based on their current state.
int i = mLruProcesses.size();
int curHiddenAdj = HIDDEN_APP_MIN_ADJ;
+ int numBg = 0;
while (i > 0) {
i--;
ProcessRecord app = mLruProcesses.get(i);
//Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
- if (updateOomAdjLocked(app, curHiddenAdj, TOP_APP)) {
- if (curHiddenAdj < EMPTY_APP_ADJ
- && app.curAdj == curHiddenAdj) {
- step++;
- if (step >= factor) {
- step = 0;
- curHiddenAdj++;
- }
+ updateOomAdjLocked(app, curHiddenAdj, TOP_APP);
+ if (curHiddenAdj < EMPTY_APP_ADJ
+ && app.curAdj == curHiddenAdj) {
+ step++;
+ if (step >= factor) {
+ step = 0;
+ curHiddenAdj++;
}
+ }
+ if (!app.killedBackground) {
if (app.curAdj >= HIDDEN_APP_MIN_ADJ) {
- if (!app.killedBackground) {
- numHidden++;
- if (numHidden > MAX_HIDDEN_APPS) {
- Slog.i(TAG, "No longer want " + app.processName
- + " (pid " + app.pid + "): hidden #" + numHidden);
- EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
- app.processName, app.setAdj, "too many background");
- app.killedBackground = true;
- Process.killProcessQuiet(app.pid);
- }
+ numHidden++;
+ if (numHidden > mProcessLimit) {
+ Slog.i(TAG, "No longer want " + app.processName
+ + " (pid " + app.pid + "): hidden #" + numHidden);
+ EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
+ app.processName, app.setAdj, "too many background");
+ app.killedBackground = true;
+ Process.killProcessQuiet(app.pid);
+ } else {
+ numBg++;
}
+ } else if (app.curAdj >= HOME_APP_ADJ) {
+ numBg++;
}
- } else {
- didOomAdj = false;
}
}
- // If we return false, we will fall back on killing processes to
- // have a fixed limit. Do this if a limit has been requested; else
- // only return false if one of the adjustments failed.
- return ENFORCE_PROCESS_LIMIT || mProcessLimit > 0 ? false : didOomAdj;
+ // Now determine the memory trimming level of background processes.
+ // Unfortunately we need to start at the back of the list to do this
+ // properly. We only do this if the number of background apps we
+ // are managing to keep around is less than half the maximum we desire;
+ // if we are keeping a good number around, we'll let them use whatever
+ // memory they want.
+ if (numHidden <= (MAX_HIDDEN_APPS/2)) {
+ final int N = mLruProcesses.size();
+ factor = numBg/3;
+ step = 0;
+ int curLevel = ComponentCallbacks.TRIM_MEMORY_COMPLETE;
+ for (i=0; i<N; i++) {
+ ProcessRecord app = mLruProcesses.get(i);
+ if (app.curAdj >= HIDDEN_APP_MIN_ADJ && !app.killedBackground) {
+ if (app.trimMemoryLevel < curLevel && app.thread != null) {
+ try {
+ app.thread.scheduleTrimMemory(curLevel);
+ } catch (RemoteException e) {
+ }
+ if (curLevel >= ComponentCallbacks.TRIM_MEMORY_COMPLETE) {
+ // For these apps we will also finish their activities
+ // to help them free memory.
+ mMainStack.destroyActivitiesLocked(app, false);
+ }
+ }
+ app.trimMemoryLevel = curLevel;
+ step++;
+ if (step >= factor) {
+ switch (curLevel) {
+ case ComponentCallbacks.TRIM_MEMORY_COMPLETE:
+ curLevel = ComponentCallbacks.TRIM_MEMORY_MODERATE;
+ break;
+ case ComponentCallbacks.TRIM_MEMORY_MODERATE:
+ curLevel = ComponentCallbacks.TRIM_MEMORY_BACKGROUND;
+ break;
+ }
+ }
+ } else if (app.curAdj >= PERCEPTIBLE_APP_ADJ) {
+ if (app.trimMemoryLevel < ComponentCallbacks.TRIM_MEMORY_INVISIBLE
+ && app.thread != null) {
+ try {
+ app.thread.scheduleTrimMemory(ComponentCallbacks.TRIM_MEMORY_INVISIBLE);
+ } catch (RemoteException e) {
+ }
+ }
+ app.trimMemoryLevel = ComponentCallbacks.TRIM_MEMORY_INVISIBLE;
+ } else {
+ app.trimMemoryLevel = 0;
+ }
+ }
+ } else {
+ final int N = mLruProcesses.size();
+ for (i=0; i<N; i++) {
+ ProcessRecord app = mLruProcesses.get(i);
+ app.trimMemoryLevel = 0;
+ }
+ }
+
+ if (mAlwaysFinishActivities) {
+ mMainStack.destroyActivitiesLocked(null, false);
+ }
}
final void trimApplications() {
@@ -13307,165 +13323,8 @@
}
}
- // Now try updating the OOM adjustment for each of the
- // application processes based on their current state.
- // If the setOomAdj() API is not supported, then go with our
- // back-up plan...
- if (!updateOomAdjLocked()) {
-
- // Count how many processes are running services.
- int numServiceProcs = 0;
- for (i=mLruProcesses.size()-1; i>=0; i--) {
- final ProcessRecord app = mLruProcesses.get(i);
-
- if (app.persistent || app.services.size() != 0
- || app.curReceiver != null) {
- // Don't count processes holding services against our
- // maximum process count.
- if (localLOGV) Slog.v(
- TAG, "Not trimming app " + app + " with services: "
- + app.services);
- numServiceProcs++;
- }
- }
-
- int curMaxProcs = mProcessLimit;
- if (curMaxProcs <= 0) curMaxProcs = MAX_PROCESSES;
- if (mAlwaysFinishActivities) {
- curMaxProcs = 1;
- }
- curMaxProcs += numServiceProcs;
-
- // Quit as many processes as we can to get down to the desired
- // process count. First remove any processes that no longer
- // have activites running in them.
- for ( i=0;
- i<mLruProcesses.size()
- && mLruProcesses.size() > curMaxProcs;
- i++) {
- final ProcessRecord app = mLruProcesses.get(i);
- // Quit an application only if it is not currently
- // running any activities.
- if (!app.persistent && app.activities.size() == 0
- && app.curReceiver == null && app.services.size() == 0) {
- Slog.i(
- TAG, "Exiting empty application process "
- + app.processName + " ("
- + (app.thread != null ? app.thread.asBinder() : null)
- + ")\n");
- if (app.pid > 0 && app.pid != MY_PID) {
- EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
- app.processName, app.setAdj, "empty");
- Process.killProcessQuiet(app.pid);
- } else {
- try {
- app.thread.scheduleExit();
- } catch (Exception e) {
- // Ignore exceptions.
- }
- }
- // todo: For now we assume the application is not buggy
- // or evil, and will quit as a result of our request.
- // Eventually we need to drive this off of the death
- // notification, and kill the process if it takes too long.
- cleanUpApplicationRecordLocked(app, false, i);
- i--;
- }
- }
-
- // If we still have too many processes, now from the least
- // recently used process we start finishing activities.
- if (false) Slog.v(
- TAG, "*** NOW HAVE " + mLruProcesses.size() +
- " of " + curMaxProcs + " processes");
- for ( i=0;
- i<mLruProcesses.size()
- && mLruProcesses.size() > curMaxProcs;
- i++) {
- final ProcessRecord app = mLruProcesses.get(i);
- // Quit the application only if we have a state saved for
- // all of its activities.
- boolean canQuit = !app.persistent && app.curReceiver == null
- && app.services.size() == 0;
- int NUMA = app.activities.size();
- int j;
- if (false) Slog.v(
- TAG, "Looking to quit " + app.processName);
- for (j=0; j<NUMA && canQuit; j++) {
- ActivityRecord r = app.activities.get(j);
- if (false) Slog.v(
- TAG, " " + r.intent.getComponent().flattenToShortString()
- + ": frozen=" + r.haveState + ", visible=" + r.visible);
- canQuit = (r.haveState || !r.stateNotNeeded)
- && !r.visible && r.stopped;
- }
- if (canQuit) {
- // Finish all of the activities, and then the app itself.
- for (j=0; j<NUMA; j++) {
- ActivityRecord r = app.activities.get(j);
- if (!r.finishing) {
- r.stack.destroyActivityLocked(r, false);
- }
- r.resultTo = null;
- }
- Slog.i(TAG, "Exiting application process "
- + app.processName + " ("
- + (app.thread != null ? app.thread.asBinder() : null)
- + ")\n");
- if (app.pid > 0 && app.pid != MY_PID) {
- EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
- app.processName, app.setAdj, "old background");
- Process.killProcessQuiet(app.pid);
- } else {
- try {
- app.thread.scheduleExit();
- } catch (Exception e) {
- // Ignore exceptions.
- }
- }
- // todo: For now we assume the application is not buggy
- // or evil, and will quit as a result of our request.
- // Eventually we need to drive this off of the death
- // notification, and kill the process if it takes too long.
- cleanUpApplicationRecordLocked(app, false, i);
- i--;
- //dump();
- }
- }
-
- }
-
- int curMaxActivities = MAX_ACTIVITIES;
- if (mAlwaysFinishActivities) {
- curMaxActivities = 1;
- }
-
- // Finally, if there are too many activities now running, try to
- // finish as many as we can to get back down to the limit.
- for ( i=0;
- i<mMainStack.mLRUActivities.size()
- && mMainStack.mLRUActivities.size() > curMaxActivities;
- i++) {
- final ActivityRecord r
- = (ActivityRecord)mMainStack.mLRUActivities.get(i);
-
- // We can finish this one if we have its icicle saved and
- // it is not persistent.
- if ((r.haveState || !r.stateNotNeeded) && !r.visible
- && r.stopped && !r.finishing) {
- final int origSize = mMainStack.mLRUActivities.size();
- r.stack.destroyActivityLocked(r, true);
-
- // This will remove it from the LRU list, so keep
- // our index at the same value. Note that this check to
- // see if the size changes is just paranoia -- if
- // something unexpected happens, we don't want to end up
- // in an infinite loop.
- if (origSize > mMainStack.mLRUActivities.size()) {
- i--;
- }
- }
- }
+ // Now update the oom adj for all processes.
+ updateOomAdjLocked();
}
}
diff --git a/services/java/com/android/server/am/ActivityStack.java b/services/java/com/android/server/am/ActivityStack.java
index b1da69f..93d8164 100644
--- a/services/java/com/android/server/am/ActivityStack.java
+++ b/services/java/com/android/server/am/ActivityStack.java
@@ -52,6 +52,7 @@
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Binder;
+import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
@@ -83,6 +84,8 @@
static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
+ static final boolean DEBUG_STATES = false;
+
static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
// How long we wait until giving up on the last activity telling us it
@@ -392,19 +395,25 @@
}
final int indexOfTokenLocked(IBinder token) {
- int count = mHistory.size();
-
- // convert the token to an entry in the history.
- int index = -1;
- for (int i=count-1; i>=0; i--) {
- Object o = mHistory.get(i);
- if (o == token) {
- index = i;
- break;
- }
+ try {
+ ActivityRecord r = (ActivityRecord)token;
+ return mHistory.indexOf(r);
+ } catch (ClassCastException e) {
+ Slog.w(TAG, "Bad activity token: " + token, e);
+ return -1;
}
+ }
- return index;
+ final ActivityRecord isInStackLocked(IBinder token) {
+ try {
+ ActivityRecord r = (ActivityRecord)token;
+ if (mHistory.contains(r)) {
+ return r;
+ }
+ } catch (ClassCastException e) {
+ Slog.w(TAG, "Bad activity token: " + token, e);
+ }
+ return null;
}
private final boolean updateLRUListLocked(ActivityRecord r) {
@@ -604,6 +613,8 @@
// As part of the process of launching, ActivityThread also performs
// a resume.
r.state = ActivityState.RESUMED;
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
+ + " (starting new instance)");
r.stopped = false;
mResumedActivity = r;
r.task.touchActiveTime();
@@ -617,6 +628,8 @@
// should look like we asked it to pause+stop (but remain visible),
// and it has done so and reported back the current icicle and
// other state.
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
+ + " (starting in stopped state)");
r.state = ActivityState.STOPPED;
r.stopped = true;
}
@@ -797,7 +810,8 @@
resumeTopActivityLocked(null);
return;
}
- if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
+ else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
mResumedActivity = null;
mPausingActivity = prev;
mLastPausedActivity = prev;
@@ -879,6 +893,8 @@
r = mHistory.get(index);
mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
if (mPausingActivity == r) {
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
+ + (timeout ? " (due to timeout)" : " (pause complete)"));
r.state = ActivityState.PAUSED;
completePauseLocked();
} else {
@@ -891,6 +907,22 @@
}
}
+ final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
+ CharSequence description) {
+ r.icicle = icicle;
+ r.haveState = true;
+ r.updateThumbnail(thumbnail, description);
+ r.stopped = true;
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
+ r.state = ActivityState.STOPPED;
+ if (!r.finishing) {
+ if (r.configDestroy) {
+ destroyActivityLocked(r, true, false);
+ resumeTopActivityLocked(null);
+ }
+ }
+ }
+
private final void completePauseLocked() {
ActivityRecord prev = mPausingActivity;
if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
@@ -914,7 +946,7 @@
// instance right now, we need to first completely stop
// the current instance before starting the new one.
if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
- destroyActivityLocked(prev, true);
+ destroyActivityLocked(prev, true, false);
} else {
mStoppingActivities.add(prev);
if (mStoppingActivities.size() > 3) {
@@ -1371,6 +1403,7 @@
mService.updateCpuStats();
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
next.state = ActivityState.RESUMED;
mResumedActivity = next;
next.task.touchActiveTime();
@@ -1447,6 +1480,8 @@
} catch (Exception e) {
// Whoops, need to restart this activity!
+ if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
+ + lastState + ": " + next);
next.state = lastState;
mResumedActivity = lastResumedActivity;
Slog.i(TAG, "Restarting because process died: " + next);
@@ -2960,6 +2995,8 @@
r.resumeKeyDispatchingLocked();
try {
r.stopped = false;
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
+ + " (stop requested)");
r.state = ActivityState.STOPPING;
if (DEBUG_VISBILITY) Slog.v(
TAG, "Stopping visible=" + r.visible + " for " + r);
@@ -2977,9 +3014,10 @@
Slog.w(TAG, "Exception thrown during pause", e);
// Just in case, assume it to be stopped.
r.stopped = true;
+ if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
r.state = ActivityState.STOPPED;
if (r.configDestroy) {
- destroyActivityLocked(r, true);
+ destroyActivityLocked(r, true, false);
}
}
}
@@ -3145,7 +3183,7 @@
for (i=0; i<NF; i++) {
ActivityRecord r = (ActivityRecord)finishes.get(i);
synchronized (mService) {
- destroyActivityLocked(r, true);
+ destroyActivityLocked(r, true, false);
}
}
@@ -3340,6 +3378,8 @@
checkReadyForSleepLocked();
}
}
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
+ + " (finish requested)");
r.state = ActivityState.STOPPING;
mService.updateOomAdjLocked();
return r;
@@ -3353,6 +3393,7 @@
mResumedActivity = null;
}
final ActivityState prevState = r.state;
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
r.state = ActivityState.FINISHING;
if (mode == FINISH_IMMEDIATELY
@@ -3360,7 +3401,7 @@
|| prevState == ActivityState.INITIALIZING) {
// If this activity is already stopped, we can just finish
// it right now.
- return destroyActivityLocked(r, true) ? null : r;
+ return destroyActivityLocked(r, true, true) ? null : r;
} else {
// Need to go through the full pause cycle to get this
// activity into the stopped state and then finish it.
@@ -3378,7 +3419,8 @@
* processing going away, in which case there is no remaining client-side
* state to destroy so only the cleanup here is needed.
*/
- final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices) {
+ final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
+ boolean setState) {
if (mResumedActivity == r) {
mResumedActivity = null;
}
@@ -3389,6 +3431,11 @@
r.configDestroy = false;
r.frozenBeforeDestroy = false;
+ if (setState) {
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
+ r.state = ActivityState.DESTROYED;
+ }
+
// Make sure this record is no longer in the pending finishes list.
// This could happen, for example, if we are trimming activities
// down to the max limit while they are still waiting to finish.
@@ -3428,6 +3475,8 @@
r.makeFinishing();
mHistory.remove(r);
r.takeFromHistory();
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
+ + " (removed from history)");
r.state = ActivityState.DESTROYED;
mService.mWindowManager.removeAppToken(r);
if (VALIDATE_TOKENS) {
@@ -3453,6 +3502,22 @@
}
}
+ final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj) {
+ for (int i=mHistory.size()-1; i>=0; i--) {
+ ActivityRecord r = mHistory.get(i);
+ if (owner != null && r.app != owner) {
+ continue;
+ }
+ // We can destroy this one if we have its icicle saved and
+ // it is not in the process of pausing/stopping/finishing.
+ if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
+ && r.state != ActivityState.DESTROYING
+ && r.state != ActivityState.DESTROYED) {
+ destroyActivityLocked(r, true, oomAdj);
+ }
+ }
+ }
+
/**
* Destroy the current CLIENT SIDE instance of an activity. This may be
* called both when actually finishing an activity, or when performing
@@ -3460,7 +3525,7 @@
* but then create a new client-side object for this same HistoryRecord.
*/
final boolean destroyActivityLocked(ActivityRecord r,
- boolean removeFromApp) {
+ boolean removeFromApp, boolean oomAdj) {
if (DEBUG_SWITCH) Slog.v(
TAG, "Removing activity: token=" + r
+ ", app=" + (r.app != null ? r.app.processName : "(null)"));
@@ -3470,7 +3535,7 @@
boolean removedFromHistory = false;
- cleanUpActivityLocked(r, false);
+ cleanUpActivityLocked(r, false, false);
final boolean hadApp = r.app != null;
@@ -3488,7 +3553,7 @@
if (r.app.activities.size() == 0) {
// No longer have activities, so update location in
// LRU list.
- mService.updateLruProcessLocked(r.app, true, false);
+ mService.updateLruProcessLocked(r.app, oomAdj, false);
}
}
@@ -3513,12 +3578,23 @@
r.app = null;
r.nowVisible = false;
+ // If the activity is finishing, we need to wait on removing it
+ // from the list to give it a chance to do its cleanup. During
+ // that time it may make calls back with its token so we need to
+ // be able to find it on the list and so we don't want to remove
+ // it from the list yet. Otherwise, we can just immediately put
+ // it in the destroyed state since we are not removing it from the
+ // list.
if (r.finishing && !skipDestroy) {
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
+ + " (destroy requested)");
r.state = ActivityState.DESTROYING;
Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
msg.obj = r;
mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
} else {
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
+ + " (destroy skipped)");
r.state = ActivityState.DESTROYED;
}
} else {
@@ -3527,6 +3603,8 @@
removeActivityFromHistoryLocked(r);
removedFromHistory = true;
} else {
+ if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
+ + " (no app)");
r.state = ActivityState.DESTROYED;
}
}
@@ -3919,7 +3997,7 @@
if (r.app == null || r.app.thread == null) {
if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
"Switch is destroying non-running " + r);
- destroyActivityLocked(r, true);
+ destroyActivityLocked(r, true, false);
} else if (r.state == ActivityState.PAUSING) {
// A little annoying: we are waiting for this activity to
// finish pausing. Let's not do anything now, but just
diff --git a/services/java/com/android/server/am/ProcessRecord.java b/services/java/com/android/server/am/ProcessRecord.java
index da83e7d..99830f9 100644
--- a/services/java/com/android/server/am/ProcessRecord.java
+++ b/services/java/com/android/server/am/ProcessRecord.java
@@ -61,6 +61,7 @@
int setAdj; // Last set OOM adjustment for this process
int curSchedGroup; // Currently desired scheduling class
int setSchedGroup; // Last set to background scheduling class
+ int trimMemoryLevel; // Last selected memory trimming level
boolean keeping; // Actively running code so don't kill due to that?
boolean setIsForeground; // Running foreground UI when last set?
boolean foregroundServices; // Running any services that are foreground?
@@ -181,7 +182,8 @@
pw.print(" cur="); pw.print(curAdj);
pw.print(" set="); pw.println(setAdj);
pw.print(prefix); pw.print("curSchedGroup="); pw.print(curSchedGroup);
- pw.print(" setSchedGroup="); pw.println(setSchedGroup);
+ pw.print(" setSchedGroup="); pw.print(setSchedGroup);
+ pw.print(" trimMemoryLevel="); pw.println(trimMemoryLevel);
pw.print(prefix); pw.print("setIsForeground="); pw.print(setIsForeground);
pw.print(" foregroundServices="); pw.print(foregroundServices);
pw.print(" forcingToForeground="); pw.println(forcingToForeground);
@@ -305,8 +307,6 @@
}
void toShortString(StringBuilder sb) {
- sb.append(Integer.toHexString(System.identityHashCode(this)));
- sb.append(' ');
sb.append(pid);
sb.append(':');
sb.append(processName);
@@ -320,6 +320,8 @@
}
StringBuilder sb = new StringBuilder(128);
sb.append("ProcessRecord{");
+ sb.append(Integer.toHexString(System.identityHashCode(this)));
+ sb.append(' ');
toShortString(sb);
sb.append('}');
return stringName = sb.toString();
diff --git a/services/java/com/android/server/connectivity/Vpn.java b/services/java/com/android/server/connectivity/Vpn.java
index c185012..9fb9349 100644
--- a/services/java/com/android/server/connectivity/Vpn.java
+++ b/services/java/com/android/server/connectivity/Vpn.java
@@ -41,6 +41,9 @@
import com.android.internal.net.VpnConfig;
import com.android.server.ConnectivityService.VpnCallback;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charsets;
import java.util.Arrays;
@@ -67,22 +70,14 @@
/**
* Protect a socket from routing changes by binding it to the given
- * interface. The socket IS closed by this method.
+ * interface. The socket is NOT closed by this method.
*
* @param socket The socket to be bound.
* @param name The name of the interface.
*/
public void protect(ParcelFileDescriptor socket, String interfaze) {
- try {
- mContext.enforceCallingPermission(VPN, "protect");
- jniProtect(socket.getFd(), interfaze);
- } finally {
- try {
- socket.close();
- } catch (Exception e) {
- // ignore
- }
- }
+ mContext.enforceCallingPermission(VPN, "protect");
+ jniProtect(socket.getFd(), interfaze);
}
/**
@@ -192,10 +187,15 @@
}
// Configure the interface. Abort if any of these steps fails.
- ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(
- jniConfigure(config.mtu, config.addresses, config.routes));
+ ParcelFileDescriptor tun = ParcelFileDescriptor.adoptFd(jniCreate(config.mtu));
try {
String interfaze = jniGetName(tun.getFd());
+ if (jniSetAddresses(interfaze, config.addresses) < 1) {
+ throw new IllegalArgumentException("At least one address must be specified");
+ }
+ if (config.routes != null) {
+ jniSetRoutes(interfaze, config.routes);
+ }
if (mInterface != null && !mInterface.equals(interfaze)) {
jniReset(mInterface);
}
@@ -279,8 +279,10 @@
}
}
- private native int jniConfigure(int mtu, String addresses, String routes);
+ private native int jniCreate(int mtu);
private native String jniGetName(int tun);
+ private native int jniSetAddresses(String interfaze, String addresses);
+ private native int jniSetRoutes(String interfaze, String routes);
private native void jniReset(String interfaze);
private native int jniCheck(String interfaze);
private native void jniProtect(int socket, String interfaze);
@@ -323,7 +325,6 @@
*/
private class LegacyVpnRunner extends Thread {
private static final String TAG = "LegacyVpnRunner";
- private static final String NONE = "--";
private final VpnConfig mConfig;
private final String[] mDaemons;
@@ -346,10 +347,10 @@
public void exit() {
// We assume that everything is reset after the daemons die.
+ interrupt();
for (String daemon : mDaemons) {
SystemProperties.set("ctl.stop", daemon);
}
- interrupt();
}
public LegacyVpnInfo getInfo() {
@@ -380,7 +381,7 @@
Thread.sleep(yield ? 200 : 1);
} else {
mInfo.state = LegacyVpnInfo.STATE_TIMEOUT;
- throw new IllegalStateException("time is up");
+ throw new IllegalStateException("Time is up");
}
}
@@ -404,12 +405,11 @@
}
}
- // Reset the properties.
- SystemProperties.set("vpn.dns", NONE);
- SystemProperties.set("vpn.via", NONE);
- while (!NONE.equals(SystemProperties.get("vpn.dns")) ||
- !NONE.equals(SystemProperties.get("vpn.via"))) {
- checkpoint(true);
+ // Clear the previous state.
+ File state = new File("/data/misc/vpn/state");
+ state.delete();
+ if (state.exists()) {
+ throw new IllegalStateException("Cannot delete the state");
}
// Check if we need to restart any of the daemons.
@@ -461,29 +461,34 @@
OutputStream out = socket.getOutputStream();
for (String argument : arguments) {
byte[] bytes = argument.getBytes(Charsets.UTF_8);
- if (bytes.length >= 0xFFFF) {
- throw new IllegalArgumentException("argument is too large");
+ if (bytes.length > 0xFFFF) {
+ throw new IllegalArgumentException("Argument is too large");
}
out.write(bytes.length >> 8);
out.write(bytes.length);
out.write(bytes);
checkpoint(false);
}
-
- // Send End-Of-Arguments.
- out.write(0xFF);
- out.write(0xFF);
out.flush();
+ socket.shutdownOutput();
+
+ // Wait for End-of-File.
+ InputStream in = socket.getInputStream();
+ while (true) {
+ try {
+ if (in.read() == -1) {
+ break;
+ }
+ } catch (Exception e) {
+ // ignore
+ }
+ checkpoint(true);
+ }
socket.close();
}
- // Now here is the beast from the old days. We check few
- // properties to figure out the current status. Ideally we
- // can read things back from the sockets and get rid of the
- // properties, but we have no time...
- while (NONE.equals(SystemProperties.get("vpn.dns")) ||
- NONE.equals(SystemProperties.get("vpn.via"))) {
-
+ // Wait for the daemons to create the new state.
+ while (!state.exists()) {
// Check if a running daemon is dead.
for (int i = 0; i < mDaemons.length; ++i) {
String daemon = mDaemons[i];
@@ -495,20 +500,45 @@
checkpoint(true);
}
- // Now we are connected. Get the interface.
- mConfig.interfaze = SystemProperties.get("vpn.via");
+ // Now we are connected. Read and parse the new state.
+ byte[] buffer = new byte[(int) state.length()];
+ if (new FileInputStream(state).read(buffer) != buffer.length) {
+ throw new IllegalStateException("Cannot read the state");
+ }
+ String[] parameters = new String(buffer, Charsets.UTF_8).split("\n", -1);
+ if (parameters.length != 6) {
+ throw new IllegalStateException("Cannot parse the state");
+ }
- // Get the DNS servers if they are not set in config.
+ // Set the interface and the addresses in the config.
+ mConfig.interfaze = parameters[0].trim();
+ mConfig.addresses = parameters[1].trim();
+
+ // Set the routes if they are not set in the config.
+ if (mConfig.routes == null || mConfig.routes.isEmpty()) {
+ mConfig.routes = parameters[2].trim();
+ }
+
+ // Set the DNS servers if they are not set in the config.
if (mConfig.dnsServers == null || mConfig.dnsServers.size() == 0) {
- String dnsServers = SystemProperties.get("vpn.dns").trim();
+ String dnsServers = parameters[3].trim();
if (!dnsServers.isEmpty()) {
mConfig.dnsServers = Arrays.asList(dnsServers.split(" "));
}
}
- // TODO: support search domains from ISAKMP mode config.
+ // Set the search domains if they are not set in the config.
+ if (mConfig.searchDomains == null || mConfig.searchDomains.size() == 0) {
+ String searchDomains = parameters[4].trim();
+ if (!searchDomains.isEmpty()) {
+ mConfig.searchDomains = Arrays.asList(searchDomains.split(" "));
+ }
+ }
- // The final step must be synchronized.
+ // Set the routes.
+ jniSetRoutes(mConfig.interfaze, mConfig.routes);
+
+ // Here is the last step and it must be done synchronously.
synchronized (Vpn.this) {
// Check if the thread is interrupted while we are waiting.
checkpoint(false);
diff --git a/services/jni/com_android_server_connectivity_Vpn.cpp b/services/jni/com_android_server_connectivity_Vpn.cpp
index 5f920f1..d28a6b4 100644
--- a/services/jni/com_android_server_connectivity_Vpn.cpp
+++ b/services/jni/com_android_server_connectivity_Vpn.cpp
@@ -18,7 +18,6 @@
#define LOG_TAG "VpnJni"
#include <cutils/log.h>
-#include <cutils/properties.h>
#include <stdio.h>
#include <string.h>
@@ -54,7 +53,7 @@
#define SYSTEM_ERROR -1
#define BAD_ARGUMENT -2
-static int create_interface(char *name, int *index, int mtu)
+static int create_interface(int mtu)
{
int tun = open("/dev/tun", O_RDWR | O_NONBLOCK);
@@ -82,14 +81,6 @@
goto error;
}
- // Get interface index.
- if (ioctl(inet4, SIOGIFINDEX, &ifr4)) {
- LOGE("Cannot get index of %s: %s", ifr4.ifr_name, strerror(errno));
- goto error;
- }
-
- strncpy(name, ifr4.ifr_name, IFNAMSIZ);
- *index = ifr4.ifr_ifindex;
return tun;
error:
@@ -97,12 +88,40 @@
return SYSTEM_ERROR;
}
-static int set_addresses(const char *name, int index, const char *addresses)
+static int get_interface_name(char *name, int tun)
{
ifreq ifr4;
+ if (ioctl(tun, TUNGETIFF, &ifr4)) {
+ LOGE("Cannot get interface name: %s", strerror(errno));
+ return SYSTEM_ERROR;
+ }
+ strncpy(name, ifr4.ifr_name, IFNAMSIZ);
+ return 0;
+}
+
+static int get_interface_index(const char *name)
+{
+ ifreq ifr4;
+ strncpy(ifr4.ifr_name, name, IFNAMSIZ);
+ if (ioctl(inet4, SIOGIFINDEX, &ifr4)) {
+ LOGE("Cannot get index of %s: %s", name, strerror(errno));
+ return SYSTEM_ERROR;
+ }
+ return ifr4.ifr_ifindex;
+}
+
+static int set_addresses(const char *name, const char *addresses)
+{
+ int index = get_interface_index(name);
+ if (index < 0) {
+ return index;
+ }
+
+ ifreq ifr4;
memset(&ifr4, 0, sizeof(ifr4));
strncpy(ifr4.ifr_name, name, IFNAMSIZ);
ifr4.ifr_addr.sa_family = AF_INET;
+ ifr4.ifr_netmask.sa_family = AF_INET;
in6_ifreq ifr6;
memset(&ifr6, 0, sizeof(ifr6));
@@ -146,7 +165,7 @@
}
in_addr_t mask = prefix ? (~0 << (32 - prefix)) : 0;
- *as_in_addr(&ifr4.ifr_addr) = htonl(mask);
+ *as_in_addr(&ifr4.ifr_netmask) = htonl(mask);
if (ioctl(inet4, SIOCSIFNETMASK, &ifr4)) {
count = (errno == EINVAL) ? BAD_ARGUMENT : SYSTEM_ERROR;
break;
@@ -168,8 +187,13 @@
return count;
}
-static int set_routes(const char *name, int index, const char *routes)
+static int set_routes(const char *name, const char *routes)
{
+ int index = get_interface_index(name);
+ if (index < 0) {
+ return index;
+ }
+
rtentry rt4;
memset(&rt4, 0, sizeof(rt4));
rt4.rt_dev = (char *)name;
@@ -253,17 +277,6 @@
return count;
}
-static int get_interface_name(char *name, int tun)
-{
- ifreq ifr4;
- if (ioctl(tun, TUNGETIFF, &ifr4)) {
- LOGE("Cannot get interface name: %s", strerror(errno));
- return SYSTEM_ERROR;
- }
- strncpy(name, ifr4.ifr_name, IFNAMSIZ);
- return 0;
-}
-
static int reset_interface(const char *name)
{
ifreq ifr4;
@@ -309,53 +322,14 @@
}
}
-static jint configure(JNIEnv *env, jobject thiz,
- jint mtu, jstring jAddresses, jstring jRoutes)
+static jint create(JNIEnv *env, jobject thiz, jint mtu)
{
- char name[IFNAMSIZ];
- int index;
- int tun = create_interface(name, &index, mtu);
+ int tun = create_interface(mtu);
if (tun < 0) {
throwException(env, tun, "Cannot create interface");
return -1;
}
-
- const char *addresses = NULL;
- const char *routes = NULL;
- int count;
-
- // At least one address must be set.
- addresses = jAddresses ? env->GetStringUTFChars(jAddresses, NULL) : NULL;
- if (!addresses) {
- jniThrowNullPointerException(env, "address");
- goto error;
- }
- count = set_addresses(name, index, addresses);
- env->ReleaseStringUTFChars(jAddresses, addresses);
- if (count <= 0) {
- throwException(env, count, "Cannot set address");
- goto error;
- }
- LOGD("Configured %d address(es) on %s", count, name);
-
- // On the contrary, routes are optional.
- routes = jRoutes ? env->GetStringUTFChars(jRoutes, NULL) : NULL;
- if (routes) {
- count = set_routes(name, index, routes);
- env->ReleaseStringUTFChars(jRoutes, routes);
- if (count < 0) {
- throwException(env, count, "Cannot set route");
- goto error;
- }
- LOGD("Configured %d route(s) on %s", count, name);
- }
-
return tun;
-
-error:
- close(tun);
- LOGD("%s is destroyed", name);
- return -1;
}
static jstring getName(JNIEnv *env, jobject thiz, jint tun)
@@ -368,6 +342,72 @@
return env->NewStringUTF(name);
}
+static jint setAddresses(JNIEnv *env, jobject thiz, jstring jName,
+ jstring jAddresses)
+{
+ const char *name = NULL;
+ const char *addresses = NULL;
+ int count = -1;
+
+ name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
+ if (!name) {
+ jniThrowNullPointerException(env, "name");
+ goto error;
+ }
+ addresses = jAddresses ? env->GetStringUTFChars(jAddresses, NULL) : NULL;
+ if (!addresses) {
+ jniThrowNullPointerException(env, "addresses");
+ goto error;
+ }
+ count = set_addresses(name, addresses);
+ if (count < 0) {
+ throwException(env, count, "Cannot set address");
+ count = -1;
+ }
+
+error:
+ if (name) {
+ env->ReleaseStringUTFChars(jName, name);
+ }
+ if (addresses) {
+ env->ReleaseStringUTFChars(jAddresses, addresses);
+ }
+ return count;
+}
+
+static jint setRoutes(JNIEnv *env, jobject thiz, jstring jName,
+ jstring jRoutes)
+{
+ const char *name = NULL;
+ const char *routes = NULL;
+ int count = -1;
+
+ name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
+ if (!name) {
+ jniThrowNullPointerException(env, "name");
+ goto error;
+ }
+ routes = jRoutes ? env->GetStringUTFChars(jRoutes, NULL) : NULL;
+ if (!routes) {
+ jniThrowNullPointerException(env, "routes");
+ goto error;
+ }
+ count = set_routes(name, routes);
+ if (count < 0) {
+ throwException(env, count, "Cannot set route");
+ count = -1;
+ }
+
+error:
+ if (name) {
+ env->ReleaseStringUTFChars(jName, name);
+ }
+ if (routes) {
+ env->ReleaseStringUTFChars(jRoutes, routes);
+ }
+ return count;
+}
+
static void reset(JNIEnv *env, jobject thiz, jstring jName)
{
const char *name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
@@ -409,8 +449,10 @@
//------------------------------------------------------------------------------
static JNINativeMethod gMethods[] = {
- {"jniConfigure", "(ILjava/lang/String;Ljava/lang/String;)I", (void *)configure},
+ {"jniCreate", "(I)I", (void *)create},
{"jniGetName", "(I)Ljava/lang/String;", (void *)getName},
+ {"jniSetAddresses", "(Ljava/lang/String;Ljava/lang/String;)I", (void *)setAddresses},
+ {"jniSetRoutes", "(Ljava/lang/String;Ljava/lang/String;)I", (void *)setRoutes},
{"jniReset", "(Ljava/lang/String;)V", (void *)reset},
{"jniCheck", "(Ljava/lang/String;)I", (void *)check},
{"jniProtect", "(ILjava/lang/String;)V", (void *)protect},
diff --git a/telephony/java/com/android/internal/telephony/DataCallState.java b/telephony/java/com/android/internal/telephony/DataCallState.java
index fba3184..a69ce8b 100644
--- a/telephony/java/com/android/internal/telephony/DataCallState.java
+++ b/telephony/java/com/android/internal/telephony/DataCallState.java
@@ -52,7 +52,7 @@
/**
* Class returned by onSetupConnectionCompleted.
*/
- protected enum SetupResult {
+ public enum SetupResult {
SUCCESS,
ERR_BadCommand,
ERR_UnacceptableParameter,
diff --git a/telephony/java/com/android/internal/telephony/DataConnection.java b/telephony/java/com/android/internal/telephony/DataConnection.java
index 5c84fdc..1bba8e3 100644
--- a/telephony/java/com/android/internal/telephony/DataConnection.java
+++ b/telephony/java/com/android/internal/telephony/DataConnection.java
@@ -17,30 +17,25 @@
package com.android.internal.telephony;
+import com.android.internal.telephony.DataCallState.SetupResult;
import com.android.internal.util.AsyncChannel;
import com.android.internal.util.Protocol;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
import android.app.PendingIntent;
-import android.net.LinkAddress;
import android.net.LinkCapabilities;
import android.net.LinkProperties;
-import android.net.NetworkUtils;
+import android.net.LinkProperties.CompareAddressesResult;
import android.net.ProxyProperties;
import android.os.AsyncResult;
-import android.os.Bundle;
import android.os.Message;
-import android.os.Parcel;
-import android.os.Parcelable;
import android.os.SystemProperties;
import android.text.TextUtils;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.HashMap;
import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
/**
* {@hide}
@@ -497,8 +492,7 @@
} else {
if (DBG) log("onSetupConnectionCompleted received DataCallState: " + response);
cid = response.cid;
- // set link properties based on data call response
- result = setLinkProperties(response, mLinkProperties);
+ result = updateLinkProperty(response).setupResult;
}
return result;
@@ -527,48 +521,41 @@
return response.setLinkProperties(lp, okToUseSystemPropertyDns);
}
- private DataConnectionAc.LinkPropertyChangeAction updateLinkProperty(
- DataCallState newState) {
- DataConnectionAc.LinkPropertyChangeAction changed =
- DataConnectionAc.LinkPropertyChangeAction.NONE;
+ public static class UpdateLinkPropertyResult {
+ public DataCallState.SetupResult setupResult = DataCallState.SetupResult.SUCCESS;
+ public LinkProperties oldLp;
+ public LinkProperties newLp;
+ public UpdateLinkPropertyResult(LinkProperties curLp) {
+ oldLp = curLp;
+ newLp = curLp;
+ }
+ }
- if (newState == null) return changed;
+ private UpdateLinkPropertyResult updateLinkProperty(DataCallState newState) {
+ UpdateLinkPropertyResult result = new UpdateLinkPropertyResult(mLinkProperties);
- DataCallState.SetupResult result;
- LinkProperties newLp = new LinkProperties();
+ if (newState == null) return result;
+
+ DataCallState.SetupResult setupResult;
+ result.newLp = new LinkProperties();
// set link properties based on data call response
- result = setLinkProperties(newState, newLp);
- if (result != DataCallState.SetupResult.SUCCESS) {
- if (DBG) log("UpdateLinkProperty failed : " + result);
- return changed;
+ result.setupResult = setLinkProperties(newState, result.newLp);
+ if (result.setupResult != DataCallState.SetupResult.SUCCESS) {
+ if (DBG) log("updateLinkProperty failed : " + result.setupResult);
+ return result;
}
// copy HTTP proxy as it is not part DataCallState.
- newLp.setHttpProxy(mLinkProperties.getHttpProxy());
+ result.newLp.setHttpProxy(mLinkProperties.getHttpProxy());
- if (DBG) log("old LP=" + mLinkProperties);
- if (DBG) log("new LP=" + newLp);
-
- // Check consistency of link address. Currently we expect
- // only one "global" address is assigned per each IP type.
- Collection<LinkAddress> oLinks = mLinkProperties.getLinkAddresses();
- Collection<LinkAddress> nLinks = newLp.getLinkAddresses();
- for (LinkAddress oldLink : oLinks) {
- for (LinkAddress newLink : nLinks) {
- if ((NetworkUtils.addressTypeMatches(oldLink.getAddress(),
- newLink.getAddress())) &&
- (oldLink.equals(newLink) == false)) {
- return DataConnectionAc.LinkPropertyChangeAction.RESET;
- }
- }
+ if (DBG && (! result.oldLp.equals(result.newLp))) {
+ if (DBG) log("updateLinkProperty old != new");
+ if (VDBG) log("updateLinkProperty old LP=" + result.oldLp);
+ if (VDBG) log("updateLinkProperty new LP=" + result.newLp);
}
+ mLinkProperties = result.newLp;
- if (mLinkProperties == null || !mLinkProperties.equals(newLp)) {
- mLinkProperties = newLp;
- changed = DataConnectionAc.LinkPropertyChangeAction.CHANGED;
- }
-
- return changed;
+ return result;
}
/**
@@ -643,14 +630,15 @@
}
case DataConnectionAc.REQ_UPDATE_LINK_PROPERTIES_DATA_CALL_STATE: {
DataCallState newState = (DataCallState) msg.obj;
- DataConnectionAc.LinkPropertyChangeAction action = updateLinkProperty(newState);
+ UpdateLinkPropertyResult result =
+ updateLinkProperty(newState);
if (VDBG) {
- log("REQ_UPDATE_LINK_PROPERTIES_DATA_CALL_STATE action="
- + action + " newState=" + newState);
+ log("REQ_UPDATE_LINK_PROPERTIES_DATA_CALL_STATE result="
+ + result + " newState=" + newState);
}
mAc.replyToMessage(msg,
DataConnectionAc.RSP_UPDATE_LINK_PROPERTIES_DATA_CALL_STATE,
- action.ordinal());
+ result);
break;
}
case DataConnectionAc.REQ_GET_LINK_CAPABILITIES: {
@@ -688,7 +676,7 @@
case DataConnectionAc.REQ_GET_APNCONTEXT_LIST: {
if (VDBG) log("REQ_GET_APNCONTEXT_LIST num in list=" + mApnList.size());
mAc.replyToMessage(msg, DataConnectionAc.RSP_GET_APNCONTEXT_LIST,
- new ArrayList(mApnList));
+ new ArrayList<ApnContext>(mApnList));
break;
}
case DataConnectionAc.REQ_SET_RECONNECT_INTENT: {
diff --git a/telephony/java/com/android/internal/telephony/DataConnectionAc.java b/telephony/java/com/android/internal/telephony/DataConnectionAc.java
index 309dbed..9e185e5 100644
--- a/telephony/java/com/android/internal/telephony/DataConnectionAc.java
+++ b/telephony/java/com/android/internal/telephony/DataConnectionAc.java
@@ -16,12 +16,14 @@
package com.android.internal.telephony;
+import com.android.internal.telephony.DataConnection.UpdateLinkPropertyResult;
import com.android.internal.util.AsyncChannel;
import com.android.internal.util.Protocol;
import android.app.PendingIntent;
import android.net.LinkCapabilities;
import android.net.LinkProperties;
+import android.net.LinkProperties.CompareAddressesResult;
import android.net.ProxyProperties;
import android.os.Message;
@@ -310,18 +312,18 @@
if (DBG) log("reqUpdateLinkPropertiesDataCallState");
}
- public LinkPropertyChangeAction rspUpdateLinkPropertiesDataCallState(Message response) {
- LinkPropertyChangeAction retVal = LinkPropertyChangeAction.fromInt(response.arg1);
- if (DBG) log("rspUpdateLinkPropertiesState=" + retVal);
+ public UpdateLinkPropertyResult rspUpdateLinkPropertiesDataCallState(Message response) {
+ UpdateLinkPropertyResult retVal = (UpdateLinkPropertyResult)response.obj;
+ if (DBG) log("rspUpdateLinkPropertiesState: retVal=" + retVal);
return retVal;
}
/**
* Update link properties in the data connection
*
- * @return true if link property has been updated. false otherwise.
+ * @return the removed and added addresses.
*/
- public LinkPropertyChangeAction updateLinkPropertiesDataCallStateSync(DataCallState newState) {
+ public UpdateLinkPropertyResult updateLinkPropertiesDataCallStateSync(DataCallState newState) {
Message response =
sendMessageSynchronously(REQ_UPDATE_LINK_PROPERTIES_DATA_CALL_STATE, newState);
if ((response != null) &&
@@ -329,7 +331,7 @@
return rspUpdateLinkPropertiesDataCallState(response);
} else {
log("getLinkProperties error response=" + response);
- return LinkPropertyChangeAction.NONE;
+ return new UpdateLinkPropertyResult(new LinkProperties());
}
}
diff --git a/telephony/java/com/android/internal/telephony/Phone.java b/telephony/java/com/android/internal/telephony/Phone.java
index 48c5318..4b02e8e 100644
--- a/telephony/java/com/android/internal/telephony/Phone.java
+++ b/telephony/java/com/android/internal/telephony/Phone.java
@@ -1430,6 +1430,11 @@
String getMeid();
/**
+ * Retrieves IMEI for phones. Returns null if IMEI is not set.
+ */
+ String getImei();
+
+ /**
* Retrieves the PhoneSubInfo of the Phone
*/
public PhoneSubInfo getPhoneSubInfo();
diff --git a/telephony/java/com/android/internal/telephony/PhoneProxy.java b/telephony/java/com/android/internal/telephony/PhoneProxy.java
index c2212db..b5bfc76f 100644
--- a/telephony/java/com/android/internal/telephony/PhoneProxy.java
+++ b/telephony/java/com/android/internal/telephony/PhoneProxy.java
@@ -685,6 +685,10 @@
return mActivePhone.getMeid();
}
+ public String getImei() {
+ return mActivePhone.getImei();
+ }
+
public PhoneSubInfo getPhoneSubInfo(){
return mActivePhone.getPhoneSubInfo();
}
diff --git a/telephony/java/com/android/internal/telephony/cdma/CDMALTEPhone.java b/telephony/java/com/android/internal/telephony/cdma/CDMALTEPhone.java
index a31b704..0d9d27d 100644
--- a/telephony/java/com/android/internal/telephony/cdma/CDMALTEPhone.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CDMALTEPhone.java
@@ -136,6 +136,11 @@
}
@Override
+ public String getImei() {
+ return mImei;
+ }
+
+ @Override
protected void log(String s) {
if (DBG)
Log.d(LOG_TAG, "[CDMALTEPhone] " + s);
diff --git a/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java b/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java
index 8a60b5a..286515e 100755
--- a/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java
+++ b/telephony/java/com/android/internal/telephony/cdma/CDMAPhone.java
@@ -122,6 +122,8 @@
//keep track of if phone is in emergency callback mode
private boolean mIsPhoneInEcmState;
private Registrant mEcmExitRespRegistrant;
+ protected String mImei;
+ protected String mImeiSv;
private String mEsn;
private String mMeid;
// string to define how the carrier specifies its own ota sp number
@@ -489,6 +491,11 @@
return mSST.getImsi();
}
+ public String getImei() {
+ Log.e(LOG_TAG, "IMEI is not available in CDMA");
+ return null;
+ }
+
public boolean canConference() {
Log.e(LOG_TAG, "canConference: not possible in CDMA");
return false;
@@ -987,6 +994,8 @@
break;
}
String[] respId = (String[])ar.result;
+ mImei = respId[0];
+ mImeiSv = respId[1];
mEsn = respId[2];
mMeid = respId[3];
}
diff --git a/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java b/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java
index d357eac..1db9860 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GSMPhone.java
@@ -855,6 +855,10 @@
return mImeiSv;
}
+ public String getImei() {
+ return mImei;
+ }
+
public String getEsn() {
Log.e(LOG_TAG, "[GSMPhone] getEsn() is a CDMA method");
return "0";
diff --git a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
index df5898b..bf964b7 100644
--- a/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
+++ b/telephony/java/com/android/internal/telephony/gsm/GsmDataConnectionTracker.java
@@ -26,6 +26,9 @@
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.ConnectivityManager;
+import android.net.LinkAddress;
+import android.net.LinkProperties.CompareAddressesResult;
+import android.net.NetworkUtils;
import android.net.ProxyProperties;
import android.net.TrafficStats;
import android.net.Uri;
@@ -53,6 +56,7 @@
import com.android.internal.telephony.ApnSetting;
import com.android.internal.telephony.DataCallState;
import com.android.internal.telephony.DataConnection;
+import com.android.internal.telephony.DataConnection.UpdateLinkPropertyResult;
import com.android.internal.telephony.DataConnectionAc;
import com.android.internal.telephony.DataConnectionTracker;
import com.android.internal.telephony.Phone;
@@ -1037,7 +1041,7 @@
/**
* @param dcacs Collection of DataConnectionAc reported from RIL.
- * @return List of ApnContext whihc is connected, but does not present in
+ * @return List of ApnContext which is connected, but is not present in
* data connection list reported from RIL.
*/
private List<ApnContext> findApnContextToClean(Collection<DataConnectionAc> dcacs) {
@@ -1091,32 +1095,30 @@
if (DBG) log("onDataStateChanged(ar): DataCallState size=" + dataCallStates.size());
// Create a hash map to store the dataCallState of each DataConnectionAc
- // TODO: Depends on how frequent the DATA_CALL_LIST got updated,
- // may cache response to reduce comparison.
- HashMap<DataCallState, DataConnectionAc> response;
- response = new HashMap<DataCallState, DataConnectionAc>();
+ HashMap<DataCallState, DataConnectionAc> dataCallStateToDcac;
+ dataCallStateToDcac = new HashMap<DataCallState, DataConnectionAc>();
for (DataCallState dataCallState : dataCallStates) {
DataConnectionAc dcac = findDataConnectionAcByCid(dataCallState.cid);
- if (dcac != null) response.put(dataCallState, dcac);
+ if (dcac != null) dataCallStateToDcac.put(dataCallState, dcac);
}
- // step1: Find a list of "connected" APN which does not have reference to
- // calls listed in the Data Call List.
- List<ApnContext> apnsToClear = findApnContextToClean(response.values());
+ // A list of apns to cleanup, those that aren't in the list we know we have to cleanup
+ List<ApnContext> apnsToCleanup = findApnContextToClean(dataCallStateToDcac.values());
- // step2: Check status of each calls in Data Call List.
- // Collect list of ApnContext associated with the data call if the link
- // has to be cleared.
+ // Find which connections have changed state and send a notification or cleanup
for (DataCallState newState : dataCallStates) {
- DataConnectionAc dcac = response.get(newState);
+ DataConnectionAc dcac = dataCallStateToDcac.get(newState);
- // no associated DataConnection found. Ignore.
- if (dcac == null) continue;
+ if (dcac == null) {
+ loge("onDataStateChanged(ar): No associated DataConnection ignore");
+ continue;
+ }
+ // The list of apn's associated with this DataConnection
Collection<ApnContext> apns = dcac.getApnListSync();
- // filter out ApnContext with "Connected/Connecting" state.
+ // Find which ApnContexts of this DC are in the "Connected/Connecting" state.
ArrayList<ApnContext> connectedApns = new ArrayList<ApnContext>();
for (ApnContext apnContext : apns) {
if (apnContext.getState() == State.CONNECTED ||
@@ -1125,67 +1127,86 @@
connectedApns.add(apnContext);
}
}
-
- // No "Connected" ApnContext associated with this CID. Ignore.
- if (connectedApns.isEmpty()) {
- continue;
- }
-
- if (DBG) log("onDataStateChanged(ar): Found ConnId=" + newState.cid
- + " newState=" + newState.toString());
- if (newState.active != 0) {
- boolean resetConnection;
- switch (dcac.updateLinkPropertiesDataCallStateSync(newState)) {
- case NONE:
- if (DBG) log("onDataStateChanged(ar): Found but no change, skip");
- resetConnection = false;
- break;
- case CHANGED:
- for (ApnContext apnContext : connectedApns) {
- if (DBG) log("onDataStateChanged(ar): Found and changed, notify (" +
- apnContext.toString() + ")");
- mPhone.notifyDataConnection(Phone.REASON_LINK_PROPERTIES_CHANGED,
- apnContext.getApnType());
+ if (connectedApns.size() == 0) {
+ if (DBG) log("onDataStateChanged(ar): no connected apns");
+ } else {
+ // Determine if the connection/apnContext should be cleaned up
+ // or just a notification should be sent out.
+ if (DBG) log("onDataStateChanged(ar): Found ConnId=" + newState.cid
+ + " newState=" + newState.toString());
+ if (newState.active == 0) {
+ if (DBG) {
+ log("onDataStateChanged(ar): inactive, cleanup apns=" + connectedApns);
}
- // Temporary hack, at this time a transition from CDMA -> Global
- // fails so we'll hope for the best and not reset the connection.
- // @see bug/4455071
- if (SystemProperties.getBoolean("telephony.ignore-state-changes",
- true)) {
- log("onDataStateChanged(ar): STOPSHIP don't reset, continue");
- resetConnection = false;
+ apnsToCleanup.addAll(connectedApns);
+ } else {
+ // Its active so update the DataConnections link properties
+ UpdateLinkPropertyResult result =
+ dcac.updateLinkPropertiesDataCallStateSync(newState);
+ if (result.oldLp.equals(result.newLp)) {
+ if (DBG) log("onDataStateChanged(ar): no change");
} else {
- // Things changed so reset connection, when hack is removed
- // this is the normal path.
- log("onDataStateChanged(ar): changed so resetting connection");
- resetConnection = true;
+ if (result.oldLp.isIdenticalInterfaceName(result.newLp)) {
+ if (! result.oldLp.isIdenticalDnses(result.newLp) ||
+ ! result.oldLp.isIdenticalRoutes(result.newLp) ||
+ ! result.oldLp.isIdenticalHttpProxy(result.newLp) ||
+ ! result.oldLp.isIdenticalAddresses(result.newLp)) {
+ // If the same address type was removed and added we need to cleanup
+ CompareAddressesResult car =
+ result.oldLp.compareAddresses(result.newLp);
+ boolean needToClean = false;
+ for (LinkAddress added : car.added) {
+ for (LinkAddress removed : car.removed) {
+ if (NetworkUtils.addressTypeMatches(removed.getAddress(),
+ added.getAddress())) {
+ needToClean = true;
+ break;
+ }
+ }
+ }
+ if (needToClean) {
+ if (DBG) {
+ log("onDataStateChanged(ar): addr change, cleanup apns=" +
+ connectedApns);
+ }
+ apnsToCleanup.addAll(connectedApns);
+ } else {
+ if (DBG) log("onDataStateChanged(ar): simple change");
+ for (ApnContext apnContext : connectedApns) {
+ mPhone.notifyDataConnection(
+ Phone.REASON_LINK_PROPERTIES_CHANGED,
+ apnContext.getApnType());
+ }
+ }
+ } else {
+ if (DBG) {
+ log("onDataStateChanged(ar): no changes");
+ }
+ }
+ } else {
+ if (DBG) {
+ log("onDataStateChanged(ar): interface change, cleanup apns="
+ + connectedApns);
+ }
+ apnsToCleanup.addAll(connectedApns);
+ }
}
- break;
- case RESET:
- default:
- if (DBG) log("onDataStateChanged(ar): an error, reset connection");
- resetConnection = true;
- break;
}
- if (resetConnection == false) continue;
}
-
- if (DBG) log("onDataStateChanged(ar): reset connection.");
-
- apnsToClear.addAll(connectedApns);
}
- // step3: Clear apn connection if applicable.
- if (!apnsToClear.isEmpty()) {
+ if (apnsToCleanup.size() != 0) {
// Add an event log when the network drops PDP
int cid = getCellLocationId();
EventLog.writeEvent(EventLogTags.PDP_NETWORK_DROP, cid,
TelephonyManager.getDefault().getNetworkType());
}
- for (ApnContext apnContext : apnsToClear) {
+ // Cleanup those dropped connections
+ for (ApnContext apnContext : apnsToCleanup) {
cleanUpConnection(true, apnContext);
}
+
if (DBG) log("onDataStateChanged(ar): X");
}
diff --git a/telephony/java/com/android/internal/telephony/sip/SipPhoneBase.java b/telephony/java/com/android/internal/telephony/sip/SipPhoneBase.java
index 9dfc015..5c4b446 100755
--- a/telephony/java/com/android/internal/telephony/sip/SipPhoneBase.java
+++ b/telephony/java/com/android/internal/telephony/sip/SipPhoneBase.java
@@ -264,6 +264,10 @@
return null;
}
+ public String getImei() {
+ return null;
+ }
+
public String getEsn() {
Log.e(LOG_TAG, "[SipPhone] getEsn() is a CDMA method");
return "0";
diff --git a/tests/GridLayoutTest/src/com/android/test/layout/Activity2.java b/tests/GridLayoutTest/src/com/android/test/layout/Activity2.java
index b9bf526..af5006f 100644
--- a/tests/GridLayoutTest/src/com/android/test/layout/Activity2.java
+++ b/tests/GridLayoutTest/src/com/android/test/layout/Activity2.java
@@ -38,20 +38,20 @@
vg.setUseDefaultMargins(true);
vg.setAlignmentMode(ALIGN_BOUNDS);
- Group row1 = new Group(1, CENTER);
- Group row2 = new Group(2, CENTER);
- Group row3 = new Group(3, BASELINE);
- Group row4 = new Group(4, BASELINE);
- Group row5 = new Group(5, FILL);
- Group row6 = new Group(6, CENTER);
- Group row7 = new Group(7, CENTER);
+ Spec row1 = spec(0, CENTER);
+ Spec row2 = spec(1, CENTER);
+ Spec row3 = spec(2, BASELINE);
+ Spec row4 = spec(3, BASELINE);
+ Spec row5 = spec(4, FILL, CAN_STRETCH);
+ Spec row6 = spec(5, CENTER);
+ Spec row7 = spec(6, CENTER);
- Group col1a = new Group(1, 4, CENTER);
- Group col1b = new Group(1, 4, LEFT);
- Group col1c = new Group(1, RIGHT);
- Group col2 = new Group(2, LEFT);
- Group col3 = new Group(3, FILL);
- Group col4 = new Group(4, FILL);
+ Spec col1a = spec(0, 4, CENTER);
+ Spec col1b = spec(0, 4, LEFT);
+ Spec col1c = spec(0, RIGHT);
+ Spec col2 = spec(1, LEFT);
+ Spec col3 = spec(2, FILL, CAN_STRETCH);
+ Spec col4 = spec(3, FILL);
{
TextView v = new TextView(context);
@@ -96,10 +96,7 @@
{
Space v = new Space(context);
{
- LayoutParams lp = new LayoutParams(row5, col3);
- lp.columnGroup.flexibility = CAN_STRETCH;
- lp.rowGroup.flexibility = CAN_STRETCH;
- vg.addView(v, lp);
+ vg.addView(v, new LayoutParams(row5, col3));
}
}
{
diff --git a/tests/GridLayoutTest/src/com/android/test/layout/AlignmentTest.java b/tests/GridLayoutTest/src/com/android/test/layout/AlignmentTest.java
index 505c83d..b1c4486 100755
--- a/tests/GridLayoutTest/src/com/android/test/layout/AlignmentTest.java
+++ b/tests/GridLayoutTest/src/com/android/test/layout/AlignmentTest.java
@@ -21,7 +21,6 @@
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
-import android.view.ViewParent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
@@ -84,9 +83,7 @@
Alignment va = VERTICAL_ALIGNMENTS[i];
for (int j = 0; j < HORIZONTAL_ALIGNMENTS.length; j++) {
Alignment ha = HORIZONTAL_ALIGNMENTS[j];
- Group rowGroup = new Group(i, va);
- Group colGroup = new Group(j, ha);
- LayoutParams layoutParams = new LayoutParams(rowGroup, colGroup);
+ LayoutParams layoutParams = new LayoutParams(spec(i, va), spec(j, ha));
String name = VERTICAL_NAMES[i] + "-" + HORIZONTAL_NAMES[j];
ViewFactory factory = FACTORIES[(i + j) % FACTORIES.length];
container.addView(factory.create(name, 20), layoutParams);
diff --git a/tests/GridLayoutTest/src/com/android/test/layout/GridLayoutTest.java b/tests/GridLayoutTest/src/com/android/test/layout/GridLayoutTest.java
index c5681e2..4ce449a 100644
--- a/tests/GridLayoutTest/src/com/android/test/layout/GridLayoutTest.java
+++ b/tests/GridLayoutTest/src/com/android/test/layout/GridLayoutTest.java
@@ -33,9 +33,9 @@
int va = VERTICAL_ALIGNMENTS[i];
for (int j = 0; j < HORIZONTAL_ALIGNMENTS.length; j++) {
int ha = HORIZONTAL_ALIGNMENTS[j];
- GridLayout.Group rowGroup = new GridLayout.Group(UNDEFINED, null);
- GridLayout.Group colGroup = new GridLayout.Group(UNDEFINED, null);
- GridLayout.LayoutParams lp = new GridLayout.LayoutParams(rowGroup, colGroup);
+ Spec rowSpec = spec(UNDEFINED, null);
+ Spec colSpec = spec(UNDEFINED, null);
+ GridLayout.LayoutParams lp = new GridLayout.LayoutParams(rowSpec, colSpec);
//GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
lp.setGravity(va | ha);
View v = create(context, VERTICAL_NAMES[i] + "-" + HORIZONTAL_NAMES[j], 20);
diff --git a/tools/aidl/Type.cpp b/tools/aidl/Type.cpp
index a44072d..6b69864 100755
--- a/tools/aidl/Type.cpp
+++ b/tools/aidl/Type.cpp
@@ -198,7 +198,7 @@
}
void
-Type::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+Type::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d qualifiedName=%s\n",
__FILE__, __LINE__, m_qualifiedName.c_str());
@@ -207,7 +207,7 @@
}
void
-Type::ReadFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+Type::ReadFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d qualifiedName=%s\n",
__FILE__, __LINE__, m_qualifiedName.c_str());
@@ -226,7 +226,7 @@
void
Type::CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d qualifiedName=%s\n",
__FILE__, __LINE__, m_qualifiedName.c_str());
@@ -235,7 +235,7 @@
}
void
-Type::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+Type::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d qualifiedName=%s\n",
__FILE__, __LINE__, m_qualifiedName.c_str());
@@ -284,7 +284,7 @@
}
void
-BasicType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+BasicType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
addTo->Add(new Assignment(v, new MethodCall(parcel, m_unmarshallMethod)));
}
@@ -303,13 +303,13 @@
void
BasicType::CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
addTo->Add(new Assignment(v, new MethodCall(parcel, m_createArrayMethod)));
}
void
-BasicType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+BasicType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
addTo->Add(new MethodCall(parcel, m_readArrayMethod, 1, v));
}
@@ -331,7 +331,7 @@
}
void
-BooleanType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+BooleanType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
addTo->Add(new Assignment(v, new Comparison(new LiteralExpression("0"),
"!=", new MethodCall(parcel, "readInt"))));
@@ -351,13 +351,13 @@
void
BooleanType::CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
addTo->Add(new Assignment(v, new MethodCall(parcel, "createBooleanArray")));
}
void
-BooleanType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+BooleanType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
addTo->Add(new MethodCall(parcel, "readBooleanArray", 1, v));
}
@@ -378,7 +378,7 @@
}
void
-CharType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+CharType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
addTo->Add(new Assignment(v, new MethodCall(parcel, "readInt"), this));
}
@@ -397,13 +397,13 @@
void
CharType::CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
addTo->Add(new Assignment(v, new MethodCall(parcel, "createCharArray")));
}
void
-CharType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+CharType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
addTo->Add(new MethodCall(parcel, "readCharArray", 1, v));
}
@@ -428,7 +428,7 @@
}
void
-StringType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+StringType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
addTo->Add(new Assignment(v, new MethodCall(parcel, "readString")));
}
@@ -447,13 +447,13 @@
void
StringType::CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
addTo->Add(new Assignment(v, new MethodCall(parcel, "createStringArray")));
}
void
-StringType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+StringType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
addTo->Add(new MethodCall(parcel, "readStringArray", 1, v));
}
@@ -496,7 +496,7 @@
void
CharSequenceType::CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
// if (0 != parcel.readInt()) {
// v = TextUtils.createFromParcel(parcel)
@@ -532,7 +532,7 @@
}
void
-RemoteExceptionType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+RemoteExceptionType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d\n", __FILE__, __LINE__);
}
@@ -551,7 +551,7 @@
}
void
-RuntimeExceptionType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+RuntimeExceptionType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d\n", __FILE__, __LINE__);
}
@@ -571,7 +571,7 @@
}
void
-IBinderType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+IBinderType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
addTo->Add(new Assignment(v, new MethodCall(parcel, "readStrongBinder")));
}
@@ -584,13 +584,13 @@
void
IBinderType::CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
addTo->Add(new Assignment(v, new MethodCall(parcel, "createBinderArray")));
}
void
-IBinderType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+IBinderType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
addTo->Add(new MethodCall(parcel, "readBinderArray", 1, v));
}
@@ -610,7 +610,7 @@
}
void
-IInterfaceType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+IInterfaceType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d\n", __FILE__, __LINE__);
}
@@ -631,7 +631,7 @@
void
BinderType::CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d\n", __FILE__, __LINE__);
}
@@ -652,7 +652,7 @@
void
BinderProxyType::CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d\n", __FILE__, __LINE__);
}
@@ -672,7 +672,7 @@
}
void
-ParcelType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+ParcelType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d\n", __FILE__, __LINE__);
}
@@ -691,7 +691,7 @@
}
void
-ParcelableInterfaceType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+ParcelableInterfaceType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
fprintf(stderr, "aidl:internal error %s:%d\n", __FILE__, __LINE__);
}
@@ -709,25 +709,31 @@
addTo->Add(new MethodCall(parcel, "writeMap", 1, v));
}
-void
-MapType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+static void EnsureClassLoader(StatementBlock* addTo, Variable** cl)
{
- Variable *cl = new Variable(CLASSLOADER_TYPE, "cl");
- addTo->Add(new VariableDeclaration(cl,
- new LiteralExpression("this.getClass().getClassLoader()"),
- CLASSLOADER_TYPE));
- addTo->Add(new Assignment(v, new MethodCall(parcel, "readHashMap", 1, cl)));
+ // We don't want to look up the class loader once for every
+ // collection argument, so ensure we do it at most once per method.
+ if (*cl == NULL) {
+ *cl = new Variable(CLASSLOADER_TYPE, "cl");
+ addTo->Add(new VariableDeclaration(*cl,
+ new LiteralExpression("this.getClass().getClassLoader()"),
+ CLASSLOADER_TYPE));
+ }
+}
+
+void
+MapType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable** cl)
+{
+ EnsureClassLoader(addTo, cl);
+ addTo->Add(new Assignment(v, new MethodCall(parcel, "readHashMap", 1, *cl)));
}
void
MapType::ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable** cl)
{
- Variable *cl = new Variable(CLASSLOADER_TYPE, "cl");
- addTo->Add(new VariableDeclaration(cl,
- new LiteralExpression("this.getClass().getClassLoader()"),
- CLASSLOADER_TYPE));
- addTo->Add(new MethodCall(parcel, "readMap", 2, v, cl));
+ EnsureClassLoader(addTo, cl);
+ addTo->Add(new MethodCall(parcel, "readMap", 2, v, *cl));
}
@@ -751,24 +757,18 @@
}
void
-ListType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+ListType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable** cl)
{
- Variable *cl = new Variable(CLASSLOADER_TYPE, "cl");
- addTo->Add(new VariableDeclaration(cl,
- new LiteralExpression("this.getClass().getClassLoader()"),
- CLASSLOADER_TYPE));
- addTo->Add(new Assignment(v, new MethodCall(parcel, "readArrayList", 1, cl)));
+ EnsureClassLoader(addTo, cl);
+ addTo->Add(new Assignment(v, new MethodCall(parcel, "readArrayList", 1, *cl)));
}
void
ListType::ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable** cl)
{
- Variable *cl = new Variable(CLASSLOADER_TYPE, "cl");
- addTo->Add(new VariableDeclaration(cl,
- new LiteralExpression("this.getClass().getClassLoader()"),
- CLASSLOADER_TYPE));
- addTo->Add(new MethodCall(parcel, "readList", 2, v, cl));
+ EnsureClassLoader(addTo, cl);
+ addTo->Add(new MethodCall(parcel, "readList", 2, v, *cl));
}
@@ -811,7 +811,7 @@
}
void
-ParcelableType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+ParcelableType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
// if (0 != parcel.readInt()) {
// v = CLASS.CREATOR.createFromParcel(parcel)
@@ -833,7 +833,7 @@
void
ParcelableType::ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
// TODO: really, we don't need to have this extra check, but we
// don't have two separate marshalling code paths
@@ -862,7 +862,7 @@
void
ParcelableType::CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
string creator = v->type->QualifiedName() + ".CREATOR";
addTo->Add(new Assignment(v, new MethodCall(parcel,
@@ -870,7 +870,7 @@
}
void
-ParcelableType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+ParcelableType::ReadArrayFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
string creator = v->type->QualifiedName() + ".CREATOR";
addTo->Add(new MethodCall(parcel, "readTypedArray", 2,
@@ -907,7 +907,7 @@
}
void
-InterfaceType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+InterfaceType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
// v = Interface.asInterface(parcel.readStrongBinder());
string type = v->type->QualifiedName();
@@ -961,14 +961,14 @@
}
void
-GenericType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+GenericType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
fprintf(stderr, "implement GenericType::CreateFromParcel\n");
}
void
GenericType::ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
fprintf(stderr, "implement GenericType::ReadFromParcel\n");
}
@@ -1009,7 +1009,7 @@
}
void
-GenericListType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel)
+GenericListType::CreateFromParcel(StatementBlock* addTo, Variable* v, Variable* parcel, Variable**)
{
if (m_creator == STRING_TYPE->CreatorName()) {
addTo->Add(new Assignment(v,
@@ -1027,7 +1027,7 @@
void
GenericListType::ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable**)
{
if (m_creator == STRING_TYPE->CreatorName()) {
addTo->Add(new MethodCall(parcel, "readStringList", 1, v));
diff --git a/tools/aidl/Type.h b/tools/aidl/Type.h
index 2ea3ac9..662e3a2 100755
--- a/tools/aidl/Type.h
+++ b/tools/aidl/Type.h
@@ -46,18 +46,18 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual bool CanBeArray() const;
virtual void WriteArrayToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
protected:
void SetQualifiedName(const string& qualified);
@@ -89,16 +89,16 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual bool CanBeArray() const;
virtual void WriteArrayToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
private:
string m_marshallMethod;
@@ -116,16 +116,16 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual bool CanBeArray() const;
virtual void WriteArrayToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class CharType : public Type
@@ -136,16 +136,16 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual bool CanBeArray() const;
virtual void WriteArrayToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
@@ -159,16 +159,16 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual bool CanBeArray() const;
virtual void WriteArrayToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class CharSequenceType : public Type
@@ -181,7 +181,7 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class RemoteExceptionType : public Type
@@ -192,7 +192,7 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class RuntimeExceptionType : public Type
@@ -203,7 +203,7 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class IBinderType : public Type
@@ -214,14 +214,14 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void WriteArrayToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class IInterfaceType : public Type
@@ -232,7 +232,7 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class BinderType : public Type
@@ -243,7 +243,7 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class BinderProxyType : public Type
@@ -254,7 +254,7 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class ParcelType : public Type
@@ -265,7 +265,7 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class ParcelableInterfaceType : public Type
@@ -276,7 +276,7 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class MapType : public Type
@@ -287,9 +287,9 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class ListType : public Type
@@ -302,9 +302,9 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class ParcelableType : public Type
@@ -318,18 +318,18 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual bool CanBeArray() const;
virtual void WriteArrayToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadArrayFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
};
class InterfaceType : public Type
@@ -344,7 +344,7 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
private:
bool m_oneway;
@@ -364,9 +364,9 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
private:
string m_genericArguments;
@@ -387,9 +387,9 @@
virtual void WriteToParcel(StatementBlock* addTo, Variable* v,
Variable* parcel, int flags);
virtual void CreateFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
virtual void ReadFromParcel(StatementBlock* addTo, Variable* v,
- Variable* parcel);
+ Variable* parcel, Variable** cl);
private:
string m_creator;
diff --git a/tools/aidl/aidl.cpp b/tools/aidl/aidl.cpp
index f17f66b..92f5b64 100644
--- a/tools/aidl/aidl.cpp
+++ b/tools/aidl/aidl.cpp
@@ -948,8 +948,6 @@
int
main(int argc, const char **argv)
{
- int err = 0;
-
Options options;
int result = parse_options(argc, argv, &options);
if (result) {
diff --git a/tools/aidl/generate_java.cpp b/tools/aidl/generate_java.cpp
index 0f18132..83e3bbc 100644
--- a/tools/aidl/generate_java.cpp
+++ b/tools/aidl/generate_java.cpp
@@ -286,25 +286,25 @@
static void
generate_create_from_parcel(Type* t, StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable** cl)
{
if (v->dimension == 0) {
- t->CreateFromParcel(addTo, v, parcel);
+ t->CreateFromParcel(addTo, v, parcel, cl);
}
if (v->dimension == 1) {
- t->CreateArrayFromParcel(addTo, v, parcel);
+ t->CreateArrayFromParcel(addTo, v, parcel, cl);
}
}
static void
generate_read_from_parcel(Type* t, StatementBlock* addTo, Variable* v,
- Variable* parcel)
+ Variable* parcel, Variable** cl)
{
if (v->dimension == 0) {
- t->ReadFromParcel(addTo, v, parcel);
+ t->ReadFromParcel(addTo, v, parcel, cl);
}
if (v->dimension == 1) {
- t->ReadArrayFromParcel(addTo, v, parcel);
+ t->ReadArrayFromParcel(addTo, v, parcel, cl);
}
}
@@ -362,6 +362,7 @@
"enforceInterface", 1, new LiteralExpression("DESCRIPTOR")));
// args
+ Variable* cl = NULL;
VariableFactory stubArgs("_arg");
arg = method->args;
while (arg != NULL) {
@@ -373,7 +374,7 @@
if (convert_direction(arg->direction.data) & IN_PARAMETER) {
generate_create_from_parcel(t, c->statements, v,
- stubClass->transact_data);
+ stubClass->transact_data, &cl);
} else {
if (arg->type.dimension == 0) {
c->statements->Add(new Assignment(
@@ -531,7 +532,7 @@
if (_reply != NULL) {
if (_result != NULL) {
generate_create_from_parcel(proxy->returnType,
- tryStatement->statements, _result, _reply);
+ tryStatement->statements, _result, _reply, &cl);
}
// the out/inout parameters
@@ -541,7 +542,7 @@
Variable* v = new Variable(t, arg->name.data, arg->type.dimension);
if (convert_direction(arg->direction.data) & OUT_PARAMETER) {
generate_read_from_parcel(t, tryStatement->statements,
- v, _reply);
+ v, _reply, &cl);
}
arg = arg->next;
}