Merge "Support buildLayer in new pipeline" into nyc-dev
diff --git a/api/current.txt b/api/current.txt
index dd70a32..c81284b 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -5855,7 +5855,7 @@
method public boolean getCrossProfileContactsSearchDisabled(android.content.ComponentName);
method public java.util.List<java.lang.String> getCrossProfileWidgetProviders(android.content.ComponentName);
method public int getCurrentFailedPasswordAttempts();
- method public java.lang.String getDeviceOwnerLockScreenInfo();
+ method public java.lang.CharSequence getDeviceOwnerLockScreenInfo();
method public java.util.List<byte[]> getInstalledCaCerts(android.content.ComponentName);
method public int getKeyguardDisabledFeatures(android.content.ComponentName);
method public java.lang.String getLongSupportMessage(android.content.ComponentName);
@@ -5926,7 +5926,7 @@
method public void setCertInstallerPackage(android.content.ComponentName, java.lang.String) throws java.lang.SecurityException;
method public void setCrossProfileCallerIdDisabled(android.content.ComponentName, boolean);
method public void setCrossProfileContactsSearchDisabled(android.content.ComponentName, boolean);
- method public boolean setDeviceOwnerLockScreenInfo(android.content.ComponentName, java.lang.String);
+ method public void setDeviceOwnerLockScreenInfo(android.content.ComponentName, java.lang.CharSequence);
method public void setGlobalSetting(android.content.ComponentName, java.lang.String, java.lang.String);
method public boolean setKeyguardDisabled(android.content.ComponentName, boolean);
method public void setKeyguardDisabledFeatures(android.content.ComponentName, int);
@@ -10001,6 +10001,7 @@
method public android.content.Intent getIntent();
method public long getLastChangedTimestamp();
method public java.lang.String getPackageName();
+ method public java.lang.String getText();
method public java.lang.String getTitle();
method public int getWeight();
method public boolean hasIconFile();
@@ -10028,6 +10029,7 @@
method public android.content.pm.ShortcutInfo.Builder setIcon(android.graphics.drawable.Icon);
method public android.content.pm.ShortcutInfo.Builder setId(java.lang.String);
method public android.content.pm.ShortcutInfo.Builder setIntent(android.content.Intent);
+ method public android.content.pm.ShortcutInfo.Builder setText(java.lang.String);
method public android.content.pm.ShortcutInfo.Builder setTitle(java.lang.String);
method public android.content.pm.ShortcutInfo.Builder setWeight(int);
}
@@ -30370,7 +30372,7 @@
method public final boolean isDestroyed();
method public final boolean isPrinterDiscoveryStarted();
method public abstract void onDestroy();
- method public void onRequestCustomPrinterIcon(android.print.PrinterId, android.printservice.CustomPrinterIconCallback);
+ method public void onRequestCustomPrinterIcon(android.print.PrinterId, android.os.CancellationSignal, android.printservice.CustomPrinterIconCallback);
method public abstract void onStartPrinterDiscovery(java.util.List<android.print.PrinterId>);
method public abstract void onStartPrinterStateTracking(android.print.PrinterId);
method public abstract void onStopPrinterDiscovery();
diff --git a/api/system-current.txt b/api/system-current.txt
index 0fe632d..071d1f1 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -5995,7 +5995,7 @@
method public deprecated java.lang.String getDeviceInitializerApp();
method public deprecated android.content.ComponentName getDeviceInitializerComponent();
method public java.lang.String getDeviceOwner();
- method public java.lang.String getDeviceOwnerLockScreenInfo();
+ method public java.lang.CharSequence getDeviceOwnerLockScreenInfo();
method public java.lang.String getDeviceOwnerNameOnAnyUser();
method public java.util.List<byte[]> getInstalledCaCerts(android.content.ComponentName);
method public int getKeyguardDisabledFeatures(android.content.ComponentName);
@@ -6074,7 +6074,7 @@
method public void setCertInstallerPackage(android.content.ComponentName, java.lang.String) throws java.lang.SecurityException;
method public void setCrossProfileCallerIdDisabled(android.content.ComponentName, boolean);
method public void setCrossProfileContactsSearchDisabled(android.content.ComponentName, boolean);
- method public boolean setDeviceOwnerLockScreenInfo(android.content.ComponentName, java.lang.String);
+ method public void setDeviceOwnerLockScreenInfo(android.content.ComponentName, java.lang.CharSequence);
method public void setGlobalSetting(android.content.ComponentName, java.lang.String, java.lang.String);
method public boolean setKeyguardDisabled(android.content.ComponentName, boolean);
method public void setKeyguardDisabledFeatures(android.content.ComponentName, int);
@@ -10399,6 +10399,7 @@
method public android.content.Intent getIntent();
method public long getLastChangedTimestamp();
method public java.lang.String getPackageName();
+ method public java.lang.String getText();
method public java.lang.String getTitle();
method public int getWeight();
method public boolean hasIconFile();
@@ -10426,6 +10427,7 @@
method public android.content.pm.ShortcutInfo.Builder setIcon(android.graphics.drawable.Icon);
method public android.content.pm.ShortcutInfo.Builder setId(java.lang.String);
method public android.content.pm.ShortcutInfo.Builder setIntent(android.content.Intent);
+ method public android.content.pm.ShortcutInfo.Builder setText(java.lang.String);
method public android.content.pm.ShortcutInfo.Builder setTitle(java.lang.String);
method public android.content.pm.ShortcutInfo.Builder setWeight(int);
}
@@ -32685,7 +32687,7 @@
method public final boolean isDestroyed();
method public final boolean isPrinterDiscoveryStarted();
method public abstract void onDestroy();
- method public void onRequestCustomPrinterIcon(android.print.PrinterId, android.printservice.CustomPrinterIconCallback);
+ method public void onRequestCustomPrinterIcon(android.print.PrinterId, android.os.CancellationSignal, android.printservice.CustomPrinterIconCallback);
method public abstract void onStartPrinterDiscovery(java.util.List<android.print.PrinterId>);
method public abstract void onStartPrinterStateTracking(android.print.PrinterId);
method public abstract void onStopPrinterDiscovery();
diff --git a/api/test-current.txt b/api/test-current.txt
index d59fa27..8216146 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -5859,7 +5859,7 @@
method public boolean getCrossProfileContactsSearchDisabled(android.content.ComponentName);
method public java.util.List<java.lang.String> getCrossProfileWidgetProviders(android.content.ComponentName);
method public int getCurrentFailedPasswordAttempts();
- method public java.lang.String getDeviceOwnerLockScreenInfo();
+ method public java.lang.CharSequence getDeviceOwnerLockScreenInfo();
method public java.util.List<byte[]> getInstalledCaCerts(android.content.ComponentName);
method public int getKeyguardDisabledFeatures(android.content.ComponentName);
method public java.lang.String getLongSupportMessage(android.content.ComponentName);
@@ -5930,7 +5930,7 @@
method public void setCertInstallerPackage(android.content.ComponentName, java.lang.String) throws java.lang.SecurityException;
method public void setCrossProfileCallerIdDisabled(android.content.ComponentName, boolean);
method public void setCrossProfileContactsSearchDisabled(android.content.ComponentName, boolean);
- method public boolean setDeviceOwnerLockScreenInfo(android.content.ComponentName, java.lang.String);
+ method public void setDeviceOwnerLockScreenInfo(android.content.ComponentName, java.lang.CharSequence);
method public void setGlobalSetting(android.content.ComponentName, java.lang.String, java.lang.String);
method public boolean setKeyguardDisabled(android.content.ComponentName, boolean);
method public void setKeyguardDisabledFeatures(android.content.ComponentName, int);
@@ -10011,6 +10011,7 @@
method public android.content.Intent getIntent();
method public long getLastChangedTimestamp();
method public java.lang.String getPackageName();
+ method public java.lang.String getText();
method public java.lang.String getTitle();
method public int getWeight();
method public boolean hasIconFile();
@@ -10038,6 +10039,7 @@
method public android.content.pm.ShortcutInfo.Builder setIcon(android.graphics.drawable.Icon);
method public android.content.pm.ShortcutInfo.Builder setId(java.lang.String);
method public android.content.pm.ShortcutInfo.Builder setIntent(android.content.Intent);
+ method public android.content.pm.ShortcutInfo.Builder setText(java.lang.String);
method public android.content.pm.ShortcutInfo.Builder setTitle(java.lang.String);
method public android.content.pm.ShortcutInfo.Builder setWeight(int);
}
@@ -30439,7 +30441,7 @@
method public final boolean isDestroyed();
method public final boolean isPrinterDiscoveryStarted();
method public abstract void onDestroy();
- method public void onRequestCustomPrinterIcon(android.print.PrinterId, android.printservice.CustomPrinterIconCallback);
+ method public void onRequestCustomPrinterIcon(android.print.PrinterId, android.os.CancellationSignal, android.printservice.CustomPrinterIconCallback);
method public abstract void onStartPrinterDiscovery(java.util.List<android.print.PrinterId>);
method public abstract void onStartPrinterStateTracking(android.print.PrinterId);
method public abstract void onStopPrinterDiscovery();
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index e7427bf..e1afb17 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -3736,24 +3736,22 @@
*
* @param admin The name of the admin component to check.
* @param info Device owner information which will be displayed instead of the user owner info.
- * @return Whether the device owner information has been set.
* @throws SecurityException if {@code admin} is not a device owner.
*/
- public boolean setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, String info) {
+ public void setDeviceOwnerLockScreenInfo(@NonNull ComponentName admin, CharSequence info) {
if (mService != null) {
try {
- return mService.setDeviceOwnerLockScreenInfo(admin, info);
+ mService.setDeviceOwnerLockScreenInfo(admin, info);
} catch (RemoteException re) {
throw re.rethrowFromSystemServer();
}
}
- return false;
}
/**
* @return The device owner information. If it is not set returns {@code null}.
*/
- public String getDeviceOwnerLockScreenInfo() {
+ public CharSequence getDeviceOwnerLockScreenInfo() {
if (mService != null) {
try {
return mService.getDeviceOwnerLockScreenInfo();
@@ -5919,7 +5917,7 @@
/**
* Called by a profile owner of a managed profile to set the color used for customization. This
* color is used as background color of the confirm credentials screen for that user. The
- * default color is {@link android.graphics.Color#GRAY}.
+ * default color is teal (#00796B).
* <p>
* The confirm credentials screen can be created using
* {@link android.app.KeyguardManager#createConfirmDeviceCredentialIntent}.
diff --git a/core/java/android/app/admin/IDevicePolicyManager.aidl b/core/java/android/app/admin/IDevicePolicyManager.aidl
index aed220d..97383a3 100644
--- a/core/java/android/app/admin/IDevicePolicyManager.aidl
+++ b/core/java/android/app/admin/IDevicePolicyManager.aidl
@@ -135,8 +135,8 @@
void clearProfileOwner(in ComponentName who);
boolean hasUserSetupCompleted();
- boolean setDeviceOwnerLockScreenInfo(in ComponentName who, String deviceOwnerInfo);
- String getDeviceOwnerLockScreenInfo();
+ void setDeviceOwnerLockScreenInfo(in ComponentName who, CharSequence deviceOwnerInfo);
+ CharSequence getDeviceOwnerLockScreenInfo();
String[] setPackagesSuspended(in ComponentName admin, in String[] packageNames, boolean suspended);
boolean getPackageSuspended(in ComponentName admin, String packageName);
diff --git a/core/java/android/bluetooth/BluetoothGatt.java b/core/java/android/bluetooth/BluetoothGatt.java
index 68442ea..b8a40dc 100644
--- a/core/java/android/bluetooth/BluetoothGatt.java
+++ b/core/java/android/bluetooth/BluetoothGatt.java
@@ -422,7 +422,7 @@
try {
mAuthRetry = true;
mService.writeDescriptor(mClientIf, address, handle,
- descriptor.getCharacteristic().getWriteType(),
+ BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
AUTHENTICATION_MITM, descriptor.getValue());
return;
} catch (RemoteException e) {
@@ -545,7 +545,6 @@
/*package*/ BluetoothGattCharacteristic getCharacteristicById(BluetoothDevice device, int instanceId) {
for(BluetoothGattService svc : mServices) {
for(BluetoothGattCharacteristic charac : svc.getCharacteristics()) {
- Log.w(TAG, "getCharacteristicById() comparing " + charac.getInstanceId() + " and " + instanceId);
if (charac.getInstanceId() == instanceId)
return charac;
}
@@ -944,7 +943,8 @@
try {
mService.writeDescriptor(mClientIf, device.getAddress(), descriptor.getInstanceId(),
- characteristic.getWriteType(), AUTHENTICATION_NONE, descriptor.getValue());
+ BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, AUTHENTICATION_NONE,
+ descriptor.getValue());
} catch (RemoteException e) {
Log.e(TAG,"",e);
mDeviceBusy = false;
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index a0238fb..6fce36b 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -437,10 +437,9 @@
void performFstrimIfNeeded();
/**
- * Ask the package manager to extract packages if needed, to save
- * the VM unzipping the APK in memory during launch.
+ * Ask the package manager to update packages if needed.
*/
- void extractPackagesIfNeeded();
+ void updatePackagesIfNeeded();
/**
* Notify the package manager that a package is going to be used.
diff --git a/core/java/android/content/pm/ShortcutInfo.java b/core/java/android/content/pm/ShortcutInfo.java
index ae75e3f..7408c34 100644
--- a/core/java/android/content/pm/ShortcutInfo.java
+++ b/core/java/android/content/pm/ShortcutInfo.java
@@ -118,6 +118,9 @@
@NonNull
private String mTitle;
+ @Nullable
+ private String mText;
+
/**
* Intent *with extras removed*.
*/
@@ -157,6 +160,7 @@
mActivityComponent = b.mActivityComponent;
mIcon = b.mIcon;
mTitle = b.mTitle;
+ mText = b.mText;
mIntent = b.mIntent;
if (mIntent != null) {
final Bundle intentExtras = mIntent.getExtras();
@@ -176,6 +180,7 @@
* @hide
*/
public void enforceMandatoryFields() {
+ Preconditions.checkStringNotEmpty(mId, "Shortcut ID must be provided");
Preconditions.checkStringNotEmpty(mTitle, "Shortcut title must be provided");
Preconditions.checkNotNull(mIntent, "Shortcut Intent must be provided");
}
@@ -195,16 +200,17 @@
if ((cloneFlags & CLONE_REMOVE_ICON) == 0) {
mIcon = source.mIcon;
mBitmapPath = source.mBitmapPath;
+ mIconResourceId = source.mIconResourceId;
}
mTitle = source.mTitle;
+ mText = source.mText;
if ((cloneFlags & CLONE_REMOVE_INTENT) == 0) {
mIntent = source.mIntent;
mIntentPersistableExtras = source.mIntentPersistableExtras;
}
mWeight = source.mWeight;
mExtras = source.mExtras;
- mIconResourceId = source.mIconResourceId;
} else {
// Set this bit.
mFlags |= FLAG_KEY_FIELDS_ONLY;
@@ -244,6 +250,9 @@
if (source.mTitle != null) {
mTitle = source.mTitle;
}
+ if (source.mText != null) {
+ mText = source.mText;
+ }
if (source.mIntent != null) {
mIntent = source.mIntent;
mIntentPersistableExtras = source.mIntentPersistableExtras;
@@ -305,6 +314,8 @@
private String mTitle;
+ private String mText;
+
private Intent mIntent;
private int mWeight;
@@ -368,6 +379,15 @@
}
/**
+ * Sets the text of a shortcut. This is an optional field.
+ */
+ @NonNull
+ public Builder setText(@NonNull String text) {
+ mText = Preconditions.checkStringNotEmpty(text, "text");
+ return this;
+ }
+
+ /**
* Sets the intent of a shortcut. This is a mandatory field. The extras must only contain
* persistable information. (See {@link PersistableBundle}).
*/
@@ -457,6 +477,14 @@
}
/**
+ * Return the shortcut text.
+ */
+ @Nullable
+ public String getText() {
+ return mText;
+ }
+
+ /**
* Return the intent.
*
* <p>All shortcuts must have an intent, but this method will return null when
@@ -630,6 +658,7 @@
mActivityComponent = source.readParcelable(cl);
mIcon = source.readParcelable(cl);
mTitle = source.readString();
+ mText = source.readString();
mIntent = source.readParcelable(cl);
mIntentPersistableExtras = source.readParcelable(cl);
mWeight = source.readInt();
@@ -647,6 +676,7 @@
dest.writeParcelable(mActivityComponent, flags);
dest.writeParcelable(mIcon, flags);
dest.writeString(mTitle);
+ dest.writeString(mText);
dest.writeParcelable(mIntent, flags);
dest.writeParcelable(mIntentPersistableExtras, flags);
dest.writeInt(mWeight);
@@ -708,6 +738,9 @@
sb.append(", title=");
sb.append(secure ? "***" : mTitle);
+ sb.append(", text=");
+ sb.append(secure ? "***" : mText);
+
sb.append(", icon=");
sb.append(mIcon);
@@ -744,7 +777,8 @@
/** @hide */
public ShortcutInfo(String id, String packageName, ComponentName activityComponent,
- Icon icon, String title, Intent intent, PersistableBundle intentPersistableExtras,
+ Icon icon, String title, String text, Intent intent,
+ PersistableBundle intentPersistableExtras,
int weight, PersistableBundle extras, long lastChangedTimestamp,
int flags, int iconResId, String bitmapPath) {
mId = id;
@@ -752,6 +786,7 @@
mActivityComponent = activityComponent;
mIcon = icon;
mTitle = title;
+ mText = text;
mIntent = intent;
mIntentPersistableExtras = intentPersistableExtras;
mWeight = weight;
diff --git a/services/net/java/android/net/metrics/CaptivePortalCheckResultEvent.java b/core/java/android/net/metrics/CaptivePortalCheckResultEvent.java
similarity index 98%
rename from services/net/java/android/net/metrics/CaptivePortalCheckResultEvent.java
rename to core/java/android/net/metrics/CaptivePortalCheckResultEvent.java
index 163f7e40..2239a25 100644
--- a/services/net/java/android/net/metrics/CaptivePortalCheckResultEvent.java
+++ b/core/java/android/net/metrics/CaptivePortalCheckResultEvent.java
@@ -19,6 +19,9 @@
import android.os.Parcel;
import android.os.Parcelable;
+/**
+ * {@hide}
+ */
public class CaptivePortalCheckResultEvent extends IpConnectivityEvent implements Parcelable {
public static final String TAG = "CaptivePortalCheckResultEvent";
diff --git a/services/net/java/android/net/metrics/CaptivePortalStateChangeEvent.java b/core/java/android/net/metrics/CaptivePortalStateChangeEvent.java
similarity index 98%
rename from services/net/java/android/net/metrics/CaptivePortalStateChangeEvent.java
rename to core/java/android/net/metrics/CaptivePortalStateChangeEvent.java
index d0cc120..00808c1 100644
--- a/services/net/java/android/net/metrics/CaptivePortalStateChangeEvent.java
+++ b/core/java/android/net/metrics/CaptivePortalStateChangeEvent.java
@@ -19,6 +19,9 @@
import android.os.Parcel;
import android.os.Parcelable;
+/**
+ * {@hide}
+ */
public class CaptivePortalStateChangeEvent extends IpConnectivityEvent implements Parcelable {
public static final String TAG = "CaptivePortalStateChangeEvent";
diff --git a/services/net/java/android/net/metrics/ConnectivityServiceChangeEvent.java b/core/java/android/net/metrics/ConnectivityServiceChangeEvent.java
similarity index 98%
rename from services/net/java/android/net/metrics/ConnectivityServiceChangeEvent.java
rename to core/java/android/net/metrics/ConnectivityServiceChangeEvent.java
index 92b376c..c6fcb2d 100644
--- a/services/net/java/android/net/metrics/ConnectivityServiceChangeEvent.java
+++ b/core/java/android/net/metrics/ConnectivityServiceChangeEvent.java
@@ -19,6 +19,9 @@
import android.os.Parcel;
import android.os.Parcelable;
+/**
+ * {@hide}
+ */
public class ConnectivityServiceChangeEvent extends IpConnectivityEvent implements Parcelable {
public static final String TAG = "ConnectivityServiceChangeEvent";
diff --git a/services/net/java/android/net/metrics/DhcpClientEvent.java b/core/java/android/net/metrics/DhcpClientEvent.java
similarity index 98%
rename from services/net/java/android/net/metrics/DhcpClientEvent.java
rename to core/java/android/net/metrics/DhcpClientEvent.java
index 2c24034..7b44664 100644
--- a/services/net/java/android/net/metrics/DhcpClientEvent.java
+++ b/core/java/android/net/metrics/DhcpClientEvent.java
@@ -19,6 +19,9 @@
import android.os.Parcel;
import android.os.Parcelable;
+/**
+ * {@hide}
+ */
public class DhcpClientEvent extends IpConnectivityEvent implements Parcelable {
public static final String TAG = "DhcpClientEvent";
diff --git a/services/net/java/android/net/metrics/IpConnectivityEvent.java b/core/java/android/net/metrics/IpConnectivityEvent.java
similarity index 98%
rename from services/net/java/android/net/metrics/IpConnectivityEvent.java
rename to core/java/android/net/metrics/IpConnectivityEvent.java
index f277bd0..ec42890 100644
--- a/services/net/java/android/net/metrics/IpConnectivityEvent.java
+++ b/core/java/android/net/metrics/IpConnectivityEvent.java
@@ -20,6 +20,9 @@
import android.os.Parcel;
import android.os.Parcelable;
+/**
+ * {@hide}
+ */
public class IpConnectivityEvent implements Parcelable {
// IPRM = IpReachabilityMonitor
// DHCP = DhcpClient
diff --git a/services/net/java/android/net/metrics/IpReachabilityMonitorMessageEvent.java b/core/java/android/net/metrics/IpReachabilityMonitorMessageEvent.java
similarity index 98%
rename from services/net/java/android/net/metrics/IpReachabilityMonitorMessageEvent.java
rename to core/java/android/net/metrics/IpReachabilityMonitorMessageEvent.java
index a8c18d6..e71b0be 100644
--- a/services/net/java/android/net/metrics/IpReachabilityMonitorMessageEvent.java
+++ b/core/java/android/net/metrics/IpReachabilityMonitorMessageEvent.java
@@ -19,6 +19,9 @@
import android.os.Parcel;
import android.os.Parcelable;
+/**
+ * {@hide}
+ */
public class IpReachabilityMonitorMessageEvent extends IpConnectivityEvent
implements Parcelable {
public static final String TAG = "IpReachabilityMonitorMessageEvent";
diff --git a/services/net/java/android/net/metrics/IpReachabilityMonitorProbeEvent.java b/core/java/android/net/metrics/IpReachabilityMonitorProbeEvent.java
similarity index 98%
rename from services/net/java/android/net/metrics/IpReachabilityMonitorProbeEvent.java
rename to core/java/android/net/metrics/IpReachabilityMonitorProbeEvent.java
index 172cbf8..182b778 100644
--- a/services/net/java/android/net/metrics/IpReachabilityMonitorProbeEvent.java
+++ b/core/java/android/net/metrics/IpReachabilityMonitorProbeEvent.java
@@ -19,6 +19,9 @@
import android.os.Parcel;
import android.os.Parcelable;
+/**
+ * {@hide}
+ */
public class IpReachabilityMonitorProbeEvent extends IpConnectivityEvent
implements Parcelable {
public static final String TAG = "IpReachabilityMonitorProbeEvent";
diff --git a/core/java/android/printservice/PrinterDiscoverySession.java b/core/java/android/printservice/PrinterDiscoverySession.java
index cd5a903..7b9533d 100644
--- a/core/java/android/printservice/PrinterDiscoverySession.java
+++ b/core/java/android/printservice/PrinterDiscoverySession.java
@@ -18,6 +18,7 @@
import android.annotation.NonNull;
import android.content.pm.ParceledListSlice;
+import android.os.CancellationSignal;
import android.os.RemoteException;
import android.print.PrinterCapabilitiesInfo;
import android.print.PrinterId;
@@ -412,11 +413,13 @@
* service.
*
* @param printerId The printer to icon belongs to.
+ * @param cancellationSignal Signal used to cancel the request
* @param callback Callback for returning the icon to the print spooler.
*
* @see android.print.PrinterInfo.Builder#setHasCustomPrinterIcon()
*/
public void onRequestCustomPrinterIcon(@NonNull PrinterId printerId,
+ @NonNull CancellationSignal cancellationSignal,
@NonNull CustomPrinterIconCallback callback) {
}
@@ -533,7 +536,7 @@
if (!mIsDestroyed && mObserver != null) {
CustomPrinterIconCallback callback = new CustomPrinterIconCallback(printerId,
mObserver);
- onRequestCustomPrinterIcon(printerId, callback);
+ onRequestCustomPrinterIcon(printerId, new CancellationSignal(), callback);
}
}
diff --git a/core/java/android/view/IWindowSession.aidl b/core/java/android/view/IWindowSession.aidl
index a1e2e94..8e1609c 100644
--- a/core/java/android/view/IWindowSession.aidl
+++ b/core/java/android/view/IWindowSession.aidl
@@ -116,14 +116,11 @@
* @param top The new top position
* @param right The new right position
* @param bottom The new bottom position
- * @param requestedWidth The new requested width
- * @param requestedHeight The new requested height
* @param deferTransactionUntilFrame Frame number from our parent (attached) to
* defer this action until.
* @param outFrame Rect in which is placed the new position/size on screen.
*/
void repositionChild(IWindow childWindow, int left, int top, int right, int bottom,
- int requestedWidth, int requestedHeight,
long deferTransactionUntilFrame, out Rect outFrame);
/*
diff --git a/core/java/android/view/SurfaceView.java b/core/java/android/view/SurfaceView.java
index 477ffd9..8a8fb43 100644
--- a/core/java/android/view/SurfaceView.java
+++ b/core/java/android/view/SurfaceView.java
@@ -490,7 +490,7 @@
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
;
- if (!creating && !force && !mUpdateWindowNeeded) {
+ if (!creating && !force && !mUpdateWindowNeeded && !sizeChanged) {
mLayout.privateFlags |=
WindowManager.LayoutParams.PRIVATE_FLAG_PRESERVE_GEOMETRY;
} else {
@@ -584,18 +584,6 @@
mSurface.transferFrom(mNewSurface);
if (visible && mSurface.isValid()) {
- // We set SCALING_MODE_NO_SCALE_CROP to allow the WindowManager
- // to update our Surface crop without requiring a new buffer from
- // us. In the default mode of SCALING_MODE_FREEZE, surface geometry
- // state (which includes crop) is only applied when a buffer
- // with appropriate geometry is available. During drag resize
- // it is quite frequent that a matching buffer will not be available
- // (because we are constantly being resized and have fallen behind).
- // However in such situations the WindowManager still needs to be able
- // to update our crop to ensure we stay within the bounds of the containing
- // window.
- mSurface.setScalingMode(Surface.SCALING_MODE_NO_SCALE_CROP);
-
if (!mSurfaceCreated && (surfaceChanged || visibleChanged)) {
mSurfaceCreated = true;
mIsCreating = true;
@@ -666,7 +654,6 @@
mLocation[0], mLocation[1]));
mSession.repositionChild(mWindow, mWindowSpaceLeft, mWindowSpaceTop,
mLocation[0], mLocation[1],
- mWindowSpaceWidth, mWindowSpaceHeight,
-1, mWinFrame);
} catch (RemoteException ex) {
Log.e(TAG, "Exception from relayout", ex);
@@ -703,7 +690,6 @@
}
// Just using mRTLastReportedPosition as a dummy rect here
session.repositionChild(window, left, top, right, bottom,
- mWindowSpaceWidth, mWindowSpaceHeight,
frameNumber,
mRTLastReportedPosition);
// Now overwrite mRTLastReportedPosition with our values
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 816d9c4..f695873 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -6749,7 +6749,8 @@
@Override
public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
int dxUnconsumed, int dyUnconsumed) {
- // Do nothing
+ // Re-dispatch up the tree by default
+ dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, null);
}
/**
@@ -6757,7 +6758,8 @@
*/
@Override
public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
- // Do nothing
+ // Re-dispatch up the tree by default
+ dispatchNestedPreScroll(dx, dy, consumed, null);
}
/**
@@ -6765,7 +6767,8 @@
*/
@Override
public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
- return false;
+ // Re-dispatch up the tree by default
+ return dispatchNestedFling(velocityX, velocityY, consumed);
}
/**
@@ -6773,7 +6776,8 @@
*/
@Override
public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
- return false;
+ // Re-dispatch up the tree by default
+ return dispatchNestedPreFling(velocityX, velocityY);
}
/**
diff --git a/core/java/android/widget/SimpleMonthView.java b/core/java/android/widget/SimpleMonthView.java
index 43cf5a1..ee716df 100644
--- a/core/java/android/widget/SimpleMonthView.java
+++ b/core/java/android/widget/SimpleMonthView.java
@@ -16,6 +16,9 @@
package android.widget;
+import com.android.internal.R;
+import com.android.internal.widget.ExploreByTouchHelper;
+
import android.annotation.Nullable;
import android.content.Context;
import android.content.res.ColorStateList;
@@ -44,14 +47,13 @@
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction;
-import com.android.internal.R;
-import com.android.internal.widget.ExploreByTouchHelper;
-
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Locale;
+import libcore.icu.LocaleData;
+
/**
* A calendar-like view displaying a specified month and the appropriate selectable day numbers
* within the specified month.
@@ -66,7 +68,6 @@
private static final int DEFAULT_WEEK_START = Calendar.SUNDAY;
private static final String MONTH_YEAR_FORMAT = "MMMMy";
- private static final String DAY_OF_WEEK_FORMAT = "EEEEE";
private static final int SELECTED_HIGHLIGHT_ALPHA = 0xB0;
@@ -80,6 +81,7 @@
private final Paint mDayHighlightPaint = new Paint();
private final Paint mDayHighlightSelectorPaint = new Paint();
+ /** Array of single-character weekday labels ordered by column index. */
private final String[] mDayOfWeekLabels = new String[7];
private final Calendar mCalendar;
@@ -120,7 +122,7 @@
*/
private int mToday = DEFAULT_SELECTED_DAY;
- /** The first day of the week (ex. Calendar.SUNDAY). */
+ /** The first day of the week (ex. Calendar.SUNDAY) indexed from one. */
private int mWeekStart = DEFAULT_WEEK_START;
/** The number of days (ex. 28) in the current month. */
@@ -199,13 +201,11 @@
Log.d(LOG_TAG, "mWeekStart => " + mWeekStart);
}
- final Calendar calendar = Calendar.getInstance(mLocale);
- calendar.setFirstDayOfWeek(mWeekStart);
-
- final SimpleDateFormat formatter = new SimpleDateFormat(DAY_OF_WEEK_FORMAT, mLocale);
- for (int i = 0; i < 7; i++) {
- calendar.set(Calendar.DAY_OF_WEEK, i);
- mDayOfWeekLabels[i] = formatter.format(calendar.getTime());
+ // Use tiny (e.g. single-character) weekday names from ICU. The indices
+ // for this list correspond to Calendar days, e.g. SUNDAY is index 1.
+ final String[] tinyWeekdayNames = LocaleData.get(mLocale).tinyWeekdayNames;
+ for (int i = 0; i < DAYS_IN_WEEK; i++) {
+ mDayOfWeekLabels[i] = tinyWeekdayNames[(mWeekStart + i - 1) % DAYS_IN_WEEK + 1];
}
if (DEBUG_WRONG_DATE) {
@@ -662,8 +662,7 @@
colCenterRtl = colCenter;
}
- final int dayOfWeek = (col + mWeekStart) % DAYS_IN_WEEK;
- final String label = mDayOfWeekLabels[dayOfWeek];
+ final String label = mDayOfWeekLabels[col];
canvas.drawText(label, colCenterRtl, rowCenter - halfLineHeight, p);
}
}
@@ -813,6 +812,11 @@
*/
void setMonthParams(int selectedDay, int month, int year, int weekStart, int enabledDayStart,
int enabledDayEnd) {
+ if (DEBUG_WRONG_DATE) {
+ Log.d(LOG_TAG, "setMonthParams(" + selectedDay + ", " + month + ", " + year + ", "
+ + weekStart + ", " + enabledDayStart + ", " + enabledDayEnd + ")");
+ }
+
mActivatedDay = selectedDay;
if (isValidMonth(month)) {
@@ -849,6 +853,14 @@
mTouchHelper.invalidateRoot();
updateMonthYearLabel();
+
+ if (DEBUG_WRONG_DATE) {
+ Log.d(LOG_TAG, "mMonth = " + mMonth);
+ Log.d(LOG_TAG, "mDayOfWeekStart = " + mDayOfWeekStart);
+ Log.d(LOG_TAG, "mWeekStart = " + mWeekStart);
+ Log.d(LOG_TAG, "mDaysInMonth = " + mDaysInMonth);
+ Log.d(LOG_TAG, "mToday = " + mToday);
+ }
}
private static int getDaysInMonth(int month, int year) {
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index a9af654..4a68d3c 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -3411,17 +3411,10 @@
}
/**
- * Sets whether the movement method will automatically be set to {@link LinkMovementMethod}
- * after {@link #setText} or {@link #append} is called. The movement method is set if one of the
- * following is true:
- * <ul>
- * <li>{@link #setAutoLinkMask} has been set to nonzero and links are detected in
- * {@link #setText} or {@link #append}.
- * <li>The input for {@link #setText} or {@link #append} contains a {@link ClickableSpan}.
- * </ul>
- *
- * <p>This function does not have an immediate effect, movement method will be set only after a
- * call to {@link #setText} or {@link #append}. The default is true.</p>
+ * Sets whether the movement method will automatically be set to
+ * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been
+ * set to nonzero and links are detected in {@link #setText}.
+ * The default is true.
*
* @attr ref android.R.styleable#TextView_linksClickable
*/
@@ -3431,14 +3424,10 @@
}
/**
- * Returns whether the movement method will automatically be set to {@link LinkMovementMethod}
- * after {@link #setText} or {@link #append} is called.
- *
- * See {@link #setLinksClickable} for details.
- *
- * <p>The default is true.</p>
- *
- * @see #setLinksClickable
+ * Returns whether the movement method will automatically be set to
+ * {@link LinkMovementMethod} if {@link #setAutoLinkMask} has been
+ * set to nonzero and links are detected in {@link #setText}.
+ * The default is true.
*
* @attr ref android.R.styleable#TextView_linksClickable
*/
@@ -4032,19 +4021,13 @@
((Editable) mText).append(text, start, end);
- boolean hasClickableSpans = false;
if (mAutoLinkMask != 0) {
- hasClickableSpans = Linkify.addLinks((Spannable) mText, mAutoLinkMask);
- } else if (mLinksClickable && text instanceof Spanned) {
- ClickableSpan[] clickableSpans =
- ((Spanned) text).getSpans(0, text.length(), ClickableSpan.class);
- hasClickableSpans = clickableSpans != null && clickableSpans.length > 0;
- }
-
- // Do not change the movement method for text that supports text selection as it
- // would prevent an arbitrary cursor displacement.
- if (hasClickableSpans && mLinksClickable && !textCanBeSelected()) {
- setMovementMethod(LinkMovementMethod.getInstance());
+ boolean linksWereAdded = Linkify.addLinks((Spannable) mText, mAutoLinkMask);
+ // Do not change the movement method for text that support text selection as it
+ // would prevent an arbitrary cursor displacement.
+ if (linksWereAdded && mLinksClickable && !textCanBeSelected()) {
+ setMovementMethod(LinkMovementMethod.getInstance());
+ }
}
}
@@ -4397,7 +4380,6 @@
text = TextUtils.stringOrSpannedString(text);
}
- boolean hasClickableSpans = false;
if (mAutoLinkMask != 0) {
Spannable s2;
@@ -4407,32 +4389,22 @@
s2 = mSpannableFactory.newSpannable(text);
}
- hasClickableSpans = Linkify.addLinks(s2, mAutoLinkMask);
- if (hasClickableSpans) {
+ if (Linkify.addLinks(s2, mAutoLinkMask)) {
text = s2;
- }
- } else if (mLinksClickable && text instanceof Spanned) {
- ClickableSpan[] clickableSpans =
- ((Spanned) text).getSpans(0, text.length(), ClickableSpan.class);
- hasClickableSpans = clickableSpans != null && clickableSpans.length > 0;
- if (hasClickableSpans && !(text instanceof Spannable)) {
- text = mSpannableFactory.newSpannable(text);
- }
- }
+ type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE;
- if (hasClickableSpans) {
- type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE;
- /*
- * We must go ahead and set the text before changing the
- * movement method, because setMovementMethod() may call
- * setText() again to try to upgrade the buffer type.
- */
- mText = text;
+ /*
+ * We must go ahead and set the text before changing the
+ * movement method, because setMovementMethod() may call
+ * setText() again to try to upgrade the buffer type.
+ */
+ mText = text;
- // Do not change the movement method for text that supports text selection as it
- // would prevent an arbitrary cursor displacement.
- if (mLinksClickable && !textCanBeSelected()) {
- setMovementMethod(LinkMovementMethod.getInstance());
+ // Do not change the movement method for text that support text selection as it
+ // would prevent an arbitrary cursor displacement.
+ if (mLinksClickable && !textCanBeSelected()) {
+ setMovementMethod(LinkMovementMethod.getInstance());
+ }
}
}
diff --git a/core/java/com/android/internal/policy/DecorView.java b/core/java/com/android/internal/policy/DecorView.java
index 4b695b9..ea0fbda 100644
--- a/core/java/com/android/internal/policy/DecorView.java
+++ b/core/java/com/android/internal/policy/DecorView.java
@@ -209,6 +209,7 @@
private Drawable mResizingBackgroundDrawable;
private Drawable mCaptionBackgroundDrawable;
private Drawable mUserCaptionBackgroundDrawable;
+ private Drawable mOriginalBackgroundDrawable;
private float mAvailableWidth;
@@ -888,6 +889,11 @@
mBackgroundPadding.setEmpty();
}
drawableChanged();
+
+ // Make sure we don't reset to the old drawable when finishing resizing.
+ if (mResizeMode != RESIZE_MODE_INVALID) {
+ mOriginalBackgroundDrawable = null;
+ }
}
}
@@ -1950,6 +1956,9 @@
updateElevation();
updateColorViews(null /* insets */, false);
+
+ mOriginalBackgroundDrawable = getBackground();
+ setBackgroundDrawable(null);
}
mResizeMode = resizeMode;
getViewRootImpl().requestInvalidateRootRenderNode();
@@ -1961,6 +1970,10 @@
updateColorViews(null /* insets */, false);
mResizeMode = RESIZE_MODE_INVALID;
getViewRootImpl().requestInvalidateRootRenderNode();
+ if (mOriginalBackgroundDrawable != null) {
+ setBackgroundDrawable(mOriginalBackgroundDrawable);
+ mOriginalBackgroundDrawable = null;
+ }
}
@Override
diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml
index d7381ab..4429001 100644
--- a/core/res/res/values/attrs.xml
+++ b/core/res/res/values/attrs.xml
@@ -4384,8 +4384,7 @@
<attr name="autoLink" />
<!-- If set to false, keeps the movement method from being set
to the link movement method even if autoLink causes links
- to be found or the input text contains a
- {@link android.text.style.ClickableSpan ClickableSpan}. -->
+ to be found. -->
<attr name="linksClickable" format="boolean" />
<!-- If set, specifies that this TextView has a numeric input method.
The default is false.
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 6041f637c..b878b00 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -2953,10 +2953,11 @@
<!-- Title of the physical keyboard category in the input method selector [CHAR LIMIT=30] -->
<string name="hardware">Show virtual keyboard</string>
- <!-- Title of the notification to prompt the user to select a keyboard layout. -->
- <string name="select_keyboard_layout_notification_title">Select keyboard layout</string>
- <!-- Message of the notification to prompt the user to select a keyboard layout. -->
- <string name="select_keyboard_layout_notification_message">Touch to select a keyboard layout.</string>
+ <!-- Title of the notification to prompt the user to configure physical keyboard settings. -->
+ <string name="select_keyboard_layout_notification_title">Configure physical keyboard</string>
+ <!-- Message of the notification to prompt the user to configure physical keyboard settings
+ where the user can associate language with physical keyboard layout. -->
+ <string name="select_keyboard_layout_notification_message">Tap to select language and layout</string>
<string name="fast_scroll_alphabet">\u0020ABCDEFGHIJKLMNOPQRSTUVWXYZ</string>
<string name="fast_scroll_numeric_alphabet">\u00200123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ</string>
diff --git a/core/tests/coretests/src/android/print/BasePrintTest.java b/core/tests/coretests/src/android/print/BasePrintTest.java
index c9bc8aa..d56a405 100644
--- a/core/tests/coretests/src/android/print/BasePrintTest.java
+++ b/core/tests/coretests/src/android/print/BasePrintTest.java
@@ -28,6 +28,7 @@
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
+import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.os.SystemClock;
import android.print.PrintAttributes;
@@ -281,7 +282,8 @@
}
if (onRequestCustomPrinterIcon != null) {
doAnswer(onRequestCustomPrinterIcon).when(callbacks).onRequestCustomPrinterIcon(
- any(PrinterId.class), any(CustomPrinterIconCallback.class));
+ any(PrinterId.class), any(CancellationSignal.class),
+ any(CustomPrinterIconCallback.class));
}
if (onStopPrinterStateTracking != null) {
doAnswer(onStopPrinterStateTracking).when(callbacks).onStopPrinterStateTracking(
diff --git a/core/tests/coretests/src/android/print/mockservice/PrinterDiscoverySessionCallbacks.java b/core/tests/coretests/src/android/print/mockservice/PrinterDiscoverySessionCallbacks.java
index 26b7cae..be002e2 100644
--- a/core/tests/coretests/src/android/print/mockservice/PrinterDiscoverySessionCallbacks.java
+++ b/core/tests/coretests/src/android/print/mockservice/PrinterDiscoverySessionCallbacks.java
@@ -16,6 +16,7 @@
package android.print.mockservice;
+import android.os.CancellationSignal;
import android.print.PrinterId;
import android.printservice.CustomPrinterIconCallback;
@@ -42,7 +43,7 @@
public abstract void onStartPrinterStateTracking(PrinterId printerId);
public abstract void onRequestCustomPrinterIcon(PrinterId printerId,
- CustomPrinterIconCallback callback);
+ CancellationSignal cancellationSignal, CustomPrinterIconCallback callback);
public abstract void onStopPrinterStateTracking(PrinterId printerId);
diff --git a/core/tests/coretests/src/android/print/mockservice/StubbablePrinterDiscoverySession.java b/core/tests/coretests/src/android/print/mockservice/StubbablePrinterDiscoverySession.java
index 04683f2..e132d79 100644
--- a/core/tests/coretests/src/android/print/mockservice/StubbablePrinterDiscoverySession.java
+++ b/core/tests/coretests/src/android/print/mockservice/StubbablePrinterDiscoverySession.java
@@ -16,6 +16,7 @@
package android.print.mockservice;
+import android.os.CancellationSignal;
import android.print.PrinterId;
import android.printservice.CustomPrinterIconCallback;
import android.printservice.PrintService;
@@ -70,9 +71,9 @@
@Override
public void onRequestCustomPrinterIcon(PrinterId printerId,
- CustomPrinterIconCallback callback) {
+ CancellationSignal cancellationSignal, CustomPrinterIconCallback callback) {
if (mCallbacks != null) {
- mCallbacks.onRequestCustomPrinterIcon(printerId, callback);
+ mCallbacks.onRequestCustomPrinterIcon(printerId, cancellationSignal, callback);
}
}
diff --git a/graphics/java/android/graphics/FontListParser.java b/graphics/java/android/graphics/FontListParser.java
index 8f7c6a62..7871aa8 100644
--- a/graphics/java/android/graphics/FontListParser.java
+++ b/graphics/java/android/graphics/FontListParser.java
@@ -179,10 +179,10 @@
int tag = 0;
String tagStr = parser.getAttributeValue(null, "tag");
if (tagStr != null && TAG_PATTERN.matcher(tagStr).matches()) {
- tag = tagStr.charAt(0) << 24 +
- tagStr.charAt(1) << 16 +
- tagStr.charAt(2) << 8 +
- tagStr.charAt(3);
+ tag = (tagStr.charAt(0) << 24) +
+ (tagStr.charAt(1) << 16) +
+ (tagStr.charAt(2) << 8) +
+ (tagStr.charAt(3) );
} else {
throw new XmlPullParserException("Invalid tag attribute value.", parser, null);
}
diff --git a/media/java/android/media/ExifInterface.java b/media/java/android/media/ExifInterface.java
index 4bf0852..cd2d51d 100644
--- a/media/java/android/media/ExifInterface.java
+++ b/media/java/android/media/ExifInterface.java
@@ -693,7 +693,7 @@
*/
public ExifInterface(FileDescriptor fileDescriptor) throws IOException {
if (fileDescriptor == null) {
- throw new IllegalArgumentException("parcelFileDescriptor cannot be null");
+ throw new IllegalArgumentException("fileDescriptor cannot be null");
}
mAssetInputStream = null;
mFilename = null;
@@ -705,7 +705,7 @@
try {
fileDescriptor = Os.dup(fileDescriptor);
} catch (ErrnoException e) {
- e.rethrowAsIOException();
+ throw e.rethrowAsIOException();
}
} else {
mSeekableFileDescriptor = null;
@@ -811,6 +811,9 @@
*/
public void setAttribute(String tag, String value) {
for (int i = 0 ; i < EXIF_TAGS.length; ++i) {
+ if (i == IFD_THUMBNAIL_HINT && !mHasThumbnail) {
+ continue;
+ }
if (sExifTagMapsForWriting[i].containsKey(tag)) {
mAttributes[i].put(tag, value);
}
@@ -818,6 +821,35 @@
}
/**
+ * Update the values of the tags in the tag groups if any value for the tag already was stored.
+ *
+ * @param tag the name of the tag.
+ * @param value the value of the tag.
+ * @return Returns {@code true} if updating is placed.
+ */
+ private boolean updateAttribute(String tag, String value) {
+ boolean updated = false;
+ for (int i = 0 ; i < EXIF_TAGS.length; ++i) {
+ if (mAttributes[i].containsKey(tag)) {
+ mAttributes[i].put(tag, value);
+ updated = true;
+ }
+ }
+ return updated;
+ }
+
+ /**
+ * Remove any values of the specified tag.
+ *
+ * @param tag the name of the tag.
+ */
+ private void removeAttribute(String tag) {
+ for (int i = 0 ; i < EXIF_TAGS.length; ++i) {
+ mAttributes[i].remove(tag);
+ }
+ }
+
+ /**
* This function decides which parser to read the image data according to the given input stream
* type and the content of the input stream. In each case, it reads the first three bytes to
* determine whether the image data format is JPEG or not.
@@ -853,7 +885,7 @@
} catch (IOException e) {
// Ignore exceptions in order to keep the compatibility with the old versions of
// ExifInterface.
- Log.w(TAG, "Invalid JPEG: ExifInterface got an unsupported image format file"
+ Log.w(TAG, "Invalid image: ExifInterface got an unsupported image format file"
+ "(ExifInterface supports JPEG and some RAW image formats only) "
+ "or a corrupted JPEG file to ExifInterface.", e);
} finally {
@@ -882,27 +914,22 @@
// Mark for disabling the save feature.
mIsRaw = true;
- for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
- String attrName = (String) entry.getKey();
-
- switch (attrName) {
- case TAG_HAS_THUMBNAIL:
- mHasThumbnail = ((String) entry.getValue()).equalsIgnoreCase("true");
- break;
- case TAG_THUMBNAIL_OFFSET:
- mThumbnailOffset = Integer.parseInt((String) entry.getValue());
- break;
- case TAG_THUMBNAIL_LENGTH:
- mThumbnailLength = Integer.parseInt((String) entry.getValue());
- break;
- case TAG_THUMBNAIL_DATA:
- mThumbnailBytes = (byte[]) entry.getValue();
- break;
- default:
- setAttribute(attrName, (String) entry.getValue());
- break;
- }
+ String value = (String) map.remove(TAG_HAS_THUMBNAIL);
+ mHasThumbnail = value != null && value.equalsIgnoreCase("true");
+ value = (String) map.remove(TAG_THUMBNAIL_OFFSET);
+ if (value != null) {
+ mThumbnailOffset = Integer.parseInt(value);
}
+ value = (String) map.remove(TAG_THUMBNAIL_LENGTH);
+ if (value != null) {
+ mThumbnailLength = Integer.parseInt(value);
+ }
+ mThumbnailBytes = (byte[]) map.remove(TAG_THUMBNAIL_DATA);
+
+ for (Map.Entry entry : (Set<Map.Entry>) map.entrySet()) {
+ setAttribute((String) entry.getKey(), (String) entry.getValue());
+ }
+
return true;
}
@@ -928,7 +955,7 @@
/**
* Save the tag data into the original image file. This is expensive because it involves
* copying all the data from one file to another and deleting the old file and renaming the
- * other. It's best to use{@link #setAttribute(String,String)} to set all attributes to write
+ * other. It's best to use {@link #setAttribute(String,String)} to set all attributes to write
* and make a single call rather than multiple calls for each attribute.
*/
public void saveAttributes() throws IOException {
@@ -963,7 +990,7 @@
Streams.copy(in, out);
}
} catch (ErrnoException e) {
- e.rethrowAsIOException();
+ throw e.rethrowAsIOException();
} finally {
IoUtils.closeQuietly(in);
IoUtils.closeQuietly(out);
@@ -982,7 +1009,7 @@
}
saveJpegAttributes(in, out);
} catch (ErrnoException e) {
- e.rethrowAsIOException();
+ throw e.rethrowAsIOException();
} finally {
IoUtils.closeQuietly(in);
IoUtils.closeQuietly(out);
@@ -1276,7 +1303,8 @@
throw new IOException("Invalid exif");
}
length = 0;
- setAttribute("UserComment", new String(bytes, Charset.forName("US-ASCII")));
+ mAttributes[IFD_EXIF_HINT].put(TAG_USER_COMMENT,
+ new String(bytes, Charset.forName("US-ASCII")));
break;
}
@@ -1296,9 +1324,10 @@
if (dataInputStream.skipBytes(1) != 1) {
throw new IOException("Invalid SOFx");
}
- setAttribute("ImageLength",
+ mAttributes[IFD_TIFF_HINT].put(TAG_IMAGE_LENGTH,
String.valueOf(dataInputStream.readUnsignedShort()));
- setAttribute("ImageWidth", String.valueOf(dataInputStream.readUnsignedShort()));
+ mAttributes[IFD_TIFF_HINT].put(TAG_IMAGE_WIDTH,
+ String.valueOf(dataInputStream.readUnsignedShort()));
length -= 5;
break;
}
@@ -1521,31 +1550,31 @@
convertToInt(TAG_GPS_ALTITUDE_REF);
convertToRational(TAG_GPS_LONGITUDE);
convertToRational(TAG_GPS_LATITUDE);
- convertToTimetamp(TAG_GPS_TIMESTAMP);
+ convertToTimestamp(TAG_GPS_TIMESTAMP);
// The value of DATETIME tag has the same value of DATETIME_ORIGINAL tag.
- String valueOfDateTimeOriginal = getAttribute("DateTimeOriginal");
+ String valueOfDateTimeOriginal = getAttribute(TAG_DATETIME_ORIGINAL);
if (valueOfDateTimeOriginal != null) {
- setAttribute(TAG_DATETIME, valueOfDateTimeOriginal);
+ mAttributes[IFD_TIFF_HINT].put(TAG_DATETIME, valueOfDateTimeOriginal);
}
// Add the default value.
if (getAttribute(TAG_IMAGE_WIDTH) == null) {
- setAttribute(TAG_IMAGE_WIDTH, "0");
+ mAttributes[IFD_TIFF_HINT].put(TAG_IMAGE_WIDTH, "0");
}
if (getAttribute(TAG_IMAGE_LENGTH) == null) {
- setAttribute(TAG_IMAGE_LENGTH, "0");
+ mAttributes[IFD_TIFF_HINT].put(TAG_IMAGE_LENGTH, "0");
}
if (getAttribute(TAG_ORIENTATION) == null) {
- setAttribute(TAG_ORIENTATION, "0");
+ mAttributes[IFD_TIFF_HINT].put(TAG_ORIENTATION, "0");
}
if (getAttribute(TAG_LIGHT_SOURCE) == null) {
- setAttribute(TAG_LIGHT_SOURCE, "0");
+ mAttributes[IFD_EXIF_HINT].put(TAG_LIGHT_SOURCE, "0");
}
}
// Converts the tag value to timestamp; Otherwise deletes the given tag.
- private void convertToTimetamp(String tagName) {
+ private void convertToTimestamp(String tagName) {
String entryValue = getAttribute(tagName);
if (entryValue == null) return;
int dataFormat = getDataFormatOfExifEntryValue(entryValue);
@@ -1566,9 +1595,9 @@
int value = numerator / denominator;
stringBuilder.append(String.format("%02d", value));
}
- setAttribute(tagName, stringBuilder.toString());
+ updateAttribute(tagName, stringBuilder.toString());
} else if (dataFormat != IFD_FORMAT_STRING) {
- setAttribute(tagName, null);
+ removeAttribute(tagName);
}
}
@@ -1595,14 +1624,14 @@
}
stringBuilder.append((double) numerator / denominator);
}
- setAttribute(tagName, stringBuilder.toString());
+ updateAttribute(tagName, stringBuilder.toString());
break;
}
case IFD_FORMAT_DOUBLE:
// Keep it as is.
break;
default:
- setAttribute(tagName, null);
+ removeAttribute(tagName);
break;
}
}
@@ -1624,14 +1653,14 @@
double doubleValue = Double.parseDouble(component);
stringBuilder.append((int) (doubleValue * 10000.0)).append("/").append(10000);
}
- setAttribute(tagName, stringBuilder.toString());
+ updateAttribute(tagName, stringBuilder.toString());
break;
}
case IFD_FORMAT_SRATIONAL:
// Keep it as is.
break;
default:
- setAttribute(tagName, null);
+ removeAttribute(tagName);
break;
}
}
@@ -1642,7 +1671,7 @@
if (entryValue == null) return;
int dataFormat = getDataFormatOfExifEntryValue(entryValue);
if (dataFormat != IFD_FORMAT_SLONG) {
- setAttribute(tagName, null);
+ removeAttribute(tagName);
}
}
@@ -1758,7 +1787,7 @@
String entryValue = readExifEntryValue(
dataInputStream, dataFormat, numberOfComponents);
if (entryValue != null) {
- setAttribute(tagName, entryValue);
+ mAttributes[hint].put(tagName, entryValue);
}
} else {
StringBuilder entryValueBuilder = new StringBuilder();
@@ -1769,7 +1798,7 @@
entryValueBuilder.append(readExifEntryValue(
dataInputStream, dataFormat, numberOfComponents));
}
- setAttribute(tagName, entryValueBuilder.toString());
+ mAttributes[hint].put(tagName, entryValueBuilder.toString());
}
if (dataInputStream.peek() != nextEntryOffset) {
@@ -1886,11 +1915,11 @@
// Remove IFD pointer tags (we'll re-add it later.)
for (ExifTag tag : IFD_POINTER_TAGS) {
- setAttribute(tag.name, null);
+ removeAttribute(tag.name);
}
// Remove old thumbnail data
- setAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name, null);
- setAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name, null);
+ removeAttribute(JPEG_INTERCHANGE_FORMAT_TAG.name);
+ removeAttribute(JPEG_INTERCHANGE_FORMAT_LENGTH_TAG.name);
// Remove null value tags.
for (int hint = 0; hint < EXIF_TAGS.length; ++hint) {
diff --git a/media/tests/MediaFrameworkTest/res/values/exifinterface.xml b/media/tests/MediaFrameworkTest/res/values/exifinterface.xml
index d556ad3..3c5dd37 100644
--- a/media/tests/MediaFrameworkTest/res/values/exifinterface.xml
+++ b/media/tests/MediaFrameworkTest/res/values/exifinterface.xml
@@ -103,7 +103,7 @@
<item>600</item>
<item>800</item>
<item>1</item>
- <item />
+ <item>0</item>
</array>
<array name="volantis_jpg">
<item>false</item>
diff --git a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/ExifInterfaceTest.java b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/ExifInterfaceTest.java
index 6207f7d..dde9bda 100644
--- a/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/ExifInterfaceTest.java
+++ b/media/tests/MediaFrameworkTest/src/com/android/mediaframeworktest/unit/ExifInterfaceTest.java
@@ -45,7 +45,7 @@
private static final String TAG = ExifInterface.class.getSimpleName();
private static final boolean VERBOSE = false; // lots of logging
- private static final double DIFFERENCE_TOLERANCE = .005;
+ private static final double DIFFERENCE_TOLERANCE = .001;
// List of files.
private static final String EXIF_BYTE_ORDER_II_JPEG = "image_exif_byte_order_ii.jpg";
@@ -111,11 +111,11 @@
public final String gpsLongitudeRef;
public final String gpsProcessingMethod;
public final String gpsTimestamp;
- public final String imageLength;
- public final String imageWidth;
+ public final int imageLength;
+ public final int imageWidth;
public final String iso;
- public final String whiteBalance;
- public final String orientation;
+ public final int orientation;
+ public final int whiteBalance;
private static String getString(TypedArray typedArray, int index) {
String stringValue = typedArray.getString(index);
@@ -137,7 +137,7 @@
longitude = typedArray.getFloat(5, 0f);
altitude = typedArray.getFloat(6, 0f);
- // Read values.
+ // Reads values.
make = getString(typedArray, 7);
model = getString(typedArray, 8);
aperture = typedArray.getFloat(9, 0f);
@@ -154,11 +154,11 @@
gpsLongitudeRef = getString(typedArray, 20);
gpsProcessingMethod = getString(typedArray, 21);
gpsTimestamp = getString(typedArray, 22);
- imageLength = getString(typedArray, 23);
- imageWidth = getString(typedArray, 24);
+ imageLength = typedArray.getInt(23, 0);
+ imageWidth = typedArray.getInt(24, 0);
iso = getString(typedArray, 25);
- orientation = getString(typedArray, 26);
- whiteBalance = getString(typedArray, 27);
+ orientation = typedArray.getInt(26, 0);
+ whiteBalance = typedArray.getInt(27, 0);
typedArray.recycle();
}
@@ -208,11 +208,13 @@
+ bitmap.getHeight());
}
} else {
- Log.e(TAG, fileName + " Corrupted image (no thumbnail)");
+ Log.e(TAG, fileName + " Unexpected result: No thumbnails were found. "
+ + "A thumbnail is expected.");
}
} else {
if (exifInterface.getThumbnail() != null) {
- Log.e(TAG, fileName + " Corrupted image (a thumbnail exists)");
+ Log.e(TAG, fileName + " Unexpected result: A thumbnail was found. "
+ + "No thumbnail is expected.");
} else {
Log.v(TAG, fileName + " No thumbnail");
}
@@ -226,28 +228,27 @@
Log.v(TAG, fileName + " Latitude = " + latLong[0]);
Log.v(TAG, fileName + " Longitude = " + latLong[1]);
} else {
- Log.v(TAG, fileName + "No latlong data");
+ Log.v(TAG, fileName + " No latlong data");
}
// Prints values.
for (String tagKey : EXIF_TAGS) {
String tagValue = exifInterface.getAttribute(tagKey);
- Log.v(TAG, fileName + "Key{" + tagKey + "} = '" + tagValue + "'");
+ Log.v(TAG, fileName + " Key{" + tagKey + "} = '" + tagValue + "'");
}
}
- private void compareFloatTag(ExifInterface exifInterface, String tag, float expectedValue) {
- String stringValue = exifInterface.getAttribute(tag);
- float floatValue = 0f;
-
- if (stringValue != null) {
- floatValue = Float.parseFloat(stringValue);
- }
-
- assertEquals(expectedValue, floatValue, DIFFERENCE_TOLERANCE);
+ private void assertIntTag(ExifInterface exifInterface, String tag, int expectedValue) {
+ int intValue = exifInterface.getAttributeInt(tag, 0);
+ assertEquals(expectedValue, intValue);
}
- private void compareStringTag(ExifInterface exifInterface, String tag, String expectedValue) {
+ private void assertFloatTag(ExifInterface exifInterface, String tag, float expectedValue) {
+ double doubleValue = exifInterface.getAttributeDouble(tag, 0.0);
+ assertEquals(expectedValue, doubleValue, DIFFERENCE_TOLERANCE);
+ }
+
+ private void assertStringTag(ExifInterface exifInterface, String tag, String expectedValue) {
String stringValue = exifInterface.getAttribute(tag);
if (stringValue != null) {
stringValue = stringValue.trim();
@@ -257,7 +258,10 @@
}
private void compareWithExpectedValue(ExifInterface exifInterface,
- ExpectedValue expectedValue) {
+ ExpectedValue expectedValue, String verboseTag) {
+ if (VERBOSE) {
+ printExifTagsAndValues(verboseTag, exifInterface);
+ }
// Checks a thumbnail image.
assertEquals(expectedValue.hasThumbnail, exifInterface.hasThumbnail());
if (expectedValue.hasThumbnail) {
@@ -282,78 +286,144 @@
assertEquals(expectedValue.altitude, exifInterface.getAltitude(.0), DIFFERENCE_TOLERANCE);
// Checks values.
- compareStringTag(exifInterface, ExifInterface.TAG_MAKE, expectedValue.make);
- compareStringTag(exifInterface, ExifInterface.TAG_MODEL, expectedValue.model);
- compareFloatTag(exifInterface, ExifInterface.TAG_APERTURE, expectedValue.aperture);
- compareStringTag(exifInterface, ExifInterface.TAG_DATETIME, expectedValue.datetime);
- compareFloatTag(exifInterface, ExifInterface.TAG_EXPOSURE_TIME, expectedValue.exposureTime);
- compareFloatTag(exifInterface, ExifInterface.TAG_FLASH, expectedValue.flash);
- compareStringTag(exifInterface, ExifInterface.TAG_FOCAL_LENGTH, expectedValue.focalLength);
- compareStringTag(exifInterface, ExifInterface.TAG_GPS_ALTITUDE, expectedValue.gpsAltitude);
- compareStringTag(exifInterface, ExifInterface.TAG_GPS_ALTITUDE_REF,
+ assertStringTag(exifInterface, ExifInterface.TAG_MAKE, expectedValue.make);
+ assertStringTag(exifInterface, ExifInterface.TAG_MODEL, expectedValue.model);
+ assertFloatTag(exifInterface, ExifInterface.TAG_APERTURE, expectedValue.aperture);
+ assertStringTag(exifInterface, ExifInterface.TAG_DATETIME, expectedValue.datetime);
+ assertFloatTag(exifInterface, ExifInterface.TAG_EXPOSURE_TIME, expectedValue.exposureTime);
+ assertFloatTag(exifInterface, ExifInterface.TAG_FLASH, expectedValue.flash);
+ assertStringTag(exifInterface, ExifInterface.TAG_FOCAL_LENGTH, expectedValue.focalLength);
+ assertStringTag(exifInterface, ExifInterface.TAG_GPS_ALTITUDE, expectedValue.gpsAltitude);
+ assertStringTag(exifInterface, ExifInterface.TAG_GPS_ALTITUDE_REF,
expectedValue.gpsAltitudeRef);
- compareStringTag(exifInterface, ExifInterface.TAG_GPS_DATESTAMP,
- expectedValue.gpsDatestamp);
- compareStringTag(exifInterface, ExifInterface.TAG_GPS_LATITUDE, expectedValue.gpsLatitude);
- compareStringTag(exifInterface, ExifInterface.TAG_GPS_LATITUDE_REF,
+ assertStringTag(exifInterface, ExifInterface.TAG_GPS_DATESTAMP, expectedValue.gpsDatestamp);
+ assertStringTag(exifInterface, ExifInterface.TAG_GPS_LATITUDE, expectedValue.gpsLatitude);
+ assertStringTag(exifInterface, ExifInterface.TAG_GPS_LATITUDE_REF,
expectedValue.gpsLatitudeRef);
- compareStringTag(exifInterface, ExifInterface.TAG_GPS_LONGITUDE,
- expectedValue.gpsLongitude);
- compareStringTag(exifInterface, ExifInterface.TAG_GPS_LONGITUDE_REF,
+ assertStringTag(exifInterface, ExifInterface.TAG_GPS_LONGITUDE, expectedValue.gpsLongitude);
+ assertStringTag(exifInterface, ExifInterface.TAG_GPS_LONGITUDE_REF,
expectedValue.gpsLongitudeRef);
- compareStringTag(exifInterface, ExifInterface.TAG_GPS_PROCESSING_METHOD,
+ assertStringTag(exifInterface, ExifInterface.TAG_GPS_PROCESSING_METHOD,
expectedValue.gpsProcessingMethod);
- compareStringTag(exifInterface, ExifInterface.TAG_GPS_TIMESTAMP,
- expectedValue.gpsTimestamp);
- compareStringTag(exifInterface, ExifInterface.TAG_IMAGE_LENGTH, expectedValue.imageLength);
- compareStringTag(exifInterface, ExifInterface.TAG_IMAGE_WIDTH, expectedValue.imageWidth);
- compareStringTag(exifInterface, ExifInterface.TAG_ISO, expectedValue.iso);
- compareStringTag(exifInterface, ExifInterface.TAG_ORIENTATION, expectedValue.orientation);
- compareStringTag(exifInterface, ExifInterface.TAG_WHITE_BALANCE,
- expectedValue.whiteBalance);
+ assertStringTag(exifInterface, ExifInterface.TAG_GPS_TIMESTAMP, expectedValue.gpsTimestamp);
+ assertIntTag(exifInterface, ExifInterface.TAG_IMAGE_LENGTH, expectedValue.imageLength);
+ assertIntTag(exifInterface, ExifInterface.TAG_IMAGE_WIDTH, expectedValue.imageWidth);
+ assertStringTag(exifInterface, ExifInterface.TAG_ISO, expectedValue.iso);
+ assertIntTag(exifInterface, ExifInterface.TAG_ORIENTATION, expectedValue.orientation);
+ assertIntTag(exifInterface, ExifInterface.TAG_WHITE_BALANCE, expectedValue.whiteBalance);
}
private void testExifInterfaceCommon(File imageFile, ExpectedValue expectedValue)
throws IOException {
- // Created via path.
+ String verboseTag = imageFile.getName();
+
+ // Creates via path.
ExifInterface exifInterface = new ExifInterface(imageFile.getAbsolutePath());
- if (VERBOSE) {
- printExifTagsAndValues(imageFile.getName(), exifInterface);
- }
- compareWithExpectedValue(exifInterface, expectedValue);
+ compareWithExpectedValue(exifInterface, expectedValue, verboseTag);
- // Created from an asset file.
- InputStream in = mContext.getAssets().open(imageFile.getName());
- exifInterface = new ExifInterface(in);
- if (VERBOSE) {
- printExifTagsAndValues(imageFile.getName(), exifInterface);
- }
- compareWithExpectedValue(exifInterface, expectedValue);
-
- // Created via InputStream.
- in = null;
+ // Creates from an asset file.
+ InputStream in = null;
try {
- in = new BufferedInputStream(new FileInputStream(imageFile.getAbsolutePath()));
+ in = mContext.getAssets().open(imageFile.getName());
exifInterface = new ExifInterface(in);
- if (VERBOSE) {
- printExifTagsAndValues(imageFile.getName(), exifInterface);
- }
- compareWithExpectedValue(exifInterface, expectedValue);
+ compareWithExpectedValue(exifInterface, expectedValue, verboseTag);
} finally {
IoUtils.closeQuietly(in);
}
- // Created via FileDescriptor.
+ // Creates via InputStream.
+ in = null;
try {
- FileDescriptor fd = Os.open(imageFile.getAbsolutePath(), OsConstants.O_RDONLY, 0600);
- exifInterface = new ExifInterface(fd);
- if (VERBOSE) {
- printExifTagsAndValues(imageFile.getName(), exifInterface);
- }
- compareWithExpectedValue(exifInterface, expectedValue);
- } catch (ErrnoException e) {
- e.rethrowAsIOException();
+ in = new BufferedInputStream(new FileInputStream(imageFile.getAbsolutePath()));
+ exifInterface = new ExifInterface(in);
+ compareWithExpectedValue(exifInterface, expectedValue, verboseTag);
+ } finally {
+ IoUtils.closeQuietly(in);
}
+
+ // Creates via FileDescriptor.
+ FileDescriptor fd = null;
+ try {
+ fd = Os.open(imageFile.getAbsolutePath(), OsConstants.O_RDONLY, 0600);
+ exifInterface = new ExifInterface(fd);
+ compareWithExpectedValue(exifInterface, expectedValue, verboseTag);
+ } catch (ErrnoException e) {
+ throw e.rethrowAsIOException();
+ } finally {
+ IoUtils.closeQuietly(fd);
+ }
+ }
+
+ private void testSaveAttributes_withFileName(File imageFile, ExpectedValue expectedValue)
+ throws IOException {
+ String verboseTag = imageFile.getName();
+
+ ExifInterface exifInterface = new ExifInterface(imageFile.getAbsolutePath());
+ exifInterface.saveAttributes();
+ exifInterface = new ExifInterface(imageFile.getAbsolutePath());
+ compareWithExpectedValue(exifInterface, expectedValue, verboseTag);
+
+ // Test for modifying one attribute.
+ String backupValue = exifInterface.getAttribute(ExifInterface.TAG_MAKE);
+ exifInterface.setAttribute(ExifInterface.TAG_MAKE, "abc");
+ exifInterface.saveAttributes();
+ exifInterface = new ExifInterface(imageFile.getAbsolutePath());
+ assertEquals("abc", exifInterface.getAttribute(ExifInterface.TAG_MAKE));
+ // Restore the backup value.
+ exifInterface.setAttribute(ExifInterface.TAG_MAKE, backupValue);
+ exifInterface.saveAttributes();
+ exifInterface = new ExifInterface(imageFile.getAbsolutePath());
+ compareWithExpectedValue(exifInterface, expectedValue, verboseTag);
+ }
+
+ private void testSaveAttributes_withFileDescriptor(File imageFile, ExpectedValue expectedValue)
+ throws IOException {
+ String verboseTag = imageFile.getName();
+
+ FileDescriptor fd = null;
+ try {
+ fd = Os.open(imageFile.getAbsolutePath(), OsConstants.O_RDWR, 0600);
+ ExifInterface exifInterface = new ExifInterface(fd);
+ exifInterface.saveAttributes();
+ Os.lseek(fd, 0, OsConstants.SEEK_SET);
+ exifInterface = new ExifInterface(fd);
+ compareWithExpectedValue(exifInterface, expectedValue, verboseTag);
+
+ // Test for modifying one attribute.
+ String backupValue = exifInterface.getAttribute(ExifInterface.TAG_MAKE);
+ exifInterface.setAttribute(ExifInterface.TAG_MAKE, "abc");
+ exifInterface.saveAttributes();
+ Os.lseek(fd, 0, OsConstants.SEEK_SET);
+ exifInterface = new ExifInterface(fd);
+ assertEquals("abc", exifInterface.getAttribute(ExifInterface.TAG_MAKE));
+ // Restore the backup value.
+ exifInterface.setAttribute(ExifInterface.TAG_MAKE, backupValue);
+ exifInterface.saveAttributes();
+ Os.lseek(fd, 0, OsConstants.SEEK_SET);
+ exifInterface = new ExifInterface(fd);
+ compareWithExpectedValue(exifInterface, expectedValue, verboseTag);
+ } catch (ErrnoException e) {
+ throw e.rethrowAsIOException();
+ } finally {
+ IoUtils.closeQuietly(fd);
+ }
+ }
+
+ private void testSaveAttributes_withInputStream(File imageFile, ExpectedValue expectedValue)
+ throws IOException {
+ InputStream in = null;
+ try {
+ in = getContext().getAssets().open(imageFile.getName());
+ ExifInterface exifInterface = new ExifInterface(in);
+ exifInterface.saveAttributes();
+ } catch (UnsupportedOperationException e) {
+ // Expected. saveAttributes is not supported with an ExifInterface object which was
+ // created with InputStream.
+ return;
+ } finally {
+ IoUtils.closeQuietly(in);
+ }
+ fail("Should not reach here!");
}
private void testExifInterfaceForJpeg(String fileName, int typedArrayResourceId)
@@ -366,30 +436,9 @@
testExifInterfaceCommon(imageFile, expectedValue);
// Test for saving attributes.
- ExifInterface exifInterface;
- try {
- FileDescriptor fd = Os.open(imageFile.getAbsolutePath(), OsConstants.O_RDWR, 0600);
- exifInterface = new ExifInterface(fd);
- exifInterface.saveAttributes();
- fd = Os.open(imageFile.getAbsolutePath(), OsConstants.O_RDWR, 0600);
- exifInterface = new ExifInterface(fd);
- if (VERBOSE) {
- printExifTagsAndValues(fileName, exifInterface);
- }
- compareWithExpectedValue(exifInterface, expectedValue);
- } catch (ErrnoException e) {
- e.rethrowAsIOException();
- }
-
- // Test for modifying one attribute.
- exifInterface = new ExifInterface(imageFile.getAbsolutePath());
- exifInterface.setAttribute(ExifInterface.TAG_MAKE, "abc");
- exifInterface.saveAttributes();
- exifInterface = new ExifInterface(imageFile.getAbsolutePath());
- if (VERBOSE) {
- printExifTagsAndValues(fileName, exifInterface);
- }
- assertEquals("abc", exifInterface.getAttribute(ExifInterface.TAG_MAKE));
+ testSaveAttributes_withFileName(imageFile, expectedValue);
+ testSaveAttributes_withFileDescriptor(imageFile, expectedValue);
+ testSaveAttributes_withInputStream(imageFile, expectedValue);
}
private void testExifInterfaceForRaw(String fileName, int typedArrayResourceId)
diff --git a/packages/DocumentsUI/perf-tests/Android.mk b/packages/DocumentsUI/perf-tests/Android.mk
index 919fc56..5ebf85f 100644
--- a/packages/DocumentsUI/perf-tests/Android.mk
+++ b/packages/DocumentsUI/perf-tests/Android.mk
@@ -2,8 +2,8 @@
include $(CLEAR_VARS)
LOCAL_MODULE_TAGS := tests
-#LOCAL_SDK_VERSION := current
+LOCAL_RESOURCE_DIR := $(LOCAL_PATH)/res
LOCAL_SRC_FILES := $(call all-java-files-under, src) \
$(call all-java-files-under, ../tests/src/com/android/documentsui/bots) \
../tests/src/com/android/documentsui/ActivityTest.java \
diff --git a/packages/DocumentsUI/perf-tests/res/raw/earth_small.jpg b/packages/DocumentsUI/perf-tests/res/raw/earth_small.jpg
new file mode 100644
index 0000000..dd2da3e
--- /dev/null
+++ b/packages/DocumentsUI/perf-tests/res/raw/earth_small.jpg
Binary files differ
diff --git a/packages/DocumentsUI/perf-tests/src/com/android/documentsui/StressProvider.java b/packages/DocumentsUI/perf-tests/src/com/android/documentsui/StressProvider.java
index 6147a71..f9b06f8 100644
--- a/packages/DocumentsUI/perf-tests/src/com/android/documentsui/StressProvider.java
+++ b/packages/DocumentsUI/perf-tests/src/com/android/documentsui/StressProvider.java
@@ -18,9 +18,11 @@
import android.content.Context;
import android.content.pm.ProviderInfo;
+import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.database.MatrixCursor.RowBuilder;
import android.database.MatrixCursor;
+import android.graphics.Point;
import android.os.CancellationSignal;
import android.os.FileUtils;
import android.os.ParcelFileDescriptor;
@@ -31,6 +33,7 @@
import java.io.File;
import java.io.FileNotFoundException;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -102,7 +105,14 @@
children = new ArrayList<StubDocument>();
mChildDocuments.put(STRESS_ROOT_2_DOC_ID, children);
for (int i = 0; i < STRESS_ROOT_2_ITEMS; i++) {
- document = StubDocument.createFile(STRESS_ROOT_1_ITEMS + i);
+ try {
+ document = StubDocument.createFile(
+ getContext(), MIME_TYPE_IMAGE,
+ com.android.documentsui.perftests.R.raw.earth_small,
+ STRESS_ROOT_1_ITEMS + i);
+ } catch (IOException e) {
+ return false;
+ }
mDocuments.put(document.id, document);
children.add(document);
}
@@ -151,6 +161,14 @@
}
@Override
+ public AssetFileDescriptor openDocumentThumbnail(String docId, Point sizeHint,
+ CancellationSignal signal)
+ throws FileNotFoundException {
+ final StubDocument document = mDocuments.get(docId);
+ return getContext().getResources().openRawResourceFd(document.thumbnail);
+ }
+
+ @Override
public ParcelFileDescriptor openDocument(String docId, String mode,
CancellationSignal signal)
throws FileNotFoundException {
@@ -171,7 +189,8 @@
row.add(Document.COLUMN_DISPLAY_NAME, document.id);
row.add(Document.COLUMN_SIZE, document.size);
row.add(Document.COLUMN_MIME_TYPE, document.mimeType);
- row.add(Document.COLUMN_FLAGS, 0);
+ row.add(Document.COLUMN_FLAGS,
+ document.thumbnail != -1 ? Document.FLAG_SUPPORTS_THUMBNAIL : 0);
row.add(Document.COLUMN_LAST_MODIFIED, document.lastModified);
}
@@ -184,28 +203,32 @@
final String id;
final int size;
final long lastModified;
+ final int thumbnail;
- private StubDocument(String mimeType, String id, int size, long lastModified) {
+ private StubDocument(String mimeType, String id, int size, long lastModified,
+ int thumbnail) {
this.mimeType = mimeType;
this.id = id;
this.size = size;
this.lastModified = lastModified;
+ this.thumbnail = thumbnail;
}
public static StubDocument createDirectory(int index) {
return new StubDocument(
DocumentsContract.Document.MIME_TYPE_DIR, createRandomId(index), 0,
- createRandomTime(index));
+ createRandomTime(index), -1);
}
public static StubDocument createDirectory(String id) {
- return new StubDocument(DocumentsContract.Document.MIME_TYPE_DIR, id, 0, 0);
+ return new StubDocument(DocumentsContract.Document.MIME_TYPE_DIR, id, 0, 0, -1);
}
- public static StubDocument createFile(int index) {
+ public static StubDocument createFile(Context context, String mimeType, int thumbnail,
+ int index) throws IOException {
return new StubDocument(
- MIME_TYPE_IMAGE, createRandomId(index), createRandomSize(index),
- createRandomTime(index));
+ mimeType, createRandomId(index), createRandomSize(index),
+ createRandomTime(index), thumbnail);
}
private static String createRandomId(int index) {
diff --git a/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java b/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java
index 9ed2abf..f10af43 100644
--- a/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java
+++ b/packages/DocumentsUI/src/com/android/documentsui/services/CopyJob.java
@@ -45,6 +45,8 @@
import android.os.RemoteException;
import android.provider.DocumentsContract;
import android.provider.DocumentsContract.Document;
+import android.system.ErrnoException;
+import android.system.Os;
import android.text.format.DateUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
@@ -451,7 +453,7 @@
ParcelFileDescriptor srcFile = null;
ParcelFileDescriptor dstFile = null;
InputStream in = null;
- OutputStream out = null;
+ ParcelFileDescriptor.AutoCloseOutputStream out = null;
boolean success = false;
try {
@@ -502,6 +504,8 @@
makeCopyProgress(len);
}
+ // Need to invoke IoUtils.close explicitly to avoid from ignoring errors at flush.
+ IoUtils.close(dstFile.getFileDescriptor());
srcFile.checkError();
} catch (IOException e) {
throw new ResourceException(
diff --git a/packages/MtpDocumentsProvider/jni/com_android_mtp_AppFuse.cpp b/packages/MtpDocumentsProvider/jni/com_android_mtp_AppFuse.cpp
index 1d4ed1d..eb96015 100644
--- a/packages/MtpDocumentsProvider/jni/com_android_mtp_AppFuse.cpp
+++ b/packages/MtpDocumentsProvider/jni/com_android_mtp_AppFuse.cpp
@@ -52,6 +52,8 @@
static jmethodID app_fuse_get_file_size;
static jmethodID app_fuse_read_object_bytes;
static jmethodID app_fuse_write_object_bytes;
+static jmethodID app_fuse_flush_file_handle;
+static jmethodID app_fuse_close_file_handle;
static jfieldID app_fuse_buffer;
// NOTE:
@@ -307,7 +309,8 @@
const uint32_t size = in->size;
const void* const buffer = reinterpret_cast<const uint8_t*>(in) + sizeof(fuse_write_in);
uint32_t written_size;
- const int result = write_object_bytes(it->second, offset, size, buffer, &written_size);
+ const int result = write_object_bytes(
+ in->fh, it->second, offset, size, buffer, &written_size);
if (result < 0) {
return result;
}
@@ -320,13 +323,13 @@
const fuse_release_in* in,
FuseResponse<void>* /* out */) {
handles_.erase(in->fh);
- return 0;
+ return env_->CallIntMethod(self_, app_fuse_close_file_handle, file_handle_to_jlong(in->fh));
}
int handle_fuse_flush(const fuse_in_header& /* header */,
- const void* /* in */,
+ const fuse_flush_in* in,
FuseResponse<void>* /* out */) {
- return 0;
+ return env_->CallIntMethod(self_, app_fuse_flush_file_handle, file_handle_to_jlong(in->fh));
}
template <typename T, typename S>
@@ -382,8 +385,10 @@
return read_size;
}
- int write_object_bytes(int inode, uint64_t offset, uint32_t size, const void* buffer,
- uint32_t* written_size) {
+ int write_object_bytes(uint64_t handle, int inode, uint64_t offset, uint32_t size,
+ const void* buffer, uint32_t* written_size) {
+ static_assert(sizeof(uint64_t) <= sizeof(jlong),
+ "jlong must be able to express any uint64_t values");
ScopedLocalRef<jbyteArray> array(
env_,
static_cast<jbyteArray>(env_->GetObjectField(self_, app_fuse_buffer)));
@@ -394,15 +399,28 @@
}
memcpy(bytes.get(), buffer, size);
}
- *written_size = env_->CallIntMethod(
- self_, app_fuse_write_object_bytes, inode, offset, size, array.get());
- if (env_->ExceptionCheck()) {
- env_->ExceptionClear();
- return -EIO;
+ const int result = env_->CallIntMethod(
+ self_,
+ app_fuse_write_object_bytes,
+ file_handle_to_jlong(handle),
+ inode,
+ offset,
+ size,
+ array.get());
+ if (result < 0) {
+ return result;
}
+ *written_size = result;
return 0;
}
+ static jlong file_handle_to_jlong(uint64_t handle) {
+ static_assert(
+ sizeof(uint64_t) <= sizeof(jlong),
+ "jlong must be able to express any uint64_t values");
+ return static_cast<jlong>(handle);
+ }
+
static void fuse_reply(int fd, int unique, int reply_code, void* reply_data,
size_t reply_size) {
// Don't send any data for error case.
@@ -511,15 +529,21 @@
return -1;
}
- app_fuse_buffer = env->GetFieldID(app_fuse_class, "mBuffer", "[B");
- if (app_fuse_buffer == nullptr) {
- ALOGE("Can't find mBuffer");
+ app_fuse_write_object_bytes = env->GetMethodID(app_fuse_class, "writeObjectBytes", "(JIJI[B)I");
+ if (app_fuse_write_object_bytes == nullptr) {
+ ALOGE("Can't find writeObjectBytes");
return -1;
}
- app_fuse_write_object_bytes = env->GetMethodID(app_fuse_class, "writeObjectBytes", "(IJI[B)I");
- if (app_fuse_write_object_bytes == nullptr) {
- ALOGE("Can't find getWriteObjectBytes");
+ app_fuse_flush_file_handle = env->GetMethodID(app_fuse_class, "flushFileHandle", "(J)I");
+ if (app_fuse_flush_file_handle == nullptr) {
+ ALOGE("Can't find flushFileHandle");
+ return -1;
+ }
+
+ app_fuse_close_file_handle = env->GetMethodID(app_fuse_class, "closeFileHandle", "(J)I");
+ if (app_fuse_close_file_handle == nullptr) {
+ ALOGE("Can't find closeFileHandle");
return -1;
}
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/AppFuse.java b/packages/MtpDocumentsProvider/src/com/android/mtp/AppFuse.java
index 777dc60..88858a8 100644
--- a/packages/MtpDocumentsProvider/src/com/android/mtp/AppFuse.java
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/AppFuse.java
@@ -20,6 +20,7 @@
import android.os.ParcelFileDescriptor;
import android.os.Process;
import android.os.storage.StorageManager;
+import android.system.ErrnoException;
import android.system.OsConstants;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
@@ -34,6 +35,8 @@
System.loadLibrary("appfuse_jni");
}
+ private static final boolean DEBUG = false;
+
/**
* Max read amount specified at the FUSE kernel implementation.
* The value is copied from sdcard.c.
@@ -94,7 +97,8 @@
public ParcelFileDescriptor openFile(int i, int mode) throws FileNotFoundException {
Preconditions.checkArgument(
mode == ParcelFileDescriptor.MODE_READ_ONLY ||
- mode == ParcelFileDescriptor.MODE_WRITE_ONLY);
+ mode == (ParcelFileDescriptor.MODE_WRITE_ONLY |
+ ParcelFileDescriptor.MODE_TRUNCATE));
return ParcelFileDescriptor.open(new File(
getMountPoint(),
Integer.toString(i)),
@@ -127,6 +131,7 @@
/**
* Handles writing bytes for the give inode.
+ * @param fileHandle
* @param inode
* @param offset Offset for file bytes.
* @param size Size for file bytes.
@@ -134,7 +139,23 @@
* @return Number of read bytes. Must not be negative.
* @throws IOException
*/
- int writeObjectBytes(int inode, long offset, int size, byte[] bytes) throws IOException;
+ int writeObjectBytes(long fileHandle, int inode, long offset, int size, byte[] bytes)
+ throws IOException, ErrnoException;
+
+ /**
+ * Flushes bytes for file handle.
+ * @param fileHandle
+ * @throws IOException
+ * @throws ErrnoException
+ */
+ void flushFileHandle(long fileHandle) throws IOException, ErrnoException;
+
+ /**
+ * Closes file handle.
+ * @param fileHandle
+ * @throws IOException
+ */
+ void closeFileHandle(long fileHandle) throws IOException, ErrnoException;
}
@UsedByNative("com_android_mtp_AppFuse.cpp")
@@ -142,10 +163,8 @@
private long getFileSize(int inode) {
try {
return mCallback.getFileSize(inode);
- } catch (FileNotFoundException e) {
- return -OsConstants.ENOENT;
- } catch (UnsupportedOperationException e) {
- return -OsConstants.ENOTSUP;
+ } catch (Exception error) {
+ return -getErrnoFromException(error);
}
}
@@ -159,20 +178,62 @@
// It's OK to share the same mBuffer among requests because the requests are processed
// by AppFuseMessageThread sequentially.
return mCallback.readObjectBytes(inode, offset, size, mBuffer);
- } catch (IOException e) {
- return -OsConstants.EIO;
- } catch (UnsupportedOperationException e) {
- return -OsConstants.ENOTSUP;
+ } catch (Exception error) {
+ return -getErrnoFromException(error);
}
}
@UsedByNative("com_android_mtp_AppFuse.cpp")
@WorkerThread
- private /* unsgined */ int writeObjectBytes(int inode,
+ private /* unsgined */ int writeObjectBytes(long fileHandler,
+ int inode,
/* unsigned */ long offset,
/* unsigned */ int size,
- byte[] bytes) throws IOException {
- return mCallback.writeObjectBytes(inode, offset, size, bytes);
+ byte[] bytes) {
+ try {
+ return mCallback.writeObjectBytes(fileHandler, inode, offset, size, bytes);
+ } catch (Exception error) {
+ return -getErrnoFromException(error);
+ }
+ }
+
+ @UsedByNative("com_android_mtp_AppFuse.cpp")
+ @WorkerThread
+ private int flushFileHandle(long fileHandle) {
+ try {
+ mCallback.flushFileHandle(fileHandle);
+ return 0;
+ } catch (Exception error) {
+ return -getErrnoFromException(error);
+ }
+ }
+
+ @UsedByNative("com_android_mtp_AppFuse.cpp")
+ @WorkerThread
+ private int closeFileHandle(long fileHandle) {
+ try {
+ mCallback.closeFileHandle(fileHandle);
+ return 0;
+ } catch (Exception error) {
+ return -getErrnoFromException(error);
+ }
+ }
+
+ private static int getErrnoFromException(Exception error) {
+ if (DEBUG) {
+ Log.e(MtpDocumentsProvider.TAG, "AppFuse callbacks", error);
+ }
+ if (error instanceof FileNotFoundException) {
+ return OsConstants.ENOENT;
+ } else if (error instanceof IOException) {
+ return OsConstants.EIO;
+ } else if (error instanceof UnsupportedOperationException) {
+ return OsConstants.ENOTSUP;
+ } else if (error instanceof IllegalArgumentException) {
+ return OsConstants.EINVAL;
+ } else {
+ return OsConstants.EIO;
+ }
}
private native boolean native_start_app_fuse_loop(int fd);
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java
index 9f64046ce..50781bf 100644
--- a/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpDocumentsProvider.java
@@ -17,6 +17,7 @@
package com.android.mtp;
import android.content.ContentResolver;
+import android.content.Context;
import android.content.UriPermission;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
@@ -38,11 +39,16 @@
import android.provider.DocumentsContract;
import android.provider.DocumentsProvider;
import android.provider.Settings;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
import android.util.Log;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
+import java.io.File;
+import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
@@ -82,6 +88,7 @@
private MtpDatabase mDatabase;
private AppFuse mAppFuse;
private ServiceIntentSender mIntentSender;
+ private Context mContext;
/**
* Provides singleton instance to MtpDocumentsService.
@@ -93,6 +100,7 @@
@Override
public boolean onCreate() {
sSingleton = this;
+ mContext = getContext();
mResources = getContext().getResources();
mMtpManager = new MtpManager(getContext());
mResolver = getContext().getContentResolver();
@@ -137,12 +145,14 @@
@VisibleForTesting
boolean onCreateForTesting(
+ Context context,
Resources resources,
MtpManager mtpManager,
ContentResolver resolver,
MtpDatabase database,
StorageManager storageManager,
ServiceIntentSender intentSender) {
+ mContext = context;
mResources = resources;
mMtpManager = mtpManager;
mResolver = resolver;
@@ -232,43 +242,43 @@
try {
openDevice(identifier.mDeviceId);
final MtpDeviceRecord device = getDeviceToolkit(identifier.mDeviceId).mDeviceRecord;
- switch (mode) {
- case "r":
- long fileSize;
- try {
- fileSize = getFileSize(documentId);
- } catch (UnsupportedOperationException exception) {
- fileSize = -1;
- }
- // MTP getPartialObject operation does not support files that are larger than
- // 4GB. Fallback to non-seekable file descriptor.
- if (MtpDeviceRecord.isPartialReadSupported(
- device.operationsSupported, fileSize)) {
- return mAppFuse.openFile(
- Integer.parseInt(documentId), ParcelFileDescriptor.MODE_READ_ONLY);
- } else {
- return getPipeManager(identifier).readDocument(mMtpManager, identifier);
- }
- case "w":
- // TODO: Clear the parent document loader task (if exists) and call notify
- // when writing is completed.
- if (MtpDeviceRecord.isWritingSupported(device.operationsSupported)) {
- return getPipeManager(identifier).writeDocument(
- getContext(), mMtpManager, identifier, device.operationsSupported);
- } else {
- throw new UnsupportedOperationException(
- "The device does not support writing operation.");
- }
- case "rw":
- // TODO: Add support for "rw" mode.
+ // Turn off MODE_CREATE because openDocument does not allow to create new files.
+ final int modeFlag =
+ ParcelFileDescriptor.parseMode(mode) & ~ParcelFileDescriptor.MODE_CREATE;
+ if ((modeFlag & ParcelFileDescriptor.MODE_READ_ONLY) != 0) {
+ long fileSize;
+ try {
+ fileSize = getFileSize(documentId);
+ } catch (UnsupportedOperationException exception) {
+ fileSize = -1;
+ }
+ if (MtpDeviceRecord.isPartialReadSupported(
+ device.operationsSupported, fileSize)) {
+ return mAppFuse.openFile(Integer.parseInt(documentId), modeFlag);
+ } else {
+ // If getPartialObject{|64} are not supported for the device, returns
+ // non-seekable pipe FD instead.
+ return getPipeManager(identifier).readDocument(mMtpManager, identifier);
+ }
+ } else if ((modeFlag & ParcelFileDescriptor.MODE_WRITE_ONLY) != 0) {
+ // TODO: Clear the parent document loader task (if exists) and call notify
+ // when writing is completed.
+ if (MtpDeviceRecord.isWritingSupported(device.operationsSupported)) {
+ return mAppFuse.openFile(Integer.parseInt(documentId), modeFlag);
+ } else {
throw new UnsupportedOperationException(
- "The provider does not support 'rw' mode.");
- default:
- throw new IllegalArgumentException("Unknown mode for openDocument: " + mode);
+ "The device does not support writing operation.");
+ }
+ } else {
+ // TODO: Add support for "rw" mode.
+ throw new UnsupportedOperationException("The provider does not support 'rw' mode.");
}
+ } catch (FileNotFoundException | RuntimeException error) {
+ Log.e(MtpDocumentsProvider.TAG, "openDocument", error);
+ throw error;
} catch (IOException error) {
Log.e(MtpDocumentsProvider.TAG, "openDocument", error);
- throw new FileNotFoundException(error.getMessage());
+ throw new IllegalStateException(error);
}
}
@@ -595,6 +605,13 @@
}
private class AppFuseCallback implements AppFuse.Callback {
+ private final Map<Long, MtpFileWriter> mWriters = new HashMap<>();
+
+ @Override
+ public long getFileSize(int inode) throws FileNotFoundException {
+ return MtpDocumentsProvider.this.getFileSize(String.valueOf(inode));
+ }
+
@Override
public long readObjectBytes(
int inode, long offset, long size, byte[] buffer) throws IOException {
@@ -617,15 +634,43 @@
}
@Override
- public long getFileSize(int inode) throws FileNotFoundException {
- return MtpDocumentsProvider.this.getFileSize(String.valueOf(inode));
+ public int writeObjectBytes(
+ long fileHandle, int inode, long offset, int size, byte[] bytes)
+ throws IOException, ErrnoException {
+ final MtpFileWriter writer;
+ if (mWriters.containsKey(fileHandle)) {
+ writer = mWriters.get(fileHandle);
+ } else {
+ writer = new MtpFileWriter(mContext, String.valueOf(inode));
+ mWriters.put(fileHandle, writer);
+ }
+ return writer.write(offset, size, bytes);
}
@Override
- public int writeObjectBytes(int inode, long offset, int size, byte[] bytes)
- throws IOException {
- // TODO: Implement it.
- throw new IOException();
+ public void flushFileHandle(long fileHandle) throws IOException, ErrnoException {
+ final MtpFileWriter writer = mWriters.get(fileHandle);
+ if (writer == null) {
+ // File handle for reading.
+ return;
+ }
+ final MtpDeviceRecord device = getDeviceToolkit(
+ mDatabase.createIdentifier(writer.getDocumentId()).mDeviceId).mDeviceRecord;
+ writer.flush(mMtpManager, mDatabase, device.operationsSupported);
+ }
+
+ @Override
+ public void closeFileHandle(long fileHandle) throws IOException, ErrnoException {
+ final MtpFileWriter writer = mWriters.get(fileHandle);
+ if (writer == null) {
+ // File handle for reading.
+ return;
+ }
+ try {
+ writer.close();
+ } finally {
+ mWriters.remove(fileHandle);
+ }
}
}
}
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/MtpFileWriter.java b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpFileWriter.java
new file mode 100644
index 0000000..3e1bedc
--- /dev/null
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/MtpFileWriter.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.mtp;
+
+import android.content.Context;
+import android.mtp.MtpObjectInfo;
+import android.os.ParcelFileDescriptor;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
+
+import com.android.internal.util.Preconditions;
+
+import java.io.File;
+import java.io.IOException;
+
+class MtpFileWriter implements AutoCloseable {
+ final ParcelFileDescriptor mCacheFd;
+ final String mDocumentId;
+ boolean mDirty;
+
+ MtpFileWriter(Context context, String documentId) throws IOException {
+ mDocumentId = documentId;
+ mDirty = false;
+ final File tempFile = File.createTempFile("mtp", "tmp", context.getCacheDir());
+ mCacheFd = ParcelFileDescriptor.open(
+ tempFile,
+ ParcelFileDescriptor.MODE_READ_WRITE |
+ ParcelFileDescriptor.MODE_TRUNCATE |
+ ParcelFileDescriptor.MODE_CREATE);
+ tempFile.delete();
+ }
+
+ String getDocumentId() {
+ return mDocumentId;
+ }
+
+ int write(long offset, int size, byte[] bytes) throws IOException, ErrnoException {
+ Preconditions.checkArgumentNonnegative(offset, "offset");
+ Preconditions.checkArgumentNonnegative(size, "size");
+ Preconditions.checkArgument(size <= bytes.length);
+ if (size == 0) {
+ return 0;
+ }
+ mDirty = true;
+ Os.lseek(mCacheFd.getFileDescriptor(), offset, OsConstants.SEEK_SET);
+ return Os.write(mCacheFd.getFileDescriptor(), bytes, 0, size);
+ }
+
+ void flush(MtpManager manager, MtpDatabase database, int[] operationsSupported)
+ throws IOException, ErrnoException {
+ // Skip unnecessary flush.
+ if (!mDirty) {
+ return;
+ }
+
+ // Get the placeholder object info.
+ final Identifier identifier = database.createIdentifier(mDocumentId);
+ final MtpObjectInfo placeholderObjectInfo =
+ manager.getObjectInfo(identifier.mDeviceId, identifier.mObjectHandle);
+
+ // Delete the target object info if it already exists (as a placeholder).
+ manager.deleteDocument(identifier.mDeviceId, identifier.mObjectHandle);
+
+ // Create the target object info with a correct file size and upload the file.
+ final long size = Os.lseek(mCacheFd.getFileDescriptor(), 0, OsConstants.SEEK_END);
+ final MtpObjectInfo targetObjectInfo = new MtpObjectInfo.Builder(placeholderObjectInfo)
+ .setCompressedSize(size)
+ .build();
+
+ Os.lseek(mCacheFd.getFileDescriptor(), 0, OsConstants.SEEK_SET);
+ final int newObjectHandle = manager.createDocument(
+ identifier.mDeviceId, targetObjectInfo, mCacheFd);
+
+ final MtpObjectInfo newObjectInfo = manager.getObjectInfo(
+ identifier.mDeviceId, newObjectHandle);
+ final Identifier parentIdentifier =
+ database.getParentIdentifier(identifier.mDocumentId);
+ database.updateObject(
+ identifier.mDocumentId,
+ identifier.mDeviceId,
+ parentIdentifier.mDocumentId,
+ operationsSupported,
+ newObjectInfo,
+ size);
+
+ mDirty = false;
+ }
+
+ @Override
+ public void close() throws IOException {
+ mCacheFd.close();
+ }
+}
diff --git a/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java b/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java
index 1520f3b..795bbc1 100644
--- a/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java
+++ b/packages/MtpDocumentsProvider/src/com/android/mtp/PipeManager.java
@@ -16,13 +16,9 @@
package com.android.mtp;
-import android.content.Context;
-import android.mtp.MtpObjectInfo;
import android.os.ParcelFileDescriptor;
import android.util.Log;
-import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -52,15 +48,6 @@
return task.getReadingFileDescriptor();
}
- ParcelFileDescriptor writeDocument(Context context, MtpManager model, Identifier identifier,
- int[] operationsSupported)
- throws IOException {
- final Task task = new WriteDocumentTask(
- context, model, identifier, operationsSupported, mDatabase);
- mExecutor.execute(task);
- return task.getWritingFileDescriptor();
- }
-
ParcelFileDescriptor readThumbnail(MtpManager model, Identifier identifier) throws IOException {
final Task task = new GetThumbnailTask(model, identifier);
mExecutor.execute(task);
@@ -81,10 +68,6 @@
ParcelFileDescriptor getReadingFileDescriptor() {
return mDescriptors[0];
}
-
- ParcelFileDescriptor getWritingFileDescriptor() {
- return mDescriptors[1];
- }
}
private static class ImportFileTask extends Task {
@@ -108,85 +91,6 @@
}
}
- private static class WriteDocumentTask extends Task {
- private final Context mContext;
- private final MtpDatabase mDatabase;
- private final int[] mOperationsSupported;
-
- WriteDocumentTask(Context context,
- MtpManager model,
- Identifier identifier,
- int[] supportedOperations,
- MtpDatabase database)
- throws IOException {
- super(model, identifier);
- mContext = context;
- mDatabase = database;
- mOperationsSupported = supportedOperations;
- }
-
- @Override
- public void run() {
- File tempFile = null;
- try {
- // Obtain a temporary file and copy the data to it.
- tempFile = File.createTempFile("mtp", "tmp", mContext.getCacheDir());
- try (
- final FileOutputStream tempOutputStream =
- new ParcelFileDescriptor.AutoCloseOutputStream(
- ParcelFileDescriptor.open(
- tempFile, ParcelFileDescriptor.MODE_WRITE_ONLY));
- final ParcelFileDescriptor.AutoCloseInputStream inputStream =
- new ParcelFileDescriptor.AutoCloseInputStream(mDescriptors[0])
- ) {
- final byte[] buffer = new byte[32 * 1024];
- int bytes;
- while ((bytes = inputStream.read(buffer)) != -1) {
- mDescriptors[0].checkError();
- tempOutputStream.write(buffer, 0, bytes);
- }
- tempOutputStream.flush();
- }
-
- // Get the placeholder object info.
- final MtpObjectInfo placeholderObjectInfo =
- mManager.getObjectInfo(mIdentifier.mDeviceId, mIdentifier.mObjectHandle);
-
- // Delete the target object info if it already exists (as a placeholder).
- mManager.deleteDocument(mIdentifier.mDeviceId, mIdentifier.mObjectHandle);
-
- // Create the target object info with a correct file size and upload the file.
- final MtpObjectInfo targetObjectInfo =
- new MtpObjectInfo.Builder(placeholderObjectInfo)
- .setCompressedSize(tempFile.length())
- .build();
- final ParcelFileDescriptor tempInputDescriptor = ParcelFileDescriptor.open(
- tempFile, ParcelFileDescriptor.MODE_READ_ONLY);
- final int newObjectHandle = mManager.createDocument(
- mIdentifier.mDeviceId, targetObjectInfo, tempInputDescriptor);
-
- final MtpObjectInfo newObjectInfo = mManager.getObjectInfo(
- mIdentifier.mDeviceId, newObjectHandle);
- final Identifier parentIdentifier =
- mDatabase.getParentIdentifier(mIdentifier.mDocumentId);
- mDatabase.updateObject(
- mIdentifier.mDocumentId,
- mIdentifier.mDeviceId,
- parentIdentifier.mDocumentId,
- mOperationsSupported,
- newObjectInfo,
- tempFile.length());
- } catch (IOException error) {
- Log.w(MtpDocumentsProvider.TAG,
- "Failed to send a file because of: " + error.getMessage());
- } finally {
- if (tempFile != null) {
- tempFile.delete();
- }
- }
- }
- }
-
private static class GetThumbnailTask extends Task {
GetThumbnailTask(MtpManager model, Identifier identifier) throws IOException {
super(model, identifier);
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/AppFuseTest.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/AppFuseTest.java
index 3b92506..e421de71 100644
--- a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/AppFuseTest.java
+++ b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/AppFuseTest.java
@@ -23,6 +23,8 @@
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.MediumTest;
+import libcore.io.IoUtils;
+
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
@@ -143,7 +145,8 @@
}
@Override
- public int writeObjectBytes(int inode, long offset, int size, byte[] bytes) {
+ public int writeObjectBytes(
+ long fileHandle, int inode, long offset, int size, byte[] bytes) {
for (int i = 0; i < size; i++) {
resultBytes[(int)(offset + i)] = bytes[i];
}
@@ -152,7 +155,7 @@
});
appFuse.mount(storageManager);
final ParcelFileDescriptor fd = appFuse.openFile(
- INODE, ParcelFileDescriptor.MODE_WRITE_ONLY);
+ INODE, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_TRUNCATE);
try (final ParcelFileDescriptor.AutoCloseOutputStream stream =
new ParcelFileDescriptor.AutoCloseOutputStream(fd)) {
stream.write('a');
@@ -182,7 +185,7 @@
});
appFuse.mount(storageManager);
final ParcelFileDescriptor fd = appFuse.openFile(
- INODE, ParcelFileDescriptor.MODE_WRITE_ONLY);
+ INODE, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_TRUNCATE);
try (final ParcelFileDescriptor.AutoCloseOutputStream stream =
new ParcelFileDescriptor.AutoCloseOutputStream(fd)) {
stream.write('a');
@@ -192,6 +195,46 @@
appFuse.close();
}
+ public void testWriteFile_flushError() throws IOException {
+ final StorageManager storageManager = getContext().getSystemService(StorageManager.class);
+ final int INODE = 10;
+ final AppFuse appFuse = new AppFuse(
+ "test",
+ new TestCallback() {
+ @Override
+ public long getFileSize(int inode) throws FileNotFoundException {
+ if (inode != INODE) {
+ throw new FileNotFoundException();
+ }
+ return 5;
+ }
+
+ @Override
+ public int writeObjectBytes(
+ long fileHandle, int inode, long offset, int size, byte[] bytes) {
+ return size;
+ }
+
+ @Override
+ public void flushFileHandle(long fileHandle) throws IOException {
+ throw new IOException();
+ }
+ });
+ appFuse.mount(storageManager);
+ final ParcelFileDescriptor fd = appFuse.openFile(
+ INODE, ParcelFileDescriptor.MODE_WRITE_ONLY | ParcelFileDescriptor.MODE_TRUNCATE);
+ try (final ParcelFileDescriptor.AutoCloseOutputStream stream =
+ new ParcelFileDescriptor.AutoCloseOutputStream(fd)) {
+ stream.write('a');
+ try {
+ IoUtils.close(fd.getFileDescriptor());
+ fail();
+ } catch (IOException e) {
+ }
+ }
+ appFuse.close();
+ }
+
private static class TestCallback implements AppFuse.Callback {
@Override
public long getFileSize(int inode) throws FileNotFoundException {
@@ -205,9 +248,15 @@
}
@Override
- public int writeObjectBytes(int inode, long offset, int size, byte[] bytes)
+ public int writeObjectBytes(long fileHandle, int inode, long offset, int size, byte[] bytes)
throws IOException {
throw new IOException();
}
+
+ @Override
+ public void flushFileHandle(long fileHandle) throws IOException {}
+
+ @Override
+ public void closeFileHandle(long fileHandle) {}
}
}
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java
index 0de761cb..9ed15c8 100644
--- a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java
+++ b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/MtpDocumentsProviderTest.java
@@ -21,6 +21,7 @@
import android.mtp.MtpObjectInfo;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
+import android.os.ParcelFileDescriptor.AutoCloseOutputStream;
import android.os.storage.StorageManager;
import android.provider.DocumentsContract.Document;
import android.provider.DocumentsContract.Root;
@@ -533,6 +534,30 @@
}
}
+ public void testOpenDocument_writing() throws Exception {
+ setupProvider(MtpDatabaseConstants.FLAG_DATABASE_IN_MEMORY);
+ setupRoots(0, new MtpRoot[] {
+ new MtpRoot(0, 0, "Storage", 0, 0, "")
+ });
+ final String documentId = mProvider.createDocument("2", "text/plain", "test.txt");
+ {
+ final ParcelFileDescriptor fd = mProvider.openDocument(documentId, "w", null);
+ try (ParcelFileDescriptor.AutoCloseOutputStream stream =
+ new ParcelFileDescriptor.AutoCloseOutputStream(fd)) {
+ stream.write("Hello".getBytes());
+ }
+ }
+ {
+ final ParcelFileDescriptor fd = mProvider.openDocument(documentId, "r", null);
+ try (ParcelFileDescriptor.AutoCloseInputStream stream =
+ new ParcelFileDescriptor.AutoCloseInputStream(fd)) {
+ final byte[] bytes = new byte[5];
+ stream.read(bytes);
+ assertTrue(Arrays.equals("Hello".getBytes(), bytes));
+ }
+ }
+ }
+
public void testBusyDevice() throws Exception {
mMtpManager = new TestMtpManager(getContext()) {
@Override
@@ -740,6 +765,7 @@
mProvider = new MtpDocumentsProvider();
final StorageManager storageManager = getContext().getSystemService(StorageManager.class);
assertTrue(mProvider.onCreateForTesting(
+ getContext(),
mResources,
mMtpManager,
mResolver,
diff --git a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/PipeManagerTest.java b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/PipeManagerTest.java
index 8611797..53dc3db 100644
--- a/packages/MtpDocumentsProvider/tests/src/com/android/mtp/PipeManagerTest.java
+++ b/packages/MtpDocumentsProvider/tests/src/com/android/mtp/PipeManagerTest.java
@@ -16,10 +16,7 @@
package com.android.mtp;
-import android.database.Cursor;
-import android.mtp.MtpObjectInfo;
import android.os.ParcelFileDescriptor;
-import android.provider.DocumentsContract.Document;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.MediumTest;
@@ -66,64 +63,6 @@
assertDescriptorError(descriptor);
}
- public void testWriteDocument_basic() throws Exception {
- TestUtil.addTestDevice(mDatabase);
- TestUtil.addTestStorage(mDatabase, "1");
-
- final MtpObjectInfo info =
- new MtpObjectInfo.Builder().setObjectHandle(1).setName("note.txt").build();
- mDatabase.getMapper().startAddingDocuments("2");
- mDatabase.getMapper().putChildDocuments(
- 0, "2", TestUtil.OPERATIONS_SUPPORTED,
- new MtpObjectInfo[] { info },
- new long[] { 0L });
- mDatabase.getMapper().stopAddingDocuments("2");
- // Create a placeholder file which should be replaced by a real file later.
- mtpManager.setObjectInfo(0, info);
-
- // Upload testing bytes.
- final ParcelFileDescriptor descriptor = mPipeManager.writeDocument(
- getContext(),
- mtpManager,
- new Identifier(0, 0, 1, "2", MtpDatabaseConstants.DOCUMENT_TYPE_OBJECT),
- TestUtil.OPERATIONS_SUPPORTED);
- final ParcelFileDescriptor.AutoCloseOutputStream outputStream =
- new ParcelFileDescriptor.AutoCloseOutputStream(descriptor);
- outputStream.write(HELLO_BYTES, 0, HELLO_BYTES.length);
- outputStream.close();
- mExecutor.shutdown();
- assertTrue(mExecutor.awaitTermination(1000, TimeUnit.MILLISECONDS));
-
- // Check if the placeholder file is removed.
- try {
- mtpManager.getObjectInfo(0, 1);
- fail(); // The placeholder file has not been deleted.
- } catch (IOException e) {
- // Expected error, as the file is gone.
- }
-
- // Confirm that the target file is created.
- final MtpObjectInfo targetDocument = mtpManager.getObjectInfo(
- 0, TestMtpManager.CREATED_DOCUMENT_HANDLE);
- assertTrue(targetDocument != null);
-
- // Confirm the object handle is updated.
- try (final Cursor cursor = mDatabase.queryDocument(
- "2", new String[] { MtpDatabaseConstants.COLUMN_OBJECT_HANDLE })) {
- assertEquals(1, cursor.getCount());
- cursor.moveToNext();
- assertEquals(TestMtpManager.CREATED_DOCUMENT_HANDLE, cursor.getInt(0));
- }
-
- // Verify uploaded bytes.
- final byte[] uploadedBytes = mtpManager.getImportFileBytes(
- 0, TestMtpManager.CREATED_DOCUMENT_HANDLE);
- assertEquals(HELLO_BYTES.length, uploadedBytes.length);
- for (int i = 0; i < HELLO_BYTES.length; i++) {
- assertEquals(HELLO_BYTES[i], uploadedBytes[i]);
- }
- }
-
public void testReadThumbnail_basic() throws Exception {
mtpManager.setThumbnail(0, 1, HELLO_BYTES);
final ParcelFileDescriptor descriptor = mPipeManager.readThumbnail(
diff --git a/packages/PrintSpooler/src/com/android/printspooler/model/RemotePrintDocument.java b/packages/PrintSpooler/src/com/android/printspooler/model/RemotePrintDocument.java
index 2d3935b..99145b7b 100644
--- a/packages/PrintSpooler/src/com/android/printspooler/model/RemotePrintDocument.java
+++ b/packages/PrintSpooler/src/com/android/printspooler/model/RemotePrintDocument.java
@@ -178,6 +178,8 @@
}
if (mState == STATE_FAILED) {
Log.w(LOG_TAG, "Failed before start.");
+ } else if (mState == STATE_DESTROYED) {
+ Log.w(LOG_TAG, "Destroyed before start.");
} else {
if (mState != STATE_INITIAL) {
throw new IllegalStateException("Cannot start in state:" + stateToString(mState));
@@ -267,7 +269,7 @@
}
if (mState != STATE_STARTED && mState != STATE_UPDATED
&& mState != STATE_FAILED && mState != STATE_CANCELING
- && mState != STATE_CANCELED) {
+ && mState != STATE_CANCELED && mState != STATE_DESTROYED) {
throw new IllegalStateException("Cannot finish in state:"
+ stateToString(mState));
}
diff --git a/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java b/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java
index c3a5089..ff70190 100644
--- a/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java
+++ b/packages/SettingsLib/src/com/android/settingslib/drawer/SettingsDrawerActivity.java
@@ -176,8 +176,11 @@
@Override
public void setContentView(@LayoutRes int layoutResID) {
- LayoutInflater.from(this).inflate(layoutResID,
- (ViewGroup) findViewById(R.id.content_frame));
+ final ViewGroup parent = (ViewGroup) findViewById(R.id.content_frame);
+ if (parent != null) {
+ parent.removeAllViews();
+ }
+ LayoutInflater.from(this).inflate(layoutResID, parent);
}
@Override
diff --git a/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml b/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
index cb861ec..b88846b 100644
--- a/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
+++ b/packages/SystemUI/res/layout/quick_status_bar_expanded_header.xml
@@ -26,9 +26,6 @@
android:clipChildren="false"
android:clipToPadding="false"
android:baselineAligned="false"
- android:background="@drawable/quick_header_bg"
- android:clickable="true"
- android:focusable="true"
>
<LinearLayout
@@ -83,6 +80,10 @@
android:id="@+id/expand_indicator"
android:layout_width="48dp"
android:layout_height="48dp"
+ android:clipToPadding="false"
+ android:clickable="true"
+ android:focusable="true"
+ android:background="?android:attr/selectableItemBackgroundBorderless"
android:padding="12dp" />
</LinearLayout>
diff --git a/packages/SystemUI/res/layout/recents_stack_action_button.xml b/packages/SystemUI/res/layout/recents_stack_action_button.xml
index 8783261..2b2ce4e 100644
--- a/packages/SystemUI/res/layout/recents_stack_action_button.xml
+++ b/packages/SystemUI/res/layout/recents_stack_action_button.xml
@@ -27,8 +27,6 @@
android:textSize="14sp"
android:textColor="#FFFFFF"
android:textAllCaps="true"
- android:drawableStart="@drawable/ic_history"
- android:drawablePadding="6dp"
android:shadowColor="#99000000"
android:shadowDx="0"
android:shadowDy="2"
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index 622ae71..fd051b1 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -153,6 +153,9 @@
<!-- The animation duration for animating the removal of a task view. -->
<integer name="recents_animate_task_view_remove_duration">175</integer>
+ <!-- The base animation duration for animating the removal of all task views. -->
+ <integer name="recents_animate_task_views_remove_all_duration">300</integer>
+
<!-- The animation duration for scrolling the stack to a particular item. -->
<integer name="recents_animate_task_stack_scroll_duration">200</integer>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index d1faa4a..c094da9 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -574,10 +574,12 @@
<dimen name="recents_layout_bottom_margin">16dp</dimen>
<dimen name="recents_layout_side_margin_phone">16dp</dimen>
<dimen name="recents_layout_side_margin_tablet">48dp</dimen>
+ <dimen name="recents_layout_side_margin_tablet_docked">16dp</dimen>
<dimen name="recents_layout_side_margin_tablet_xlarge">64dp</dimen>
+ <dimen name="recents_layout_side_margin_tablet_xlarge_docked">16dp</dimen>
<!-- The height between the top margin and the top of the focused task. -->
- <dimen name="recents_layout_top_peek_size">56dp</dimen>
+ <dimen name="recents_layout_top_peek_size">48dp</dimen>
<!-- The height between the bottom margin and the top of task in front of the focused task. -->
<dimen name="recents_layout_bottom_peek_size">56dp</dimen>
diff --git a/packages/SystemUI/src/com/android/systemui/Interpolators.java b/packages/SystemUI/src/com/android/systemui/Interpolators.java
index 5e33a9f..17f4dab 100644
--- a/packages/SystemUI/src/com/android/systemui/Interpolators.java
+++ b/packages/SystemUI/src/com/android/systemui/Interpolators.java
@@ -17,6 +17,7 @@
package com.android.systemui;
import android.view.animation.AccelerateDecelerateInterpolator;
+import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
@@ -32,6 +33,7 @@
public static final Interpolator ALPHA_IN = new PathInterpolator(0.4f, 0f, 1f, 1f);
public static final Interpolator ALPHA_OUT = new PathInterpolator(0f, 0f, 0.8f, 1f);
public static final Interpolator LINEAR = new LinearInterpolator();
+ public static final Interpolator ACCELERATE = new AccelerateInterpolator();
public static final Interpolator ACCELERATE_DECELERATE = new AccelerateDecelerateInterpolator();
public static final Interpolator DECELERATE_QUINT = new DecelerateInterpolator(2.5f);
diff --git a/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java b/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
index fd43aa0..115c9d0 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/PagedTileLayout.java
@@ -1,13 +1,13 @@
package com.android.systemui.qs;
import android.content.Context;
+import android.support.v4.view.PagerAdapter;
+import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import com.android.internal.widget.PagerAdapter;
-import com.android.internal.widget.ViewPager;
import com.android.systemui.R;
import com.android.systemui.qs.QSPanel.QSTileLayout;
import com.android.systemui.qs.QSPanel.TileRecord;
@@ -37,7 +37,8 @@
public void onPageSelected(int position) {
if (mPageIndicator == null) return;
if (mPageListener != null) {
- mPageListener.onPageChanged(position == 0);
+ mPageListener.onPageChanged(isLayoutRtl() ? position == mPages.size() - 1
+ : position == 0);
}
}
@@ -47,7 +48,8 @@
if (mPageIndicator == null) return;
mPageIndicator.setLocation(position + positionOffset);
if (mPageListener != null) {
- mPageListener.onPageChanged(position == 0 && positionOffsetPixels == 0);
+ mPageListener.onPageChanged(positionOffsetPixels == 0 &&
+ (isLayoutRtl() ? position == mPages.size() - 1 : position == 0));
}
}
@@ -59,6 +61,21 @@
}
@Override
+ public void onRtlPropertiesChanged(int layoutDirection) {
+ super.onRtlPropertiesChanged(layoutDirection);
+ setAdapter(mAdapter);
+ setCurrentItem(0, false);
+ }
+
+ @Override
+ public void setCurrentItem(int item, boolean smoothScroll) {
+ if (isLayoutRtl()) {
+ item = mPages.size() - 1 - item;
+ }
+ super.setCurrentItem(item, smoothScroll);
+ }
+
+ @Override
public boolean hasOverlappingRendering() {
return false;
}
@@ -128,6 +145,7 @@
mNumPages = index + 1;
mPageIndicator.setNumPages(mNumPages);
mAdapter.notifyDataSetChanged();
+ setCurrentItem(0, false);
}
}
@@ -206,6 +224,9 @@
public Object instantiateItem(ViewGroup container, int position) {
if (DEBUG) Log.d(TAG, "Instantiating " + position);
+ if (isLayoutRtl()) {
+ position = mPages.size() - 1 - position;
+ }
ViewGroup view = mPages.get(position);
container.addView(view);
return view;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSAnimator.java b/packages/SystemUI/src/com/android/systemui/qs/QSAnimator.java
index 0b6eaba..83736ad 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSAnimator.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSAnimator.java
@@ -80,6 +80,10 @@
}
}
+ public void onRtlChanged() {
+ updateAnimators();
+ }
+
public void setOnKeyguard(boolean onKeyguard) {
mOnKeyguard = onKeyguard;
if (mOnKeyguard) {
@@ -246,7 +250,7 @@
private void getRelativePositionInt(int[] loc1, View view, View parent) {
if(view == parent || view == null) return;
- loc1[0] += view.getLeft();
+ loc1[0] += view.getX();
loc1[1] += view.getTop();
getRelativePositionInt(loc1, (View) view.getParent(), parent);
}
@@ -312,7 +316,7 @@
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
int oldTop, int oldRight, int oldBottom) {
- updateAnimators();
+ mQsPanel.post(mUpdateAnimators);
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSContainer.java b/packages/SystemUI/src/com/android/systemui/qs/QSContainer.java
index 43ebe04..5d06aeb 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSContainer.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSContainer.java
@@ -20,6 +20,7 @@
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.graphics.Point;
+import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
@@ -43,6 +44,7 @@
private static final boolean DEBUG = false;
private final Point mSizePoint = new Point();
+ private final Rect mQsBounds = new Rect();
private int mHeightOverride = -1;
private QSPanel mQSPanel;
@@ -76,6 +78,12 @@
mQSCustomizer.setQsContainer(this);
}
+ @Override
+ public void onRtlPropertiesChanged(int layoutDirection) {
+ super.onRtlPropertiesChanged(layoutDirection);
+ mQSAnimator.onRtlChanged();
+ }
+
public void setHost(QSTileHost qsh) {
mQSPanel.setHost(qsh, mQSCustomizer);
mHeader.setQSPanel(mQSPanel);
@@ -226,6 +234,12 @@
mQSDetail.setFullyExpanded(expansion == 1);
mQSAnimator.setPosition(expansion);
updateBottom();
+
+ // Set bounds on the QS panel so it doesn't run over the header.
+ mQsBounds.top = (int) (mQSPanel.getHeight() * (1 - expansion));
+ mQsBounds.right = mQSPanel.getWidth();
+ mQsBounds.bottom = mQSPanel.getHeight();
+ mQSPanel.setClipBounds(mQsBounds);
}
public void animateHeaderSlidingIn(long delay) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QSTile.java b/packages/SystemUI/src/com/android/systemui/qs/QSTile.java
index 1659888..8777a91 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QSTile.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QSTile.java
@@ -24,11 +24,15 @@
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
+import android.os.UserHandle;
+import android.os.UserManager;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
+import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.MetricsProto.MetricsEvent;
import com.android.settingslib.RestrictedLockUtils;
import com.android.systemui.qs.QSTile.State;
import com.android.systemui.qs.external.TileServices;
@@ -81,6 +85,8 @@
abstract protected void handleClick();
abstract protected void handleUpdateState(TState state, Object arg);
+ private UserManager mUserManager;
+
/**
* Declare the category of this tile.
*
@@ -93,6 +99,7 @@
mHost = host;
mContext = host.getContext();
mHandler = new H(host.getLooper());
+ mUserManager = UserManager.get(mContext);
}
public String getTileSpec() {
@@ -212,6 +219,7 @@
}
protected void handleLongClick() {
+ MetricsLogger.action(mContext, MetricsEvent.ACTION_QS_LONG_PRESS, getTileSpec());
mHost.startActivityDismissingKeyguard(getLongClickIntent());
}
@@ -282,12 +290,11 @@
}
protected void checkIfRestrictionEnforcedByAdminOnly(State state, String userRestriction) {
- EnforcedAdmin admin = RestrictedLockUtils.checkIfRestrictionEnforced(mContext,
- userRestriction, ActivityManager.getCurrentUser());
- if (admin != null && !RestrictedLockUtils.hasBaseUserRestriction(mContext,
- userRestriction, ActivityManager.getCurrentUser())) {
+ UserHandle user = UserHandle.of(ActivityManager.getCurrentUser());
+ if (mUserManager.hasUserRestriction(userRestriction, user)
+ && !mUserManager.hasBaseUserRestriction(userRestriction, user)) {
state.disabledByPolicy = true;
- state.enforcedAdmin = admin;
+ state.enforcedAdmin = EnforcedAdmin.MULTIPLE_ENFORCED_ADMIN;
} else {
state.disabledByPolicy = false;
state.enforcedAdmin = null;
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java b/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
index aeca840..83ac45c 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/QSCustomizer.java
@@ -32,6 +32,8 @@
import android.widget.LinearLayout;
import android.widget.Toolbar;
import android.widget.Toolbar.OnMenuItemClickListener;
+import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.MetricsProto;
import com.android.systemui.R;
import com.android.systemui.qs.QSContainer;
import com.android.systemui.qs.QSDetailClipper;
@@ -116,6 +118,7 @@
public void show(int x, int y) {
if (!isShown) {
+ MetricsLogger.visible(getContext(), MetricsProto.MetricsEvent.QS_EDIT);
isShown = true;
setTileSpecs();
setVisibility(View.VISIBLE);
@@ -127,6 +130,7 @@
public void hide(int x, int y) {
if (isShown) {
+ MetricsLogger.hidden(getContext(), MetricsProto.MetricsEvent.QS_EDIT);
isShown = false;
mToolbar.dismissPopupMenus();
setCustomizing(false);
@@ -149,6 +153,7 @@
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case MENU_RESET:
+ MetricsLogger.action(getContext(), MetricsProto.MetricsEvent.ACTION_QS_EDIT_RESET);
reset();
break;
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java b/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
index 353c6b6..4c13451 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/customize/TileAdapter.java
@@ -16,6 +16,7 @@
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
+import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
@@ -36,12 +37,15 @@
import android.view.accessibility.AccessibilityManager;
import android.widget.FrameLayout;
import android.widget.TextView;
+import com.android.internal.logging.MetricsLogger;
+import com.android.internal.logging.MetricsProto;
import com.android.systemui.R;
import com.android.systemui.qs.QSIconView;
import com.android.systemui.qs.QSTileView;
import com.android.systemui.qs.customize.TileAdapter.Holder;
import com.android.systemui.qs.customize.TileQueryHelper.TileInfo;
import com.android.systemui.qs.customize.TileQueryHelper.TileStateListener;
+import com.android.systemui.qs.external.CustomTile;
import com.android.systemui.statusbar.phone.QSTileHost;
import com.android.systemui.statusbar.phone.SystemUIDialog;
@@ -304,12 +308,24 @@
notifyItemMoved(from, to);
CharSequence announcement;
if (to >= mDividerIndex) {
+ MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_QS_EDIT_REMOVE_SPEC,
+ strip(mTiles.get(to)));
+ MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_QS_EDIT_REMOVE,
+ from);
announcement = mContext.getString(R.string.accessibility_qs_edit_tile_removed,
fromLabel);
} else if (from >= mDividerIndex) {
+ MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_QS_EDIT_ADD_SPEC,
+ strip(mTiles.get(to)));
+ MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_QS_EDIT_ADD,
+ to);
announcement = mContext.getString(R.string.accessibility_qs_edit_tile_added,
fromLabel, (to + 1));
} else {
+ MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_QS_EDIT_MOVE_SPEC,
+ strip(mTiles.get(to)));
+ MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_QS_EDIT_MOVE,
+ to);
announcement = mContext.getString(R.string.accessibility_qs_edit_tile_moved,
fromLabel, (to + 1));
}
@@ -317,6 +333,15 @@
return true;
}
+ private String strip(TileInfo tileInfo) {
+ String spec = tileInfo.spec;
+ if (spec.startsWith(CustomTile.PREFIX)) {
+ ComponentName component = CustomTile.getComponentFromSpec(spec);
+ return component.getPackageName();
+ }
+ return spec;
+ }
+
private <T> void move(int from, int to, List<T> list) {
list.add(from > to ? to : to + 1, list.get(from));
list.remove(from > to ? from + 1 : from);
diff --git a/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java b/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java
index b89c2f6..d7777d5 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/RecentsActivity.java
@@ -90,6 +90,7 @@
private RecentsPackageMonitor mPackageMonitor;
private long mLastTabKeyEventTime;
+ private int mLastOrientation = Configuration.ORIENTATION_UNDEFINED;
private boolean mFinishedOnStartup;
private boolean mIgnoreAltTabRelease;
private boolean mIsVisible;
@@ -266,6 +267,7 @@
getWindow().getAttributes().privateFlags |=
WindowManager.LayoutParams.PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY;
+ mLastOrientation = getResources().getConfiguration().orientation;
mFocusTimerDuration = getResources().getInteger(R.integer.recents_auto_advance_duration);
mIterateTrigger = new DozeTrigger(mFocusTimerDuration, new Runnable() {
@Override
@@ -274,6 +276,9 @@
}
});
+ // Set the window background
+ getWindow().setBackgroundDrawable(mRecentsView.getBackgroundScrim());
+
// Create the home intent runnable
mHomeIntent = new Intent(Intent.ACTION_MAIN, null);
mHomeIntent.addCategory(Intent.CATEGORY_HOME);
@@ -415,13 +420,18 @@
// Update the nav bar for the current orientation
updateNavBarScrim(false /* animateNavBarScrim */, AnimationProps.IMMEDIATE);
- EventBus.getDefault().send(new ConfigurationChangedEvent(false /* fromMultiWindow */));
+ // Notify of the config change
+ int newOrientation = getResources().getConfiguration().orientation;
+ EventBus.getDefault().send(new ConfigurationChangedEvent(false /* fromMultiWindow */,
+ (mLastOrientation != newOrientation)));
+ mLastOrientation = newOrientation;
}
@Override
public void onMultiWindowChanged(boolean inMultiWindow) {
super.onMultiWindowChanged(inMultiWindow);
- EventBus.getDefault().send(new ConfigurationChangedEvent(true /* fromMultiWindow */));
+ EventBus.getDefault().send(new ConfigurationChangedEvent(true /* fromMultiWindow */,
+ false /* fromOrientationChange */));
if (mRecentsView != null) {
// Reload the task stack completely
diff --git a/packages/SystemUI/src/com/android/systemui/recents/RecentsDebugFlags.java b/packages/SystemUI/src/com/android/systemui/recents/RecentsDebugFlags.java
index 043510e..1715356 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/RecentsDebugFlags.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/RecentsDebugFlags.java
@@ -36,7 +36,7 @@
// Enables the task affiliations
public static final boolean EnableAffiliatedTaskGroups = false;
// TODO: To be repurposed
- public static final boolean EnableStackActionButton = false;
+ public static final boolean EnableStackActionButton = true;
// Overrides the Tuner flags and enables the timeout
private static final boolean EnableFastToggleTimeout = false;
// Overrides the Tuner flags and enables the paging via the Recents button
diff --git a/packages/SystemUI/src/com/android/systemui/recents/RecentsImpl.java b/packages/SystemUI/src/com/android/systemui/recents/RecentsImpl.java
index ffc037d..43d627d 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/RecentsImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/RecentsImpl.java
@@ -663,13 +663,18 @@
@Override
public void run() {
final Bitmap transitionBitmap = drawThumbnailTransitionBitmap(toTask, toTransform);
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- mThumbnailTransitionBitmapCache = transitionBitmap;
- mThumbnailTransitionBitmapCacheKey = toTask;
- }
- });
+ if (transitionBitmap != null) {
+ mHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ mThumbnailTransitionBitmapCache = transitionBitmap;
+ mThumbnailTransitionBitmapCacheKey = toTask;
+ }
+ });
+ } else {
+ Log.e(TAG, "Could not load thumbnail for task: " + toTask + " at transform: " +
+ toTransform);
+ }
}
});
}
@@ -774,7 +779,7 @@
// Get the transform for the running task
stackView.updateLayoutAlgorithm(true /* boundScroll */);
stackView.updateToInitialState(true /* scrollToInitialState */);
- mTmpTransform = stackView.getStackAlgorithm().getStackTransformScreenCoordinates(launchTask,
+ stackView.getStackAlgorithm().getStackTransformScreenCoordinates(launchTask,
stackView.getScroller().getStackScroll(), mTmpTransform, null);
return mTmpTransform;
}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/events/activity/ConfigurationChangedEvent.java b/packages/SystemUI/src/com/android/systemui/recents/events/activity/ConfigurationChangedEvent.java
index c234c34..8be9ca7 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/events/activity/ConfigurationChangedEvent.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/events/activity/ConfigurationChangedEvent.java
@@ -24,8 +24,10 @@
public class ConfigurationChangedEvent extends EventBus.AnimatedEvent {
public final boolean fromMultiWindow;
+ public final boolean fromOrientationChange;
- public ConfigurationChangedEvent(boolean fromMultiWindow) {
+ public ConfigurationChangedEvent(boolean fromMultiWindow, boolean fromOrientationChange) {
this.fromMultiWindow = fromMultiWindow;
+ this.fromOrientationChange = fromOrientationChange;
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/events/ui/ResetBackgroundScrimEvent.java b/packages/SystemUI/src/com/android/systemui/recents/events/ui/DismissAllTaskViewsEvent.java
similarity index 78%
rename from packages/SystemUI/src/com/android/systemui/recents/events/ui/ResetBackgroundScrimEvent.java
rename to packages/SystemUI/src/com/android/systemui/recents/events/ui/DismissAllTaskViewsEvent.java
index 863f40b..f8b59c7 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/events/ui/ResetBackgroundScrimEvent.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/events/ui/DismissAllTaskViewsEvent.java
@@ -17,10 +17,11 @@
package com.android.systemui.recents.events.ui;
import com.android.systemui.recents.events.EventBus;
+import com.android.systemui.recents.views.TaskView;
/**
- * This is sent to reset the background scrim back to the initial state.
+ * This event is sent to request that all the {@link TaskView}s are dismissed.
*/
-public class ResetBackgroundScrimEvent extends EventBus.Event {
+public class DismissAllTaskViewsEvent extends EventBus.AnimatedEvent {
// Simple event
}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/events/ui/DismissTaskViewEvent.java b/packages/SystemUI/src/com/android/systemui/recents/events/ui/DismissTaskViewEvent.java
index 1165f4e..1f8c644 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/events/ui/DismissTaskViewEvent.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/events/ui/DismissTaskViewEvent.java
@@ -17,7 +17,6 @@
package com.android.systemui.recents.events.ui;
import com.android.systemui.recents.events.EventBus;
-import com.android.systemui.recents.model.Task;
import com.android.systemui.recents.views.TaskView;
/**
@@ -26,10 +25,8 @@
public class DismissTaskViewEvent extends EventBus.AnimatedEvent {
public final TaskView taskView;
- public final Task task;
- public DismissTaskViewEvent(TaskView taskView, Task task) {
+ public DismissTaskViewEvent(TaskView taskView) {
this.taskView = taskView;
- this.task = task;
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/events/ui/UpdateBackgroundScrimEvent.java b/packages/SystemUI/src/com/android/systemui/recents/events/ui/UpdateBackgroundScrimEvent.java
deleted file mode 100644
index fdd4c67..0000000
--- a/packages/SystemUI/src/com/android/systemui/recents/events/ui/UpdateBackgroundScrimEvent.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.systemui.recents.events.ui;
-
-import com.android.systemui.recents.events.EventBus;
-
-/**
- * This is sent to request an update to the background scrim.
- */
-public class UpdateBackgroundScrimEvent extends EventBus.Event {
-
- public final float alpha;
-
- public UpdateBackgroundScrimEvent(float alpha) {
- this.alpha = alpha;
- }
-}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/model/TaskStack.java b/packages/SystemUI/src/com/android/systemui/recents/model/TaskStack.java
index 5a2507d..df3f56c 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/model/TaskStack.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/model/TaskStack.java
@@ -222,6 +222,11 @@
Task newFrontMostTask, AnimationProps animation, boolean fromDockGesture);
/**
+ * Notifies when all tasks have been removed from the stack.
+ */
+ void onStackTasksRemoved(TaskStack stack);
+
+ /**
* Notifies when tasks in the stack have been updated.
*/
void onStackTasksUpdated(TaskStack stack);
@@ -510,6 +515,22 @@
}
/**
+ * Removes all tasks from the stack.
+ */
+ public void removeAllTasks() {
+ ArrayList<Task> tasks = mStackTaskList.getTasks();
+ for (int i = tasks.size() - 1; i >= 0; i--) {
+ Task t = tasks.get(i);
+ removeTaskImpl(mStackTaskList, t);
+ mRawTaskList.remove(t);
+ }
+ if (mCb != null) {
+ // Notify that all tasks have been removed
+ mCb.onStackTasksRemoved(this);
+ }
+ }
+
+ /**
* Sets a few tasks in one go, without calling any callbacks.
*
* @param tasks the new set of tasks to replace the current set.
diff --git a/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalGridView.java b/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalGridView.java
index 3d0e75a..5eb9fda 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalGridView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/tv/views/TaskStackHorizontalGridView.java
@@ -158,6 +158,11 @@
}
@Override
+ public void onStackTasksRemoved(TaskStack stack) {
+ // Do nothing
+ }
+
+ @Override
public void onStackTasksUpdated(TaskStack stack) {
// Do nothing
}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/RecentsTransitionHelper.java b/packages/SystemUI/src/com/android/systemui/recents/views/RecentsTransitionHelper.java
index 9dc3fb1..9eec2ce 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/RecentsTransitionHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/RecentsTransitionHelper.java
@@ -28,11 +28,13 @@
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
+import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.IRemoteCallback;
import android.os.RemoteException;
+import android.util.Log;
import android.view.AppTransitionAnimationSpec;
import android.view.IAppTransitionAnimationSpecsFuture;
@@ -252,12 +254,13 @@
/**
* Composes the transition spec when docking a task, which includes a full task bitmap.
*/
- public List<AppTransitionAnimationSpec> composeDockAnimationSpec(
- TaskView taskView, Rect transform) {
- TaskViewTransform viewTransform = new TaskViewTransform();
- viewTransform.fillIn(taskView);
- return Collections.singletonList(new AppTransitionAnimationSpec(taskView.getTask().key.id,
- RecentsTransitionHelper.composeTaskBitmap(taskView, viewTransform), transform));
+ public List<AppTransitionAnimationSpec> composeDockAnimationSpec(TaskView taskView,
+ Rect bounds) {
+ mTmpTransform.fillIn(taskView);
+ Task task = taskView.getTask();
+ Bitmap thumbnail = RecentsTransitionHelper.composeTaskBitmap(taskView, mTmpTransform);
+ return Collections.singletonList(new AppTransitionAnimationSpec(task.key.id, thumbnail,
+ bounds));
}
/**
@@ -336,18 +339,27 @@
float scale = transform.scale;
int fromWidth = (int) (transform.rect.width() * scale);
int fromHeight = (int) (transform.rect.height() * scale);
- Bitmap b = Bitmap.createBitmap(fromWidth, fromHeight,
- Bitmap.Config.ARGB_8888);
+ if (fromWidth == 0 || fromHeight == 0) {
+ Log.e(TAG, "Could not compose thumbnail for task: " + taskView.getTask() +
+ " at transform: " + transform);
- if (RecentsDebugFlags.Static.EnableTransitionThumbnailDebugMode) {
- b.eraseColor(0xFFff0000);
+ Bitmap b = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+ b.eraseColor(Color.TRANSPARENT);
+ return b;
} else {
- Canvas c = new Canvas(b);
- c.scale(scale, scale);
- taskView.draw(c);
- c.setBitmap(null);
+ Bitmap b = Bitmap.createBitmap(fromWidth, fromHeight,
+ Bitmap.Config.ARGB_8888);
+
+ if (RecentsDebugFlags.Static.EnableTransitionThumbnailDebugMode) {
+ b.eraseColor(0xFFff0000);
+ } else {
+ Canvas c = new Canvas(b);
+ c.scale(scale, scale);
+ taskView.draw(c);
+ c.setBitmap(null);
+ }
+ return b.createAshmemBitmap();
}
- return b.createAshmemBitmap();
}
private static Bitmap composeHeaderBitmap(TaskView taskView,
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java b/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java
index b23b01f..da2f721 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/RecentsView.java
@@ -58,10 +58,11 @@
import com.android.systemui.recents.events.activity.HideStackActionButtonEvent;
import com.android.systemui.recents.events.activity.LaunchTaskEvent;
import com.android.systemui.recents.events.activity.ShowStackActionButtonEvent;
+import com.android.systemui.recents.events.ui.AllTaskViewsDismissedEvent;
+import com.android.systemui.recents.events.ui.DeleteTaskDataEvent;
+import com.android.systemui.recents.events.ui.DismissAllTaskViewsEvent;
import com.android.systemui.recents.events.ui.DraggingInRecentsEndedEvent;
import com.android.systemui.recents.events.ui.DraggingInRecentsEvent;
-import com.android.systemui.recents.events.ui.ResetBackgroundScrimEvent;
-import com.android.systemui.recents.events.ui.UpdateBackgroundScrimEvent;
import com.android.systemui.recents.events.ui.dragndrop.DragDropTargetChangedEvent;
import com.android.systemui.recents.events.ui.dragndrop.DragEndEvent;
import com.android.systemui.recents.events.ui.dragndrop.DragStartEvent;
@@ -87,6 +88,9 @@
private static final int DEFAULT_UPDATE_SCRIM_DURATION = 200;
private static final float DEFAULT_SCRIM_ALPHA = 0.33f;
+ private static final int SHOW_STACK_ACTION_BUTTON_DURATION = 150;
+ private static final int HIDE_STACK_ACTION_BUTTON_DURATION = 100;
+
private TaskStack mStack;
private TaskStackView mTaskStackView;
private TextView mStackActionButton;
@@ -99,7 +103,8 @@
private Rect mSystemInsets = new Rect();
private int mDividerSize;
- private ColorDrawable mBackgroundScrim = new ColorDrawable(Color.BLACK);
+ private Drawable mBackgroundScrim = new ColorDrawable(
+ Color.argb((int) (DEFAULT_SCRIM_ALPHA * 255), 0, 0, 0)).mutate();
private Animator mBackgroundScrimAnimator;
private RecentsTransitionHelper mTransitionHelper;
@@ -135,10 +140,11 @@
R.dimen.recents_task_view_rounded_corners_radius);
mStackActionButton = (TextView) inflater.inflate(R.layout.recents_stack_action_button,
this, false);
+ mStackActionButton.forceHasOverlappingRendering(false);
mStackActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
- // TODO: To be implemented
+ EventBus.getDefault().send(new DismissAllTaskViewsEvent());
}
});
addView(mStackActionButton);
@@ -152,8 +158,6 @@
}
mEmptyView = (TextView) inflater.inflate(R.layout.recents_empty, this, false);
addView(mEmptyView);
-
- setBackground(mBackgroundScrim);
}
/**
@@ -179,14 +183,14 @@
if (isResumingFromVisible) {
// If we are already visible, then restore the background scrim
- animateBackgroundScrim(DEFAULT_SCRIM_ALPHA, DEFAULT_UPDATE_SCRIM_DURATION);
+ animateBackgroundScrim(1f, DEFAULT_UPDATE_SCRIM_DURATION);
} else {
// If we are already occluded by the app, then set the final background scrim alpha now.
// Otherwise, defer until the enter animation completes to animate the scrim alpha with
// the tasks for the home animation.
if (launchState.launchedViaDockGesture || launchState.launchedFromApp
|| isTaskStackEmpty) {
- mBackgroundScrim.setAlpha((int) (DEFAULT_SCRIM_ALPHA * 255));
+ mBackgroundScrim.setAlpha(255);
} else {
mBackgroundScrim.setAlpha(0);
}
@@ -215,6 +219,13 @@
return mStack;
}
+ /*
+ * Returns the window background scrim.
+ */
+ public Drawable getBackgroundScrim() {
+ return mBackgroundScrim;
+ }
+
/**
* Returns whether the last task launched was in the freeform stack or not.
*/
@@ -566,17 +577,21 @@
RecentsActivityLaunchState launchState = Recents.getConfiguration().getLaunchState();
if (!launchState.launchedViaDockGesture && !launchState.launchedFromApp
&& mStack.getTaskCount() > 0) {
- animateBackgroundScrim(DEFAULT_SCRIM_ALPHA,
+ animateBackgroundScrim(1f,
TaskStackAnimationHelper.ENTER_FROM_HOME_TRANSLATION_DURATION);
}
}
- public final void onBusEvent(UpdateBackgroundScrimEvent event) {
- animateBackgroundScrim(event.alpha, DEFAULT_UPDATE_SCRIM_DURATION);
+ public final void onBusEvent(AllTaskViewsDismissedEvent event) {
+ hideStackActionButton(HIDE_STACK_ACTION_BUTTON_DURATION, true /* translate */);
}
- public final void onBusEvent(ResetBackgroundScrimEvent event) {
- animateBackgroundScrim(DEFAULT_SCRIM_ALPHA, DEFAULT_UPDATE_SCRIM_DURATION);
+ public final void onBusEvent(DismissAllTaskViewsEvent event) {
+ SystemServicesProxy ssp = Recents.getSystemServices();
+ if (!ssp.hasDockedTask()) {
+ // Animate the background away only if we are dismissing Recents to home
+ animateBackgroundScrim(0f, DEFAULT_UPDATE_SCRIM_DURATION);
+ }
}
public final void onBusEvent(ShowStackActionButtonEvent event) {
@@ -584,7 +599,7 @@
return;
}
- showStackActionButton(150, event.translate);
+ showStackActionButton(SHOW_STACK_ACTION_BUTTON_DURATION, event.translate);
}
public final void onBusEvent(HideStackActionButtonEvent event) {
@@ -592,7 +607,7 @@
return;
}
- hideStackActionButton(100, true /* translate */);
+ hideStackActionButton(HIDE_STACK_ACTION_BUTTON_DURATION, true /* translate */);
}
/**
@@ -623,7 +638,6 @@
.alpha(1f)
.setDuration(duration)
.setInterpolator(Interpolators.FAST_OUT_SLOW_IN)
- .withLayer()
.start();
}
});
@@ -669,7 +683,6 @@
postAnimationTrigger.decrement();
}
})
- .withLayer()
.start();
postAnimationTrigger.increment();
}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/SystemBarScrimViews.java b/packages/SystemUI/src/com/android/systemui/recents/views/SystemBarScrimViews.java
index 9c8189a..13ad9a5 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/SystemBarScrimViews.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/SystemBarScrimViews.java
@@ -24,6 +24,7 @@
import com.android.systemui.R;
import com.android.systemui.recents.events.activity.DismissRecentsToHomeAnimationStarted;
import com.android.systemui.recents.events.activity.EnterRecentsWindowAnimationCompletedEvent;
+import com.android.systemui.recents.events.ui.DismissAllTaskViewsEvent;
/** Manages the scrims for the various system bars. */
public class SystemBarScrimViews {
@@ -107,4 +108,14 @@
animateNavBarScrimVisibility(false, animation);
}
}
+
+ public final void onBusEvent(DismissAllTaskViewsEvent event) {
+ if (mHasNavBarScrim) {
+ AnimationProps animation = new AnimationProps()
+ .setDuration(AnimationProps.BOUNDS,
+ TaskStackAnimationHelper.EXIT_TO_HOME_TRANSLATION_DURATION)
+ .setInterpolator(AnimationProps.BOUNDS, Interpolators.FAST_OUT_SLOW_IN);
+ animateNavBarScrimVisibility(false, animation);
+ }
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java
index 8db81f7..1c433d8 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackAnimationHelper.java
@@ -31,6 +31,7 @@
import com.android.systemui.recents.RecentsActivityLaunchState;
import com.android.systemui.recents.RecentsConfiguration;
import com.android.systemui.recents.misc.ReferenceCountedTrigger;
+import com.android.systemui.recents.misc.Utilities;
import com.android.systemui.recents.model.Task;
import com.android.systemui.recents.model.TaskStack;
@@ -277,7 +278,6 @@
public void startExitToHomeAnimation(boolean animated,
ReferenceCountedTrigger postAnimationTrigger) {
TaskStackLayoutAlgorithm stackLayout = mStackView.getStackAlgorithm();
- TaskStackViewScroller stackScroller = mStackView.getScroller();
TaskStack stack = mStackView.getStack();
// Break early if there are no tasks
@@ -313,8 +313,7 @@
taskAnimation = AnimationProps.IMMEDIATE;
}
- stackLayout.getStackTransform(task, stackScroller.getStackScroll(), mTmpTransform,
- null);
+ mTmpTransform.fillIn(tv);
mTmpTransform.alpha = 0f;
mTmpTransform.rect.offset(0, offscreenYOffset);
mStackView.updateTaskViewToTransform(tv, mTmpTransform, taskAnimation);
@@ -328,8 +327,6 @@
public void startLaunchTaskAnimation(TaskView launchingTaskView, boolean screenPinningRequested,
final ReferenceCountedTrigger postAnimationTrigger) {
Resources res = mStackView.getResources();
- TaskStackLayoutAlgorithm stackLayout = mStackView.getStackAlgorithm();
- TaskStackViewScroller stackScroller = mStackView.getScroller();
int taskViewExitToAppDuration = res.getInteger(
R.integer.recents_task_exit_to_app_duration);
@@ -362,8 +359,7 @@
postAnimationTrigger.decrementOnAnimationEnd());
postAnimationTrigger.increment();
- stackLayout.getStackTransform(task, stackScroller.getStackScroll(), mTmpTransform,
- null);
+ mTmpTransform.fillIn(tv);
mTmpTransform.alpha = 0f;
mTmpTransform.rect.offset(0, taskViewAffiliateGroupEnterOffset);
mStackView.updateTaskViewToTransform(tv, mTmpTransform, taskAnimation);
@@ -374,16 +370,14 @@
/**
* Starts the delete animation for the specified {@link TaskView}.
*/
- public void startDeleteTaskAnimation(Task deleteTask, final TaskView deleteTaskView,
+ public void startDeleteTaskAnimation(final TaskView deleteTaskView,
final ReferenceCountedTrigger postAnimationTrigger) {
Resources res = mStackView.getResources();
TaskStackLayoutAlgorithm stackLayout = mStackView.getStackAlgorithm();
- TaskStackViewScroller stackScroller = mStackView.getScroller();
int taskViewRemoveAnimDuration = res.getInteger(
R.integer.recents_animate_task_view_remove_duration);
- int taskViewRemoveAnimTranslationXPx = res.getDimensionPixelSize(
- R.dimen.recents_task_view_remove_anim_translation_x);
+ int offscreenXOffset = mStackView.getMeasuredWidth() - stackLayout.mTaskRect.left;
// Disabling clipping with the stack while the view is animating away, this will get
// restored when the task is next picked up from the view pool
@@ -399,14 +393,58 @@
});
postAnimationTrigger.increment();
- stackLayout.getStackTransform(deleteTask, stackScroller.getStackScroll(), mTmpTransform,
- null);
+ mTmpTransform.fillIn(deleteTaskView);
mTmpTransform.alpha = 0f;
- mTmpTransform.rect.offset(taskViewRemoveAnimTranslationXPx, 0);
+ mTmpTransform.rect.offset(offscreenXOffset, 0);
mStackView.updateTaskViewToTransform(deleteTaskView, mTmpTransform, taskAnimation);
}
/**
+ * Starts the delete animation for all the {@link TaskView}s.
+ */
+ public void startDeleteAllTasksAnimation(final List<TaskView> taskViews,
+ final ReferenceCountedTrigger postAnimationTrigger) {
+ Resources res = mStackView.getResources();
+ TaskStackLayoutAlgorithm stackLayout = mStackView.getStackAlgorithm();
+
+ int taskViewRemoveAnimDuration = res.getInteger(
+ R.integer.recents_animate_task_views_remove_all_duration);
+ int offscreenXOffset = mStackView.getMeasuredWidth() - stackLayout.mTaskRect.left;
+
+ int taskViewCount = taskViews.size();
+ int startDelayMax = 125;
+
+ for (int i = taskViewCount - 1; i >= 0; i--) {
+ TaskView tv = taskViews.get(i);
+ int indexFromFront = taskViewCount - i - 1;
+ float x = Interpolators.ACCELERATE.getInterpolation((float) indexFromFront /
+ taskViewCount);
+ int startDelay = (int) Utilities.mapRange(x, 0, startDelayMax);
+
+ // Disabling clipping with the stack while the view is animating away
+ tv.setClipViewInStack(false);
+
+ // Compose the new animation and transform and star the animation
+ AnimationProps taskAnimation = new AnimationProps(startDelay,
+ taskViewRemoveAnimDuration, Interpolators.FAST_OUT_LINEAR_IN,
+ new AnimatorListenerAdapter() {
+ @Override
+ public void onAnimationEnd(Animator animation) {
+ postAnimationTrigger.decrement();
+
+ // Re-enable clipping with the stack (we will reuse this view)
+ tv.setClipViewInStack(true);
+ }
+ });
+ postAnimationTrigger.increment();
+
+ mTmpTransform.fillIn(tv);
+ mTmpTransform.rect.offset(offscreenXOffset, 0);
+ mStackView.updateTaskViewToTransform(tv, mTmpTransform, taskAnimation);
+ }
+ }
+
+ /**
* Starts the animation to focus the next {@link TaskView} when paging through recents.
*
* @return whether or not this will trigger a scroll in the stack
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java
index 4b1faf3..2508304 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackLayoutAlgorithm.java
@@ -557,15 +557,17 @@
mInitialScrollP = Utilities.clamp(launchTaskIndex, mMinScrollP, mMaxScrollP);
mInitialNormX = null;
} else {
- float normX = getNormalizedXFromUnfocusedY(mInitialTopOffset, FROM_TOP);
- mInitialScrollP = Math.max(mMinScrollP, Math.min(mMaxScrollP, (mNumStackTasks - 2)) -
- Math.max(0, mUnfocusedRange.getAbsoluteX(normX)));
+ // We are overriding the initial two task positions, so set the initial scroll
+ // position to match the second task (aka focused task) position
+ float initialTopNormX = getNormalizedXFromUnfocusedY(mInitialTopOffset, FROM_TOP);
+ mInitialScrollP = Math.max(mMinScrollP, Math.min(mMaxScrollP, (mNumStackTasks - 2))
+ - Math.max(0, mUnfocusedRange.getAbsoluteX(initialTopNormX)));
// Set the initial scroll to the predefined state (which differs from the stack)
mInitialNormX = new float[] {
getNormalizedXFromUnfocusedY(mSystemInsets.bottom + mInitialBottomOffset,
FROM_BOTTOM),
- normX
+ initialTopNormX
};
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java
index 04f153f..5416a48 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackView.java
@@ -72,6 +72,7 @@
import com.android.systemui.recents.events.activity.ShowStackActionButtonEvent;
import com.android.systemui.recents.events.ui.AllTaskViewsDismissedEvent;
import com.android.systemui.recents.events.ui.DeleteTaskDataEvent;
+import com.android.systemui.recents.events.ui.DismissAllTaskViewsEvent;
import com.android.systemui.recents.events.ui.DismissTaskViewEvent;
import com.android.systemui.recents.events.ui.TaskViewDismissedEvent;
import com.android.systemui.recents.events.ui.UpdateFreeformTaskViewVisibilityEvent;
@@ -1322,7 +1323,8 @@
}
// Update the stack action button visibility
- if (mStackScroller.getStackScroll() < SHOW_STACK_ACTION_BUTTON_SCROLL_THRESHOLD) {
+ if (mStackScroller.getStackScroll() < SHOW_STACK_ACTION_BUTTON_SCROLL_THRESHOLD &&
+ mStack.getTaskCount() > 0) {
EventBus.getDefault().send(new ShowStackActionButtonEvent(false /* translate */));
} else {
EventBus.getDefault().send(new HideStackActionButtonEvent());
@@ -1447,6 +1449,26 @@
}
@Override
+ public void onStackTasksRemoved(TaskStack stack) {
+ // Reset the focused task
+ resetFocusedTask(getFocusedTask());
+
+ // Return all the views to the pool
+ List<TaskView> taskViews = new ArrayList<>();
+ taskViews.addAll(getTaskViews());
+ for (int i = taskViews.size() - 1; i >= 0; i--) {
+ mViewPool.returnViewToPool(taskViews.get(i));
+ }
+
+ // Remove all the ignore tasks
+ mIgnoreTasks.clear();
+
+ // If there are no remaining tasks, then just close recents
+ EventBus.getDefault().send(new AllTaskViewsDismissedEvent(
+ R.string.recents_empty_message_dismissed_all));
+ }
+
+ @Override
public void onStackTasksUpdated(TaskStack stack) {
// Update the layout and immediately layout
updateLayoutAlgorithm(false /* boundScroll */);
@@ -1597,7 +1619,8 @@
if (mEnterAnimationComplete) {
if (prevScroll > SHOW_STACK_ACTION_BUTTON_SCROLL_THRESHOLD &&
- curScroll <= SHOW_STACK_ACTION_BUTTON_SCROLL_THRESHOLD) {
+ curScroll <= SHOW_STACK_ACTION_BUTTON_SCROLL_THRESHOLD &&
+ mStack.getTaskCount() > 0) {
EventBus.getDefault().send(new ShowStackActionButtonEvent(true /* translate */));
} else if (prevScroll < HIDE_STACK_ACTION_BUTTON_SCROLL_THRESHOLD &&
curScroll >= HIDE_STACK_ACTION_BUTTON_SCROLL_THRESHOLD) {
@@ -1705,14 +1728,42 @@
}
}
- public final void onBusEvent(final DismissTaskViewEvent event) {
+ public final void onBusEvent(DismissTaskViewEvent event) {
// For visible children, defer removing the task until after the animation
- mAnimationHelper.startDeleteTaskAnimation(event.task, event.taskView,
- event.getAnimationTrigger());
+ mAnimationHelper.startDeleteTaskAnimation(event.taskView, event.getAnimationTrigger());
+ }
+
+ public final void onBusEvent(final DismissAllTaskViewsEvent event) {
+ // Keep track of the tasks which will have their data removed
+ ArrayList<Task> tasks = new ArrayList<>(mStack.getStackTasks());
+ mAnimationHelper.startDeleteAllTasksAnimation(getTaskViews(), event.getAnimationTrigger());
+ event.addPostAnimationCallback(new Runnable() {
+ @Override
+ public void run() {
+ // Announce for accessibility
+ announceForAccessibility(getContext().getString(
+ R.string.accessibility_recents_all_items_dismissed));
+
+ // Remove all tasks and delete the task data for all tasks
+ mStack.removeAllTasks();
+ for (int i = tasks.size() - 1; i >= 0; i--) {
+ EventBus.getDefault().send(new DeleteTaskDataEvent(tasks.get(i)));
+ }
+
+ MetricsLogger.action(getContext(), MetricsEvent.OVERVIEW_DISMISS_ALL);
+ }
+ });
+
}
public final void onBusEvent(TaskViewDismissedEvent event) {
- removeTaskViewFromStack(event.taskView, event.task);
+ // Announce for accessibility
+ announceForAccessibility(getContext().getString(
+ R.string.accessibility_recents_item_dismissed, event.task.title));
+
+ // Remove the task from the stack
+ mStack.removeTask(event.task, new AnimationProps(DEFAULT_SYNC_STACK_DURATION,
+ Interpolators.FAST_OUT_SLOW_IN), false /* fromDockGesture */);
EventBus.getDefault().send(new DeleteTaskDataEvent(event.task));
MetricsLogger.action(getContext(), MetricsEvent.OVERVIEW_DISMISS,
@@ -1948,28 +1999,16 @@
}
}
- // Trigger a new layout and scroll to the initial state
- mInitialState = event.fromMultiWindow
- ? INITIAL_STATE_UPDATE_ALL
- : INITIAL_STATE_UPDATE_LAYOUT_ONLY;
+ // Trigger a new layout and update to the initial state if necessary
+ if (event.fromMultiWindow) {
+ mInitialState = INITIAL_STATE_UPDATE_ALL;
+ } else if (event.fromOrientationChange) {
+ mInitialState = INITIAL_STATE_UPDATE_LAYOUT_ONLY;
+ }
requestLayout();
}
/**
- * Removes the task from the stack, and updates the focus to the next task in the stack if the
- * removed TaskView was focused.
- */
- private void removeTaskViewFromStack(TaskView tv, Task task) {
- // Announce for accessibility
- tv.announceForAccessibility(getContext().getString(
- R.string.accessibility_recents_item_dismissed, task.title));
-
- // Remove the task from the stack
- mStack.removeTask(task, new AnimationProps(DEFAULT_SYNC_STACK_DURATION,
- Interpolators.FAST_OUT_SLOW_IN), false /* fromDockGesture */);
- }
-
- /**
* Starts an alpha animation on the freeform workspace background.
*/
private void animateFreeformWorkspaceBackgroundAlpha(int targetAlpha,
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java
index aed19c3..ee0de1a 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskStackViewTouchHandler.java
@@ -356,6 +356,11 @@
return;
}
+ // Disallow tapping above and below the stack to dismiss recents
+ if (x > mSv.mLayoutAlgorithm.mStackRect.left && x < mSv.mLayoutAlgorithm.mStackRect.right) {
+ return;
+ }
+
// If tapping on the freeform workspace background, just launch the first freeform task
SystemServicesProxy ssp = Recents.getSystemServices();
if (ssp.hasFreeformWorkspaceSupport()) {
@@ -507,13 +512,13 @@
tv.setClipViewInStack(true);
// Re-enable touch events from this task view
tv.setTouchEnabled(true);
+ // Remove the task view from the stack
+ EventBus.getDefault().send(new TaskViewDismissedEvent(tv.getTask(), tv));
// Update the scroll to the final scroll position from onBeginDrag()
mSv.getScroller().setStackScroll(mTargetStackScroll, null);
// Update the focus state to the final focus state
mSv.getStackAlgorithm().setFocusState(TaskStackLayoutAlgorithm.STATE_UNFOCUSED);
mSv.getStackAlgorithm().clearUnfocusedTaskOverrides();
- // Remove the task view from the stack
- EventBus.getDefault().send(new TaskViewDismissedEvent(tv.getTask(), tv));
// Stop tracking this deletion animation
mSwipeHelperAnimations.remove(v);
// Keep track of deletions by keyboard
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskView.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskView.java
index c085d80..f8ed700 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskView.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskView.java
@@ -384,7 +384,7 @@
void dismissTask() {
// Animate out the view and call the callback
final TaskView tv = this;
- DismissTaskViewEvent dismissEvent = new DismissTaskViewEvent(tv, mTask);
+ DismissTaskViewEvent dismissEvent = new DismissTaskViewEvent(tv);
dismissEvent.addPostAnimationCallback(new Runnable() {
@Override
public void run() {
diff --git a/packages/SystemUI/src/com/android/systemui/recents/views/TaskViewTransform.java b/packages/SystemUI/src/com/android/systemui/recents/views/TaskViewTransform.java
index dc76e61..b512393 100644
--- a/packages/SystemUI/src/com/android/systemui/recents/views/TaskViewTransform.java
+++ b/packages/SystemUI/src/com/android/systemui/recents/views/TaskViewTransform.java
@@ -226,4 +226,9 @@
v.getViewBounds().setClipBottom(0);
v.setLeftTopRightBottom(0, 0, 0, 0);
}
+
+ @Override
+ public String toString() {
+ return "R: " + rect + " V: " + visible;
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
index 023c4d0..45e94f7 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -225,7 +225,8 @@
public void onInflated(View v) {
mQsContainer = (QSContainer) v.findViewById(R.id.quick_settings_container);
mQsContainer.setPanelView(NotificationPanelView.this);
- mQsContainer.getHeader().setOnClickListener(NotificationPanelView.this);
+ mQsContainer.getHeader().findViewById(R.id.expand_indicator)
+ .setOnClickListener(NotificationPanelView.this);
}
});
mClockView = (TextView) findViewById(R.id.clock_view);
@@ -1760,7 +1761,7 @@
@Override
public void onClick(View v) {
- if (v == mQsContainer.getHeader()) {
+ if (v.getId() == R.id.expand_indicator) {
onQsExpansionStarted();
if (mQsExpanded) {
flingSettings(0 /* vel */, false /* expand */, null, true /* isClick */);
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
index 8f329c4..b507903 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickStatusBarHeader.java
@@ -124,7 +124,6 @@
// RenderThread is doing more harm than good when touching the header (to expand quick
// settings), so disable it for this view
- ((RippleDrawable) getBackground()).setForceSoftware(true);
((RippleDrawable) mSettingsButton.getBackground()).setForceSoftware(true);
updateResources();
@@ -136,6 +135,12 @@
updateResources();
}
+ @Override
+ public void onRtlPropertiesChanged(int layoutDirection) {
+ super.onRtlPropertiesChanged(layoutDirection);
+ updateResources();
+ }
+
private void updateResources() {
FontSizeUtils.updateFontSize(mAlarmStatus, R.dimen.qs_date_collapsed_size);
FontSizeUtils.updateFontSize(mEmergencyOnly, R.dimen.qs_emergency_calls_only_text_size);
@@ -175,6 +180,20 @@
.addFloat(mMultiUserSwitch, "alpha", 0, 1)
.setStartDelay(QSAnimator.EXPANDED_TILE_DELAY)
.build();
+
+ final boolean isRtl = isLayoutRtl();
+ if (isRtl && mDateTimeGroup.getWidth() == 0) {
+ mDateTimeGroup.addOnLayoutChangeListener(new OnLayoutChangeListener() {
+ @Override
+ public void onLayoutChange(View v, int left, int top, int right, int bottom,
+ int oldLeft, int oldTop, int oldRight, int oldBottom) {
+ mDateTimeGroup.setPivotX(getWidth());
+ mDateTimeGroup.removeOnLayoutChangeListener(this);
+ }
+ });
+ } else {
+ mDateTimeGroup.setPivotX(isRtl ? mDateTimeGroup.getWidth() : 0);
+ }
}
@Override
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
index ab44b6a..84e785d 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java
@@ -654,12 +654,11 @@
}
private void checkIfAddUserDisallowedByAdminOnly(UserRecord record) {
- EnforcedAdmin admin = RestrictedLockUtils.checkIfRestrictionEnforced(mContext,
- UserManager.DISALLOW_ADD_USER, ActivityManager.getCurrentUser());
- if (admin != null && !RestrictedLockUtils.hasBaseUserRestriction(mContext,
- UserManager.DISALLOW_ADD_USER, ActivityManager.getCurrentUser())) {
+ UserHandle user = UserHandle.of(ActivityManager.getCurrentUser());
+ if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, user)
+ && !mUserManager.hasBaseUserRestriction(UserManager.DISALLOW_ADD_USER, user)) {
record.isDisabledByAdmin = true;
- record.enforcedAdmin = admin;
+ record.enforcedAdmin = EnforcedAdmin.MULTIPLE_ENFORCED_ADMIN;
} else {
record.isDisabledByAdmin = false;
record.enforcedAdmin = null;
diff --git a/packages/SystemUI/tests/AndroidManifest.xml b/packages/SystemUI/tests/AndroidManifest.xml
index 5389c804..53a9976 100644
--- a/packages/SystemUI/tests/AndroidManifest.xml
+++ b/packages/SystemUI/tests/AndroidManifest.xml
@@ -23,6 +23,8 @@
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<uses-permission android:name="android.permission.MANAGE_USERS" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+ <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<application>
<uses-library android:name="android.test.runner" />
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/TouchAnimatorTests.java b/packages/SystemUI/tests/src/com/android/systemui/qs/TouchAnimatorTests.java
index 1d81fd4..e9b85b9 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/TouchAnimatorTests.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/TouchAnimatorTests.java
@@ -14,11 +14,13 @@
package com.android.systemui.qs;
+import android.test.suitebuilder.annotation.SmallTest;
import android.view.View;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.qs.TouchAnimator.Listener;
import org.mockito.Mockito;
+@SmallTest
public class TouchAnimatorTests extends SysuiTestCase {
private Listener mTouchListener;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileLifecycleManagerTests.java b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileLifecycleManagerTests.java
index f86c6a4..6a81659 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileLifecycleManagerTests.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileLifecycleManagerTests.java
@@ -32,9 +32,11 @@
import android.service.quicksettings.IQSTileService;
import android.service.quicksettings.Tile;
import android.test.AndroidTestCase;
+import android.test.suitebuilder.annotation.SmallTest;
import android.util.ArraySet;
import android.util.Log;
+@SmallTest
public class TileLifecycleManagerTests extends AndroidTestCase {
public static final String TILE_UPDATE_BROADCAST = "com.android.systemui.tests.TILE_UPDATE";
public static final String EXTRA_CALLBACK = "callback";
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServiceManagerTests.java b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServiceManagerTests.java
index efdb50d..f24b541 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServiceManagerTests.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServiceManagerTests.java
@@ -19,10 +19,12 @@
import android.os.Handler;
import android.os.HandlerThread;
import android.service.quicksettings.TileService;
+import android.test.suitebuilder.annotation.SmallTest;
import com.android.systemui.SysuiTestCase;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
+@SmallTest
public class TileServiceManagerTests extends SysuiTestCase {
private TileServices mTileServices;
diff --git a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServicesTests.java b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServicesTests.java
index 01514646b..94c98d6 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServicesTests.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/qs/external/TileServicesTests.java
@@ -17,6 +17,7 @@
import android.content.ComponentName;
import android.os.Looper;
+import android.test.suitebuilder.annotation.SmallTest;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.statusbar.phone.QSTileHost;
import com.android.systemui.statusbar.policy.DataSaverController;
@@ -27,6 +28,7 @@
import java.util.ArrayList;
+@SmallTest
public class TileServicesTests extends SysuiTestCase {
private static int NUM_FAKES = TileServices.DEFAULT_MAX_BOUND * 2;
diff --git a/proto/src/metrics_constants.proto b/proto/src/metrics_constants.proto
index d6f1499..2580e2c 100644
--- a/proto/src/metrics_constants.proto
+++ b/proto/src/metrics_constants.proto
@@ -2017,6 +2017,36 @@
// action pass package name of calling package.
ACTION_SCOPED_DIRECTORY_ACCESS_DENIED_AND_PERSIST_BY_PACKAGE = 356;
+ // Logged when a user dismisses all task in overview
+ OVERVIEW_DISMISS_ALL = 357;
+
+ // Quick Settings -> Edit
+ QS_EDIT = 358;
+
+ // Quick Settings -> Edit -> Overflow -> Reset
+ ACTION_QS_EDIT_RESET = 359;
+
+ // QS -> Edit - Drag a tile out of the active tiles.
+ // The _SPEC contains either the spec of the tile or
+ // the package of the 3rd party app in the PKG field.
+ ACTION_QS_EDIT_REMOVE_SPEC = 360;
+ ACTION_QS_EDIT_REMOVE = 361;
+
+ // QS -> Edit - Drag a tile into the active tiles.
+ // The _SPEC contains either the spec of the tile or
+ // the package of the 3rd party app in the PKG field.
+ ACTION_QS_EDIT_ADD_SPEC = 362;
+ ACTION_QS_EDIT_ADD = 363;
+
+ // QS -> Edit - Drag a tile within the active tiles.
+ // The _SPEC contains either the spec of the tile or
+ // the package of the 3rd party app in the PKG field.
+ ACTION_QS_EDIT_MOVE_SPEC = 364;
+ ACTION_QS_EDIT_MOVE = 365;
+
+ // Long-press on a QS tile. Tile spec in package field.
+ ACTION_QS_LONG_PRESS = 366;
+
// Add new aosp constants above this line.
// END OF AOSP CONSTANTS
}
diff --git a/rs/java/android/renderscript/Allocation.java b/rs/java/android/renderscript/Allocation.java
index f2ef065..81f63ae 100644
--- a/rs/java/android/renderscript/Allocation.java
+++ b/rs/java/android/renderscript/Allocation.java
@@ -296,8 +296,13 @@
}
/**
- * Enable/Disable AutoPadding for Vec3 elements.
- * By default: Diabled.
+ * Enable/Disable AutoPadding for Vec3 Elements.
+ *
+ * <p> Vec3 Elements, such as {@link Element#U8_3} are treated as Vec4 Elements
+ * with the fourth vector element used as padding. Enabling the AutoPadding feature
+ * will automatically add/remove the padding when you copy to/from an Allocation
+ * with a Vec3 Element.
+ * <p> By default: Disabled.
*
* @param useAutoPadding True: enable AutoPadding; False: disable AutoPadding
*
diff --git a/rs/java/android/renderscript/Script.java b/rs/java/android/renderscript/Script.java
index 2b06780..f6f93cb 100644
--- a/rs/java/android/renderscript/Script.java
+++ b/rs/java/android/renderscript/Script.java
@@ -541,21 +541,22 @@
/**
* Class for specifying the specifics about how a kernel will be
- * launched
+ * launched.
*
* This class can specify a potential range of cells on which to
* run a kernel. If no set is called for a dimension then this
* class will have no impact on that dimension when the kernel
* is executed.
*
- * The forEach launch will operate over the intersection of the
- * dimensions.
+ * The forEach kernel launch will operate over the intersection of
+ * the dimensions.
*
* Example:
* LaunchOptions with setX(5, 15)
* Allocation with dimension X=10, Y=10
- * The resulting forEach run would execute over x = 5 to 10 and
- * y = 0 to 10.
+ * The resulting forEach run would execute over:
+ * x = 5 to 9 (inclusive) and
+ * y = 0 to 9 (inclusive).
*
*
*/
@@ -569,11 +570,11 @@
private int strategy;
/**
- * Set the X range. If the end value is set to 0 the X dimension is not
- * clipped.
+ * Set the X range. xstartArg is the lowest coordinate of the range,
+ * and xendArg-1 is the highest coordinate of the range.
*
* @param xstartArg Must be >= 0
- * @param xendArg Must be >= xstartArg
+ * @param xendArg Must be > xstartArg
*
* @return LaunchOptions
*/
@@ -587,11 +588,11 @@
}
/**
- * Set the Y range. If the end value is set to 0 the Y dimension is not
- * clipped.
+ * Set the Y range. ystartArg is the lowest coordinate of the range,
+ * and yendArg-1 is the highest coordinate of the range.
*
* @param ystartArg Must be >= 0
- * @param yendArg Must be >= ystartArg
+ * @param yendArg Must be > ystartArg
*
* @return LaunchOptions
*/
@@ -605,11 +606,11 @@
}
/**
- * Set the Z range. If the end value is set to 0 the Z dimension is not
- * clipped.
+ * Set the Z range. zstartArg is the lowest coordinate of the range,
+ * and zendArg-1 is the highest coordinate of the range.
*
* @param zstartArg Must be >= 0
- * @param zendArg Must be >= zstartArg
+ * @param zendArg Must be > zstartArg
*
* @return LaunchOptions
*/
diff --git a/rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java b/rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
index 76da781..339e0e9 100644
--- a/rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicConvolve3x3.java
@@ -32,10 +32,9 @@
* Supported elements types are {@link Element#U8}, {@link
* Element#U8_2}, {@link Element#U8_3}, {@link Element#U8_4},
* {@link Element#F32}, {@link Element#F32_2}, {@link
- * Element#F32_3}, and {@link Element#F32_4}
+ * Element#F32_3}, and {@link Element#F32_4}.
*
- * The default coefficients are.
- *
+ * <p> The default coefficients are:
* <code>
* <p> [ 0, 0, 0 ]
* <p> [ 0, 1, 0 ]
@@ -67,7 +66,7 @@
}
/**
- * Set the input of the blur.
+ * Set the input of the 3x3 convolve.
* Must match the element type supplied during create.
*
* @param ain The input allocation.
@@ -80,7 +79,7 @@
/**
* Set the coefficients for the convolve.
*
- * The convolve layout is
+ * <p> The convolve layout is:
* <code>
* <p> [ 0, 1, 2 ]
* <p> [ 3, 4, 5 ]
diff --git a/rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java b/rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
index 2d37600..a288cee 100644
--- a/rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
+++ b/rs/java/android/renderscript/ScriptIntrinsicConvolve5x5.java
@@ -32,9 +32,9 @@
* Supported elements types are {@link Element#U8}, {@link
* Element#U8_2}, {@link Element#U8_3}, {@link Element#U8_4},
* {@link Element#F32}, {@link Element#F32_2}, {@link
- * Element#F32_3}, and {@link Element#F32_4}
+ * Element#F32_3}, and {@link Element#F32_4}.
*
- * The default coefficients are.
+ * <p> The default coefficients are:
* <code>
* <p> [ 0, 0, 0, 0, 0 ]
* <p> [ 0, 0, 0, 0, 0 ]
@@ -66,7 +66,7 @@
}
/**
- * Set the input of the blur.
+ * Set the input of the 5x5 convolve.
* Must match the element type supplied during create.
*
* @param ain The input allocation.
@@ -79,7 +79,7 @@
/**
* Set the coefficients for the convolve.
*
- * The convolve layout is
+ * <p> The convolve layout is:
* <code>
* <p> [ 0, 1, 2, 3, 4 ]
* <p> [ 5, 6, 7, 8, 9 ]
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
index e3dac28..4b96e7a 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
@@ -1774,17 +1774,22 @@
private void updateSoftKeyboardShowModeLocked(UserState userState) {
final int userId = userState.mUserId;
- if (userId == mCurrentUserId) {
- // Check whether any Accessibility Services are still enabled and, if not, remove flag
- // requesting no soft keyboard
- final boolean accessibilityRequestingNoIme = userState.mSoftKeyboardShowMode == 1;
- if (accessibilityRequestingNoIme && !userState.isHandlingAccessibilityEvents()) {
- // No active Accessibility Services can be requesting the soft keyboard to be hidden
+ // Only check whether we need to reset the soft keyboard mode if it is not set to the
+ // default.
+ if ((userId == mCurrentUserId) && (userState.mSoftKeyboardShowMode != 0)) {
+ // Check whether the last Accessibility Service that changed the soft keyboard mode to
+ // something other than the default is still enabled and, if not, remove flag and
+ // reset to the default soft keyboard behavior.
+ boolean serviceChangingSoftKeyboardModeIsEnabled =
+ userState.mEnabledServices.contains(userState.mServiceChangingSoftKeyboardMode);
+
+ if (!serviceChangingSoftKeyboardModeIsEnabled) {
Settings.Secure.putIntForUser(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE,
0,
userState.mUserId);
userState.mSoftKeyboardShowMode = 0;
+ userState.mServiceChangingSoftKeyboardMode = null;
}
notifySoftKeyboardShowModeChangedLocked(userState.mSoftKeyboardShowMode);
@@ -2966,6 +2971,14 @@
final long identity = Binder.clearCallingIdentity();
try {
+ // Keep track of the last service to request a non-default show mode. The show mode
+ // should be restored to default should this service be disabled.
+ if (showMode == Settings.Secure.SHOW_MODE_AUTO) {
+ userState.mServiceChangingSoftKeyboardMode = null;
+ } else {
+ userState.mServiceChangingSoftKeyboardMode = mComponentName;
+ }
+
Settings.Secure.putIntForUser(mContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_SOFT_KEYBOARD_MODE, showMode,
userState.mUserId);
@@ -4115,6 +4128,8 @@
public final Set<ComponentName> mTouchExplorationGrantedServices =
new HashSet<>();
+ public ComponentName mServiceChangingSoftKeyboardMode;
+
public int mLastSentClientState = -1;
public int mSoftKeyboardShowMode = 0;
diff --git a/services/core/java/com/android/server/DeviceIdleController.java b/services/core/java/com/android/server/DeviceIdleController.java
index 4749417..6023d7f 100644
--- a/services/core/java/com/android/server/DeviceIdleController.java
+++ b/services/core/java/com/android/server/DeviceIdleController.java
@@ -108,7 +108,7 @@
private static final boolean COMPRESS_TIME = false;
- private static final int EVENT_BUFFER_SIZE = 40;
+ private static final int EVENT_BUFFER_SIZE = 100;
private AlarmManager mAlarmManager;
private IBatteryStats mBatteryStats;
@@ -192,6 +192,7 @@
private long mNextAlarmTime;
private long mNextIdlePendingDelay;
private long mNextIdleDelay;
+ private long mNextLightIdleDelay;
private long mNextLightAlarmTime;
private long mCurIdleBudget;
private long mMaintenanceStartTime;
@@ -353,6 +354,8 @@
}
};
+ private boolean mMaintenanceMinCheckScheduled;
+
private final BroadcastReceiver mIdleStartedDoneReceiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
decActiveIdleOps();
@@ -477,7 +480,11 @@
*/
private final class Constants extends ContentObserver {
// Key names stored in the settings value.
+ private static final String KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
+ = "light_after_inactive_to";
private static final String KEY_LIGHT_IDLE_TIMEOUT = "light_idle_to";
+ private static final String KEY_LIGHT_IDLE_FACTOR = "light_idle_factor";
+ private static final String KEY_LIGHT_MAX_IDLE_TIMEOUT = "light_max_idle_to";
private static final String KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET
= "light_idle_maintenance_min_budget";
private static final String KEY_LIGHT_IDLE_MAINTENANCE_MAX_BUDGET
@@ -505,14 +512,35 @@
"sms_temp_app_whitelist_duration";
/**
- * This is the time, after becoming inactive, that we will start going
- * in to light-weight idle mode.
+ * This is the time, after becoming inactive, that we go in to the first
+ * light-weight idle mode.
+ * @see Settings.Global#DEVICE_IDLE_CONSTANTS
+ * @see #KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT
+ */
+ public long LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT;
+
+ /**
+ * This is the initial time that we will run in idle maintenance mode.
* @see Settings.Global#DEVICE_IDLE_CONSTANTS
* @see #KEY_LIGHT_IDLE_TIMEOUT
*/
public long LIGHT_IDLE_TIMEOUT;
/**
+ * Scaling factor to apply to the light idle mode time each time we complete a cycle.
+ * @see Settings.Global#DEVICE_IDLE_CONSTANTS
+ * @see #KEY_LIGHT_IDLE_FACTOR
+ */
+ public float LIGHT_IDLE_FACTOR;
+
+ /**
+ * This is the maximum time we will run in idle maintenence mode.
+ * @see Settings.Global#DEVICE_IDLE_CONSTANTS
+ * @see #KEY_LIGHT_MAX_IDLE_TIMEOUT
+ */
+ public long LIGHT_MAX_IDLE_TIMEOUT;
+
+ /**
* This is the minimum amount of time we want to make available for maintenance mode
* when lightly idling. That is, we will always have at least this amount of time
* available maintenance before timing out and cutting off maintenance mode.
@@ -716,7 +744,14 @@
Slog.e(TAG, "Bad device idle settings", e);
}
+ LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT = mParser.getLong(
+ KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT,
+ !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
LIGHT_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_IDLE_TIMEOUT,
+ !COMPRESS_TIME ? 5 * 60 * 1000L : 15 * 1000L);
+ LIGHT_IDLE_FACTOR = mParser.getFloat(KEY_LIGHT_IDLE_FACTOR,
+ 2f);
+ LIGHT_MAX_IDLE_TIMEOUT = mParser.getLong(KEY_LIGHT_MAX_IDLE_TIMEOUT,
!COMPRESS_TIME ? 15 * 60 * 1000L : 60 * 1000L);
LIGHT_IDLE_MAINTENANCE_MIN_BUDGET = mParser.getLong(
KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET,
@@ -770,10 +805,22 @@
void dump(PrintWriter pw) {
pw.println(" Settings:");
+ pw.print(" "); pw.print(KEY_LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT); pw.print("=");
+ TimeUtils.formatDuration(LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT, pw);
+ pw.println();
+
pw.print(" "); pw.print(KEY_LIGHT_IDLE_TIMEOUT); pw.print("=");
TimeUtils.formatDuration(LIGHT_IDLE_TIMEOUT, pw);
pw.println();
+ pw.print(" "); pw.print(KEY_LIGHT_IDLE_FACTOR); pw.print("=");
+ pw.print(LIGHT_IDLE_FACTOR);
+ pw.println();
+
+ pw.print(" "); pw.print(KEY_LIGHT_MAX_IDLE_TIMEOUT); pw.print("=");
+ TimeUtils.formatDuration(LIGHT_MAX_IDLE_TIMEOUT, pw);
+ pw.println();
+
pw.print(" "); pw.print(KEY_LIGHT_IDLE_MAINTENANCE_MIN_BUDGET); pw.print("=");
TimeUtils.formatDuration(LIGHT_IDLE_MAINTENANCE_MIN_BUDGET, pw);
pw.println();
@@ -1640,7 +1687,10 @@
mInactiveTimeout = mConstants.INACTIVE_TIMEOUT;
mCurIdleBudget = 0;
mMaintenanceStartTime = 0;
- mAlarmManager.cancel(mMaintenanceMinCheckListener);
+ if (mMaintenanceMinCheckScheduled) {
+ mAlarmManager.cancel(mMaintenanceMinCheckListener);
+ mMaintenanceMinCheckScheduled = false;
+ }
resetIdleManagementLocked();
resetLightIdleManagementLocked();
addEvent(EVENT_NORMAL);
@@ -1663,7 +1713,7 @@
mLightState = LIGHT_STATE_INACTIVE;
if (DEBUG) Slog.d(TAG, "Moved from LIGHT_STATE_ACTIVE to LIGHT_STATE_INACTIVE");
resetLightIdleManagementLocked();
- scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_TIMEOUT);
+ scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_AFTER_INACTIVE_TIMEOUT);
EventLogTags.writeDeviceIdleLight(mLightState, "no activity");
}
}
@@ -1672,6 +1722,7 @@
void resetIdleManagementLocked() {
mNextIdlePendingDelay = 0;
mNextIdleDelay = 0;
+ mNextLightIdleDelay = 0;
cancelAlarmLocked();
cancelLocatingLocked();
stopMonitoringMotionLocked();
@@ -1704,6 +1755,8 @@
switch (mLightState) {
case LIGHT_STATE_INACTIVE:
mCurIdleBudget = mConstants.LIGHT_IDLE_MAINTENANCE_MIN_BUDGET;
+ // Reset the upcoming idle delays.
+ mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
mMaintenanceStartTime = 0;
case LIGHT_STATE_IDLE_MAINTENANCE:
if (mMaintenanceStartTime != 0) {
@@ -1717,13 +1770,21 @@
}
}
mMaintenanceStartTime = 0;
- scheduleLightAlarmLocked(mConstants.LIGHT_IDLE_TIMEOUT);
+ scheduleLightAlarmLocked(mNextLightIdleDelay);
+ mNextLightIdleDelay = Math.min(mConstants.LIGHT_MAX_IDLE_TIMEOUT,
+ (long)(mNextLightIdleDelay * mConstants.LIGHT_IDLE_FACTOR));
+ if (mNextLightIdleDelay < mConstants.LIGHT_IDLE_TIMEOUT) {
+ mNextLightIdleDelay = mConstants.LIGHT_IDLE_TIMEOUT;
+ }
if (DEBUG) Slog.d(TAG, "Moved to LIGHT_STATE_IDLE.");
mLightState = LIGHT_STATE_IDLE;
EventLogTags.writeDeviceIdleLight(mLightState, reason);
addEvent(EVENT_LIGHT_IDLE);
mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON_LIGHT);
- mAlarmManager.cancel(mMaintenanceMinCheckListener);
+ if (mMaintenanceMinCheckScheduled) {
+ mAlarmManager.cancel(mMaintenanceMinCheckListener);
+ mMaintenanceMinCheckScheduled = false;
+ }
break;
case LIGHT_STATE_IDLE:
// We have been idling long enough, now it is time to do some work.
@@ -1744,6 +1805,7 @@
mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME,
mMaintenanceStartTime + mConstants.MIN_LIGHT_MAINTENANCE_TIME,
"DeviceIdleController.maint-check", mMaintenanceMinCheckListener, mHandler);
+ mMaintenanceMinCheckScheduled = true;
break;
}
}
@@ -1820,6 +1882,7 @@
cancelAlarmLocked();
cancelLocatingLocked();
mAnyMotionDetector.stop();
+
case STATE_IDLE_MAINTENANCE:
scheduleAlarmLocked(mNextIdleDelay, true);
if (DEBUG) Slog.d(TAG, "Moved to STATE_IDLE. Next alarm in " + mNextIdleDelay +
@@ -1827,6 +1890,9 @@
mNextIdleDelay = (long)(mNextIdleDelay * mConstants.IDLE_FACTOR);
if (DEBUG) Slog.d(TAG, "Setting mNextIdleDelay = " + mNextIdleDelay);
mNextIdleDelay = Math.min(mNextIdleDelay, mConstants.MAX_IDLE_TIMEOUT);
+ if (mNextIdleDelay < mConstants.IDLE_TIMEOUT) {
+ mNextIdleDelay = mConstants.IDLE_TIMEOUT;
+ }
mState = STATE_IDLE;
if (mLightState != LIGHT_STATE_OVERRIDE) {
mLightState = LIGHT_STATE_OVERRIDE;
@@ -1835,7 +1901,10 @@
EventLogTags.writeDeviceIdle(mState, reason);
addEvent(EVENT_DEEP_IDLE);
mHandler.sendEmptyMessage(MSG_REPORT_IDLE_ON);
- mAlarmManager.cancel(mMaintenanceMinCheckListener);
+ if (mMaintenanceMinCheckScheduled) {
+ mAlarmManager.cancel(mMaintenanceMinCheckListener);
+ mMaintenanceMinCheckScheduled = false;
+ }
break;
case STATE_IDLE:
// We have been idling long enough, now it is time to do some work.
@@ -1846,6 +1915,9 @@
mMaintenanceStartTime = SystemClock.elapsedRealtime();
mNextIdlePendingDelay = Math.min(mConstants.MAX_IDLE_PENDING_TIMEOUT,
(long)(mNextIdlePendingDelay * mConstants.IDLE_PENDING_FACTOR));
+ if (mNextIdlePendingDelay < mConstants.IDLE_PENDING_TIMEOUT) {
+ mNextIdlePendingDelay = mConstants.IDLE_PENDING_TIMEOUT;
+ }
mState = STATE_IDLE_MAINTENANCE;
EventLogTags.writeDeviceIdle(mState, reason);
addEvent(EVENT_DEEP_MAINTENANCE);
@@ -1853,6 +1925,7 @@
mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME,
mMaintenanceStartTime + mConstants.MIN_DEEP_MAINTENANCE_TIME,
"DeviceIdleController.maint-check", mMaintenanceMinCheckListener, mHandler);
+ mMaintenanceMinCheckScheduled = true;
break;
}
}
@@ -2735,6 +2808,11 @@
TimeUtils.formatDuration(mNextIdleDelay, pw);
pw.println();
}
+ if (mNextLightIdleDelay != 0) {
+ pw.print(" mNextIdleDelay=");
+ TimeUtils.formatDuration(mNextLightIdleDelay, pw);
+ pw.println();
+ }
if (mNextLightAlarmTime != 0) {
pw.print(" mNextLightAlarmTime=");
TimeUtils.formatDuration(mNextLightAlarmTime, SystemClock.elapsedRealtime(), pw);
@@ -2750,6 +2828,10 @@
TimeUtils.formatDuration(mMaintenanceStartTime, SystemClock.elapsedRealtime(), pw);
pw.println();
}
+ if (mMaintenanceMinCheckScheduled) {
+ pw.print(" mMaintenanceMinCheckScheduled=");
+ pw.println(mMaintenanceMinCheckScheduled);
+ }
if (mJobsActive) {
pw.print(" mJobsActive="); pw.println(mJobsActive);
}
diff --git a/services/core/java/com/android/server/InputMethodManagerService.java b/services/core/java/com/android/server/InputMethodManagerService.java
index e042483..77b3111 100644
--- a/services/core/java/com/android/server/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/InputMethodManagerService.java
@@ -1715,8 +1715,9 @@
// exists in the IME switcher dialog. Might be OK to remove this condition once
// SHOW_IME_WITH_HARD_KEYBOARD settings finds a good place to live.
return true;
+ } else if ((visibility & InputMethodService.IME_VISIBLE) == 0) {
+ return false;
}
- if ((visibility & InputMethodService.IME_VISIBLE) == 0) return false;
List<InputMethodInfo> imis = mSettings.getEnabledInputMethodListLocked();
final int N = imis.size();
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index cd4d472..4bb3a54 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -1468,6 +1468,9 @@
static final int FIRST_COMPAT_MODE_MSG = 300;
static final int FIRST_SUPERVISOR_STACK_MSG = 100;
+ static ServiceThread sKillThread = null;
+ static KillHandler sKillHandler = null;
+
CompatModeDialog mCompatModeDialog;
long mLastMemUsageReportTime = 0;
@@ -1491,6 +1494,30 @@
PackageManagerInternal mPackageManagerInt;
+ final class KillHandler extends Handler {
+ static final int KILL_PROCESS_GROUP_MSG = 4000;
+
+ public KillHandler(Looper looper) {
+ super(looper, null, true);
+ }
+
+ @Override
+ public void handleMessage(Message msg) {
+ switch (msg.what) {
+ case KILL_PROCESS_GROUP_MSG:
+ {
+ Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "killProcessGroup");
+ Process.killProcessGroup(msg.arg1 /* uid */, msg.arg2 /* pid */);
+ Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
+ }
+ break;
+
+ default:
+ super.handleMessage(msg);
+ }
+ }
+ }
+
final class UiHandler extends Handler {
public UiHandler() {
super(com.android.server.UiThread.get().getLooper(), null, true);
@@ -2459,6 +2486,14 @@
mHandler = new MainHandler(mHandlerThread.getLooper());
mUiHandler = new UiHandler();
+ /* static; one-time init here */
+ if (sKillHandler == null) {
+ sKillThread = new ServiceThread(TAG + ":kill",
+ android.os.Process.THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
+ sKillThread.start();
+ sKillHandler = new KillHandler(sKillThread.getLooper());
+ }
+
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", BROADCAST_FG_TIMEOUT, false);
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
@@ -3007,9 +3042,13 @@
}
static void killProcessGroup(int uid, int pid) {
- Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "killProcessGroup");
- Process.killProcessGroup(uid, pid);
- Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
+ if (sKillHandler != null) {
+ sKillHandler.sendMessage(
+ sKillHandler.obtainMessage(KillHandler.KILL_PROCESS_GROUP_MSG, uid, pid));
+ } else {
+ Slog.w(TAG, "Asked to kill process group before system bringup!");
+ Process.killProcessGroup(uid, pid);
+ }
}
final void removeLruProcessLocked(ProcessRecord app) {
@@ -7182,6 +7221,15 @@
}
}
+ // NOTE: this is an internal method used by the OnShellCommand implementation only and should
+ // be guarded by permission checking.
+ int getUidState(int uid) {
+ synchronized (this) {
+ UidRecord uidRec = mActiveUids.get(uid);
+ return uidRec == null ? ActivityManager.PROCESS_STATE_NONEXISTENT : uidRec.curProcState;
+ }
+ }
+
@Override
public boolean inMultiWindow(IBinder token) {
final long origId = Binder.clearCallingIdentity();
@@ -13205,6 +13253,7 @@
}
}
+ @Override
public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
enforceNotIsolatedCaller("getProcessesInErrorState");
// assume our apps are happy - lazy create the list
@@ -13281,6 +13330,7 @@
outInfo.processState = app.curProcState;
}
+ @Override
public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
enforceNotIsolatedCaller("getRunningAppProcesses");
@@ -13332,6 +13382,7 @@
return runList;
}
+ @Override
public List<ApplicationInfo> getRunningExternalApplications() {
enforceNotIsolatedCaller("getRunningExternalApplications");
List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
diff --git a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
index 0253976..d570be9 100644
--- a/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
+++ b/services/core/java/com/android/server/am/ActivityManagerShellCommand.java
@@ -16,10 +16,12 @@
package com.android.server.am;
+import android.app.ActivityManager;
import android.app.IActivityManager;
import android.os.RemoteException;
import android.os.ShellCommand;
import android.os.UserHandle;
+import android.util.DebugUtils;
import com.android.internal.util.ArrayUtils;
@@ -64,6 +66,8 @@
return runIsUserStopped(pw);
case "lenient-background-check":
return runLenientBackgroundCheck(pw);
+ case "get-uid-state":
+ return getUidState(pw);
default:
return handleDefaultCommands(cmd);
}
@@ -170,6 +174,17 @@
return 0;
}
+ int getUidState(PrintWriter pw) throws RemoteException {
+ mInternal.enforceCallingPermission(android.Manifest.permission.DUMP,
+ "getUidState()");
+ int state = mInternal.getUidState(Integer.parseInt(getNextArgRequired()));
+ pw.print(state);
+ pw.print(" (");
+ pw.printf(DebugUtils.valueToString(ActivityManager.class, "PROCESS_STATE_", state));
+ pw.println(")");
+ return 0;
+ }
+
@Override
public void onHelp() {
PrintWriter pw = getOutPrintWriter();
@@ -212,7 +227,7 @@
pw.println(" kill [--user <USER_ID> | all | current] <PACKAGE>");
pw.println(" Kill all processes associated with the given application.");
pw.println(" kill-all");
- pw.println(" Kill all processes that are safe to kill (cached, etc)");
+ pw.println(" Kill all processes that are safe to kill (cached, etc).");
pw.println(" write");
pw.println(" Write all pending state to storage.");
pw.println(" track-associations");
@@ -220,9 +235,11 @@
pw.println(" untrack-associations");
pw.println(" Disable and clear association tracking.");
pw.println(" is-user-stopped <USER_ID>");
- pw.println(" returns whether <USER_ID> has been stopped or not");
+ pw.println(" Returns whether <USER_ID> has been stopped or not.");
pw.println(" lenient-background-check [<true|false>]");
- pw.println(" optionally controls lenient background check mode, returns current mode.");
+ pw.println(" Optionally controls lenient background check mode, returns current mode.");
+ pw.println(" get-uid-state <UID>");
+ pw.println(" Gets the process state of an app given its <UID>.");
}
}
}
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index 0993ce6..93d4060 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -560,7 +560,7 @@
}
EventLog.writeEvent(EventLogTags.AM_KILL, userId, pid, processName, setAdj, reason);
Process.killProcessQuiet(pid);
- Process.killProcessGroup(uid, pid);
+ ActivityManagerService.killProcessGroup(uid, pid);
if (!persistent) {
killed = true;
killedByAm = true;
diff --git a/services/core/java/com/android/server/connectivity/Tethering.java b/services/core/java/com/android/server/connectivity/Tethering.java
index da9c48a..d10df02 100644
--- a/services/core/java/com/android/server/connectivity/Tethering.java
+++ b/services/core/java/com/android/server/connectivity/Tethering.java
@@ -32,6 +32,7 @@
import android.content.res.Resources;
import android.hardware.usb.UsbManager;
import android.net.ConnectivityManager;
+import android.net.ConnectivityManager.NetworkCallback;
import android.net.INetworkStatsService;
import android.net.InterfaceConfiguration;
import android.net.LinkAddress;
@@ -40,6 +41,7 @@
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
+import android.net.NetworkState;
import android.net.NetworkUtils;
import android.net.RouteInfo;
import android.net.wifi.WifiManager;
@@ -88,7 +90,7 @@
*/
public class Tethering extends BaseNetworkObserver {
- private Context mContext;
+ private final Context mContext;
private final static String TAG = "Tethering";
private final static boolean DBG = false;
private final static boolean VDBG = false;
@@ -100,7 +102,7 @@
private Collection<Integer> mUpstreamIfaceTypes;
// used to synchronize public access to members
- private Object mPublicSync;
+ private final Object mPublicSync;
private static final Integer MOBILE_TYPE = new Integer(ConnectivityManager.TYPE_MOBILE);
private static final Integer HIPRI_TYPE = new Integer(ConnectivityManager.TYPE_MOBILE_HIPRI);
@@ -112,7 +114,7 @@
private final INetworkManagementService mNMService;
private final INetworkStatsService mStatsService;
- private Looper mLooper;
+ private final Looper mLooper;
private HashMap<String, TetherInterfaceSM> mIfaces; // all tethered/tetherable ifaces
@@ -143,7 +145,9 @@
private static final String DNS_DEFAULT_SERVER1 = "8.8.8.8";
private static final String DNS_DEFAULT_SERVER2 = "8.8.4.4";
- private StateMachine mTetherMasterSM;
+ private final StateMachine mTetherMasterSM;
+ private final UpstreamNetworkMonitor mUpstreamNetworkMonitor;
+ private String mCurrentUpstreamIface;
private Notification.Builder mTetheredNotificationBuilder;
private int mLastNotificationId;
@@ -167,6 +171,8 @@
mTetherMasterSM = new TetherMasterSM("TetherMaster", mLooper);
mTetherMasterSM.start();
+ mUpstreamNetworkMonitor = new UpstreamNetworkMonitor();
+
mStateReceiver = new StateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_STATE);
@@ -505,7 +511,7 @@
};
// The following is necessary to avoid unmarshalling issues when sending the receiver
- // across proccesses.
+ // across processes.
Parcel parcel = Parcel.obtain();
rr.writeToParcel(parcel,0);
parcel.setDataPosition(0);
@@ -559,6 +565,7 @@
}
}
}
+
public int tether(String iface) {
if (DBG) Log.d(TAG, "Tethering " + iface);
TetherInterfaceSM sm = null;
@@ -1371,15 +1378,115 @@
}
+ /**
+ * A NetworkCallback class that relays information of interest to the
+ * tethering master state machine thread for subsequent processing.
+ */
+ class UpstreamNetworkCallback extends NetworkCallback {
+ @Override
+ public void onLinkPropertiesChanged(Network network, LinkProperties newLp) {
+ mTetherMasterSM.sendMessage(
+ TetherMasterSM.EVENT_UPSTREAM_LINKPROPERTIES_CHANGED,
+ new NetworkState(null, newLp, null, network, null, null));
+ }
+
+ @Override
+ public void onLost(Network network) {
+ mTetherMasterSM.sendMessage(TetherMasterSM.EVENT_UPSTREAM_LOST, network);
+ }
+ }
+
+ /**
+ * A class to centralize all the network and link properties information
+ * pertaining to the current and any potential upstream network.
+ *
+ * Calling #start() registers two callbacks: one to track the system default
+ * network and a second to specifically observe TYPE_MOBILE_DUN networks.
+ *
+ * The methods and data members of this class are only to be accessed and
+ * modified from the tethering master state machine thread. Any other
+ * access semantics would necessitate the addition of locking.
+ *
+ * TODO: Investigate whether more "upstream-specific" logic/functionality
+ * could/should be moved here.
+ */
+ class UpstreamNetworkMonitor {
+ final HashMap<Network, NetworkState> mNetworkMap = new HashMap();
+ NetworkCallback mDefaultNetworkCallback;
+ NetworkCallback mDunTetheringCallback;
+
+ void start() {
+ stop();
+
+ mDefaultNetworkCallback = new UpstreamNetworkCallback();
+ getConnectivityManager().registerDefaultNetworkCallback(mDefaultNetworkCallback);
+
+ final NetworkRequest dunTetheringRequest = new NetworkRequest.Builder()
+ .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
+ .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
+ .addCapability(NetworkCapabilities.NET_CAPABILITY_DUN)
+ .build();
+ mDunTetheringCallback = new UpstreamNetworkCallback();
+ getConnectivityManager().registerNetworkCallback(
+ dunTetheringRequest, mDunTetheringCallback);
+ }
+
+ void stop() {
+ if (mDefaultNetworkCallback != null) {
+ getConnectivityManager().unregisterNetworkCallback(mDefaultNetworkCallback);
+ mDefaultNetworkCallback = null;
+ }
+
+ if (mDunTetheringCallback != null) {
+ getConnectivityManager().unregisterNetworkCallback(mDunTetheringCallback);
+ mDunTetheringCallback = null;
+ }
+
+ mNetworkMap.clear();
+ }
+
+ // Returns true if these updated LinkProperties pertain to the current
+ // upstream network interface, false otherwise (or if there is not
+ // currently any upstream tethering interface).
+ boolean processLinkPropertiesChanged(NetworkState networkState) {
+ if (networkState == null ||
+ networkState.network == null ||
+ networkState.linkProperties == null) {
+ return false;
+ }
+
+ mNetworkMap.put(networkState.network, networkState);
+
+ if (mCurrentUpstreamIface != null) {
+ for (String ifname : networkState.linkProperties.getAllInterfaceNames()) {
+ if (mCurrentUpstreamIface.equals(ifname)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ void processNetworkLost(Network network) {
+ if (network != null) {
+ mNetworkMap.remove(network);
+ }
+ }
+ }
+
class TetherMasterSM extends StateMachine {
// an interface SM has requested Tethering
- static final int CMD_TETHER_MODE_REQUESTED = 1;
+ static final int CMD_TETHER_MODE_REQUESTED = 1;
// an interface SM has unrequested Tethering
- static final int CMD_TETHER_MODE_UNREQUESTED = 2;
+ static final int CMD_TETHER_MODE_UNREQUESTED = 2;
// upstream connection change - do the right thing
- static final int CMD_UPSTREAM_CHANGED = 3;
+ static final int CMD_UPSTREAM_CHANGED = 3;
// we don't have a valid upstream conn, check again after a delay
- static final int CMD_RETRY_UPSTREAM = 4;
+ static final int CMD_RETRY_UPSTREAM = 4;
+ // Events from NetworkCallbacks that we process on the master state
+ // machine thread on behalf of the UpstreamNetworkMonitor.
+ static final int EVENT_UPSTREAM_LINKPROPERTIES_CHANGED = 5;
+ static final int EVENT_UPSTREAM_LOST = 6;
// This indicates what a timeout event relates to. A state that
// sends itself a delayed timeout event and handles incoming timeout events
@@ -1399,9 +1506,7 @@
private ArrayList<TetherInterfaceSM> mNotifyList;
private int mMobileApnReserved = ConnectivityManager.TYPE_NONE;
- private ConnectivityManager.NetworkCallback mMobileUpstreamCallback;
-
- private String mUpstreamIfaceName = null;
+ private NetworkCallback mMobileUpstreamCallback;
private static final int UPSTREAM_SETTLE_TIME_MS = 10000;
@@ -1430,8 +1535,6 @@
}
class TetherMasterUtilState extends State {
- protected final static boolean WAIT_FOR_NETWORK_TO_SETTLE = false;
-
@Override
public boolean processMessage(Message m) {
return false;
@@ -1461,27 +1564,27 @@
return false;
}
- NetworkRequest.Builder builder = new NetworkRequest.Builder()
+ final NetworkRequest.Builder builder = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
if (apnType == ConnectivityManager.TYPE_MOBILE_DUN) {
- builder.addCapability(NetworkCapabilities.NET_CAPABILITY_DUN)
- .removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
+ builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
+ .addCapability(NetworkCapabilities.NET_CAPABILITY_DUN);
} else {
builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
}
- NetworkRequest mobileUpstreamRequest = builder.build();
- // Other mechanisms notice network and interface changes and act upon them.
- // TODO, imminently: replace with a proper NetworkCallback-based scheme.
- //
+ final NetworkRequest mobileUpstreamRequest = builder.build();
+
+ // The UpstreamNetworkMonitor's callback will be notified.
+ // Therefore, to avoid duplicate notifications, we only register a no-op.
+ mMobileUpstreamCallback = new NetworkCallback();
+
// TODO: Change the timeout from 0 (no onUnavailable callback) to use some
// moderate callback time (once timeout callbacks are implemented). This might
// be useful for updating some UI. Additionally, we should definitely log a
- // message to aid in any subsequent debugging.
- mMobileUpstreamCallback = new ConnectivityManager.NetworkCallback();
+ // message to aid in any subsequent debugging
if (DBG) Log.d(TAG, "requesting mobile upstream network: " + mobileUpstreamRequest);
getConnectivityManager().requestNetwork(
mobileUpstreamRequest, mMobileUpstreamCallback, 0, apnType);
-
return true;
}
@@ -1513,6 +1616,7 @@
}
return true;
}
+
protected boolean turnOffMasterTetherSettings() {
try {
mNMService.stopTethering();
@@ -1606,34 +1710,41 @@
}
if (iface != null) {
- String[] dnsServers = mDefaultDnsServers;
- Collection<InetAddress> dnses = linkProperties.getDnsServers();
- if (dnses != null && !dnses.isEmpty()) {
- // TODO: remove this invocation of NetworkUtils.makeStrings().
- dnsServers = NetworkUtils.makeStrings(dnses);
+ Network network = getConnectivityManager().getNetworkForType(upType);
+ if (network == null) {
+ Log.e(TAG, "No Network for upstream type " + upType + "!");
}
- try {
- Network network = getConnectivityManager().getNetworkForType(upType);
- if (network == null) {
- Log.e(TAG, "No Network for upstream type " + upType + "!");
- }
- if (VDBG) {
- Log.d(TAG, "Setting DNS forwarders: Network=" + network +
- ", dnsServers=" + Arrays.toString(dnsServers));
- }
- mNMService.setDnsForwarders(network, dnsServers);
- } catch (Exception e) {
- Log.e(TAG, "Setting DNS forwarders failed!");
- transitionTo(mSetDnsForwardersErrorState);
- }
+ setDnsForwarders(network, linkProperties);
}
}
notifyTetheredOfNewUpstreamIface(iface);
}
+ protected void setDnsForwarders(final Network network, final LinkProperties lp) {
+ String[] dnsServers = mDefaultDnsServers;
+ final Collection<InetAddress> dnses = lp.getDnsServers();
+ // TODO: Properly support the absence of DNS servers.
+ if (dnses != null && !dnses.isEmpty()) {
+ // TODO: remove this invocation of NetworkUtils.makeStrings().
+ dnsServers = NetworkUtils.makeStrings(dnses);
+ }
+ if (VDBG) {
+ Log.d(TAG, "Setting DNS forwarders: Network=" + network +
+ ", dnsServers=" + Arrays.toString(dnsServers));
+ }
+ try {
+ mNMService.setDnsForwarders(network, dnsServers);
+ } catch (Exception e) {
+ // TODO: Investigate how this can fail and what exactly
+ // happens if/when such failures occur.
+ Log.e(TAG, "Setting DNS forwarders failed!");
+ transitionTo(mSetDnsForwardersErrorState);
+ }
+ }
+
protected void notifyTetheredOfNewUpstreamIface(String ifaceName) {
if (DBG) Log.d(TAG, "notifying tethered with iface =" + ifaceName);
- mUpstreamIfaceName = ifaceName;
+ mCurrentUpstreamIface = ifaceName;
for (TetherInterfaceSM sm : mNotifyList) {
sm.sendMessage(TetherInterfaceSM.CMD_TETHER_CONNECTION_CHANGED,
ifaceName);
@@ -1772,20 +1883,23 @@
}
class TetherModeAliveState extends TetherMasterUtilState {
- boolean mTryCell = !WAIT_FOR_NETWORK_TO_SETTLE;
+ boolean mTryCell = true;
@Override
public void enter() {
+ // TODO: examine if we should check the return value.
turnOnMasterTetherSettings(); // may transition us out
startListeningForSimChanges();
+ mUpstreamNetworkMonitor.start();
- mTryCell = !WAIT_FOR_NETWORK_TO_SETTLE; // better try something first pass
- // or crazy tests cases will fail
+ mTryCell = true; // better try something first pass or crazy tests cases will fail
chooseUpstreamType(mTryCell);
mTryCell = !mTryCell;
}
@Override
public void exit() {
+ // TODO: examine if we should check the return value.
turnOffUpstreamMobileConnection();
+ mUpstreamNetworkMonitor.stop();
stopListeningForSimChanges();
notifyTetheredOfNewUpstreamIface(null);
}
@@ -1799,7 +1913,7 @@
if (VDBG) Log.d(TAG, "Tether Mode requested by " + who);
mNotifyList.add(who);
who.sendMessage(TetherInterfaceSM.CMD_TETHER_CONNECTION_CHANGED,
- mUpstreamIfaceName);
+ mCurrentUpstreamIface);
break;
case CMD_TETHER_MODE_UNREQUESTED:
who = (TetherInterfaceSM)message.obj;
@@ -1823,7 +1937,7 @@
break;
case CMD_UPSTREAM_CHANGED:
// need to try DUN immediately if Wifi goes down
- mTryCell = !WAIT_FOR_NETWORK_TO_SETTLE;
+ mTryCell = true;
chooseUpstreamType(mTryCell);
mTryCell = !mTryCell;
break;
@@ -1831,6 +1945,24 @@
chooseUpstreamType(mTryCell);
mTryCell = !mTryCell;
break;
+ case EVENT_UPSTREAM_LINKPROPERTIES_CHANGED:
+ NetworkState state = (NetworkState) message.obj;
+ if (mUpstreamNetworkMonitor.processLinkPropertiesChanged(state)) {
+ setDnsForwarders(state.network, state.linkProperties);
+ } else if (mCurrentUpstreamIface == null) {
+ // If we have no upstream interface, try to run through upstream
+ // selection again. If, for example, IPv4 connectivity has shown up
+ // after IPv6 (e.g., 464xlat became available) we want the chance to
+ // notice and act accordingly.
+ chooseUpstreamType(false);
+ }
+ break;
+ case EVENT_UPSTREAM_LOST:
+ // TODO: Re-evaluate possible upstreams. Currently upstream reevaluation
+ // is triggered via received CONNECTIVITY_ACTION broadcasts that result
+ // in being passed a TetherMasterSM.CMD_UPSTREAM_CHANGED.
+ mUpstreamNetworkMonitor.processNetworkLost((Network) message.obj);
+ break;
default:
retValue = false;
break;
diff --git a/services/core/java/com/android/server/input/InputManagerService.java b/services/core/java/com/android/server/input/InputManagerService.java
index 3c04b78..e73beaa 100644
--- a/services/core/java/com/android/server/input/InputManagerService.java
+++ b/services/core/java/com/android/server/input/InputManagerService.java
@@ -948,7 +948,7 @@
// Must be called on handler.
private void showMissingKeyboardLayoutNotification(InputDevice device) {
if (!mKeyboardLayoutNotificationShown) {
- final Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
+ final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
if (device != null) {
intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
}
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 442643a..fdbbd85 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -6926,8 +6926,8 @@
}
@Override
- public void extractPackagesIfNeeded() {
- enforceSystemOrRoot("Only the system can request package extraction");
+ public void updatePackagesIfNeeded() {
+ enforceSystemOrRoot("Only the system can request package update");
// We need to re-extract after an OTA.
boolean causeUpgrade = isUpgrade();
@@ -6958,15 +6958,6 @@
Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
}
- if (!isFirstBoot()) {
- try {
- ActivityManagerNative.getDefault().showBootMessage(
- mContext.getResources().getString(R.string.android_upgrading_apk,
- curr, total), true);
- } catch (RemoteException e) {
- }
- }
-
if (PackageDexOptimizer.canOptimizePackage(pkg)) {
// If the cache was pruned, any compiled odex files will likely be out of date
// and would have to be patched (would be SELF_PATCHOAT, which is deprecated).
@@ -7247,9 +7238,9 @@
private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) {
try {
if (destroy) {
- mInstaller.clearAppProfiles(pkg.packageName);
- } else {
mInstaller.destroyAppProfiles(pkg.packageName);
+ } else {
+ mInstaller.clearAppProfiles(pkg.packageName);
}
} catch (InstallerException ex) {
Log.e(TAG, "Could not delete profiles for package " + pkg.packageName);
@@ -14521,7 +14512,6 @@
if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
res = deletePackageLI(packageName, removeForUser, true, allUsers,
flags | REMOVE_CHATTY, info, true, null);
- deleteProfilesLI(packageName, /*destroy*/ true);
synchronized (mPackages) {
if (res) {
mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
diff --git a/services/core/java/com/android/server/pm/ShortcutPackage.java b/services/core/java/com/android/server/pm/ShortcutPackage.java
index f941432..5916202 100644
--- a/services/core/java/com/android/server/pm/ShortcutPackage.java
+++ b/services/core/java/com/android/server/pm/ShortcutPackage.java
@@ -55,6 +55,7 @@
private static final String ATTR_ID = "id";
private static final String ATTR_ACTIVITY = "activity";
private static final String ATTR_TITLE = "title";
+ private static final String ATTR_TEXT = "text";
private static final String ATTR_INTENT = "intent";
private static final String ATTR_WEIGHT = "weight";
private static final String ATTR_TIMESTAMP = "timestamp";
@@ -439,6 +440,7 @@
ShortcutService.writeAttr(out, ATTR_ACTIVITY, si.getActivityComponent());
// writeAttr(out, "icon", si.getIcon()); // We don't save it.
ShortcutService.writeAttr(out, ATTR_TITLE, si.getTitle());
+ ShortcutService.writeAttr(out, ATTR_TEXT, si.getText());
ShortcutService.writeAttr(out, ATTR_INTENT, si.getIntentNoExtras());
ShortcutService.writeAttr(out, ATTR_WEIGHT, si.getWeight());
ShortcutService.writeAttr(out, ATTR_TIMESTAMP,
@@ -515,6 +517,7 @@
ComponentName activityComponent;
// Icon icon;
String title;
+ String text;
Intent intent;
PersistableBundle intentPersistableExtras = null;
int weight;
@@ -528,6 +531,7 @@
activityComponent = ShortcutService.parseComponentNameAttribute(parser,
ATTR_ACTIVITY);
title = ShortcutService.parseStringAttribute(parser, ATTR_TITLE);
+ text = ShortcutService.parseStringAttribute(parser, ATTR_TEXT);
intent = ShortcutService.parseIntentAttribute(parser, ATTR_INTENT);
weight = (int) ShortcutService.parseLongAttribute(parser, ATTR_WEIGHT);
lastChangedTimestamp = ShortcutService.parseLongAttribute(parser, ATTR_TIMESTAMP);
@@ -559,7 +563,7 @@
throw ShortcutService.throwForInvalidTag(depth, tag);
}
return new ShortcutInfo(
- id, packageName, activityComponent, /* icon =*/ null, title, intent,
+ id, packageName, activityComponent, /* icon =*/ null, title, text, intent,
intentPersistableExtras, weight, extras, lastChangedTimestamp, flags,
iconRes, bitmapPath);
}
diff --git a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
index 4a00ebd..dbbaa5e 100644
--- a/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
+++ b/services/core/java/com/android/server/statusbar/StatusBarManagerService.java
@@ -319,7 +319,7 @@
*/
@Override
public void disable2(int what, IBinder token, String pkg) {
- disableForUser(what, token, pkg, mCurrentUserId);
+ disable2ForUser(what, token, pkg, mCurrentUserId);
}
/**
diff --git a/services/core/java/com/android/server/wm/AccessibilityController.java b/services/core/java/com/android/server/wm/AccessibilityController.java
index 98d44ac..b501398 100644
--- a/services/core/java/com/android/server/wm/AccessibilityController.java
+++ b/services/core/java/com/android/server/wm/AccessibilityController.java
@@ -509,34 +509,35 @@
continue;
}
- Region windowBounds = mTempRegion2;
+ // Consider the touchable portion of the window
Matrix matrix = mTempMatrix;
populateTransformationMatrixLocked(windowState, matrix);
+ Region touchableRegion = mTempRegion3;
+ windowState.getTouchableRegion(touchableRegion);
+ Rect touchableFrame = mTempRect1;
+ touchableRegion.getBounds(touchableFrame);
RectF windowFrame = mTempRectF;
+ windowFrame.set(touchableFrame);
+ windowFrame.offset(-windowState.mFrame.left, -windowState.mFrame.top);
+ matrix.mapRect(windowFrame);
+ Region windowBounds = mTempRegion2;
+ windowBounds.set((int) windowFrame.left, (int) windowFrame.top,
+ (int) windowFrame.right, (int) windowFrame.bottom);
+ // Only update new regions
+ Region portionOfWindowAlreadyAccountedFor = mTempRegion3;
+ portionOfWindowAlreadyAccountedFor.set(mMagnifiedBounds);
+ portionOfWindowAlreadyAccountedFor.op(nonMagnifiedBounds, Region.Op.UNION);
+ windowBounds.op(portionOfWindowAlreadyAccountedFor, Region.Op.DIFFERENCE);
if (mWindowManagerService.mPolicy.canMagnifyWindow(windowState.mAttrs.type)) {
- windowFrame.set(windowState.mFrame);
- windowFrame.offset(-windowFrame.left, -windowFrame.top);
- matrix.mapRect(windowFrame);
- windowBounds.set((int) windowFrame.left, (int) windowFrame.top,
- (int) windowFrame.right, (int) windowFrame.bottom);
mMagnifiedBounds.op(windowBounds, Region.Op.UNION);
mMagnifiedBounds.op(mAvailableBounds, Region.Op.INTERSECT);
} else {
- Region touchableRegion = mTempRegion3;
- windowState.getTouchableRegion(touchableRegion);
- Rect touchableFrame = mTempRect1;
- touchableRegion.getBounds(touchableFrame);
- windowFrame.set(touchableFrame);
- windowFrame.offset(-windowState.mFrame.left, -windowState.mFrame.top);
- matrix.mapRect(windowFrame);
- windowBounds.set((int) windowFrame.left, (int) windowFrame.top,
- (int) windowFrame.right, (int) windowFrame.bottom);
nonMagnifiedBounds.op(windowBounds, Region.Op.UNION);
- windowBounds.op(mMagnifiedBounds, Region.Op.DIFFERENCE);
mAvailableBounds.op(windowBounds, Region.Op.DIFFERENCE);
}
+ // Update accounted bounds
Region accountedBounds = mTempRegion2;
accountedBounds.set(mMagnifiedBounds);
accountedBounds.op(nonMagnifiedBounds, Region.Op.UNION);
diff --git a/services/core/java/com/android/server/wm/Session.java b/services/core/java/com/android/server/wm/Session.java
index c0c1ed8..daeb860 100644
--- a/services/core/java/com/android/server/wm/Session.java
+++ b/services/core/java/com/android/server/wm/Session.java
@@ -195,10 +195,8 @@
@Override
public void repositionChild(IWindow window, int left, int top, int right, int bottom,
- int requestedWidth, int requestedHeight,
long deferTransactionUntilFrame, Rect outFrame) {
mService.repositionChild(this, window, left, top, right, bottom,
- requestedWidth, requestedHeight,
deferTransactionUntilFrame, outFrame);
}
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 6d350b0..1a9e206 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -2531,7 +2531,6 @@
void repositionChild(Session session, IWindow client,
int left, int top, int right, int bottom,
- int requestedWidth, int requestedHeight,
long deferTransactionUntilFrame, Rect outFrame) {
Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "repositionChild");
long origId = Binder.clearCallingIdentity();
@@ -2547,7 +2546,6 @@
"repositionChild called but window is not"
+ "attached to a parent win=" + win);
}
- win.setRequestedSize(requestedWidth, requestedHeight);
win.mAttrs.x = left;
win.mAttrs.y = top;
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index b2cd69d..0e80147 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -654,8 +654,8 @@
String shortSupportMessage = null;
String longSupportMessage = null;
- // Background color of confirm credentials screen. Default: gray.
- static final int DEF_ORGANIZATION_COLOR = Color.GRAY;
+ // Background color of confirm credentials screen. Default: teal.
+ static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
int organizationColor = DEF_ORGANIZATION_COLOR;
// Default title of confirm credentials screen
@@ -5696,26 +5696,25 @@
}
@Override
- public boolean setDeviceOwnerLockScreenInfo(ComponentName who, String info) {
+ public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
Preconditions.checkNotNull(who, "ComponentName is null");
if (!mHasFeature) {
- return false;
+ return;
}
synchronized (this) {
getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
long token = mInjector.binderClearCallingIdentity();
try {
- mLockPatternUtils.setDeviceOwnerInfo(info);
+ mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
} finally {
mInjector.binderRestoreCallingIdentity(token);
}
- return true;
}
}
@Override
- public String getDeviceOwnerLockScreenInfo() {
+ public CharSequence getDeviceOwnerLockScreenInfo() {
return mLockPatternUtils.getDeviceOwnerInfo();
}
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index 0a4effb..7b44f98 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -697,6 +697,14 @@
// as appropriate.
mSystemServiceManager.startService(UiModeManagerService.class);
+ Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "UpdatePackagesIfNeeded");
+ try {
+ mPackageManagerService.updatePackagesIfNeeded();
+ } catch (Throwable e) {
+ reportWtf("update packages", e);
+ }
+ Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
+
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PerformFstrimIfNeeded");
try {
mPackageManagerService.performFstrimIfNeeded();
@@ -705,14 +713,6 @@
}
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
- Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "ExtractPackagesIfNeeded");
- try {
- mPackageManagerService.extractPackagesIfNeeded();
- } catch (Throwable e) {
- reportWtf("extract packages", e);
- }
- Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
-
try {
ActivityManagerNative.getDefault().showBootMessage(
context.getResources().getText(
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutInfoTest.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutInfoTest.java
index eb16a1d..c44ffa4 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutInfoTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutInfoTest.java
@@ -16,9 +16,16 @@
*/
package com.android.server.pm;
+import android.content.ComponentName;
+import android.content.Intent;
import android.content.pm.ShortcutInfo;
+import android.graphics.drawable.Icon;
+import android.os.Bundle;
+import android.os.Parcel;
+import android.os.PersistableBundle;
import android.test.AndroidTestCase;
+import com.android.internal.util.Preconditions;
import com.android.server.testutis.TestUtils;
/**
@@ -33,12 +40,232 @@
*/
public class ShortcutInfoTest extends AndroidTestCase {
- public void testNoId() {
+ public void testMissingMandatoryFields() {
TestUtils.assertExpectException(
IllegalArgumentException.class,
"ID must be provided",
() -> new ShortcutInfo.Builder(mContext).build());
+ TestUtils.assertExpectException(
+ IllegalArgumentException.class,
+ "title must be provided",
+ () -> new ShortcutInfo.Builder(mContext).setId("id").build()
+ .enforceMandatoryFields());
+ TestUtils.assertExpectException(
+ NullPointerException.class,
+ "Intent must be provided",
+ () -> new ShortcutInfo.Builder(mContext).setId("id").setTitle("x").build()
+ .enforceMandatoryFields());
}
- // TODO Add more tests.
+ private ShortcutInfo parceled(ShortcutInfo si) {
+ Parcel p = Parcel.obtain();
+ p.writeParcelable(si, 0);
+ p.setDataPosition(0);
+ ShortcutInfo si2 = p.readParcelable(getClass().getClassLoader());
+ p.recycle();
+ return si2;
+ }
+
+ private Intent makeIntent(String action, Object... bundleKeysAndValues) {
+ final Intent intent = new Intent(action);
+ intent.replaceExtras(ShortcutManagerTest.makeBundle(bundleKeysAndValues));
+ return intent;
+ }
+
+ public void testParcel() {
+ ShortcutInfo si = parceled(new ShortcutInfo.Builder(getContext())
+ .setId("id")
+ .setTitle("title")
+ .setIntent(makeIntent("action"))
+ .build());
+ assertEquals(getContext().getPackageName(), si.getPackageName());
+ assertEquals("id", si.getId());
+ assertEquals("title", si.getTitle());
+ assertEquals("action", si.getIntent().getAction());
+
+ PersistableBundle pb = new PersistableBundle();
+ pb.putInt("k", 1);
+
+ si = new ShortcutInfo.Builder(getContext())
+ .setId("id")
+ .setActivityComponent(new ComponentName("a", "b"))
+ .setIcon(Icon.createWithContentUri("content://a.b.c/"))
+ .setTitle("title")
+ .setText("text")
+ .setIntent(makeIntent("action", "key", "val"))
+ .setWeight(123)
+ .setExtras(pb)
+ .build();
+ si.addFlags(ShortcutInfo.FLAG_PINNED);
+ si.setBitmapPath("abc");
+ si.setIconResourceId(456);
+
+ si = parceled(si);
+
+ assertEquals(getContext().getPackageName(), si.getPackageName());
+ assertEquals("id", si.getId());
+ assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+ assertEquals("content://a.b.c/", si.getIcon().getUriString());
+ assertEquals("title", si.getTitle());
+ assertEquals("text", si.getText());
+ assertEquals("action", si.getIntent().getAction());
+ assertEquals("val", si.getIntent().getStringExtra("key"));
+ assertEquals(123, si.getWeight());
+ assertEquals(1, si.getExtras().getInt("k"));
+
+ assertEquals(ShortcutInfo.FLAG_PINNED, si.getFlags());
+ assertEquals("abc", si.getBitmapPath());
+ assertEquals(456, si.getIconResourceId());
+ }
+
+ public void testClone() {
+ PersistableBundle pb = new PersistableBundle();
+ pb.putInt("k", 1);
+ ShortcutInfo sorig = new ShortcutInfo.Builder(getContext())
+ .setId("id")
+ .setActivityComponent(new ComponentName("a", "b"))
+ .setIcon(Icon.createWithContentUri("content://a.b.c/"))
+ .setTitle("title")
+ .setText("text")
+ .setIntent(makeIntent("action", "key", "val"))
+ .setWeight(123)
+ .setExtras(pb)
+ .build();
+ sorig.addFlags(ShortcutInfo.FLAG_PINNED);
+ sorig.setBitmapPath("abc");
+ sorig.setIconResourceId(456);
+
+ ShortcutInfo si = sorig.clone(/* clone flags*/ 0);
+
+ assertEquals(getContext().getPackageName(), si.getPackageName());
+ assertEquals("id", si.getId());
+ assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+ assertEquals("content://a.b.c/", si.getIcon().getUriString());
+ assertEquals("title", si.getTitle());
+ assertEquals("text", si.getText());
+ assertEquals("action", si.getIntent().getAction());
+ assertEquals("val", si.getIntent().getStringExtra("key"));
+ assertEquals(123, si.getWeight());
+ assertEquals(1, si.getExtras().getInt("k"));
+
+ assertEquals(ShortcutInfo.FLAG_PINNED, si.getFlags());
+ assertEquals("abc", si.getBitmapPath());
+ assertEquals(456, si.getIconResourceId());
+
+ si = sorig.clone(ShortcutInfo.CLONE_REMOVE_FOR_CREATOR);
+
+ assertEquals(getContext().getPackageName(), si.getPackageName());
+ assertEquals("id", si.getId());
+ assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+ assertEquals(null, si.getIcon());
+ assertEquals("title", si.getTitle());
+ assertEquals("text", si.getText());
+ assertEquals("action", si.getIntent().getAction());
+ assertEquals("val", si.getIntent().getStringExtra("key"));
+ assertEquals(123, si.getWeight());
+ assertEquals(1, si.getExtras().getInt("k"));
+
+ assertEquals(ShortcutInfo.FLAG_PINNED, si.getFlags());
+ assertEquals(null, si.getBitmapPath());
+ assertEquals(0, si.getIconResourceId());
+
+ si = sorig.clone(ShortcutInfo.CLONE_REMOVE_FOR_LAUNCHER);
+
+ assertEquals(getContext().getPackageName(), si.getPackageName());
+ assertEquals("id", si.getId());
+ assertEquals(new ComponentName("a", "b"), si.getActivityComponent());
+ assertEquals(null, si.getIcon());
+ assertEquals("title", si.getTitle());
+ assertEquals("text", si.getText());
+ assertEquals(null, si.getIntent());
+ assertEquals(123, si.getWeight());
+ assertEquals(1, si.getExtras().getInt("k"));
+
+ assertEquals(ShortcutInfo.FLAG_PINNED, si.getFlags());
+ assertEquals(null, si.getBitmapPath());
+ assertEquals(0, si.getIconResourceId());
+
+ si = sorig.clone(ShortcutInfo.CLONE_REMOVE_NON_KEY_INFO);
+
+ assertEquals(getContext().getPackageName(), si.getPackageName());
+ assertEquals("id", si.getId());
+ assertEquals(null, si.getActivityComponent());
+ assertEquals(null, si.getIcon());
+ assertEquals(null, si.getTitle());
+ assertEquals(null, si.getText());
+ assertEquals(null, si.getIntent());
+ assertEquals(0, si.getWeight());
+ assertEquals(null, si.getExtras());
+
+ assertEquals(ShortcutInfo.FLAG_PINNED | ShortcutInfo.FLAG_KEY_FIELDS_ONLY, si.getFlags());
+ assertEquals(null, si.getBitmapPath());
+ assertEquals(0, si.getIconResourceId());
+ }
+
+
+ public void testCopyNonNullFieldsFrom() {
+ PersistableBundle pb = new PersistableBundle();
+ pb.putInt("k", 1);
+ ShortcutInfo sorig = new ShortcutInfo.Builder(getContext())
+ .setId("id")
+ .setActivityComponent(new ComponentName("a", "b"))
+ .setIcon(Icon.createWithContentUri("content://a.b.c/"))
+ .setTitle("title")
+ .setText("text")
+ .setIntent(makeIntent("action", "key", "val"))
+ .setWeight(123)
+ .setExtras(pb)
+ .build();
+ sorig.addFlags(ShortcutInfo.FLAG_PINNED);
+ sorig.setBitmapPath("abc");
+ sorig.setIconResourceId(456);
+
+ ShortcutInfo si;
+
+ si = sorig.clone(/* flags=*/ 0);
+ si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getContext()).setId("id")
+ .setActivityComponent(new ComponentName("x", "y")).build());
+ assertEquals(new ComponentName("x", "y"), si.getActivityComponent());
+
+ si = sorig.clone(/* flags=*/ 0);
+ si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getContext()).setId("id")
+ .setIcon(Icon.createWithContentUri("content://x.y.z/")).build());
+ assertEquals("content://x.y.z/", si.getIcon().getUriString());
+
+ si = sorig.clone(/* flags=*/ 0);
+ si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getContext()).setId("id")
+ .setTitle("xyz").build());
+ assertEquals("xyz", si.getTitle());
+
+ si = sorig.clone(/* flags=*/ 0);
+ si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getContext()).setId("id")
+ .setText("xxx").build());
+ assertEquals("xxx", si.getText());
+
+ si = sorig.clone(/* flags=*/ 0);
+ si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getContext()).setId("id")
+ .setIntent(makeIntent("action2")).build());
+ assertEquals("action2", si.getIntent().getAction());
+ assertEquals(null, si.getIntent().getStringExtra("key"));
+
+ si = sorig.clone(/* flags=*/ 0);
+ si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getContext()).setId("id")
+ .setIntent(makeIntent("action3", "key", "x")).build());
+ assertEquals("action3", si.getIntent().getAction());
+ assertEquals("x", si.getIntent().getStringExtra("key"));
+
+ si = sorig.clone(/* flags=*/ 0);
+ si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getContext()).setId("id")
+ .setWeight(999).build());
+ assertEquals(999, si.getWeight());
+
+
+ PersistableBundle pb2 = new PersistableBundle();
+ pb2.putInt("x", 99);
+
+ si = sorig.clone(/* flags=*/ 0);
+ si.copyNonNullFieldsFrom(new ShortcutInfo.Builder(getContext()).setId("id")
+ .setExtras(pb2).build());
+ assertEquals(99, si.getExtras().getInt("x"));
+ }
}
diff --git a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest.java b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest.java
index f034d55..5d29242 100644
--- a/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/pm/ShortcutManagerTest.java
@@ -646,7 +646,7 @@
runTestOnUiThread(() -> {});
}
- private static Bundle makeBundle(Object... keysAndValues) {
+ public static Bundle makeBundle(Object... keysAndValues) {
Preconditions.checkState((keysAndValues.length % 2) == 0);
if (keysAndValues.length == 0) {
diff --git a/services/tests/servicestests/src/com/android/server/testutis/TestUtils.java b/services/tests/servicestests/src/com/android/server/testutis/TestUtils.java
index 52e8f37..d2a4484 100644
--- a/services/tests/servicestests/src/com/android/server/testutis/TestUtils.java
+++ b/services/tests/servicestests/src/com/android/server/testutis/TestUtils.java
@@ -24,19 +24,14 @@
}
public static void assertExpectException(Class<? extends Throwable> expectedExceptionType,
- Runnable r) {
- assertExpectException(expectedExceptionType, null, r);
- }
-
- public static void assertExpectException(Class<? extends Throwable> expectedExceptionType,
String expectedExceptionMessageRegex, Runnable r) {
try {
r.run();
- Assert.fail("Expected exception type " + expectedExceptionType.getClass().getName()
+ Assert.fail("Expected exception type " + expectedExceptionType.getName()
+ " was not thrown");
} catch (Throwable e) {
Assert.assertTrue(
- "Expected exception type was " + expectedExceptionType.getClass().getName()
+ "Expected exception type was " + expectedExceptionType.getName()
+ " but caught " + e.getClass().getName(),
expectedExceptionType.isAssignableFrom(e.getClass()));
if (expectedExceptionMessageRegex != null) {
diff --git a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
index 53adb41..5a6a00f 100644
--- a/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
+++ b/tools/layoutlib/bridge/src/com/android/layoutlib/bridge/android/BridgeWindowSession.java
@@ -97,7 +97,6 @@
@Override
public void repositionChild(IWindow window, int left, int top, int right, int bottom,
- int requestedWidth, int requestedHeight,
long deferTransactionUntilFrame, Rect outFrame) {
// pass for now.
return;
diff --git a/wifi/java/android/net/wifi/WifiInfo.java b/wifi/java/android/net/wifi/WifiInfo.java
index 9f8af6e..8d5efba 100644
--- a/wifi/java/android/net/wifi/WifiInfo.java
+++ b/wifi/java/android/net/wifi/WifiInfo.java
@@ -320,7 +320,8 @@
if (!TextUtils.isEmpty(unicode)) {
return "\"" + unicode + "\"";
} else {
- return mWifiSsid.getHexString();
+ String hex = mWifiSsid.getHexString();
+ return (hex != null) ? hex : WifiSsid.NONE;
}
}
return WifiSsid.NONE;
diff --git a/wifi/java/android/net/wifi/WifiSsid.java b/wifi/java/android/net/wifi/WifiSsid.java
index f8ba95d..c53cd3c 100644
--- a/wifi/java/android/net/wifi/WifiSsid.java
+++ b/wifi/java/android/net/wifi/WifiSsid.java
@@ -205,7 +205,7 @@
for (int i = 0; i < octets.size(); i++) {
out += String.format(Locale.US, "%02x", ssidbytes[i]);
}
- return out;
+ return (octets.size() > 0) ? out : null;
}
/** Implement the Parcelable interface {@hide} */