diff options
Diffstat (limited to 'core')
107 files changed, 2929 insertions, 507 deletions
diff --git a/core/java/android/app/ActivityManagerNative.java b/core/java/android/app/ActivityManagerNative.java index 2a731a3..b7cd829 100644 --- a/core/java/android/app/ActivityManagerNative.java +++ b/core/java/android/app/ActivityManagerNative.java @@ -1104,10 +1104,11 @@ public abstract class ActivityManagerNative extends Binder implements IActivityM data.enforceInterface(IActivityManager.descriptor); String process = data.readString(); boolean start = data.readInt() != 0; + int profileType = data.readInt(); String path = data.readString(); ParcelFileDescriptor fd = data.readInt() != 0 ? data.readFileDescriptor() : null; - boolean res = profileControl(process, start, path, fd); + boolean res = profileControl(process, start, path, fd, profileType); reply.writeNoException(); reply.writeInt(res ? 1 : 0); return true; @@ -2888,13 +2889,14 @@ class ActivityManagerProxy implements IActivityManager } public boolean profileControl(String process, boolean start, - String path, ParcelFileDescriptor fd) throws RemoteException + String path, ParcelFileDescriptor fd, int profileType) throws RemoteException { Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); data.writeInterfaceToken(IActivityManager.descriptor); data.writeString(process); data.writeInt(start ? 1 : 0); + data.writeInt(profileType); data.writeString(path); if (fd != null) { data.writeInt(1); diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java index f6cd866..9bbbd6c 100644 --- a/core/java/android/app/ActivityThread.java +++ b/core/java/android/app/ActivityThread.java @@ -676,11 +676,12 @@ public final class ActivityThread { queueOrSendMessage(H.ACTIVITY_CONFIGURATION_CHANGED, token); } - public void profilerControl(boolean start, String path, ParcelFileDescriptor fd) { + public void profilerControl(boolean start, String path, ParcelFileDescriptor fd, + int profileType) { ProfilerControlData pcd = new ProfilerControlData(); pcd.path = path; pcd.fd = fd; - queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0); + queueOrSendMessage(H.PROFILER_CONTROL, pcd, start ? 1 : 0, profileType); } public void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) { @@ -954,7 +955,7 @@ public final class ActivityThread { } public void scheduleTrimMemory(int level) { - queueOrSendMessage(H.TRIM_MEMORY, level); + queueOrSendMessage(H.TRIM_MEMORY, null, level); } } @@ -1148,7 +1149,7 @@ public final class ActivityThread { handleActivityConfigurationChanged((IBinder)msg.obj); break; case PROFILER_CONTROL: - handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj); + handleProfilerControl(msg.arg1 != 0, (ProfilerControlData)msg.obj, msg.arg2); break; case CREATE_BACKUP_AGENT: handleCreateBackupAgent((CreateBackupAgentData)msg.obj); @@ -1184,8 +1185,10 @@ public final class ActivityThread { break; case UPDATE_PACKAGE_COMPATIBILITY_INFO: handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj); + break; case TRIM_MEMORY: handleTrimMemory(msg.arg1); + break; } if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + msg.what); } @@ -3469,11 +3472,18 @@ public final class ActivityThread { performConfigurationChanged(r.activity, mCompatConfiguration); } - final void handleProfilerControl(boolean start, ProfilerControlData pcd) { + final void handleProfilerControl(boolean start, ProfilerControlData pcd, int profileType) { if (start) { try { - Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(), - 8 * 1024 * 1024, 0); + switch (profileType) { + case 1: + ViewDebug.startLooperProfiling(pcd.path, pcd.fd.getFileDescriptor()); + break; + default: + Debug.startMethodTracing(pcd.path, pcd.fd.getFileDescriptor(), + 8 * 1024 * 1024, 0); + break; + } } catch (RuntimeException e) { Slog.w(TAG, "Profiling failed on path " + pcd.path + " -- can the process access this path?"); @@ -3485,7 +3495,15 @@ public final class ActivityThread { } } } else { - Debug.stopMethodTracing(); + switch (profileType) { + case 1: + ViewDebug.stopLooperProfiling(); + break; + default: + Debug.stopMethodTracing(); + break; + + } } } diff --git a/core/java/android/app/ApplicationThreadNative.java b/core/java/android/app/ApplicationThreadNative.java index 942f245..9a5b527 100644 --- a/core/java/android/app/ApplicationThreadNative.java +++ b/core/java/android/app/ApplicationThreadNative.java @@ -376,10 +376,11 @@ public abstract class ApplicationThreadNative extends Binder { data.enforceInterface(IApplicationThread.descriptor); boolean start = data.readInt() != 0; + int profileType = data.readInt(); String path = data.readString(); ParcelFileDescriptor fd = data.readInt() != 0 ? data.readFileDescriptor() : null; - profilerControl(start, path, fd); + profilerControl(start, path, fd, profileType); return true; } @@ -936,10 +937,11 @@ class ApplicationThreadProxy implements IApplicationThread { } public void profilerControl(boolean start, String path, - ParcelFileDescriptor fd) throws RemoteException { + ParcelFileDescriptor fd, int profileType) throws RemoteException { Parcel data = Parcel.obtain(); data.writeInterfaceToken(IApplicationThread.descriptor); data.writeInt(start ? 1 : 0); + data.writeInt(profileType); data.writeString(path); if (fd != null) { data.writeInt(1); diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java index d2323e7..a99cec2 100644 --- a/core/java/android/app/ContextImpl.java +++ b/core/java/android/app/ContextImpl.java @@ -59,6 +59,8 @@ import android.net.IThrottleManager; import android.net.Uri; import android.net.wifi.IWifiManager; import android.net.wifi.WifiManager; +import android.net.wifi.p2p.IWifiP2pManager; +import android.net.wifi.p2p.WifiP2pManager; import android.nfc.NfcManager; import android.os.Binder; import android.os.Bundle; @@ -83,6 +85,7 @@ import android.view.ContextThemeWrapper; import android.view.WindowManagerImpl; import android.view.accessibility.AccessibilityManager; import android.view.inputmethod.InputMethodManager; +import android.view.textservice.TextServicesManager; import android.accounts.AccountManager; import android.accounts.IAccountManager; import android.app.admin.DevicePolicyManager; @@ -320,6 +323,11 @@ class ContextImpl extends Context { return InputMethodManager.getInstance(ctx); }}); + registerService(TEXT_SERVICES_MANAGER_SERVICE, new ServiceFetcher() { + public Object createService(ContextImpl ctx) { + return TextServicesManager.getInstance(); + }}); + registerService(KEYGUARD_SERVICE, new ServiceFetcher() { public Object getService(ContextImpl ctx) { // TODO: why isn't this caching it? It wasn't @@ -432,6 +440,13 @@ class ContextImpl extends Context { return new WifiManager(service, ctx.mMainThread.getHandler()); }}); + registerService(WIFI_P2P_SERVICE, new ServiceFetcher() { + public Object createService(ContextImpl ctx) { + IBinder b = ServiceManager.getService(WIFI_P2P_SERVICE); + IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(b); + return new WifiP2pManager(service); + }}); + registerService(WINDOW_SERVICE, new ServiceFetcher() { public Object getService(ContextImpl ctx) { return WindowManagerImpl.getDefault(ctx.mPackageInfo.mCompatibilityInfo); diff --git a/core/java/android/app/FragmentManager.java b/core/java/android/app/FragmentManager.java index c82c9ec..789d3a6 100644 --- a/core/java/android/app/FragmentManager.java +++ b/core/java/android/app/FragmentManager.java @@ -1695,6 +1695,7 @@ final class FragmentManagerImpl extends FragmentManager { public void dispatchDestroy() { mDestroyed = true; + execPendingActions(); moveToState(Fragment.INITIALIZING, false); mActivity = null; } diff --git a/core/java/android/app/IActivityManager.java b/core/java/android/app/IActivityManager.java index 93c821c..64d77e8 100644 --- a/core/java/android/app/IActivityManager.java +++ b/core/java/android/app/IActivityManager.java @@ -284,7 +284,7 @@ public interface IActivityManager extends IInterface { // Turn on/off profiling in a particular process. public boolean profileControl(String process, boolean start, - String path, ParcelFileDescriptor fd) throws RemoteException; + String path, ParcelFileDescriptor fd, int profileType) throws RemoteException; public boolean shutdown(int timeout) throws RemoteException; diff --git a/core/java/android/app/IApplicationThread.java b/core/java/android/app/IApplicationThread.java index 9de0bf4..d0607d0 100644 --- a/core/java/android/app/IApplicationThread.java +++ b/core/java/android/app/IApplicationThread.java @@ -105,7 +105,7 @@ public interface IApplicationThread extends IInterface { throws RemoteException; void scheduleLowMemory() throws RemoteException; void scheduleActivityConfigurationChanged(IBinder token) throws RemoteException; - void profilerControl(boolean start, String path, ParcelFileDescriptor fd) + void profilerControl(boolean start, String path, ParcelFileDescriptor fd, int profileType) throws RemoteException; void dumpHeap(boolean managed, String path, ParcelFileDescriptor fd) throws RemoteException; diff --git a/core/java/android/app/StatusBarManager.java b/core/java/android/app/StatusBarManager.java index 1af0983..ca64c88 100644 --- a/core/java/android/app/StatusBarManager.java +++ b/core/java/android/app/StatusBarManager.java @@ -97,9 +97,10 @@ public class StatusBarManager { } } - public void setIcon(String slot, int iconId, int iconLevel) { + public void setIcon(String slot, int iconId, int iconLevel, String contentDescription) { try { - mService.setIcon(slot, mContext.getPackageName(), iconId, iconLevel); + mService.setIcon(slot, mContext.getPackageName(), iconId, iconLevel, + contentDescription); } catch (RemoteException ex) { // system process is dead anyway. throw new RuntimeException(ex); diff --git a/core/java/android/appwidget/AppWidgetManager.java b/core/java/android/appwidget/AppWidgetManager.java index 019652c..1ef99a1 100644 --- a/core/java/android/appwidget/AppWidgetManager.java +++ b/core/java/android/appwidget/AppWidgetManager.java @@ -388,6 +388,10 @@ public class AppWidgetManager { TypedValue.complexToDimensionPixelSize(info.minWidth, mDisplayMetrics); info.minHeight = TypedValue.complexToDimensionPixelSize(info.minHeight, mDisplayMetrics); + info.minResizeWidth = + TypedValue.complexToDimensionPixelSize(info.minResizeWidth, mDisplayMetrics); + info.minResizeHeight = + TypedValue.complexToDimensionPixelSize(info.minResizeHeight, mDisplayMetrics); } return providers; } @@ -411,6 +415,10 @@ public class AppWidgetManager { TypedValue.complexToDimensionPixelSize(info.minWidth, mDisplayMetrics); info.minHeight = TypedValue.complexToDimensionPixelSize(info.minHeight, mDisplayMetrics); + info.minResizeWidth = + TypedValue.complexToDimensionPixelSize(info.minResizeWidth, mDisplayMetrics); + info.minResizeHeight = + TypedValue.complexToDimensionPixelSize(info.minResizeHeight, mDisplayMetrics); } return info; } diff --git a/core/java/android/appwidget/AppWidgetProviderInfo.java b/core/java/android/appwidget/AppWidgetProviderInfo.java index b8c5b02..9c352d5 100644 --- a/core/java/android/appwidget/AppWidgetProviderInfo.java +++ b/core/java/android/appwidget/AppWidgetProviderInfo.java @@ -187,6 +187,8 @@ public class AppWidgetProviderInfo implements Parcelable { } this.minWidth = in.readInt(); this.minHeight = in.readInt(); + this.minResizeWidth = in.readInt(); + this.minResizeHeight = in.readInt(); this.updatePeriodMillis = in.readInt(); this.initialLayout = in.readInt(); if (0 != in.readInt()) { @@ -208,6 +210,8 @@ public class AppWidgetProviderInfo implements Parcelable { } out.writeInt(this.minWidth); out.writeInt(this.minHeight); + out.writeInt(this.minResizeWidth); + out.writeInt(this.minResizeHeight); out.writeInt(this.updatePeriodMillis); out.writeInt(this.initialLayout); if (this.configure != null) { diff --git a/core/java/android/bluetooth/BluetoothDeviceProfileState.java b/core/java/android/bluetooth/BluetoothDeviceProfileState.java index ab3a426..095cd11 100644 --- a/core/java/android/bluetooth/BluetoothDeviceProfileState.java +++ b/core/java/android/bluetooth/BluetoothDeviceProfileState.java @@ -120,6 +120,7 @@ public final class BluetoothDeviceProfileState extends StateMachine { private Pair<Integer, String> mIncomingConnections; private PowerManager.WakeLock mWakeLock; private PowerManager mPowerManager; + private boolean mPairingRequestRcvd = false; private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override @@ -187,27 +188,38 @@ public final class BluetoothDeviceProfileState extends StateMachine { Message msg = obtainMessage(CONNECTION_ACCESS_REQUEST_REPLY); msg.arg1 = val; sendMessage(msg); + } else if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) { + mPairingRequestRcvd = true; + } else if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) { + int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, + BluetoothDevice.ERROR); + if (state == BluetoothDevice.BOND_BONDED && mPairingRequestRcvd) { + setTrust(BluetoothDevice.CONNECTION_ACCESS_YES); + mPairingRequestRcvd = false; + } else if (state == BluetoothDevice.BOND_NONE) { + mPairingRequestRcvd = false; + } } } }; private boolean isPhoneDocked(BluetoothDevice autoConnectDevice) { - // This works only because these broadcast intents are "sticky" - Intent i = mContext.registerReceiver(null, new IntentFilter(Intent.ACTION_DOCK_EVENT)); - if (i != null) { - int state = i.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED); - if (state != Intent.EXTRA_DOCK_STATE_UNDOCKED) { - BluetoothDevice device = i.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); - if (device != null && autoConnectDevice.equals(device)) { - return true; - } - } - } - return false; - } + // This works only because these broadcast intents are "sticky" + Intent i = mContext.registerReceiver(null, new IntentFilter(Intent.ACTION_DOCK_EVENT)); + if (i != null) { + int state = i.getIntExtra(Intent.EXTRA_DOCK_STATE, Intent.EXTRA_DOCK_STATE_UNDOCKED); + if (state != Intent.EXTRA_DOCK_STATE_UNDOCKED) { + BluetoothDevice device = i.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); + if (device != null && autoConnectDevice.equals(device)) { + return true; + } + } + } + return false; + } public BluetoothDeviceProfileState(Context context, String address, - BluetoothService service, BluetoothA2dpService a2dpService) { + BluetoothService service, BluetoothA2dpService a2dpService, boolean setTrust) { super(address); mContext = context; mDevice = new BluetoothDevice(address); @@ -231,6 +243,8 @@ public final class BluetoothDeviceProfileState extends StateMachine { filter.addAction(BluetoothInputDevice.ACTION_CONNECTION_STATE_CHANGED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); filter.addAction(BluetoothDevice.ACTION_CONNECTION_ACCESS_REPLY); + filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST); + filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); mContext.registerReceiver(mBroadcastReceiver, filter); @@ -247,6 +261,10 @@ public final class BluetoothDeviceProfileState extends StateMachine { PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, TAG); mWakeLock.setReferenceCounted(false); + + if (setTrust) { + setTrust(BluetoothDevice.CONNECTION_ACCESS_YES); + } } private BluetoothProfile.ServiceListener mBluetoothProfileServiceListener = diff --git a/core/java/android/content/ComponentCallbacks.java b/core/java/android/content/ComponentCallbacks.java index 92b98fd..37cc141 100644 --- a/core/java/android/content/ComponentCallbacks.java +++ b/core/java/android/content/ComponentCallbacks.java @@ -56,11 +56,8 @@ public interface ComponentCallbacks { static final int TRIM_MEMORY_COMPLETE = 80; /** @hide */ - static final int TRIM_MEMORY_MODERATE = 60; + static final int TRIM_MEMORY_MODERATE = 50; /** @hide */ - static final int TRIM_MEMORY_BACKGROUND = 40; - - /** @hide */ - static final int TRIM_MEMORY_INVISIBLE = 20; + static final int TRIM_MEMORY_BACKGROUND = 20; } diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java index fed6d81..cdda910 100644 --- a/core/java/android/content/Context.java +++ b/core/java/android/content/Context.java @@ -1572,6 +1572,17 @@ public abstract class Context { public static final String WIFI_SERVICE = "wifi"; /** + * Use with {@link #getSystemService} to retrieve a {@link + * android.net.wifi.p2p.WifiP2pManager} for handling management of + * Wi-Fi p2p. + * + * @see #getSystemService + * @see android.net.wifi.p2p.WifiP2pManager + * @hide + */ + public static final String WIFI_P2P_SERVICE = "wifip2p"; + + /** * Use with {@link #getSystemService} to retrieve a * {@link android.media.AudioManager} for handling management of volume, * ringer modes and audio routing. @@ -1612,6 +1623,15 @@ public abstract class Context { /** * Use with {@link #getSystemService} to retrieve a + * {@link android.view.textservice.TextServicesManager} for accessing + * text services. + * + * @see #getSystemService + */ + public static final String TEXT_SERVICES_MANAGER_SERVICE = "textservices"; + + /** + * Use with {@link #getSystemService} to retrieve a * {@link android.appwidget.AppWidgetManager} for accessing AppWidgets. * * @hide diff --git a/core/java/android/inputmethodservice/ExtractEditLayout.java b/core/java/android/inputmethodservice/ExtractEditLayout.java index eafff49..5cfa998 100644 --- a/core/java/android/inputmethodservice/ExtractEditLayout.java +++ b/core/java/android/inputmethodservice/ExtractEditLayout.java @@ -172,7 +172,10 @@ public class ExtractEditLayout extends LinearLayout { @Override public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { - return mCallback.onActionItemClicked(this, item); + if (mCallback != null) { + return mCallback.onActionItemClicked(this, item); + } + return false; } @Override diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java index ce6f697..a564d97 100644 --- a/core/java/android/net/ConnectivityManager.java +++ b/core/java/android/net/ConnectivityManager.java @@ -653,6 +653,17 @@ public class ConnectivityManager { } } + /** + * {@hide} + */ + public int setUsbTethering(boolean enable) { + try { + return mService.setUsbTethering(enable); + } catch (RemoteException e) { + return TETHER_ERROR_SERVICE_UNAVAIL; + } + } + /** {@hide} */ public static final int TETHER_ERROR_NO_ERROR = 0; /** {@hide} */ diff --git a/core/java/android/net/EthernetDataTracker.java b/core/java/android/net/EthernetDataTracker.java index a866436..b035c51 100644 --- a/core/java/android/net/EthernetDataTracker.java +++ b/core/java/android/net/EthernetDataTracker.java @@ -103,6 +103,10 @@ public class EthernetDataTracker implements NetworkStateTracker { public void interfaceRemoved(String iface) { mTracker.interfaceRemoved(iface); } + + public void limitReached(String limitName, String iface) { + // Ignored. + } } private EthernetDataTracker() { diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl index d95fc8d..b1d99a4 100644 --- a/core/java/android/net/IConnectivityManager.aidl +++ b/core/java/android/net/IConnectivityManager.aidl @@ -88,6 +88,8 @@ interface IConnectivityManager String[] getTetherableBluetoothRegexs(); + int setUsbTethering(boolean enable); + void requestNetworkTransitionWakelock(in String forWhom); void reportInetCondition(int networkType, int percentage); diff --git a/core/java/android/net/INetworkManagementEventObserver.aidl b/core/java/android/net/INetworkManagementEventObserver.aidl index 4436e6e..a97f203 100644 --- a/core/java/android/net/INetworkManagementEventObserver.aidl +++ b/core/java/android/net/INetworkManagementEventObserver.aidl @@ -52,4 +52,14 @@ interface INetworkManagementEventObserver { * @param iface The interface. */ void interfaceRemoved(String iface); + + /** + * A networking quota limit has been reached. The quota might not + * be specific to an interface. + * + * @param limitName The name of the limit that triggered. + * @param iface The interface on which the limit was detected. + */ + void limitReached(String limitName, String iface); + } diff --git a/core/java/android/net/LinkProperties.java b/core/java/android/net/LinkProperties.java index 9826bec..132f3ba 100644 --- a/core/java/android/net/LinkProperties.java +++ b/core/java/android/net/LinkProperties.java @@ -58,8 +58,8 @@ public class LinkProperties implements Parcelable { private ProxyProperties mHttpProxy; public static class CompareResult<T> { - public ArrayList<T> removed = new ArrayList<T>(); - public ArrayList<T> added = new ArrayList<T>(); + public Collection<T> removed = new ArrayList<T>(); + public Collection<T> added = new ArrayList<T>(); @Override public String toString() { diff --git a/core/java/android/net/VpnBuilder.java b/core/java/android/net/VpnBuilder.java new file mode 100644 index 0000000..4582523 --- /dev/null +++ b/core/java/android/net/VpnBuilder.java @@ -0,0 +1,413 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.net; + +import android.app.Activity; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; +import android.os.ParcelFileDescriptor; +import android.os.RemoteException; +import android.os.ServiceManager; + +import com.android.internal.net.VpnConfig; + +import java.net.InetAddress; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.DatagramSocket; +import java.net.Socket; +import java.util.ArrayList; + +/** + * VpnBuilder is a framework which enables applications to build their + * own VPN solutions. In general, it creates a virtual network interface, + * configures addresses and routing rules, and returns a file descriptor + * to the application. Each read from the descriptor retrieves an outgoing + * packet which was routed to the interface. Each write to the descriptor + * injects an incoming packet just like it was received from the interface. + * The framework is running on Internet Protocol (IP), so packets are + * always started with IP headers. The application then completes a VPN + * connection by processing and exchanging packets with a remote server + * over a secured tunnel. + * + * <p>Letting applications intercept packets raises huge security concerns. + * Besides, a VPN application can easily break the network, and two of them + * may conflict with each other. The framework takes several actions to + * address these issues. Here are some key points: + * <ul> + * <li>User action is required to create a VPN connection.</li> + * <li>There can be only one VPN connection running at the same time. The + * existing interface is deactivated when a new one is created.</li> + * <li>A system-managed notification is shown during the lifetime of a + * VPN connection.</li> + * <li>A system-managed dialog gives the information of the current VPN + * connection. It also provides a button to disconnect.</li> + * <li>The network is restored automatically when the file descriptor is + * closed. It also covers the cases when a VPN application is crashed + * or killed by the system.</li> + * </ul> + * + * <p>There are two primary methods in this class: {@link #prepare} and + * {@link #establish}. The former deals with the user action and stops + * the existing VPN connection created by another application. The latter + * creates a VPN interface using the parameters supplied to this builder. + * An application must call {@link #prepare} to grant the right to create + * an interface, and it can be revoked at any time by another application. + * The application got revoked is notified by an {@link #ACTION_VPN_REVOKED} + * broadcast. Here are the general steps to create a VPN connection: + * <ol> + * <li>When the user press the button to connect, call {@link #prepare} + * and launch the intent if necessary.</li> + * <li>Register a receiver for {@link #ACTION_VPN_REVOKED} broadcasts. + * <li>Connect to the remote server and negotiate the network parameters + * of the VPN connection.</li> + * <li>Use those parameters to configure a VpnBuilder and create a VPN + * interface by calling {@link #establish}.</li> + * <li>Start processing packets between the returned file descriptor and + * the VPN tunnel.</li> + * <li>When an {@link #ACTION_VPN_REVOKED} broadcast is received, the + * interface is already deactivated by the framework. Close the file + * descriptor and shut down the VPN tunnel gracefully. + * </ol> + * Methods in this class can be used in activities and services. However, + * the intent returned from {@link #prepare} must be launched from an + * activity. The broadcast receiver can be registered at any time, but doing + * it before calling {@link #establish} effectively avoids race conditions. + * + * <p class="note">Using this class requires + * {@link android.Manifest.permission#VPN} permission. + * @hide + */ +public class VpnBuilder { + + /** + * Broadcast intent action indicating that the VPN application has been + * revoked. This can be only received by the target application on the + * receiver explicitly registered using {@link Context#registerReceiver}. + * + * <p>This is a protected intent that can only be sent by the system. + */ + public static final String ACTION_VPN_REVOKED = VpnConfig.ACTION_VPN_REVOKED; + + /** + * Use IConnectivityManager instead since those methods are hidden and + * not available in ConnectivityManager. + */ + private static IConnectivityManager getService() { + return IConnectivityManager.Stub.asInterface( + ServiceManager.getService(Context.CONNECTIVITY_SERVICE)); + } + + /** + * Prepare to establish a VPN connection. This method returns {@code null} + * if the VPN application is already prepared. Otherwise, it returns an + * {@link Intent} to a system activity. The application should launch the + * activity using {@link Activity#startActivityForResult} to get itself + * prepared. The activity may pop up a dialog to require user action, and + * the result will come back to the application through its + * {@link Activity#onActivityResult}. The application becomes prepared if + * the result is {@link Activity#RESULT_OK}, and it is granted to create a + * VPN interface by calling {@link #establish}. + * + * <p>Only one application can be granted at the same time. The right + * is revoked when another application is granted. The application + * losing the right will be notified by an {@link #ACTION_VPN_REVOKED} + * broadcast, and its VPN interface will be deactivated by the system. + * The application should then notify the remote server and disconnect + * gracefully. Unless the application becomes prepared again, subsequent + * calls to {@link #establish} will return {@code null}. + * + * @see #establish + * @see #ACTION_VPN_REVOKED + */ + public static Intent prepare(Context context) { + try { + if (getService().prepareVpn(context.getPackageName(), null)) { + return null; + } + } catch (RemoteException e) { + // ignore + } + return VpnConfig.getIntentForConfirmation(); + } + + private VpnConfig mConfig = new VpnConfig(); + private StringBuilder mAddresses = new StringBuilder(); + private StringBuilder mRoutes = new StringBuilder(); + + /** + * Set the name of this session. It will be displayed in system-managed + * dialogs and notifications. This is recommended not required. + */ + public VpnBuilder setSession(String session) { + mConfig.session = session; + return this; + } + + /** + * Set the {@link PendingIntent} to an activity for users to configure + * the VPN connection. If it is not set, the button to configure will + * not be shown in system-managed dialogs. + */ + public VpnBuilder setConfigureIntent(PendingIntent intent) { + mConfig.configureIntent = intent; + return this; + } + + /** + * Set the maximum transmission unit (MTU) of the VPN interface. If it + * is not set, the default value in the operating system will be used. + * + * @throws IllegalArgumentException if the value is not positive. + */ + public VpnBuilder setMtu(int mtu) { + if (mtu <= 0) { + throw new IllegalArgumentException("Bad mtu"); + } + mConfig.mtu = mtu; + return this; + } + + /** + * Private method to validate address and prefixLength. + */ + private static void check(InetAddress address, int prefixLength) { + if (address.isLoopbackAddress()) { + throw new IllegalArgumentException("Bad address"); + } + if (address instanceof Inet4Address) { + if (prefixLength < 0 || prefixLength > 32) { + throw new IllegalArgumentException("Bad prefixLength"); + } + } else if (address instanceof Inet6Address) { + if (prefixLength < 0 || prefixLength > 128) { + throw new IllegalArgumentException("Bad prefixLength"); + } + } else { + throw new IllegalArgumentException("Unsupported family"); + } + } + + /** + * Convenience method to add a network address to the VPN interface + * using a numeric address string. See {@link InetAddress} for the + * definitions of numeric address formats. + * + * @throws IllegalArgumentException if the address is invalid. + * @see #addAddress(InetAddress, int) + */ + public VpnBuilder addAddress(String address, int prefixLength) { + return addAddress(InetAddress.parseNumericAddress(address), prefixLength); + } + + /** + * Add a network address to the VPN interface. Both IPv4 and IPv6 + * addresses are supported. At least one address must be set before + * calling {@link #establish}. + * + * @throws IllegalArgumentException if the address is invalid. + */ + public VpnBuilder addAddress(InetAddress address, int prefixLength) { + check(address, prefixLength); + + if (address.isAnyLocalAddress()) { + throw new IllegalArgumentException("Bad address"); + } + + mAddresses.append(String.format(" %s/%d", address.getHostAddress(), prefixLength)); + return this; + } + + /** + * Convenience method to add a network route to the VPN interface + * using a numeric address string. See {@link InetAddress} for the + * definitions of numeric address formats. + * + * @see #addRoute(InetAddress, int) + * @throws IllegalArgumentException if the route is invalid. + */ + public VpnBuilder addRoute(String address, int prefixLength) { + return addRoute(InetAddress.parseNumericAddress(address), prefixLength); + } + + /** + * Add a network route to the VPN interface. Both IPv4 and IPv6 + * routes are supported. + * + * @throws IllegalArgumentException if the route is invalid. + */ + public VpnBuilder addRoute(InetAddress address, int prefixLength) { + check(address, prefixLength); + + int offset = prefixLength / 8; + byte[] bytes = address.getAddress(); + if (offset < bytes.length) { + if ((byte)(bytes[offset] << (prefixLength % 8)) != 0) { + throw new IllegalArgumentException("Bad address"); + } + while (++offset < bytes.length) { + if (bytes[offset] != 0) { + throw new IllegalArgumentException("Bad address"); + } + } + } + + mRoutes.append(String.format(" %s/%d", address.getHostAddress(), prefixLength)); + return this; + } + + /** + * Convenience method to add a DNS server to the VPN connection + * using a numeric address string. See {@link InetAddress} for the + * definitions of numeric address formats. + * + * @throws IllegalArgumentException if the address is invalid. + * @see #addDnsServer(InetAddress) + */ + public VpnBuilder addDnsServer(String address) { + return addDnsServer(InetAddress.parseNumericAddress(address)); + } + + /** + * Add a DNS server to the VPN connection. Both IPv4 and IPv6 + * addresses are supported. If none is set, the DNS servers of + * the default network will be used. + * + * @throws IllegalArgumentException if the address is invalid. + */ + public VpnBuilder addDnsServer(InetAddress address) { + if (address.isLoopbackAddress() || address.isAnyLocalAddress()) { + throw new IllegalArgumentException("Bad address"); + } + if (mConfig.dnsServers == null) { + mConfig.dnsServers = new ArrayList<String>(); + } + mConfig.dnsServers.add(address.getHostAddress()); + return this; + } + + /** + * Add a search domain to the DNS resolver. + */ + public VpnBuilder addSearchDomain(String domain) { + if (mConfig.searchDomains == null) { + mConfig.searchDomains = new ArrayList<String>(); + } + mConfig.searchDomains.add(domain); + return this; + } + + /** + * Create a VPN interface using the parameters supplied to this builder. + * The interface works on IP packets, and a file descriptor is returned + * for the application to access them. Each read retrieves an outgoing + * packet which was routed to the interface. Each write injects an + * incoming packet just like it was received from the interface. The file + * descriptor is put into non-blocking mode by default to avoid blocking + * Java threads. To use the file descriptor completely in native space, + * see {@link ParcelFileDescriptor#detachFd()}. The application MUST + * close the file descriptor when the VPN connection is terminated. The + * VPN interface will be removed and the network will be restored by the + * framework automatically. + * + * <p>To avoid conflicts, there can be only one active VPN interface at + * the same time. Usually network parameters are never changed during the + * lifetime of a VPN connection. It is also common for an application to + * create a new file descriptor after closing the previous one. However, + * it is rare but not impossible to have two interfaces while performing a + * seamless handover. In this case, the old interface will be deactivated + * when the new one is configured successfully. Both file descriptors are + * valid but now outgoing packets will be routed to the new interface. + * Therefore, after draining the old file descriptor, the application MUST + * close it and start using the new file descriptor. If the new interface + * cannot be created, the existing interface and its file descriptor remain + * untouched. + * + * <p>An exception will be thrown if the interface cannot be created for + * any reason. However, this method returns {@code null} if the application + * is not prepared or is revoked by another application. This helps solve + * possible race conditions while handling {@link #ACTION_VPN_REVOKED} + * broadcasts. + * + * @return {@link ParcelFileDescriptor} of the VPN interface, or + * {@code null} if the application is not prepared. + * @throws IllegalArgumentException if a parameter is not accepted by the + * operating system. + * @throws IllegalStateException if a parameter cannot be applied by the + * operating system. + * @see #prepare + */ + public ParcelFileDescriptor establish() { + mConfig.addresses = mAddresses.toString(); + mConfig.routes = mRoutes.toString(); + + try { + return getService().establishVpn(mConfig); + } catch (RemoteException e) { + throw new IllegalStateException(e); + } + } + + /** + * Protect a socket from VPN connections. The socket will be bound to the + * current default network interface, so its traffic will not be forwarded + * through VPN. This method is useful if some connections need to be kept + * outside of VPN. For example, a VPN tunnel should protect itself if its + * destination is covered by VPN routes. Otherwise its outgoing packets + * will be sent back to the VPN interface and cause an infinite loop. + * + * <p>The socket is NOT closed by this method. + * + * @return {@code true} on success. + */ + public static boolean protect(int socket) { + ParcelFileDescriptor dup = null; + try { + dup = ParcelFileDescriptor.fromFd(socket); + return getService().protectVpn(dup); + } catch (Exception e) { + return false; + } finally { + try { + dup.close(); + } catch (Exception e) { + // ignore + } + } + } + + /** + * Protect a {@link Socket} from VPN connections. + * + * @return {@code true} on success. + * @see #protect(int) + */ + public static boolean protect(Socket socket) { + return protect(socket.getFileDescriptor$().getInt$()); + } + + /** + * Protect a {@link DatagramSocket} from VPN connections. + * + * @return {@code true} on success. + * @see #protect(int) + */ + public static boolean protect(DatagramSocket socket) { + return protect(socket.getFileDescriptor$().getInt$()); + } +} diff --git a/core/java/android/nfc/INfcAdapter.aidl b/core/java/android/nfc/INfcAdapter.aidl index dcbe9da..2ed6619 100644 --- a/core/java/android/nfc/INfcAdapter.aidl +++ b/core/java/android/nfc/INfcAdapter.aidl @@ -46,8 +46,6 @@ interface INfcAdapter // NfcAdapter-class related methods boolean isEnabled(); - NdefMessage localGet(); - void localSet(in NdefMessage message); void enableForegroundDispatch(in ComponentName activity, in PendingIntent intent, in IntentFilter[] filters, in TechListParcel techLists); void disableForegroundDispatch(in ComponentName activity); @@ -62,4 +60,7 @@ interface INfcAdapter int createLlcpSocket(int sap, int miu, int rw, int linearBufferLength); boolean disable(); boolean enable(); + boolean enableZeroClick(); + boolean disableZeroClick(); + boolean zeroClickEnabled(); } diff --git a/core/java/android/nfc/INfcTag.aidl b/core/java/android/nfc/INfcTag.aidl index aa5937e..7bdefe7 100644 --- a/core/java/android/nfc/INfcTag.aidl +++ b/core/java/android/nfc/INfcTag.aidl @@ -44,5 +44,6 @@ interface INfcTag Tag rediscover(int nativehandle); int setTimeout(int technology, int timeout); + int getTimeout(int technology); void resetTimeouts(); } diff --git a/core/java/android/nfc/NfcAdapter.java b/core/java/android/nfc/NfcAdapter.java index 738e75f..4d04027 100644 --- a/core/java/android/nfc/NfcAdapter.java +++ b/core/java/android/nfc/NfcAdapter.java @@ -684,44 +684,45 @@ public final class NfcAdapter { } /** - * Set the NDEF Message that this NFC adapter should appear as to Tag - * readers. - * <p> - * Any Tag reader can read the contents of the local tag when it is in - * proximity, without any further user confirmation. - * <p> - * The implementation of this method must either - * <ul> - * <li>act as a passive tag containing this NDEF message - * <li>provide the NDEF message on over LLCP to peer NFC adapters - * </ul> - * The NDEF message is preserved across reboot. - * <p>Requires {@link android.Manifest.permission#NFC} permission. - * - * @param message NDEF message to make public + * Enable zero-click sharing. + * * @hide */ - public void setLocalNdefMessage(NdefMessage message) { + public boolean enableZeroClick() { try { - sService.localSet(message); + return sService.enableZeroClick(); } catch (RemoteException e) { attemptDeadServiceRecovery(e); + return false; } } /** - * Get the NDEF Message that this adapter appears as to Tag readers. - * <p>Requires {@link android.Manifest.permission#NFC} permission. + * Disable zero-click sharing. * - * @return NDEF Message that is publicly readable * @hide */ - public NdefMessage getLocalNdefMessage() { + public boolean disableZeroClick() { try { - return sService.localGet(); + return sService.disableZeroClick(); } catch (RemoteException e) { attemptDeadServiceRecovery(e); - return null; + return false; + } + } + + /** + * Return true if zero-click sharing is enabled. + * + * @return true if zero-click sharing is enabled + * @hide + */ + public boolean zeroClickEnabled() { + try { + return sService.zeroClickEnabled(); + } catch (RemoteException e) { + attemptDeadServiceRecovery(e); + return false; } } diff --git a/core/java/android/nfc/tech/IsoDep.java b/core/java/android/nfc/tech/IsoDep.java index d02086f..0672a4e 100644 --- a/core/java/android/nfc/tech/IsoDep.java +++ b/core/java/android/nfc/tech/IsoDep.java @@ -101,6 +101,24 @@ public final class IsoDep extends BasicTagTechnology { } /** + * Gets the currently set timeout of {@link #transceive} in milliseconds. + * + * <p class="note">Requires the {@link android.Manifest.permission#NFC} permission. + * + * @return timeout value in milliseconds + * @hide + */ + // TODO Unhide for ICS + public int getTimeout() { + try { + return mTag.getTagService().getTimeout(TagTechnology.ISO_DEP); + } catch (RemoteException e) { + Log.e(TAG, "NFC service dead", e); + return 0; + } + } + + /** * Return the ISO-DEP historical bytes for {@link NfcA} tags. * <p>Does not cause any RF activity and does not block. * <p>The historical bytes can be used to help identify a tag. They are present diff --git a/core/java/android/nfc/tech/MifareClassic.java b/core/java/android/nfc/tech/MifareClassic.java index 5cafe5b..93e7cbd 100644 --- a/core/java/android/nfc/tech/MifareClassic.java +++ b/core/java/android/nfc/tech/MifareClassic.java @@ -597,6 +597,24 @@ public final class MifareClassic extends BasicTagTechnology { } } + /** + * Gets the currently set timeout of {@link #transceive} in milliseconds. + * + * <p class="note">Requires the {@link android.Manifest.permission#NFC} permission. + * + * @return timeout value in milliseconds + * @hide + */ + // TODO Unhide for ICS + public int getTimeout() { + try { + return mTag.getTagService().getTimeout(TagTechnology.MIFARE_CLASSIC); + } catch (RemoteException e) { + Log.e(TAG, "NFC service dead", e); + return 0; + } + } + private static void validateSector(int sector) { // Do not be too strict on upper bounds checking, since some cards // have more addressable memory than they report. For example, diff --git a/core/java/android/nfc/tech/MifareUltralight.java b/core/java/android/nfc/tech/MifareUltralight.java index 3d4cdd1..ca74ebe 100644 --- a/core/java/android/nfc/tech/MifareUltralight.java +++ b/core/java/android/nfc/tech/MifareUltralight.java @@ -238,6 +238,24 @@ public final class MifareUltralight extends BasicTagTechnology { } } + /** + * Gets the currently set timeout of {@link #transceive} in milliseconds. + * + * <p class="note">Requires the {@link android.Manifest.permission#NFC} permission. + * + * @return timeout value in milliseconds + * @hide + */ + // TODO Unhide for ICS + public int getTimeout() { + try { + return mTag.getTagService().getTimeout(TagTechnology.MIFARE_ULTRALIGHT); + } catch (RemoteException e) { + Log.e(TAG, "NFC service dead", e); + return 0; + } + } + private static void validatePageIndex(int pageIndex) { // Do not be too strict on upper bounds checking, since some cards // may have more addressable memory than they report. diff --git a/core/java/android/nfc/tech/NfcA.java b/core/java/android/nfc/tech/NfcA.java index 08095e6..bd1f95a 100644 --- a/core/java/android/nfc/tech/NfcA.java +++ b/core/java/android/nfc/tech/NfcA.java @@ -141,4 +141,22 @@ public final class NfcA extends BasicTagTechnology { Log.e(TAG, "NFC service dead", e); } } + + /** + * Gets the currently set timeout of {@link #transceive} in milliseconds. + * + * <p class="note">Requires the {@link android.Manifest.permission#NFC} permission. + * + * @return timeout value in milliseconds + * @hide + */ + // TODO Unhide for ICS + public int getTimeout() { + try { + return mTag.getTagService().getTimeout(TagTechnology.NFC_A); + } catch (RemoteException e) { + Log.e(TAG, "NFC service dead", e); + return 0; + } + } } diff --git a/core/java/android/nfc/tech/NfcF.java b/core/java/android/nfc/tech/NfcF.java index 85abf89..7b25a72 100644 --- a/core/java/android/nfc/tech/NfcF.java +++ b/core/java/android/nfc/tech/NfcF.java @@ -140,4 +140,22 @@ public final class NfcF extends BasicTagTechnology { Log.e(TAG, "NFC service dead", e); } } + + /** + * Gets the currently set timeout of {@link #transceive} in milliseconds. + * + * <p class="note">Requires the {@link android.Manifest.permission#NFC} permission. + * + * @return timeout value in milliseconds + * @hide + */ + // TODO Unhide for ICS + public int getTimeout() { + try { + return mTag.getTagService().getTimeout(TagTechnology.NFC_F); + } catch (RemoteException e) { + Log.e(TAG, "NFC service dead", e); + return 0; + } + } } diff --git a/core/java/android/os/Handler.java b/core/java/android/os/Handler.java index cd39d5c..bc37244 100644 --- a/core/java/android/os/Handler.java +++ b/core/java/android/os/Handler.java @@ -361,7 +361,8 @@ public class Handler { /** * Remove any pending posts of Runnable <var>r</var> with Object - * <var>token</var> that are in the message queue. + * <var>token</var> that are in the message queue. If <var>token</var> is null, + * all callbacks will be removed. */ public final void removeCallbacks(Runnable r, Object token) { @@ -517,7 +518,8 @@ public class Handler { /** * Remove any pending posts of messages with code 'what' and whose obj is - * 'object' that are in the message queue. + * 'object' that are in the message queue. If <var>token</var> is null, + * all messages will be removed. */ public final void removeMessages(int what, Object object) { mQueue.removeMessages(this, what, object, true); @@ -525,7 +527,8 @@ public class Handler { /** * Remove any pending posts of callbacks and sent messages whose - * <var>obj</var> is <var>token</var>. + * <var>obj</var> is <var>token</var>. If <var>token</var> is null, + * all callbacks and messages will be removed. */ public final void removeCallbacksAndMessages(Object token) { mQueue.removeCallbacksAndMessages(this, token); diff --git a/core/java/android/os/INetworkManagementService.aidl b/core/java/android/os/INetworkManagementService.aidl index f230526..1174e3b 100644 --- a/core/java/android/os/INetworkManagementService.aidl +++ b/core/java/android/os/INetworkManagementService.aidl @@ -180,7 +180,7 @@ interface INetworkManagementService /** * Stop Wifi Access Point */ - void stopAccessPoint(); + void stopAccessPoint(String wlanIface); /** * Set Access Point config diff --git a/core/java/android/preference/CheckBoxPreference.java b/core/java/android/preference/CheckBoxPreference.java index 437e553..166b21b 100644 --- a/core/java/android/preference/CheckBoxPreference.java +++ b/core/java/android/preference/CheckBoxPreference.java @@ -61,8 +61,8 @@ public class CheckBoxPreference extends TwoStatePreference { View checkboxView = view.findViewById(com.android.internal.R.id.checkbox); if (checkboxView != null && checkboxView instanceof Checkable) { ((Checkable) checkboxView).setChecked(mChecked); - - sendAccessibilityEventForView(checkboxView); + // Post this so this view is bound and attached when firing the event. + postSendAccessibilityEventForView(checkboxView); } syncSummaryView(view); diff --git a/core/java/android/preference/PreferenceActivity.java b/core/java/android/preference/PreferenceActivity.java index c90de17..78c9010 100644 --- a/core/java/android/preference/PreferenceActivity.java +++ b/core/java/android/preference/PreferenceActivity.java @@ -563,6 +563,12 @@ public abstract class PreferenceActivity extends ListActivity implements // Single pane, showing just a prefs fragment. findViewById(com.android.internal.R.id.headers).setVisibility(View.GONE); mPrefsContainer.setVisibility(View.VISIBLE); + if (initialTitle != 0) { + CharSequence initialTitleStr = getText(initialTitle); + CharSequence initialShortTitleStr = initialShortTitle != 0 + ? getText(initialShortTitle) : null; + showBreadCrumbs(initialTitleStr, initialShortTitleStr); + } } else if (mHeaders.size() > 0) { setListAdapter(new HeaderAdapter(this, mHeaders)); if (!mSinglePane) { @@ -1093,6 +1099,10 @@ public abstract class PreferenceActivity extends ListActivity implements } else { getListView().clearChoices(); } + showBreadCrumbs(header); + } + + void showBreadCrumbs(Header header) { if (header != null) { CharSequence title = header.getBreadCrumbTitle(getResources()); if (title == null) title = header.getTitle(getResources()); diff --git a/core/java/android/preference/SwitchPreference.java b/core/java/android/preference/SwitchPreference.java index f681526..3dbd522 100644 --- a/core/java/android/preference/SwitchPreference.java +++ b/core/java/android/preference/SwitchPreference.java @@ -102,8 +102,8 @@ public class SwitchPreference extends TwoStatePreference { View checkableView = view.findViewById(com.android.internal.R.id.switchWidget); if (checkableView != null && checkableView instanceof Checkable) { ((Checkable) checkableView).setChecked(mChecked); - - sendAccessibilityEventForView(checkableView); + // Post this so this view is bound and attached when firing the event. + postSendAccessibilityEventForView(checkableView); if (checkableView instanceof Switch) { final Switch switchView = (Switch) checkableView; diff --git a/core/java/android/preference/TwoStatePreference.java b/core/java/android/preference/TwoStatePreference.java index 8e21c4c..55ef108 100644 --- a/core/java/android/preference/TwoStatePreference.java +++ b/core/java/android/preference/TwoStatePreference.java @@ -16,7 +16,6 @@ package android.preference; -import android.app.Service; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; @@ -39,28 +38,20 @@ public abstract class TwoStatePreference extends Preference { private CharSequence mSummaryOff; boolean mChecked; private boolean mSendAccessibilityEventViewClickedType; - private AccessibilityManager mAccessibilityManager; private boolean mDisableDependentsState; + private SendAccessibilityEventTypeViewClicked mSendAccessibilityEventTypeViewClicked; + public TwoStatePreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - - mAccessibilityManager = - (AccessibilityManager) getContext().getSystemService(Service.ACCESSIBILITY_SERVICE); } public TwoStatePreference(Context context, AttributeSet attrs) { - super(context, attrs); - - mAccessibilityManager = - (AccessibilityManager) getContext().getSystemService(Service.ACCESSIBILITY_SERVICE); + this(context, attrs, 0); } public TwoStatePreference(Context context) { - super(context); - - mAccessibilityManager = - (AccessibilityManager) getContext().getSystemService(Service.ACCESSIBILITY_SERVICE); + this(context, null); } @Override @@ -198,20 +189,23 @@ public abstract class TwoStatePreference extends Preference { } /** - * Send an accessibility event for the given view if appropriate + * Post send an accessibility event for the given view if appropriate. + * * @param view View that should send the event */ - void sendAccessibilityEventForView(View view) { + void postSendAccessibilityEventForView(View view) { // send an event to announce the value change of the state. It is done here // because clicking a preference does not immediately change the checked state // for example when enabling the WiFi - if (mSendAccessibilityEventViewClickedType && - mAccessibilityManager.isEnabled() && - view.isEnabled()) { + if (mSendAccessibilityEventViewClickedType + && AccessibilityManager.getInstance(getContext()).isEnabled() + && view.isEnabled()) { mSendAccessibilityEventViewClickedType = false; - - int eventType = AccessibilityEvent.TYPE_VIEW_CLICKED; - view.sendAccessibilityEventUnchecked(AccessibilityEvent.obtain(eventType)); + if (mSendAccessibilityEventTypeViewClicked == null) { + mSendAccessibilityEventTypeViewClicked = new SendAccessibilityEventTypeViewClicked(); + } + mSendAccessibilityEventTypeViewClicked.mView = view; + view.post(mSendAccessibilityEventTypeViewClicked); } } @@ -306,4 +300,13 @@ public abstract class TwoStatePreference extends Preference { } }; } + + private final class SendAccessibilityEventTypeViewClicked implements Runnable { + private View mView; + + @Override + public void run() { + mView.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); + } + } } diff --git a/core/java/android/provider/CallLog.java b/core/java/android/provider/CallLog.java index 382fcf3..e23d6f3 100644 --- a/core/java/android/provider/CallLog.java +++ b/core/java/android/provider/CallLog.java @@ -184,6 +184,16 @@ public class CallLog { public static final String VOICEMAIL_URI = "voicemail_uri"; /** + * Whether this item has been read or otherwise consumed by the user. + * <p> + * Unlike the {@link #NEW} field, which requires the user to have acknowledged the + * existence of the entry, this implies the user has interacted with the entry. + * <P>Type: INTEGER (boolean)</P> + * @hide + */ + public static final String IS_READ = "is_read"; + + /** * Adds a call to the call log. * * @param ci the CallerInfo object to get the target contact from. Can be null diff --git a/core/java/android/provider/ContactsContract.java b/core/java/android/provider/ContactsContract.java index c299891..a0f1eec 100644 --- a/core/java/android/provider/ContactsContract.java +++ b/core/java/android/provider/ContactsContract.java @@ -1439,6 +1439,13 @@ public final class ContactsContract { CONTENT_URI, "strequent"); /** + * The content:// style URI for showing frequently contacted person listing. + * @hide + */ + public static final Uri CONTENT_FREQUENT_URI = Uri.withAppendedPath( + CONTENT_URI, "frequent"); + + /** * The content:// style URI used for "type-to-filter" functionality on the * {@link #CONTENT_STREQUENT_URI} URI. The filter string will be used to match * various parts of the contact name. The filter argument should be passed @@ -6507,6 +6514,32 @@ public final class ContactsContract { public static final String SUMMARY_COUNT = "summ_count"; /** + * A boolean query parameter that can be used with {@link Groups#CONTENT_SUMMARY_URI}. + * It will additionally return {@link #SUMMARY_GROUP_COUNT_PER_ACCOUNT}. + * + * @hide + */ + public static final String PARAM_RETURN_GROUP_COUNT_PER_ACCOUNT = + "return_group_count_per_account"; + + /** + * The total number of groups of the account that a group belongs to. + * This column is available only when the parameter + * {@link #PARAM_RETURN_GROUP_COUNT_PER_ACCOUNT} is specified in + * {@link Groups#CONTENT_SUMMARY_URI}. + * + * For example, when the account "A" has two groups "group1" and "group2", and the account + * "B" has a group "group3", the rows for "group1" and "group2" return "2" and the row for + * "group3" returns "1" for this column. + * + * Note: This counts only non-favorites, non-auto-add, and not deleted groups. + * + * Type: INTEGER + * @hide + */ + public static final String SUMMARY_GROUP_COUNT_PER_ACCOUNT = "group_count_per_account"; + + /** * The total number of {@link Contacts} that have both * {@link CommonDataKinds.GroupMembership} in this group, and also have phone numbers. * Read-only value that is only present when querying diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java index ad32047..6ebbe7c 100644 --- a/core/java/android/provider/Settings.java +++ b/core/java/android/provider/Settings.java @@ -16,8 +16,6 @@ package android.provider; - - import android.annotation.SdkConstant; import android.annotation.SdkConstant.SdkConstantType; import android.app.SearchManager; @@ -48,7 +46,6 @@ import java.net.URISyntaxException; import java.util.HashMap; import java.util.HashSet; - /** * The Settings provider contains global system-level device preferences. */ @@ -2877,6 +2874,7 @@ public final class Settings { * The acceptable packet loss percentage (range 0 - 100) before trying * another AP on the same network. */ + @Deprecated public static final String WIFI_WATCHDOG_ACCEPTABLE_PACKET_LOSS_PERCENTAGE = "wifi_watchdog_acceptable_packet_loss_percentage"; @@ -2884,11 +2882,13 @@ public final class Settings { * The number of access points required for a network in order for the * watchdog to monitor it. */ + @Deprecated public static final String WIFI_WATCHDOG_AP_COUNT = "wifi_watchdog_ap_count"; /** * The delay between background checks. */ + @Deprecated public static final String WIFI_WATCHDOG_BACKGROUND_CHECK_DELAY_MS = "wifi_watchdog_background_check_delay_ms"; @@ -2896,12 +2896,14 @@ public final class Settings { * Whether the Wi-Fi watchdog is enabled for background checking even * after it thinks the user has connected to a good access point. */ + @Deprecated public static final String WIFI_WATCHDOG_BACKGROUND_CHECK_ENABLED = "wifi_watchdog_background_check_enabled"; /** * The timeout for a background ping */ + @Deprecated public static final String WIFI_WATCHDOG_BACKGROUND_CHECK_TIMEOUT_MS = "wifi_watchdog_background_check_timeout_ms"; @@ -2911,6 +2913,7 @@ public final class Settings { * calculation. For example, one network always seemed to time out for * the first couple pings, so this is set to 3 by default. */ + @Deprecated public static final String WIFI_WATCHDOG_INITIAL_IGNORED_PING_COUNT = "wifi_watchdog_initial_ignored_ping_count"; @@ -2920,6 +2923,7 @@ public final class Settings { * initial connection state for the network. This is a safeguard for * networks containing multiple APs whose DNS does not respond to pings. */ + @Deprecated public static final String WIFI_WATCHDOG_MAX_AP_CHECKS = "wifi_watchdog_max_ap_checks"; /** @@ -2930,24 +2934,85 @@ public final class Settings { /** * A comma-separated list of SSIDs for which the Wi-Fi watchdog should be enabled. */ + @Deprecated public static final String WIFI_WATCHDOG_WATCH_LIST = "wifi_watchdog_watch_list"; /** * The number of pings to test if an access point is a good connection. */ + @Deprecated public static final String WIFI_WATCHDOG_PING_COUNT = "wifi_watchdog_ping_count"; /** * The delay between pings. */ + @Deprecated public static final String WIFI_WATCHDOG_PING_DELAY_MS = "wifi_watchdog_ping_delay_ms"; /** * The timeout per ping. */ + @Deprecated public static final String WIFI_WATCHDOG_PING_TIMEOUT_MS = "wifi_watchdog_ping_timeout_ms"; /** + * ms delay before rechecking an 'online' wifi connection when it is thought to be unstable. + * @hide + */ + public static final String WIFI_WATCHDOG_DNS_CHECK_SHORT_INTERVAL_MS = + "wifi_watchdog_dns_check_short_interval_ms"; + + /** + * ms delay before rechecking an 'online' wifi connection when it is thought to be stable. + * @hide + */ + public static final String WIFI_WATCHDOG_DNS_CHECK_LONG_INTERVAL_MS = + "wifi_watchdog_dns_check_long_interval_ms"; + + /** + * ms delay before rechecking a connect SSID for walled garden with a http download. + * @hide + */ + public static final String WIFI_WATCHDOG_WALLED_GARDEN_INTERVAL_MS = + "wifi_watchdog_walled_garden_interval_ms"; + + /** + * max blacklist calls on an SSID before full dns check failures disable the network. + * @hide + */ + public static final String WIFI_WATCHDOG_MAX_SSID_BLACKLISTS = + "wifi_watchdog_max_ssid_blacklists"; + + /** + * Number of dns pings per check. + * @hide + */ + public static final String WIFI_WATCHDOG_NUM_DNS_PINGS = "wifi_watchdog_num_dns_pings"; + + /** + * Minimum number of responses to the dns pings to consider the test 'successful'. + * @hide + */ + public static final String WIFI_WATCHDOG_MIN_DNS_RESPONSES = + "wifi_watchdog_min_dns_responses"; + + /** + * Timeout on dns pings + * @hide + */ + public static final String WIFI_WATCHDOG_DNS_PING_TIMEOUT_MS = + "wifi_watchdog_dns_ping_timeout_ms"; + + /** + * We consider action from a 'blacklist' call to have finished by the end of + * this interval. If we are connected to the same AP with no network connection, + * we are likely stuck on an SSID with no external connectivity. + * @hide + */ + public static final String WIFI_WATCHDOG_BLACKLIST_FOLLOWUP_INTERVAL_MS = + "wifi_watchdog_blacklist_followup_interval_ms"; + + /** * Setting to turn off walled garden test on Wi-Fi. Feature is enabled by default and * the setting needs to be set to 0 to disable it. * @hide @@ -2972,6 +3037,14 @@ public final class Settings { "wifi_watchdog_walled_garden_pattern"; /** + * Boolean to determine whether to notify on disabling a network. Secure setting used + * to notify user only once. This setting is not monitored continuously. + * @hide + */ + public static final String WIFI_WATCHDOG_SHOW_DISABLED_NETWORK_POPUP = + "wifi_watchdog_show_disabled_network_popup"; + + /** * The maximum number of times we will retry a connection to an access * point for which we have failed in acquiring an IP address from DHCP. * A value of N means that we will make N+1 connection attempts in all. @@ -3661,6 +3734,15 @@ public final class Settings { */ public static final String VOICE_RECOGNITION_SERVICE = "voice_recognition_service"; + + /** + * The {@link ComponentName} string of the service to be used as the spell checker + * service which is one of the services managed by the text service manager. + * + * @hide + */ + public static final String SPELL_CHECKER_SERVICE = "spell_checker_service"; + /** * What happens when the user presses the Power button while in-call * and the screen is on.<br/> @@ -3853,6 +3935,10 @@ public final class Settings { /** Timeout in milliseconds to wait for NTP server. {@hide} */ public static final String NTP_TIMEOUT = "ntp_timeout"; + /** Autofill server address (Used in WebView/browser). {@hide} */ + public static final String WEB_AUTOFILL_QUERY_URL = + "web_autofill_query_url"; + /** * @hide */ diff --git a/core/java/android/provider/VoicemailContract.java b/core/java/android/provider/VoicemailContract.java index 2ad7395..2e5a495 100644 --- a/core/java/android/provider/VoicemailContract.java +++ b/core/java/android/provider/VoicemailContract.java @@ -128,6 +128,12 @@ public class VoicemailContract { */ public static final String NEW = Calls.NEW; /** + * Whether this item has been read or otherwise consumed by the user. + * <P>Type: INTEGER (boolean)</P> + * @hide + */ + public static final String IS_READ = Calls.IS_READ; + /** * The mail box state of the voicemail. This field is currently not used by the system. * <P> Possible values: {@link #STATE_INBOX}, {@link #STATE_DELETED}, * {@link #STATE_UNDELETED}. diff --git a/core/java/android/server/BluetoothBondState.java b/core/java/android/server/BluetoothBondState.java index 75f38f9..30a8b2a 100644 --- a/core/java/android/server/BluetoothBondState.java +++ b/core/java/android/server/BluetoothBondState.java @@ -21,8 +21,13 @@ import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothA2dp; import android.bluetooth.BluetoothHeadset; +import android.content.BroadcastReceiver; +import android.content.ContentResolver; import android.content.Context; import android.content.Intent; +import android.content.IntentFilter; +import android.content.SharedPreferences; +import android.provider.Settings; import android.util.Log; import java.io.BufferedReader; @@ -74,11 +79,17 @@ class BluetoothBondState { private BluetoothA2dp mA2dpProxy; private BluetoothHeadset mHeadsetProxy; + private ArrayList<String> mPairingRequestRcvd = new ArrayList<String>(); + BluetoothBondState(Context context, BluetoothService service) { mContext = context; mService = service; mBluetoothInputProfileHandler = BluetoothInputProfileHandler.getInstance(mContext, mService); + + IntentFilter filter = new IntentFilter(); + filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST); + mContext.registerReceiver(mReceiver, filter); } synchronized void setPendingOutgoingBonding(String address) { @@ -137,11 +148,18 @@ class BluetoothBondState { } if (state == BluetoothDevice.BOND_BONDED) { - mService.addProfileState(address); + boolean setTrust = false; + if (mPairingRequestRcvd.contains(address)) setTrust = true; + + mService.addProfileState(address, setTrust); + mPairingRequestRcvd.remove(address); + } else if (state == BluetoothDevice.BOND_BONDING) { if (mA2dpProxy == null || mHeadsetProxy == null) { getProfileProxy(); } + } else if (state == BluetoothDevice.BOND_NONE) { + mPairingRequestRcvd.remove(address); } setProfilePriorities(address, state); @@ -452,4 +470,17 @@ class BluetoothBondState { } } + private final BroadcastReceiver mReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (intent == null) return; + + String action = intent.getAction(); + if (action.equals(BluetoothDevice.ACTION_PAIRING_REQUEST)) { + BluetoothDevice dev = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); + String address = dev.getAddress(); + mPairingRequestRcvd.add(address); + } + } + }; } diff --git a/core/java/android/server/BluetoothService.java b/core/java/android/server/BluetoothService.java index ff16c18..d68d8ba 100755 --- a/core/java/android/server/BluetoothService.java +++ b/core/java/android/server/BluetoothService.java @@ -527,10 +527,19 @@ public class BluetoothService extends IBluetooth.Stub { break; case MESSAGE_AUTO_PAIRING_FAILURE_ATTEMPT_DELAY: address = (String)msg.obj; - if (address != null) { + if (address == null) return; + int attempt = mBondState.getAttempt(address); + + // Try only if attemps are in progress and cap it 2 attempts + // The 2 attempts cap is a fail safe if the stack returns + // an incorrect error code for bonding failures and if the pin + // is entered wrongly twice we should abort. + if (attempt > 0 && attempt <= 2) { + mBondState.attempt(address); createBond(address); return; } + if (attempt > 0) mBondState.clearPinAttempts(address); break; } } @@ -741,7 +750,6 @@ public class BluetoothService extends IBluetooth.Stub { BluetoothDevice.BOND_NONE, result); return; } - mBondState.attempt(address); } /*package*/ BluetoothDevice getRemoteDevice(String address) { @@ -2277,11 +2285,11 @@ public class BluetoothService extends IBluetooth.Stub { return false; } - BluetoothDeviceProfileState addProfileState(String address) { + BluetoothDeviceProfileState addProfileState(String address, boolean setTrust) { BluetoothDeviceProfileState state = mDeviceProfileState.get(address); if (state != null) return state; - state = new BluetoothDeviceProfileState(mContext, address, this, mA2dpService); + state = new BluetoothDeviceProfileState(mContext, address, this, mA2dpService, setTrust); mDeviceProfileState.put(address, state); state.start(); return state; @@ -2311,7 +2319,7 @@ public class BluetoothService extends IBluetooth.Stub { } for (String path : bonds) { String address = getAddressFromObjectPath(path); - BluetoothDeviceProfileState state = addProfileState(address); + BluetoothDeviceProfileState state = addProfileState(address, false); } } diff --git a/core/java/android/service/textservice/SpellCheckerService.java b/core/java/android/service/textservice/SpellCheckerService.java new file mode 100644 index 0000000..270f512 --- /dev/null +++ b/core/java/android/service/textservice/SpellCheckerService.java @@ -0,0 +1,141 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package android.service.textservice; + +import com.android.internal.textservice.ISpellCheckerService; +import com.android.internal.textservice.ISpellCheckerSession; +import com.android.internal.textservice.ISpellCheckerSessionListener; + +import android.app.Service; +import android.content.Intent; +import android.os.IBinder; +import android.os.RemoteException; +import android.view.textservice.SuggestionsInfo; +import android.view.textservice.TextInfo; + +import java.lang.ref.WeakReference; + +/** + * SpellCheckerService provides an abstract base class for a spell checker. + * This class combines a service to the system with the spell checker service interface that + * spell checker must implement. + */ +public abstract class SpellCheckerService extends Service { + private static final String TAG = SpellCheckerService.class.getSimpleName(); + public static final String SERVICE_INTERFACE = + "android.service.textservice.SpellCheckerService"; + + private final SpellCheckerServiceBinder mBinder = new SpellCheckerServiceBinder(this); + + /** + * Get suggestions for specified text in TextInfo. + * This function will run on the incoming IPC thread. So, this is not called on the main thread, + * but will be called in series on another thread. + * @param textInfo the text metadata + * @param suggestionsLimit the number of limit of suggestions returned + * @param locale the locale for getting suggestions + * @return SuggestionInfo which contains suggestions for textInfo + */ + public abstract SuggestionsInfo getSuggestions( + TextInfo textInfo, int suggestionsLimit, String locale); + + /** + * A batch process of onGetSuggestions. + * This function will run on the incoming IPC thread. So, this is not called on the main thread, + * but will be called in series on another thread. + * @param textInfos an array of the text metadata + * @param locale the locale for getting suggestions + * @param suggestionsLimit the number of limit of suggestions returned + * @param sequentialWords true if textInfos can be treated as sequential words. + * @return an array of SuggestionInfo of onGetSuggestions + */ + public SuggestionsInfo[] getSuggestionsMultiple( + TextInfo[] textInfos, String locale, int suggestionsLimit, boolean sequentialWords) { + final int length = textInfos.length; + final SuggestionsInfo[] retval = new SuggestionsInfo[length]; + for (int i = 0; i < length; ++i) { + retval[i] = getSuggestions(textInfos[i], suggestionsLimit, locale); + retval[i].setCookieAndSequence(textInfos[i].getCookie(), textInfos[i].getSequence()); + } + return retval; + } + + /** + * Request to abort all tasks executed in SpellChecker. + * This function will run on the incoming IPC thread. So, this is not called on the main thread, + * but will be called in series on another thread. + */ + public void cancel() {} + + /** + * Implement to return the implementation of the internal spell checker + * service interface. Subclasses should not override. + */ + @Override + public final IBinder onBind(final Intent intent) { + return mBinder; + } + + private static class SpellCheckerSessionImpl extends ISpellCheckerSession.Stub { + private final WeakReference<SpellCheckerService> mInternalServiceRef; + private final String mLocale; + private final ISpellCheckerSessionListener mListener; + + public SpellCheckerSessionImpl( + SpellCheckerService service, String locale, ISpellCheckerSessionListener listener) { + mInternalServiceRef = new WeakReference<SpellCheckerService>(service); + mLocale = locale; + mListener = listener; + } + + @Override + public void getSuggestionsMultiple( + TextInfo[] textInfos, int suggestionsLimit, boolean sequentialWords) { + final SpellCheckerService service = mInternalServiceRef.get(); + if (service == null) return; + try { + mListener.onGetSuggestions( + service.getSuggestionsMultiple(textInfos, mLocale, + suggestionsLimit, sequentialWords)); + } catch (RemoteException e) { + } + } + + @Override + public void cancel() { + final SpellCheckerService service = mInternalServiceRef.get(); + if (service == null) return; + service.cancel(); + } + } + + private static class SpellCheckerServiceBinder extends ISpellCheckerService.Stub { + private final WeakReference<SpellCheckerService> mInternalServiceRef; + + public SpellCheckerServiceBinder(SpellCheckerService service) { + mInternalServiceRef = new WeakReference<SpellCheckerService>(service); + } + + @Override + public ISpellCheckerSession getISpellCheckerSession( + String locale, ISpellCheckerSessionListener listener) { + final SpellCheckerService service = mInternalServiceRef.get(); + if (service == null) return null; + return new SpellCheckerSessionImpl(service, locale, listener); + } + } +} diff --git a/core/java/android/service/textservice/SpellCheckerSession.java b/core/java/android/service/textservice/SpellCheckerSession.java new file mode 100644 index 0000000..400454d --- /dev/null +++ b/core/java/android/service/textservice/SpellCheckerSession.java @@ -0,0 +1,284 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.service.textservice; + +import com.android.internal.textservice.ISpellCheckerSession; +import com.android.internal.textservice.ISpellCheckerSessionListener; +import com.android.internal.textservice.ITextServicesManager; +import com.android.internal.textservice.ITextServicesSessionListener; + +import android.os.Handler; +import android.os.Message; +import android.os.RemoteException; +import android.util.Log; +import android.view.textservice.SpellCheckerInfo; +import android.view.textservice.SuggestionsInfo; +import android.view.textservice.TextInfo; + +import java.util.LinkedList; +import java.util.Locale; +import java.util.Queue; + +/** + * The SpellCheckerSession interface provides the per client functionality of SpellCheckerService. + */ +public class SpellCheckerSession { + private static final String TAG = SpellCheckerSession.class.getSimpleName(); + private static final boolean DBG = false; + + private static final int MSG_ON_GET_SUGGESTION_MULTIPLE = 1; + + private final InternalListener mInternalListener; + private final ITextServicesManager mTextServicesManager; + private final SpellCheckerInfo mSpellCheckerInfo; + private final SpellCheckerSessionListenerImpl mSpellCheckerSessionListenerImpl; + + private boolean mIsUsed; + private SpellCheckerSessionListener mSpellCheckerSessionListener; + + /** Handler that will execute the main tasks */ + private final Handler mHandler = new Handler() { + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MSG_ON_GET_SUGGESTION_MULTIPLE: + handleOnGetSuggestionsMultiple((SuggestionsInfo[]) msg.obj); + break; + } + } + }; + + /** + * Constructor + * @hide + */ + public SpellCheckerSession( + SpellCheckerInfo info, ITextServicesManager tsm, SpellCheckerSessionListener listener) { + if (info == null || listener == null || tsm == null) { + throw new NullPointerException(); + } + mSpellCheckerInfo = info; + mSpellCheckerSessionListenerImpl = new SpellCheckerSessionListenerImpl(mHandler); + mInternalListener = new InternalListener(); + mTextServicesManager = tsm; + mIsUsed = true; + mSpellCheckerSessionListener = listener; + } + + /** + * @return true if the connection to a text service of this session is disconnected and not + * alive. + */ + public boolean isSessionDisconnected() { + return mSpellCheckerSessionListenerImpl.isDisconnected(); + } + + /** + * Get the spell checker service info this spell checker session has. + * @return SpellCheckerInfo for the specified locale. + */ + public SpellCheckerInfo getSpellChecker() { + return mSpellCheckerInfo; + } + + /** + * Finish this session and allow TextServicesManagerService to disconnect the bound spell + * checker. + */ + public void close() { + mIsUsed = false; + try { + mTextServicesManager.finishSpellCheckerService(mSpellCheckerSessionListenerImpl); + } catch (RemoteException e) { + // do nothing + } + } + + /** + * Get candidate strings for a substring of the specified text. + * @param textInfo text metadata for a spell checker + * @param suggestionsLimit the number of limit of suggestions returned + */ + public void getSuggestions(TextInfo textInfo, int suggestionsLimit) { + getSuggestions(new TextInfo[] {textInfo}, suggestionsLimit, false); + } + + /** + * A batch process of getSuggestions + * @param textInfos an array of text metadata for a spell checker + * @param suggestionsLimit the number of limit of suggestions returned + * @param sequentialWords true if textInfos can be treated as sequential words. + */ + public void getSuggestions( + TextInfo[] textInfos, int suggestionsLimit, boolean sequentialWords) { + // TODO: Handle multiple words suggestions by using WordBreakIterator + mSpellCheckerSessionListenerImpl.getSuggestionsMultiple( + textInfos, suggestionsLimit, sequentialWords); + } + + private void handleOnGetSuggestionsMultiple(SuggestionsInfo[] suggestionInfos) { + mSpellCheckerSessionListener.onGetSuggestions(suggestionInfos); + } + + private static class SpellCheckerSessionListenerImpl extends ISpellCheckerSessionListener.Stub { + private static final int TASK_CANCEL = 1; + private static final int TASK_GET_SUGGESTIONS_MULTIPLE = 2; + private final Queue<SpellCheckerParams> mPendingTasks = + new LinkedList<SpellCheckerParams>(); + private final Handler mHandler; + + private boolean mOpened; + private ISpellCheckerSession mISpellCheckerSession; + + public SpellCheckerSessionListenerImpl(Handler handler) { + mOpened = false; + mHandler = handler; + } + + private static class SpellCheckerParams { + public final int mWhat; + public final TextInfo[] mTextInfos; + public final int mSuggestionsLimit; + public final boolean mSequentialWords; + public SpellCheckerParams(int what, TextInfo[] textInfos, int suggestionsLimit, + boolean sequentialWords) { + mWhat = what; + mTextInfos = textInfos; + mSuggestionsLimit = suggestionsLimit; + mSequentialWords = sequentialWords; + } + } + + private void processTask(SpellCheckerParams scp) { + switch (scp.mWhat) { + case TASK_CANCEL: + processCancel(); + break; + case TASK_GET_SUGGESTIONS_MULTIPLE: + processGetSuggestionsMultiple(scp); + break; + } + } + + public synchronized void onServiceConnected(ISpellCheckerSession session) { + mISpellCheckerSession = session; + mOpened = true; + if (DBG) + Log.d(TAG, "onServiceConnected - Success"); + while (!mPendingTasks.isEmpty()) { + processTask(mPendingTasks.poll()); + } + } + + public void getSuggestionsMultiple( + TextInfo[] textInfos, int suggestionsLimit, boolean sequentialWords) { + processOrEnqueueTask( + new SpellCheckerParams(TASK_GET_SUGGESTIONS_MULTIPLE, textInfos, + suggestionsLimit, sequentialWords)); + } + + public boolean isDisconnected() { + return mOpened && mISpellCheckerSession == null; + } + + public boolean checkOpenConnection() { + if (mISpellCheckerSession != null) { + return true; + } + Log.e(TAG, "not connected to the spellchecker service."); + return false; + } + + private void processOrEnqueueTask(SpellCheckerParams scp) { + if (mISpellCheckerSession == null) { + mPendingTasks.offer(scp); + } else { + processTask(scp); + } + } + + private void processCancel() { + if (!checkOpenConnection()) { + return; + } + try { + mISpellCheckerSession.cancel(); + } catch (RemoteException e) { + Log.e(TAG, "Failed to cancel " + e); + } + } + + private void processGetSuggestionsMultiple(SpellCheckerParams scp) { + if (!checkOpenConnection()) { + return; + } + try { + mISpellCheckerSession.getSuggestionsMultiple( + scp.mTextInfos, scp.mSuggestionsLimit, scp.mSequentialWords); + } catch (RemoteException e) { + Log.e(TAG, "Failed to get suggestions " + e); + } + } + + @Override + public void onGetSuggestions(SuggestionsInfo[] results) { + mHandler.sendMessage(Message.obtain(mHandler, MSG_ON_GET_SUGGESTION_MULTIPLE, results)); + } + } + + /** + * Callback for getting results from text services + */ + public interface SpellCheckerSessionListener { + /** + * Callback for "getSuggestions" + * @param results an array of results of getSuggestions + */ + public void onGetSuggestions(SuggestionsInfo[] results); + } + + private class InternalListener extends ITextServicesSessionListener.Stub { + @Override + public void onServiceConnected(ISpellCheckerSession session) { + mSpellCheckerSessionListenerImpl.onServiceConnected(session); + } + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + if (mIsUsed) { + Log.e(TAG, "SpellCheckerSession was not finished properly." + + "You should call finishShession() when you finished to use a spell checker."); + close(); + } + } + + /** + * @hide + */ + public ITextServicesSessionListener getTextServicesSessionListener() { + return mInternalListener; + } + + /** + * @hide + */ + public ISpellCheckerSessionListener getSpellCheckerSessionListener() { + return mSpellCheckerSessionListenerImpl; + } +} diff --git a/core/java/android/speech/tts/AudioPlaybackHandler.java b/core/java/android/speech/tts/AudioPlaybackHandler.java index 255b333..89b6f32 100644 --- a/core/java/android/speech/tts/AudioPlaybackHandler.java +++ b/core/java/android/speech/tts/AudioPlaybackHandler.java @@ -356,9 +356,7 @@ class AudioPlaybackHandler { mLastSynthesisRequest = param; // Create the audio track. - final AudioTrack audioTrack = createStreamingAudioTrack( - param.mStreamType, param.mSampleRateInHz, param.mAudioFormat, - param.mChannelCount, param.mVolume, param.mPan); + final AudioTrack audioTrack = createStreamingAudioTrack(param); if (DBG) Log.d(TAG, "Created audio track [" + audioTrack.hashCode() + "]"); @@ -405,16 +403,10 @@ class AudioPlaybackHandler { param.mLogger.onPlaybackStart(); } + // Wait for the audio track to stop playing, and then release its resources. private void handleSynthesisDone(MessageParams msg) { final SynthesisMessageParams params = (SynthesisMessageParams) msg; - handleSynthesisDone(params); - // This call is delayed more than it should be, but we are - // certain at this point that we have all the data we want. - params.mLogger.onWriteData(); - } - // Wait for the audio track to stop playing, and then release it's resources. - private void handleSynthesisDone(SynthesisMessageParams params) { if (DBG) Log.d(TAG, "handleSynthesisDone()"); final AudioTrack audioTrack = params.getAudioTrack(); @@ -422,6 +414,10 @@ class AudioPlaybackHandler { return; } + if (params.mBytesWritten < params.mAudioBufferSize) { + audioTrack.stop(); + } + if (DBG) Log.d(TAG, "Waiting for audio track to complete : " + audioTrack.hashCode()); blockUntilDone(params); @@ -442,8 +438,15 @@ class AudioPlaybackHandler { } params.getDispatcher().dispatchUtteranceCompleted(); mLastSynthesisRequest = null; + params.mLogger.onWriteData(); } + /** + * The minimum increment of time to wait for an audiotrack to finish + * playing. + */ + private static final long MIN_SLEEP_TIME_MS = 20; + private static void blockUntilDone(SynthesisMessageParams params) { if (params.mAudioTrack == null || params.mBytesWritten <= 0) { return; @@ -460,36 +463,41 @@ class AudioPlaybackHandler { break; } - long estimatedTimeMs = ((lengthInFrames - currentPosition) * 1000) / + final long estimatedTimeMs = ((lengthInFrames - currentPosition) * 1000) / audioTrack.getSampleRate(); - if (DBG) Log.d(TAG, "About to sleep for : " + estimatedTimeMs + " ms," + - " Playback position : " + currentPosition); + final long sleepTimeMs = Math.max(estimatedTimeMs, MIN_SLEEP_TIME_MS); + + if (DBG) Log.d(TAG, "About to sleep for : " + sleepTimeMs + " ms," + + " Playback position : " + currentPosition + ", Length in frames : " + + lengthInFrames); try { - Thread.sleep(estimatedTimeMs); + Thread.sleep(sleepTimeMs); } catch (InterruptedException ie) { break; } } } - private static AudioTrack createStreamingAudioTrack(int streamType, int sampleRateInHz, - int audioFormat, int channelCount, float volume, float pan) { - int channelConfig = getChannelConfig(channelCount); + private static AudioTrack createStreamingAudioTrack(SynthesisMessageParams params) { + final int channelConfig = getChannelConfig(params.mChannelCount); + final int sampleRateInHz = params.mSampleRateInHz; + final int audioFormat = params.mAudioFormat; int minBufferSizeInBytes = AudioTrack.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat); int bufferSizeInBytes = Math.max(MIN_AUDIO_BUFFER_SIZE, minBufferSizeInBytes); - AudioTrack audioTrack = new AudioTrack(streamType, sampleRateInHz, channelConfig, + AudioTrack audioTrack = new AudioTrack(params.mStreamType, sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes, AudioTrack.MODE_STREAM); if (audioTrack.getState() != AudioTrack.STATE_INITIALIZED) { Log.w(TAG, "Unable to create audio track."); audioTrack.release(); return null; } + params.mAudioBufferSize = bufferSizeInBytes; - setupVolume(audioTrack, volume, pan); + setupVolume(audioTrack, params.mVolume, params.mPan); return audioTrack; } diff --git a/core/java/android/speech/tts/SynthesisMessageParams.java b/core/java/android/speech/tts/SynthesisMessageParams.java index ffe70e2..7da5daa 100644 --- a/core/java/android/speech/tts/SynthesisMessageParams.java +++ b/core/java/android/speech/tts/SynthesisMessageParams.java @@ -35,6 +35,7 @@ final class SynthesisMessageParams extends MessageParams { volatile AudioTrack mAudioTrack; // Not volatile, accessed only from the synthesis thread. int mBytesWritten; + int mAudioBufferSize; private final LinkedList<ListEntry> mDataBufferList = new LinkedList<ListEntry>(); @@ -55,6 +56,7 @@ final class SynthesisMessageParams extends MessageParams { // initially null. mAudioTrack = null; mBytesWritten = 0; + mAudioBufferSize = 0; } @Override diff --git a/core/java/android/util/JsonReader.java b/core/java/android/util/JsonReader.java index f139372..f2a86c9 100644 --- a/core/java/android/util/JsonReader.java +++ b/core/java/android/util/JsonReader.java @@ -740,8 +740,8 @@ public final class JsonReader implements Closeable { limit += total; // if this is the first read, consume an optional byte order mark (BOM) if it exists - if (bufferStartLine == 1 && bufferStartColumn == 1 - && limit > 0 && buffer[0] == '\ufeff') { + if (bufferStartLine == 1 && bufferStartColumn == 1 + && limit > 0 && buffer[0] == '\ufeff') { pos++; bufferStartColumn--; } @@ -852,7 +852,7 @@ public final class JsonReader implements Closeable { private boolean skipTo(String toFind) throws IOException { outer: - for (; pos + toFind.length() < limit || fillBuffer(toFind.length()); pos++) { + for (; pos + toFind.length() <= limit || fillBuffer(toFind.length()); pos++) { for (int c = 0; c < toFind.length(); c++) { if (buffer[pos + c] != toFind.charAt(c)) { continue outer; diff --git a/core/java/android/view/CollapsibleActionView.java b/core/java/android/view/CollapsibleActionView.java new file mode 100644 index 0000000..ab2365e --- /dev/null +++ b/core/java/android/view/CollapsibleActionView.java @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.view; + +import android.view.MenuItem.OnActionExpandListener; + +/** + * When a {@link View} implements this interface it will receive callbacks + * when expanded or collapsed as an action view alongside the optional, + * app-specified callbacks to {@link OnActionExpandListener}. + * + * <p>See {@link MenuItem} for more information about action views. + * See {@link android.app.ActionBar} for more information about the action bar. + */ +public interface CollapsibleActionView { + /** + * Called when this view is expanded as an action view. + * See {@link MenuItem#expandActionView()}. + */ + public void onActionViewExpanded(); + + /** + * Called when this view is collapsed as an action view. + * See {@link MenuItem#collapseActionView()}. + */ + public void onActionViewCollapsed(); +} diff --git a/core/java/android/view/DisplayList.java b/core/java/android/view/DisplayList.java index 4484d59..f4c0249 100644 --- a/core/java/android/view/DisplayList.java +++ b/core/java/android/view/DisplayList.java @@ -41,15 +41,6 @@ public abstract class DisplayList { abstract void end(); /** - * Indicates whether this display list can be replayed or not. - * - * @return True if the display list can be replayed, false otherwise. - * - * @see android.view.HardwareCanvas#drawDisplayList(DisplayList) - */ - abstract boolean isReady(); - - /** * Invalidates the display list, indicating that it should be repopulated * with new drawing commands prior to being used again. Calling this method * causes calls to {@link #isValid()} to return <code>false</code>. diff --git a/core/java/android/view/GLES20Canvas.java b/core/java/android/view/GLES20Canvas.java index 80244bb..d22fa6e 100644 --- a/core/java/android/view/GLES20Canvas.java +++ b/core/java/android/view/GLES20Canvas.java @@ -51,6 +51,7 @@ class GLES20Canvas extends HardwareCanvas { // The native renderer will be destroyed when this object dies. // DO NOT overwrite this reference once it is set. + @SuppressWarnings("unused") private CanvasFinalizer mFinalizer; private int mWidth; @@ -97,12 +98,8 @@ class GLES20Canvas extends HardwareCanvas { protected GLES20Canvas(boolean record, boolean translucent) { mOpaque = !translucent; - setupRenderer(record); - } - - protected void setupRenderer(boolean record) { if (record) { - mRenderer = nGetDisplayListRenderer(mRenderer); + mRenderer = nCreateDisplayListRenderer(); } else { mRenderer = nCreateRenderer(); } @@ -114,43 +111,31 @@ class GLES20Canvas extends HardwareCanvas { if (mRenderer == 0) { throw new IllegalStateException("Could not create GLES20Canvas renderer"); } else { - mFinalizer = CanvasFinalizer.getFinalizer(mFinalizer, mRenderer); + mFinalizer = new CanvasFinalizer(mRenderer); } } + protected void resetDisplayListRenderer() { + nResetDisplayListRenderer(mRenderer); + } + private static native int nCreateRenderer(); private static native int nCreateLayerRenderer(int layer); - private static native int nGetDisplayListRenderer(int renderer); + private static native int nCreateDisplayListRenderer(); + private static native void nResetDisplayListRenderer(int renderer); private static native void nDestroyRenderer(int renderer); - private static class CanvasFinalizer { - int mRenderer; - - // Factory method returns new instance if old one is null, or old instance - // otherwise, destroying native renderer along the way as necessary - static CanvasFinalizer getFinalizer(CanvasFinalizer oldFinalizer, int renderer) { - if (oldFinalizer == null) { - return new CanvasFinalizer(renderer); - } - oldFinalizer.replaceNativeObject(renderer); - return oldFinalizer; - } + private static final class CanvasFinalizer { + private final int mRenderer; - private CanvasFinalizer(int renderer) { + public CanvasFinalizer(int renderer) { mRenderer = renderer; } - private void replaceNativeObject(int newRenderer) { - if (mRenderer != 0 && newRenderer != mRenderer) { - nDestroyRenderer(mRenderer); - } - mRenderer = newRenderer; - } - @Override protected void finalize() throws Throwable { try { - replaceNativeObject(0); + nDestroyRenderer(mRenderer); } finally { super.finalize(); } @@ -322,11 +307,11 @@ class GLES20Canvas extends HardwareCanvas { // Display list /////////////////////////////////////////////////////////////////////////// - int getDisplayList() { - return nGetDisplayList(mRenderer); + int getDisplayList(int displayList) { + return nGetDisplayList(mRenderer, displayList); } - private static native int nGetDisplayList(int renderer); + private static native int nGetDisplayList(int renderer, int displayList); static void destroyDisplayList(int displayList) { nDestroyDisplayList(displayList); @@ -337,7 +322,7 @@ class GLES20Canvas extends HardwareCanvas { @Override public boolean drawDisplayList(DisplayList displayList, int width, int height, Rect dirty) { return nDrawDisplayList(mRenderer, - ((GLES20DisplayList) displayList).mNativeDisplayList, width, height, dirty); + ((GLES20DisplayList) displayList).getNativeDisplayList(), width, height, dirty); } private static native boolean nDrawDisplayList(int renderer, int displayList, @@ -345,7 +330,7 @@ class GLES20Canvas extends HardwareCanvas { @Override void outputDisplayList(DisplayList displayList) { - nOutputDisplayList(mRenderer, ((GLES20DisplayList) displayList).mNativeDisplayList); + nOutputDisplayList(mRenderer, ((GLES20DisplayList) displayList).getNativeDisplayList()); } private static native void nOutputDisplayList(int renderer, int displayList); diff --git a/core/java/android/view/GLES20DisplayList.java b/core/java/android/view/GLES20DisplayList.java index aeff31f..9e649ce 100644 --- a/core/java/android/view/GLES20DisplayList.java +++ b/core/java/android/view/GLES20DisplayList.java @@ -16,52 +16,50 @@ package android.view; -import java.lang.ref.WeakReference; +import android.graphics.Bitmap; + +import java.util.ArrayList; /** * An implementation of display list for OpenGL ES 2.0. */ class GLES20DisplayList extends DisplayList { - private GLES20Canvas mCanvas; - - private boolean mStarted = false; - private boolean mRecorded = false; - private boolean mValid = false; + // These lists ensure that any Bitmaps recorded by a DisplayList are kept alive as long + // as the DisplayList is alive. The Bitmaps are populated by the GLES20RecordingCanvas. + final ArrayList<Bitmap> mBitmaps = new ArrayList<Bitmap>(5); - int mNativeDisplayList; - WeakReference<View> hostView; + private GLES20RecordingCanvas mCanvas; + private boolean mValid; // The native display list will be destroyed when this object dies. // DO NOT overwrite this reference once it is set. - @SuppressWarnings("unused") private DisplayListFinalizer mFinalizer; - public GLES20DisplayList(View view) { - hostView = new WeakReference<View>(view); + int getNativeDisplayList() { + if (!mValid || mFinalizer == null) { + throw new IllegalStateException("The display list is not valid."); + } + return mFinalizer.mNativeDisplayList; } @Override HardwareCanvas start() { - if (mStarted) { - throw new IllegalStateException("Recording has already started"); - } - if (mCanvas != null) { - ((GLES20RecordingCanvas) mCanvas).reset(); - } else { - mCanvas = new GLES20RecordingCanvas(true); + throw new IllegalStateException("Recording has already started"); } - mStarted = true; - mRecorded = false; - mValid = true; + mValid = false; + mCanvas = GLES20RecordingCanvas.obtain(this); + mCanvas.start(); return mCanvas; } @Override void invalidate() { - mStarted = false; - mRecorded = false; + if (mCanvas != null) { + mCanvas.recycle(); + mCanvas = null; + } mValid = false; } @@ -73,48 +71,28 @@ class GLES20DisplayList extends DisplayList { @Override void end() { if (mCanvas != null) { - mStarted = false; - mRecorded = true; - - mNativeDisplayList = mCanvas.getDisplayList(); - mFinalizer = DisplayListFinalizer.getFinalizer(mFinalizer, mNativeDisplayList); + if (mFinalizer != null) { + mCanvas.end(mFinalizer.mNativeDisplayList); + } else { + mFinalizer = new DisplayListFinalizer(mCanvas.end(0)); + } + mCanvas.recycle(); + mCanvas = null; + mValid = true; } } - @Override - boolean isReady() { - return !mStarted && mRecorded; - } - private static class DisplayListFinalizer { - int mNativeDisplayList; - - // Factory method returns new instance if old one is null, or old instance - // otherwise, destroying native display list along the way as necessary - static DisplayListFinalizer getFinalizer(DisplayListFinalizer oldFinalizer, - int nativeDisplayList) { - if (oldFinalizer == null) { - return new DisplayListFinalizer(nativeDisplayList); - } - oldFinalizer.replaceNativeObject(nativeDisplayList); - return oldFinalizer; - } + final int mNativeDisplayList; - private DisplayListFinalizer(int nativeDisplayList) { + public DisplayListFinalizer(int nativeDisplayList) { mNativeDisplayList = nativeDisplayList; } - private void replaceNativeObject(int newNativeDisplayList) { - if (mNativeDisplayList != 0 && mNativeDisplayList != newNativeDisplayList) { - GLES20Canvas.destroyDisplayList(mNativeDisplayList); - } - mNativeDisplayList = newNativeDisplayList; - } - @Override protected void finalize() throws Throwable { try { - replaceNativeObject(0); + GLES20Canvas.destroyDisplayList(mNativeDisplayList); } finally { super.finalize(); } diff --git a/core/java/android/view/GLES20RecordingCanvas.java b/core/java/android/view/GLES20RecordingCanvas.java index ec94fe7..078222b 100644 --- a/core/java/android/view/GLES20RecordingCanvas.java +++ b/core/java/android/view/GLES20RecordingCanvas.java @@ -24,8 +24,10 @@ import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; - -import java.util.ArrayList; +import android.util.Pool; +import android.util.Poolable; +import android.util.PoolableManager; +import android.util.Pools; /** * An implementation of a GL canvas that records drawing operations. @@ -33,62 +35,94 @@ import java.util.ArrayList; * Bitmap objects that it draws, preventing the backing memory of Bitmaps from being freed while * the DisplayList is still holding a native reference to the memory. */ -class GLES20RecordingCanvas extends GLES20Canvas { - // These lists ensure that any Bitmaps recorded by a DisplayList are kept alive as long - // as the DisplayList is alive. - @SuppressWarnings({"MismatchedQueryAndUpdateOfCollection"}) - private final ArrayList<Bitmap> mBitmaps = new ArrayList<Bitmap>(5); +class GLES20RecordingCanvas extends GLES20Canvas implements Poolable<GLES20RecordingCanvas> { + // The recording canvas pool should be large enough to handle a deeply nested + // view hierarchy because display lists are generated recursively. + private static final int POOL_LIMIT = 50; + + private static final Pool<GLES20RecordingCanvas> sPool = Pools.synchronizedPool( + Pools.finitePool(new PoolableManager<GLES20RecordingCanvas>() { + public GLES20RecordingCanvas newInstance() { + return new GLES20RecordingCanvas(); + } + @Override + public void onAcquired(GLES20RecordingCanvas element) { + } + @Override + public void onReleased(GLES20RecordingCanvas element) { + } + }, POOL_LIMIT)); + + private GLES20RecordingCanvas mNextPoolable; + private boolean mIsPooled; + + private GLES20DisplayList mDisplayList; - GLES20RecordingCanvas(boolean translucent) { - super(true, translucent); + private GLES20RecordingCanvas() { + super(true /*record*/, true /*translucent*/); + } + + static GLES20RecordingCanvas obtain(GLES20DisplayList displayList) { + GLES20RecordingCanvas canvas = sPool.acquire(); + canvas.mDisplayList = displayList; + return canvas; + } + + void recycle() { + mDisplayList = null; + resetDisplayListRenderer(); + sPool.release(this); + } + + void start() { + mDisplayList.mBitmaps.clear(); + } + + int end(int nativeDisplayList) { + return getDisplayList(nativeDisplayList); } private void recordShaderBitmap(Paint paint) { if (paint != null) { final Shader shader = paint.getShader(); if (shader instanceof BitmapShader) { - mBitmaps.add(((BitmapShader) shader).mBitmap); + mDisplayList.mBitmaps.add(((BitmapShader) shader).mBitmap); } } } - void reset() { - mBitmaps.clear(); - setupRenderer(true); - } - @Override public void drawPatch(Bitmap bitmap, byte[] chunks, RectF dst, Paint paint) { super.drawPatch(bitmap, chunks, dst, paint); - mBitmaps.add(bitmap); + mDisplayList.mBitmaps.add(bitmap); // Shaders in the Paint are ignored when drawing a Bitmap } @Override public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) { super.drawBitmap(bitmap, left, top, paint); - mBitmaps.add(bitmap); + mDisplayList.mBitmaps.add(bitmap); // Shaders in the Paint are ignored when drawing a Bitmap } @Override public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) { super.drawBitmap(bitmap, matrix, paint); - mBitmaps.add(bitmap); + mDisplayList.mBitmaps.add(bitmap); // Shaders in the Paint are ignored when drawing a Bitmap } @Override public void drawBitmap(Bitmap bitmap, Rect src, Rect dst, Paint paint) { super.drawBitmap(bitmap, src, dst, paint); - mBitmaps.add(bitmap); + mDisplayList.mBitmaps.add(bitmap); // Shaders in the Paint are ignored when drawing a Bitmap } @Override public void drawBitmap(Bitmap bitmap, Rect src, RectF dst, Paint paint) { super.drawBitmap(bitmap, src, dst, paint); - mBitmaps.add(bitmap); + mDisplayList.mBitmaps.add(bitmap); // Shaders in the Paint are ignored when drawing a Bitmap } @@ -111,7 +145,7 @@ class GLES20RecordingCanvas extends GLES20Canvas { int vertOffset, int[] colors, int colorOffset, Paint paint) { super.drawBitmapMesh(bitmap, meshWidth, meshHeight, verts, vertOffset, colors, colorOffset, paint); - mBitmaps.add(bitmap); + mDisplayList.mBitmaps.add(bitmap); // Shaders in the Paint are ignored when drawing a Bitmap } @@ -270,4 +304,24 @@ class GLES20RecordingCanvas extends GLES20Canvas { colorOffset, indices, indexOffset, indexCount, paint); recordShaderBitmap(paint); } + + @Override + public GLES20RecordingCanvas getNextPoolable() { + return mNextPoolable; + } + + @Override + public void setNextPoolable(GLES20RecordingCanvas element) { + mNextPoolable = element; + } + + @Override + public boolean isPooled() { + return mIsPooled; + } + + @Override + public void setPooled(boolean isPooled) { + mIsPooled = isPooled; + } } diff --git a/core/java/android/view/HardwareRenderer.java b/core/java/android/view/HardwareRenderer.java index b865b50..503b54b 100644 --- a/core/java/android/view/HardwareRenderer.java +++ b/core/java/android/view/HardwareRenderer.java @@ -189,7 +189,7 @@ public abstract class HardwareRenderer { * * @return A new display list. */ - abstract DisplayList createDisplayList(View v); + abstract DisplayList createDisplayList(); /** * Creates a new hardware layer. A hardware layer built by calling this @@ -852,8 +852,8 @@ public abstract class HardwareRenderer { } @Override - DisplayList createDisplayList(View v) { - return new GLES20DisplayList(v); + DisplayList createDisplayList() { + return new GLES20DisplayList(); } @Override diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java index 0108ecf..c68b01c 100644 --- a/core/java/android/view/View.java +++ b/core/java/android/view/View.java @@ -9099,7 +9099,10 @@ public class View implements Drawable.Callback2, KeyEvent.Callback, Accessibilit mPrivateFlags2 |= LAYOUT_DIRECTION_RESOLVED; } - private void resolvePadding() { + /** + * @hide + */ + protected void resolvePadding() { // If the user specified the absolute padding (either with android:padding or // android:paddingLeft/Top/Right/Bottom), use this padding, otherwise // use the default padding or the padding from the background drawable @@ -9830,7 +9833,7 @@ public class View implements Drawable.Callback2, KeyEvent.Callback, Accessibilit // we copy in child display lists into ours in drawChild() mRecreateDisplayList = true; if (mDisplayList == null) { - mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(this); + mDisplayList = mAttachInfo.mHardwareRenderer.createDisplayList(); // If we're creating a new display list, make sure our parent gets invalidated // since they will need to recreate their display list to account for this // new child display list. @@ -12025,12 +12028,13 @@ public class View implements Drawable.Callback2, KeyEvent.Callback, Accessibilit mPrivateFlags |= FORCE_LAYOUT; mPrivateFlags |= INVALIDATED; - if (mLayoutParams != null && mParent != null) { - mLayoutParams.resolveWithDirection(getResolvedLayoutDirection()); - } - - if (mParent != null && !mParent.isLayoutRequested()) { - mParent.requestLayout(); + if (mParent != null) { + if (mLayoutParams != null) { + mLayoutParams.resolveWithDirection(getResolvedLayoutDirection()); + } + if (!mParent.isLayoutRequested()) { + mParent.requestLayout(); + } } } diff --git a/core/java/android/view/ViewDebug.java b/core/java/android/view/ViewDebug.java index 3798c9d..4acf48c 100644 --- a/core/java/android/view/ViewDebug.java +++ b/core/java/android/view/ViewDebug.java @@ -25,6 +25,7 @@ import android.os.Debug; import android.os.Environment; import android.os.Looper; import android.os.Message; +import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.os.SystemClock; import android.util.DisplayMetrics; @@ -36,7 +37,7 @@ import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; -import java.io.FileNotFoundException; +import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; @@ -50,6 +51,9 @@ import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; @@ -426,22 +430,22 @@ public class ViewDebug { * and obtain the traces. Both methods must be invoked on the * same thread. * - * @param traceFile The path where to write the looper traces - * - * @see #stopLooperProfiling() + * @hide */ - public static void startLooperProfiling(File traceFile) { + public static void startLooperProfiling(String path, FileDescriptor fileDescriptor) { if (sLooperProfilerStorage.get() == null) { - LooperProfiler profiler = new LooperProfiler(traceFile); + LooperProfiler profiler = new LooperProfiler(path, fileDescriptor); sLooperProfilerStorage.set(profiler); Looper.myLooper().setMessageLogging(profiler); } - } + } /** * Stops profiling the looper associated with the current thread. * - * @see #startLooperProfiling(java.io.File) + * @see #startLooperProfiling(String, java.io.FileDescriptor) + * + * @hide */ public static void stopLooperProfiling() { LooperProfiler profiler = sLooperProfilerStorage.get(); @@ -453,21 +457,33 @@ public class ViewDebug { } private static class LooperProfiler implements Looper.Profiler, Printer { - private static final int LOOPER_PROFILER_VERSION = 1; - private static final String LOG_TAG = "LooperProfiler"; + private static final int TRACE_VERSION_NUMBER = 3; + private static final int ACTION_EXIT_METHOD = 0x1; + private static final int HEADER_SIZE = 32; + private static final String HEADER_MAGIC = "SLOW"; + private static final short HEADER_RECORD_SIZE = (short) 14; + private final long mTraceWallStart; private final long mTraceThreadStart; private final ArrayList<Entry> mTraces = new ArrayList<Entry>(512); - private final File mTraceFile; - private final HashMap<String, Short> mTraceNames = new HashMap<String, Short>(32); - private short mTraceId = 0; + private final HashMap<String, Integer> mTraceNames = new HashMap<String, Integer>(32); + private int mTraceId = 0; - LooperProfiler(File traceFile) { - mTraceFile = traceFile; + private final String mPath; + private ParcelFileDescriptor mFileDescriptor; + + LooperProfiler(String path, FileDescriptor fileDescriptor) { + mPath = path; + try { + mFileDescriptor = ParcelFileDescriptor.dup(fileDescriptor); + } catch (IOException e) { + Log.e(LOG_TAG, "Could not write trace file " + mPath, e); + throw new RuntimeException(e); + } mTraceWallStart = SystemClock.currentTimeMicro(); mTraceThreadStart = SystemClock.currentThreadTimeMicro(); } @@ -490,11 +506,11 @@ public class ViewDebug { mTraces.add(entry); } - private short getTraceId(Message message) { + private int getTraceId(Message message) { String name = message.getTarget().getMessageName(message); - Short traceId = mTraceNames.get(name); + Integer traceId = mTraceNames.get(name); if (traceId == null) { - traceId = mTraceId++; + traceId = mTraceId++ << 4; mTraceNames.put(name, traceId); } return traceId; @@ -507,62 +523,135 @@ public class ViewDebug { public void run() { saveTraces(); } - }, "LooperProfiler[" + mTraceFile + "]").start(); + }, "LooperProfiler[" + mPath + "]").start(); } private void saveTraces() { - FileOutputStream fos; - try { - fos = new FileOutputStream(mTraceFile); - } catch (FileNotFoundException e) { - Log.e(LOG_TAG, "Could not open trace file: " + mTraceFile); - return; - } - + FileOutputStream fos = new FileOutputStream(mFileDescriptor.getFileDescriptor()); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(fos)); try { - out.writeInt(LOOPER_PROFILER_VERSION); - out.writeLong(mTraceWallStart); - out.writeLong(mTraceThreadStart); + writeHeader(out, mTraceWallStart, mTraceNames, mTraces); + out.flush(); - out.writeInt(mTraceNames.size()); - for (Map.Entry<String, Short> entry : mTraceNames.entrySet()) { - saveTraceName(entry.getKey(), entry.getValue(), out); - } + writeTraces(fos, out.size(), mTraceWallStart, mTraceThreadStart, mTraces); - out.writeInt(mTraces.size()); - for (Entry entry : mTraces) { - saveTrace(entry, out); - } - - Log.d(LOG_TAG, "Looper traces ready: " + mTraceFile); + Log.d(LOG_TAG, "Looper traces ready: " + mPath); } catch (IOException e) { - Log.e(LOG_TAG, "Could not write trace file: ", e); + Log.e(LOG_TAG, "Could not write trace file " + mPath, e); } finally { try { out.close(); } catch (IOException e) { - // Ignore + Log.e(LOG_TAG, "Could not write trace file " + mPath, e); + } + try { + mFileDescriptor.close(); + } catch (IOException e) { + Log.e(LOG_TAG, "Could not write trace file " + mPath, e); } } } - - private void saveTraceName(String name, short id, DataOutputStream out) throws IOException { - out.writeShort(id); - out.writeUTF(name); + + private static void writeTraces(FileOutputStream out, long offset, long wallStart, + long threadStart, ArrayList<Entry> entries) throws IOException { + + FileChannel channel = out.getChannel(); + + // Header + ByteBuffer buffer = ByteBuffer.allocateDirect(HEADER_SIZE); + buffer.put(HEADER_MAGIC.getBytes()); + buffer = buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putShort((short) TRACE_VERSION_NUMBER); // version + buffer.putShort((short) HEADER_SIZE); // offset to data + buffer.putLong(wallStart); // start time in usec + buffer.putShort(HEADER_RECORD_SIZE); // size of a record in bytes + // padding to 32 bytes + for (int i = 0; i < HEADER_SIZE - 18; i++) { + buffer.put((byte) 0); + } + + buffer.flip(); + channel.position(offset).write(buffer); + + buffer = ByteBuffer.allocateDirect(14).order(ByteOrder.LITTLE_ENDIAN); + for (Entry entry : entries) { + buffer.putShort((short) 1); // we simulate only one thread + buffer.putInt(entry.traceId); // entering method + buffer.putInt((int) (entry.threadStart - threadStart)); + buffer.putInt((int) (entry.wallStart - wallStart)); + + buffer.flip(); + channel.write(buffer); + buffer.clear(); + + buffer.putShort((short) 1); + buffer.putInt(entry.traceId | ACTION_EXIT_METHOD); // exiting method + buffer.putInt((int) (entry.threadStart + entry.threadTime - threadStart)); + buffer.putInt((int) (entry.wallStart + entry.wallTime - wallStart)); + + buffer.flip(); + channel.write(buffer); + buffer.clear(); + } + + channel.close(); } + + private static void writeHeader(DataOutputStream out, long start, + HashMap<String, Integer> names, ArrayList<Entry> entries) throws IOException { + + Entry last = entries.get(entries.size() - 1); + long wallTotal = (last.wallStart + last.wallTime) - start; + + startSection("version", out); + addValue(null, Integer.toString(TRACE_VERSION_NUMBER), out); + addValue("data-file-overflow", "false", out); + addValue("clock", "dual", out); + addValue("elapsed-time-usec", Long.toString(wallTotal), out); + addValue("num-method-calls", Integer.toString(entries.size()), out); + addValue("clock-call-overhead-nsec", "1", out); + addValue("vm", "dalvik", out); + + startSection("threads", out); + addThreadId(1, "main", out); + + startSection("methods", out); + addMethods(names, out); + + startSection("end", out); + } + + private static void addMethods(HashMap<String, Integer> names, DataOutputStream out) + throws IOException { + + for (Map.Entry<String, Integer> name : names.entrySet()) { + out.writeBytes(String.format("0x%08x\tEventQueue\t%s\t()V\tLooper\t-2\n", + name.getValue(), name.getKey())); + } + } + + private static void addThreadId(int id, String name, DataOutputStream out) + throws IOException { - private void saveTrace(Entry entry, DataOutputStream out) throws IOException { - out.writeShort(entry.traceId); - out.writeLong(entry.wallStart); - out.writeLong(entry.wallTime); - out.writeLong(entry.threadStart); - out.writeLong(entry.threadTime); + out.writeBytes(Integer.toString(id) + '\t' + name + '\n'); + } + + private static void addValue(String name, String value, DataOutputStream out) + throws IOException { + + if (name != null) { + out.writeBytes(name + "="); + } + out.writeBytes(value + '\n'); + } + + private static void startSection(String name, DataOutputStream out) throws IOException { + out.writeBytes("*" + name + '\n'); } static class Entry { - short traceId; + int traceId; long wallStart; long wallTime; long threadStart; diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java index 54fee3c..6f90971 100644 --- a/core/java/android/view/ViewGroup.java +++ b/core/java/android/view/ViewGroup.java @@ -2148,9 +2148,12 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager onPopulateAccessibilityEvent(event); // Let our children have a shot in populating the event. for (int i = 0, count = getChildCount(); i < count; i++) { - boolean handled = getChildAt(i).dispatchPopulateAccessibilityEvent(event); - if (handled) { - return handled; + View child = getChildAt(i); + if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { + boolean handled = getChildAt(i).dispatchPopulateAccessibilityEvent(event); + if (handled) { + return handled; + } } } return false; @@ -2851,7 +2854,7 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager // display lists to render, force an invalidate to allow the animation to // continue drawing another frame invalidate(true); - if (a instanceof AlphaAnimation) { + if (a.hasAlpha()) { // alpha animations should cause the child to recreate its display list child.invalidate(true); } diff --git a/core/java/android/view/animation/AlphaAnimation.java b/core/java/android/view/animation/AlphaAnimation.java index 651fe45..c4d9afc 100644 --- a/core/java/android/view/animation/AlphaAnimation.java +++ b/core/java/android/view/animation/AlphaAnimation.java @@ -78,4 +78,12 @@ public class AlphaAnimation extends Animation { public boolean willChangeBounds() { return false; } + + /** + * @hide + */ + @Override + public boolean hasAlpha() { + return true; + } } diff --git a/core/java/android/view/animation/Animation.java b/core/java/android/view/animation/Animation.java index 87c759c..b7dfabc 100644 --- a/core/java/android/view/animation/Animation.java +++ b/core/java/android/view/animation/Animation.java @@ -1001,6 +1001,15 @@ public abstract class Animation implements Cloneable { } /** + * Return true if this animation changes the view's alpha property. + * + * @hide + */ + public boolean hasAlpha() { + return false; + } + + /** * Utility class to parse a string description of a size. */ protected static class Description { diff --git a/core/java/android/view/animation/AnimationSet.java b/core/java/android/view/animation/AnimationSet.java index 873ce53..4f2542b 100644 --- a/core/java/android/view/animation/AnimationSet.java +++ b/core/java/android/view/animation/AnimationSet.java @@ -43,6 +43,8 @@ public class AnimationSet extends Animation { private static final int PROPERTY_CHANGE_BOUNDS_MASK = 0x80; private int mFlags = 0; + private boolean mDirty; + private boolean mHasAlpha; private ArrayList<Animation> mAnimations = new ArrayList<Animation>(); @@ -138,6 +140,28 @@ public class AnimationSet extends Animation { } /** + * @hide + */ + @Override + public boolean hasAlpha() { + if (mDirty) { + mDirty = mHasAlpha = false; + + final int count = mAnimations.size(); + final ArrayList<Animation> animations = mAnimations; + + for (int i = 0; i < count; i++) { + if (animations.get(i).hasAlpha()) { + mHasAlpha = true; + break; + } + } + } + + return mHasAlpha; + } + + /** * <p>Sets the duration of every child animation.</p> * * @param durationMillis the duration of the animation, in milliseconds, for @@ -175,6 +199,8 @@ public class AnimationSet extends Animation { mLastEnd = Math.max(mLastEnd, a.getStartOffset() + a.getDuration()); mDuration = mLastEnd - mStartOffset; } + + mDirty = true; } /** diff --git a/core/java/android/view/textservice/SpellCheckerInfo.aidl b/core/java/android/view/textservice/SpellCheckerInfo.aidl new file mode 100644 index 0000000..eb5dfcc --- /dev/null +++ b/core/java/android/view/textservice/SpellCheckerInfo.aidl @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.view.textservice; + +parcelable SpellCheckerInfo; diff --git a/core/java/android/view/textservice/SpellCheckerInfo.java b/core/java/android/view/textservice/SpellCheckerInfo.java new file mode 100644 index 0000000..d88a39f --- /dev/null +++ b/core/java/android/view/textservice/SpellCheckerInfo.java @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package android.view.textservice; + +import android.content.ComponentName; +import android.content.Context; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.content.pm.ServiceInfo; +import android.graphics.drawable.Drawable; +import android.os.Parcel; +import android.os.Parcelable; + +/** + * This class is used to specify meta information of an spell checker. + */ +public final class SpellCheckerInfo implements Parcelable { + private final ResolveInfo mService; + private final String mId; + + /** + * Constructor. + * @hide + */ + public SpellCheckerInfo(Context context, ResolveInfo service) { + mService = service; + ServiceInfo si = service.serviceInfo; + mId = new ComponentName(si.packageName, si.name).flattenToShortString(); + } + + /** + * Constructor. + * @hide + */ + public SpellCheckerInfo(Parcel source) { + mId = source.readString(); + mService = ResolveInfo.CREATOR.createFromParcel(source); + } + + /** + * Return a unique ID for this spell checker. The ID is generated from + * the package and class name implementing the method. + */ + public String getId() { + return mId; + } + + + /** + * Return the component of the service that implements. + */ + public ComponentName getComponent() { + return new ComponentName( + mService.serviceInfo.packageName, mService.serviceInfo.name); + } + + /** + * Return the .apk package that implements this input method. + */ + public String getPackageName() { + return mService.serviceInfo.packageName; + } + + /** + * Used to package this object into a {@link Parcel}. + * + * @param dest The {@link Parcel} to be written. + * @param flags The flags used for parceling. + */ + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mId); + mService.writeToParcel(dest, flags); + } + + + /** + * Used to make this class parcelable. + */ + public static final Parcelable.Creator<SpellCheckerInfo> CREATOR + = new Parcelable.Creator<SpellCheckerInfo>() { + @Override + public SpellCheckerInfo createFromParcel(Parcel source) { + return new SpellCheckerInfo(source); + } + + @Override + public SpellCheckerInfo[] newArray(int size) { + return new SpellCheckerInfo[size]; + } + }; + + /** + * Load the user-displayed label for this spell checker. + * + * @param pm Supply a PackageManager used to load the spell checker's resources. + */ + public CharSequence loadLabel(PackageManager pm) { + return mService.loadLabel(pm); + } + + /** + * Load the user-displayed icon for this spell checker. + * + * @param pm Supply a PackageManager used to load the spell checker's resources. + */ + public Drawable loadIcon(PackageManager pm) { + return mService.loadIcon(pm); + } + + /** + * Used to make this class parcelable. + */ + @Override + public int describeContents() { + return 0; + } +} diff --git a/core/java/android/view/textservice/SuggestionsInfo.aidl b/core/java/android/view/textservice/SuggestionsInfo.aidl new file mode 100644 index 0000000..66e20d2 --- /dev/null +++ b/core/java/android/view/textservice/SuggestionsInfo.aidl @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.view.textservice; + +parcelable SuggestionsInfo; diff --git a/core/java/android/view/textservice/SuggestionsInfo.java b/core/java/android/view/textservice/SuggestionsInfo.java new file mode 100644 index 0000000..3332f1e --- /dev/null +++ b/core/java/android/view/textservice/SuggestionsInfo.java @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package android.view.textservice; + +import android.os.Parcel; +import android.os.Parcelable; + +/** + * This class contains a metadata of suggestions from the text service + */ +public final class SuggestionsInfo implements Parcelable { + private static final String[] EMPTY = new String[0]; + + /** + * Flag of the attributes of the suggestions that can be obtained by + * {@link #getSuggestionsAttributes}: this tells that the requested word was found + * in the dictionary in the text service. + */ + public static final int RESULT_ATTR_IN_THE_DICTIONARY = 0x0001; + /** + * Flag of the attributes of the suggestions that can be obtained by + * {@link #getSuggestionsAttributes}: this tells that the text service thinks the requested + * word looks a typo. + */ + public static final int RESULT_ATTR_LOOKS_TYPO = 0x0002; + private final int mSuggestionsAttributes; + private final String[] mSuggestions; + private final boolean mSuggestionsAvailable; + private int mCookie; + private int mSequence; + + /** + * Constructor. + * @param suggestionsAttributes from the text service + * @param suggestions from the text service + */ + public SuggestionsInfo(int suggestionsAttributes, String[] suggestions) { + mSuggestionsAttributes = suggestionsAttributes; + if (suggestions == null) { + mSuggestions = EMPTY; + mSuggestionsAvailable = false; + } else { + mSuggestions = suggestions; + mSuggestionsAvailable = true; + } + mCookie = 0; + mSequence = 0; + } + + /** + * Constructor. + * @param suggestionsAttributes from the text service + * @param suggestions from the text service + * @param cookie the cookie of the input TextInfo + * @param sequence the cookie of the input TextInfo + */ + public SuggestionsInfo( + int suggestionsAttributes, String[] suggestions, int cookie, int sequence) { + if (suggestions == null) { + mSuggestions = EMPTY; + mSuggestionsAvailable = false; + } else { + mSuggestions = suggestions; + mSuggestionsAvailable = true; + } + mSuggestionsAttributes = suggestionsAttributes; + mCookie = cookie; + mSequence = sequence; + } + + public SuggestionsInfo(Parcel source) { + mSuggestionsAttributes = source.readInt(); + mSuggestions = source.readStringArray(); + mCookie = source.readInt(); + mSequence = source.readInt(); + mSuggestionsAvailable = source.readInt() == 1; + } + + /** + * Used to package this object into a {@link Parcel}. + * + * @param dest The {@link Parcel} to be written. + * @param flags The flags used for parceling. + */ + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mSuggestionsAttributes); + dest.writeStringArray(mSuggestions); + dest.writeInt(mCookie); + dest.writeInt(mSequence); + dest.writeInt(mSuggestionsAvailable ? 1 : 0); + } + + /** + * Set the cookie and the sequence of SuggestionsInfo which are set to TextInfo from a client + * application + * @param cookie the cookie of an input TextInfo + * @param sequence the cookie of an input TextInfo + */ + public void setCookieAndSequence(int cookie, int sequence) { + mCookie = cookie; + mSequence = sequence; + } + + /** + * @return the cookie which may be set by a client application + */ + public int getCookie() { + return mCookie; + } + + /** + * @return the sequence which may be set by a client application + */ + public int getSequence() { + return mSequence; + } + + /** + * @return the attributes of suggestions. This includes whether the spell checker has the word + * in its dictionary or not and whether the spell checker has confident suggestions for the + * word or not. + */ + public int getSuggestionsAttributes() { + return mSuggestionsAttributes; + } + + /** + * @return the count of the suggestions. If there's no suggestions at all, this method returns + * -1. Even if this method returns 0, it doesn't necessarily mean that there are no suggestions + * for the requested word. For instance, the caller could have been asked to limit the maximum + * number of suggestions returned. + */ + public int getSuggestionsCount() { + if (!mSuggestionsAvailable) { + return -1; + } + return mSuggestions.length; + } + + /** + * @param i the id of suggestions + * @return the suggestion at the specified id + */ + public String getSuggestionAt(int i) { + return mSuggestions[i]; + } + + /** + * Used to make this class parcelable. + */ + public static final Parcelable.Creator<SuggestionsInfo> CREATOR + = new Parcelable.Creator<SuggestionsInfo>() { + @Override + public SuggestionsInfo createFromParcel(Parcel source) { + return new SuggestionsInfo(source); + } + + @Override + public SuggestionsInfo[] newArray(int size) { + return new SuggestionsInfo[size]; + } + }; + + /** + * Used to make this class parcelable. + */ + @Override + public int describeContents() { + return 0; + } +} diff --git a/core/java/android/view/textservice/TextInfo.aidl b/core/java/android/view/textservice/TextInfo.aidl new file mode 100644 index 0000000..d231d76 --- /dev/null +++ b/core/java/android/view/textservice/TextInfo.aidl @@ -0,0 +1,19 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.view.textservice; + +parcelable TextInfo; diff --git a/core/java/android/view/textservice/TextInfo.java b/core/java/android/view/textservice/TextInfo.java new file mode 100644 index 0000000..b534eb0 --- /dev/null +++ b/core/java/android/view/textservice/TextInfo.java @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package android.view.textservice; + +import android.os.Parcel; +import android.os.Parcelable; +import android.text.TextUtils; + +/** + * This class contains a metadata of the input of TextService + */ +public final class TextInfo implements Parcelable { + private final String mText; + private final int mCookie; + private final int mSequence; + + /** + * Constructor. + * @param text the text which will be input to TextService + */ + public TextInfo(String text) { + this(text, 0, 0); + } + + /** + * Constructor. + * @param text the text which will be input to TextService + * @param cookie the cookie for this TextInfo + * @param sequence the sequence number for this TextInfo + */ + public TextInfo(String text, int cookie, int sequence) { + if (TextUtils.isEmpty(text)) { + throw new IllegalArgumentException(text); + } + mText = text; + mCookie = cookie; + mSequence = sequence; + } + + public TextInfo(Parcel source) { + mText = source.readString(); + mCookie = source.readInt(); + mSequence = source.readInt(); + } + + /** + * Used to package this object into a {@link Parcel}. + * + * @param dest The {@link Parcel} to be written. + * @param flags The flags used for parceling. + */ + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mText); + dest.writeInt(mCookie); + dest.writeInt(mSequence); + } + + /** + * @return the text which is an input of a text service + */ + public String getText() { + return mText; + } + + /** + * @return the cookie of TextInfo + */ + public int getCookie() { + return mCookie; + } + + /** + * @return the sequence of TextInfo + */ + public int getSequence() { + return mSequence; + } + + /** + * Used to make this class parcelable. + */ + public static final Parcelable.Creator<TextInfo> CREATOR + = new Parcelable.Creator<TextInfo>() { + @Override + public TextInfo createFromParcel(Parcel source) { + return new TextInfo(source); + } + + @Override + public TextInfo[] newArray(int size) { + return new TextInfo[size]; + } + }; + + /** + * Used to make this class parcelable. + */ + @Override + public int describeContents() { + return 0; + } +} diff --git a/core/java/android/view/textservice/TextServicesManager.java b/core/java/android/view/textservice/TextServicesManager.java new file mode 100644 index 0000000..229b414 --- /dev/null +++ b/core/java/android/view/textservice/TextServicesManager.java @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +package android.view.textservice; + +import com.android.internal.textservice.ITextServicesManager; + +import android.content.Context; +import android.os.IBinder; +import android.os.RemoteException; +import android.os.ServiceManager; +import android.view.textservice.SpellCheckerInfo; +import android.service.textservice.SpellCheckerSession; +import android.service.textservice.SpellCheckerSession.SpellCheckerSessionListener; + +import java.util.Locale; + +/** + * System API to the overall text services, which arbitrates interaction between applications + * and text services. You can retrieve an instance of this interface with + * {@link Context#getSystemService(String) Context.getSystemService()}. + * + * The user can change the current text services in Settings. And also applications can specify + * the target text services. + */ +public final class TextServicesManager { + private static final String TAG = TextServicesManager.class.getSimpleName(); + + private static TextServicesManager sInstance; + private static ITextServicesManager sService; + + private TextServicesManager() { + if (sService == null) { + IBinder b = ServiceManager.getService(Context.TEXT_SERVICES_MANAGER_SERVICE); + sService = ITextServicesManager.Stub.asInterface(b); + } + } + + /** + * Retrieve the global TextServicesManager instance, creating it if it doesn't already exist. + * @hide + */ + public static TextServicesManager getInstance() { + synchronized (TextServicesManager.class) { + if (sInstance != null) { + return sInstance; + } + sInstance = new TextServicesManager(); + } + return sInstance; + } + + /** + * Get a spell checker session for the specified spell checker + * @param locale the locale for the spell checker + * @param listener a spell checker session lister for getting results from a spell checker. + * @param referToSpellCheckerLanguageSettings if true, the session for one of enabled + * languages in settings will be returned. + * @return the spell checker session of the spell checker + */ + // TODO: Add a method to get enabled spell checkers. + // TODO: Handle referToSpellCheckerLanguageSettings + public SpellCheckerSession newSpellCheckerSession(Locale locale, + SpellCheckerSessionListener listener, boolean referToSpellCheckerLanguageSettings) { + if (locale == null || listener == null) { + throw new NullPointerException(); + } + final SpellCheckerInfo info; + try { + info = sService.getCurrentSpellChecker(locale.toString()); + } catch (RemoteException e) { + return null; + } + if (info == null) { + return null; + } + final SpellCheckerSession session = new SpellCheckerSession(info, sService, listener); + try { + sService.getSpellCheckerService( + info, locale.toString(), session.getTextServicesSessionListener(), + session.getSpellCheckerSessionListener()); + } catch (RemoteException e) { + return null; + } + return session; + } + + /** + * @hide + */ + public SpellCheckerInfo[] getEnabledSpellCheckers() { + try { + return sService.getEnabledSpellCheckers(); + } catch (RemoteException e) { + return null; + } + } + + /** + * @hide + */ + public SpellCheckerInfo getCurrentSpellChecker() { + try { + // Passing null as a locale for ICS + return sService.getCurrentSpellChecker(null); + } catch (RemoteException e) { + return null; + } + } +} diff --git a/core/java/android/webkit/JniUtil.java b/core/java/android/webkit/JniUtil.java index bb4d192..620973e 100644 --- a/core/java/android/webkit/JniUtil.java +++ b/core/java/android/webkit/JniUtil.java @@ -18,6 +18,7 @@ package android.webkit; import android.content.Context; import android.net.Uri; +import android.provider.Settings; import android.util.Log; import java.io.InputStream; @@ -38,7 +39,7 @@ class JniUtil { private static boolean initialized = false; - private static void checkIntialized() { + private static void checkInitialized() { if (!initialized) { throw new IllegalStateException("Call CookieSyncManager::createInstance() or create a webview before using this class"); } @@ -63,7 +64,7 @@ class JniUtil { * @return String The application's database directory */ private static synchronized String getDatabaseDirectory() { - checkIntialized(); + checkInitialized(); if (sDatabaseDirectory == null) sDatabaseDirectory = sContext.getDatabasePath("dummy").getParent(); @@ -76,7 +77,7 @@ class JniUtil { * @return String The application's cache directory */ private static synchronized String getCacheDirectory() { - checkIntialized(); + checkInitialized(); if (sCacheDirectory == null) sCacheDirectory = sContext.getCacheDir().getAbsolutePath(); @@ -166,5 +167,13 @@ class JniUtil { return sUseChromiumHttpStack; } + private static synchronized String getAutofillQueryUrl() { + checkInitialized(); + // If the device has not checked in it won't have pulled down the system setting for the + // Autofill Url. In that case we will not make autofill server requests. + return Settings.Secure.getString(sContext.getContentResolver(), + Settings.Secure.WEB_AUTOFILL_QUERY_URL); + } + private static native boolean nativeUseChromiumHttpStack(); } diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java index b22c57b..e24ab58 100644 --- a/core/java/android/webkit/WebView.java +++ b/core/java/android/webkit/WebView.java @@ -4701,6 +4701,7 @@ public class WebView extends AbsoluteLayout private Message mUpdateMessage; private boolean mAutoFillable; private boolean mAutoComplete; + private WebSettings mWebSettings; public RequestFormData(String name, String url, Message msg, boolean autoFillable, boolean autoComplete) { @@ -4709,6 +4710,7 @@ public class WebView extends AbsoluteLayout mUpdateMessage = msg; mAutoFillable = autoFillable; mAutoComplete = autoComplete; + mWebSettings = getSettings(); } public void run() { @@ -4718,8 +4720,7 @@ public class WebView extends AbsoluteLayout // Note that code inside the adapter click handler in WebTextView depends // on the AutoFill item being at the top of the drop down list. If you change // the order, make sure to do it there too! - WebSettings settings = getSettings(); - if (settings != null && settings.getAutoFillProfile() != null) { + if (mWebSettings != null && mWebSettings.getAutoFillProfile() != null) { pastEntries.add(getResources().getText( com.android.internal.R.string.autofill_this_form).toString() + " " + @@ -6330,8 +6331,8 @@ public class WebView extends AbsoluteLayout if (action == MotionEvent.ACTION_POINTER_DOWN) { cancelTouch(); action = MotionEvent.ACTION_DOWN; - } else if (action == MotionEvent.ACTION_POINTER_UP && ev.getPointerCount() == 2) { - // set mLastTouchX/Y to the remaining point + } else if (action == MotionEvent.ACTION_POINTER_UP && ev.getPointerCount() >= 2) { + // set mLastTouchX/Y to the remaining points for multi-touch. mLastTouchX = Math.round(x); mLastTouchY = Math.round(y); } else if (action == MotionEvent.ACTION_MOVE) { @@ -9119,20 +9120,12 @@ public class WebView extends AbsoluteLayout return nativeTileProfilingNumTilesInFrame(frame); } /** @hide only used by profiling tests */ - public int tileProfilingGetX(int frame, int tile) { - return nativeTileProfilingGetX(frame, tile); + public int tileProfilingGetInt(int frame, int tile, String key) { + return nativeTileProfilingGetInt(frame, tile, key); } /** @hide only used by profiling tests */ - public int tileProfilingGetY(int frame, int tile) { - return nativeTileProfilingGetY(frame, tile); - } - /** @hide only used by profiling tests */ - public boolean tileProfilingGetReady(int frame, int tile) { - return nativeTileProfilingGetReady(frame, tile); - } - /** @hide only used by profiling tests */ - public int tileProfilingGetLevel(int frame, int tile) { - return nativeTileProfilingGetLevel(frame, tile); + public float tileProfilingGetFloat(int frame, int tile, String key) { + return nativeTileProfilingGetFloat(frame, tile, key); } private native int nativeCacheHitFramePointer(); @@ -9262,10 +9255,8 @@ public class WebView extends AbsoluteLayout private native void nativeTileProfilingClear(); private native int nativeTileProfilingNumFrames(); private native int nativeTileProfilingNumTilesInFrame(int frame); - private native int nativeTileProfilingGetX(int frame, int tile); - private native int nativeTileProfilingGetY(int frame, int tile); - private native boolean nativeTileProfilingGetReady(int frame, int tile); - private native int nativeTileProfilingGetLevel(int frame, int tile); + private native int nativeTileProfilingGetInt(int frame, int tile, String key); + private native float nativeTileProfilingGetFloat(int frame, int tile, String key); // Never call this version except by updateCachedTextfield(String) - // we always want to pass in our generation number. private native void nativeUpdateCachedTextfield(String updatedText, diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java index d7a2526..8d8023b 100644 --- a/core/java/android/webkit/WebViewCore.java +++ b/core/java/android/webkit/WebViewCore.java @@ -1069,6 +1069,15 @@ public final class WebViewCore { + " arg1=" + msg.arg1 + " arg2=" + msg.arg2 + " obj=" + msg.obj); } + if (mWebView == null + && msg.what != EventHub.RESUME_TIMERS + && msg.what != EventHub.PAUSE_TIMERS) { + if (DebugFlags.WEB_VIEW_CORE) { + Log.v(LOGTAG, "Rejecting message " + msg.what + + " because we are destroyed"); + } + return; + } switch (msg.what) { case WEBKIT_DRAW: webkitDraw(); @@ -1757,30 +1766,17 @@ public final class WebViewCore { } /** - * Removes pending messages and trigger a DESTROY message to send to - * WebCore. + * Sends a DESTROY message to WebCore. * Called from UI thread. */ void destroy() { - // We don't want anyone to post a message between removing pending - // messages and sending the destroy message. synchronized (mEventHub) { - // RESUME_TIMERS and PAUSE_TIMERS are per process base. They need to - // be preserved even the WebView is destroyed. - // Note: we should not have more than one RESUME_TIMERS/PAUSE_TIMERS - boolean hasResume = mEventHub.hasMessages(EventHub.RESUME_TIMERS); - boolean hasPause = mEventHub.hasMessages(EventHub.PAUSE_TIMERS); - mEventHub.removeMessages(); + // Do not call removeMessages as then we risk removing PAUSE_TIMERS + // or RESUME_TIMERS messages, which we must still handle as they + // are per process. DESTROY will instead trigger a white list in + // mEventHub, skipping any remaining messages in the queue mEventHub.sendMessageAtFrontOfQueue( Message.obtain(null, EventHub.DESTROY)); - if (hasPause) { - mEventHub.sendMessageAtFrontOfQueue( - Message.obtain(null, EventHub.PAUSE_TIMERS)); - } - if (hasResume) { - mEventHub.sendMessageAtFrontOfQueue( - Message.obtain(null, EventHub.RESUME_TIMERS)); - } mEventHub.blockMessages(); } } @@ -2113,13 +2109,17 @@ public final class WebViewCore { // called from JNI or WebView thread /* package */ void contentDraw() { - // don't update the Picture until we have an initial width and finish - // the first layout - if (mCurrentViewWidth == 0 || !mBrowserFrame.firstLayoutDone()) { - return; - } - // only fire an event if this is our first request synchronized (this) { + if (mWebView == null || mBrowserFrame == null) { + // We were destroyed + return; + } + // don't update the Picture until we have an initial width and finish + // the first layout + if (mCurrentViewWidth == 0 || !mBrowserFrame.firstLayoutDone()) { + return; + } + // only fire an event if this is our first request if (mDrawIsScheduled) return; mDrawIsScheduled = true; if (mDrawIsPaused) return; diff --git a/core/java/android/webkit/ZoomManager.java b/core/java/android/webkit/ZoomManager.java index 49ea944..70e48ad 100644 --- a/core/java/android/webkit/ZoomManager.java +++ b/core/java/android/webkit/ZoomManager.java @@ -794,6 +794,8 @@ class ZoomManager { mInitialZoomOverview = false; dismissZoomPicker(); mFocusMovementQueue.clear(); + mFocusX = detector.getFocusX(); + mFocusY = detector.getFocusY(); mWebView.mViewManager.startZoom(); mWebView.onPinchToZoomAnimationStart(); mAccumulatedSpan = 0; diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java index 8f8c1d0..b7c1687 100644 --- a/core/java/android/widget/AbsListView.java +++ b/core/java/android/widget/AbsListView.java @@ -4638,9 +4638,6 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te childrenTop += getVerticalFadingEdgeLength(); } } - // Don't ever focus a disabled item. - if (!mAdapter.isEnabled(i)) continue; - if (top >= childrenTop) { // Found a view whose top is fully visisble selectedPos = firstPosition + i; diff --git a/core/java/android/widget/ActivityChooserModel.java b/core/java/android/widget/ActivityChooserModel.java index d7429b3..4b0a6da 100644 --- a/core/java/android/widget/ActivityChooserModel.java +++ b/core/java/android/widget/ActivityChooserModel.java @@ -317,6 +317,7 @@ public class ActivityChooserModel extends DataSetObservable { dataModel = new ActivityChooserModel(context, historyFileName); sDataModelRegistry.put(historyFileName, dataModel); } + dataModel.readHistoricalData(); return dataModel; } } @@ -505,7 +506,7 @@ public class ActivityChooserModel extends DataSetObservable { * data is read until this method is invoked. * <p> */ - public void readHistoricalData() { + private void readHistoricalData() { synchronized (mInstanceLock) { if (!mCanReadHistoricalData || !mHistoricalRecordsChanged) { return; @@ -527,7 +528,7 @@ public class ActivityChooserModel extends DataSetObservable { * @throws IllegalStateException If this method is called before a call to * {@link #readHistoricalData()}. */ - public void persistHistoricalData() { + private void persistHistoricalData() { synchronized (mInstanceLock) { if (!mReadShareHistoryCalled) { throw new IllegalStateException("No preceding call to #readHistoricalData"); @@ -629,6 +630,7 @@ public class ActivityChooserModel extends DataSetObservable { if (added) { mHistoricalRecordsChanged = true; pruneExcessiveHistoricalRecordsLocked(); + persistHistoricalData(); sortActivities(); } return added; diff --git a/core/java/android/widget/ActivityChooserView.java b/core/java/android/widget/ActivityChooserView.java index 5b69aa8..d85f8a4 100644 --- a/core/java/android/widget/ActivityChooserView.java +++ b/core/java/android/widget/ActivityChooserView.java @@ -307,7 +307,6 @@ public class ActivityChooserView extends ViewGroup implements ActivityChooserMod ActivityChooserModel dataModel = mAdapter.getDataModel(); if (dataModel != null) { dataModel.registerObserver(mModelDataSetOberver); - dataModel.readHistoricalData(); } mIsAttachedToWindow = true; } @@ -318,7 +317,6 @@ public class ActivityChooserView extends ViewGroup implements ActivityChooserMod ActivityChooserModel dataModel = mAdapter.getDataModel(); if (dataModel != null) { dataModel.unregisterObserver(mModelDataSetOberver); - dataModel.persistHistoricalData(); } mIsAttachedToWindow = false; } diff --git a/core/java/android/widget/AdapterView.java b/core/java/android/widget/AdapterView.java index 755d4e0..00c75a9 100644 --- a/core/java/android/widget/AdapterView.java +++ b/core/java/android/widget/AdapterView.java @@ -902,15 +902,16 @@ public abstract class AdapterView<T extends Adapter> extends ViewGroup { @Override public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) { - // Add a record for ourselves as well. - AccessibilityEvent record = AccessibilityEvent.obtain(); - record.setSource(this); - // Set the class since it is not populated in #dispatchPopulateAccessibilityEvent - record.setClassName(getClass().getName()); - child.onInitializeAccessibilityEvent(record); - child.dispatchPopulateAccessibilityEvent(record); - event.appendRecord(record); - return true; + if (super.onRequestSendAccessibilityEvent(child, event)) { + // Add a record for ourselves as well. + AccessibilityEvent record = AccessibilityEvent.obtain(); + onInitializeAccessibilityEvent(record); + // Populate with the text of the requesting child. + child.dispatchPopulateAccessibilityEvent(record); + event.appendRecord(record); + return true; + } + return false; } @Override diff --git a/core/java/android/widget/CheckedTextView.java b/core/java/android/widget/CheckedTextView.java index 49616cc..f3a6da7 100644 --- a/core/java/android/widget/CheckedTextView.java +++ b/core/java/android/widget/CheckedTextView.java @@ -39,8 +39,9 @@ public class CheckedTextView extends TextView implements Checkable { private boolean mChecked; private int mCheckMarkResource; private Drawable mCheckMarkDrawable; - private int mBasePaddingRight; + private int mBasePadding; private int mCheckMarkWidth; + private boolean mNeedRequestlayout; private static final int[] CHECKED_STATE_SET = { R.attr.state_checked @@ -123,6 +124,7 @@ public class CheckedTextView extends TextView implements Checkable { mCheckMarkDrawable.setCallback(null); unscheduleDrawable(mCheckMarkDrawable); } + mNeedRequestlayout = (d != mCheckMarkDrawable); if (d != null) { d.setCallback(this); d.setVisible(getVisibility() == VISIBLE, false); @@ -130,19 +132,35 @@ public class CheckedTextView extends TextView implements Checkable { setMinHeight(d.getIntrinsicHeight()); mCheckMarkWidth = d.getIntrinsicWidth(); - mUserPaddingRight = mCheckMarkWidth + mBasePaddingRight; d.setState(getDrawableState()); } else { - mUserPaddingRight = mBasePaddingRight; + mCheckMarkWidth = 0; } mCheckMarkDrawable = d; - requestLayout(); + // Do padding resolution. This will call setPadding() and do a requestLayout() if needed. + resolvePadding(); + } + + /** + * @hide + */ + @Override + protected void resolvePadding() { + super.resolvePadding(); + int newPadding = (mCheckMarkDrawable != null) ? + mCheckMarkWidth + mBasePadding : mBasePadding; + mNeedRequestlayout |= (mPaddingRight != newPadding); + mPaddingRight = newPadding; + if (mNeedRequestlayout) { + requestLayout(); + mNeedRequestlayout = false; + } } @Override public void setPadding(int left, int top, int right, int bottom) { super.setPadding(left, top, right, bottom); - mBasePaddingRight = mUserPaddingRight; + mBasePadding = mPaddingRight; } @Override @@ -167,9 +185,9 @@ public class CheckedTextView extends TextView implements Checkable { int right = getWidth(); checkMarkDrawable.setBounds( - right - mUserPaddingRight, + right - mPaddingRight, y, - right - mUserPaddingRight + mCheckMarkWidth, + right - mPaddingRight + mCheckMarkWidth, y + height); checkMarkDrawable.draw(canvas); } diff --git a/core/java/android/widget/ImageView.java b/core/java/android/widget/ImageView.java index 161b404..299e1ff 100644 --- a/core/java/android/widget/ImageView.java +++ b/core/java/android/widget/ImageView.java @@ -30,14 +30,15 @@ import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; +import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.RemotableViewMethod; import android.view.View; import android.view.ViewDebug; +import android.view.accessibility.AccessibilityEvent; import android.widget.RemoteViews.RemoteView; - /** * Displays an arbitrary image, such as an icon. The ImageView class * can load images from various sources (such as resources or content @@ -208,7 +209,15 @@ public class ImageView extends View { } return false; } - + + @Override + public void onPopulateAccessibilityEvent(AccessibilityEvent event) { + CharSequence contentDescription = getContentDescription(); + if (!TextUtils.isEmpty(contentDescription)) { + event.getText().add(contentDescription); + } + } + /** * Set this to true if you want the ImageView to adjust its bounds * to preserve the aspect ratio of its drawable. diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java index 108ac33..a7324b0 100644 --- a/core/java/android/widget/TextView.java +++ b/core/java/android/widget/TextView.java @@ -329,7 +329,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener private int mTextEditPasteWindowLayout, mTextEditSidePasteWindowLayout; private int mTextEditNoPasteWindowLayout, mTextEditSideNoPasteWindowLayout; - private int mTextEditSuggestionsBottomWindowLayout, mTextEditSuggestionsTopWindowLayout; + private int mTextEditSuggestionsWindowLayout; private int mTextEditSuggestionItemLayout; private SuggestionsPopupWindow mSuggestionsPopupWindow; private SuggestionRangeSpan mSuggestionRangeSpan; @@ -830,12 +830,8 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener mTextEditSideNoPasteWindowLayout = a.getResourceId(attr, 0); break; - case com.android.internal.R.styleable.TextView_textEditSuggestionsBottomWindowLayout: - mTextEditSuggestionsBottomWindowLayout = a.getResourceId(attr, 0); - break; - - case com.android.internal.R.styleable.TextView_textEditSuggestionsTopWindowLayout: - mTextEditSuggestionsTopWindowLayout = a.getResourceId(attr, 0); + case com.android.internal.R.styleable.TextView_textEditSuggestionsWindowLayout: + mTextEditSuggestionsWindowLayout = a.getResourceId(attr, 0); break; case com.android.internal.R.styleable.TextView_textEditSuggestionItemLayout: @@ -8785,9 +8781,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener private static final int MAX_NUMBER_SUGGESTIONS = 5; private static final int NO_SUGGESTIONS = -1; private final PopupWindow mContainer; - private final ViewGroup[] mSuggestionViews = new ViewGroup[2]; - private final int[] mSuggestionViewLayouts = new int[] { - mTextEditSuggestionsBottomWindowLayout, mTextEditSuggestionsTopWindowLayout}; + private ViewGroup mSuggestionViewGroup; private WordIterator mSuggestionWordIterator; private TextAppearanceSpan[] mHighlightSpans = new TextAppearanceSpan[0]; @@ -8809,12 +8803,8 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener int suggestionIndex; // the index of the suggestion inside suggestionSpan } - private ViewGroup getViewGroup(boolean under) { - final int viewIndex = under ? 0 : 1; - ViewGroup viewGroup = mSuggestionViews[viewIndex]; - - if (viewGroup == null) { - final int layout = mSuggestionViewLayouts[viewIndex]; + private void initSuggestionViewGroup() { + if (mSuggestionViewGroup == null) { LayoutInflater inflater = (LayoutInflater) TextView.this.mContext. getSystemService(Context.LAYOUT_INFLATER_SERVICE); @@ -8823,19 +8813,19 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener "Unable to create TextEdit suggestion window inflater"); } - View view = inflater.inflate(layout, null); + View view = inflater.inflate(mTextEditSuggestionsWindowLayout, null); if (! (view instanceof ViewGroup)) { throw new IllegalArgumentException( "Inflated TextEdit suggestion window is not a ViewGroup: " + view); } - viewGroup = (ViewGroup) view; + mSuggestionViewGroup = (ViewGroup) view; // Inflate the suggestion items once and for all. for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) { - View childView = inflater.inflate(mTextEditSuggestionItemLayout, viewGroup, - false); + View childView = inflater.inflate(mTextEditSuggestionItemLayout, + mSuggestionViewGroup, false); if (! (childView instanceof TextView)) { throw new IllegalArgumentException( @@ -8843,14 +8833,12 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } childView.setTag(new SuggestionInfo()); - viewGroup.addView(childView); + mSuggestionViewGroup.addView(childView); childView.setOnClickListener(this); } - mSuggestionViews[viewIndex] = viewGroup; + mContainer.setContentView(mSuggestionViewGroup); } - - return viewGroup; } public void show() { @@ -8861,8 +8849,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener SuggestionSpan[] suggestionSpans = spannable.getSpans(pos, pos, SuggestionSpan.class); final int nbSpans = suggestionSpans.length; - ViewGroup viewGroup = getViewGroup(true); - mContainer.setContentView(viewGroup); + initSuggestionViewGroup(); int totalNbSuggestions = 0; int spanUnionStart = mText.length(); @@ -8878,7 +8865,8 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener String[] suggestions = suggestionSpan.getSuggestions(); int nbSuggestions = suggestions.length; for (int suggestionIndex = 0; suggestionIndex < nbSuggestions; suggestionIndex++) { - TextView textView = (TextView) viewGroup.getChildAt(totalNbSuggestions); + TextView textView = (TextView) mSuggestionViewGroup.getChildAt( + totalNbSuggestions); textView.setText(suggestions[suggestionIndex]); SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); suggestionInfo.spanStart = spanStart; @@ -8897,7 +8885,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener if (totalNbSuggestions == 0) { // TODO Replace by final text, use a dedicated layout, add a fade out timer... - TextView textView = (TextView) viewGroup.getChildAt(0); + TextView textView = (TextView) mSuggestionViewGroup.getChildAt(0); textView.setText("No suggestions available"); SuggestionInfo suggestionInfo = (SuggestionInfo) textView.getTag(); suggestionInfo.spanStart = NO_SUGGESTIONS; @@ -8908,17 +8896,24 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); for (int i = 0; i < totalNbSuggestions; i++) { - final TextView textView = (TextView) viewGroup.getChildAt(i); + final TextView textView = (TextView) mSuggestionViewGroup.getChildAt(i); highlightTextDifferences(textView, spanUnionStart, spanUnionEnd); } } - for (int i = 0; i < MAX_NUMBER_SUGGESTIONS; i++) { - viewGroup.getChildAt(i).setVisibility(i < totalNbSuggestions ? VISIBLE : GONE); + for (int i = 0; i < totalNbSuggestions; i++) { + mSuggestionViewGroup.getChildAt(i).setVisibility(VISIBLE); + } + for (int i = totalNbSuggestions; i < MAX_NUMBER_SUGGESTIONS; i++) { + mSuggestionViewGroup.getChildAt(i).setVisibility(GONE); } - final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); - viewGroup.measure(size, size); + final DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics(); + final int screenWidth = displayMetrics.widthPixels; + final int screenHeight = displayMetrics.heightPixels; + mSuggestionViewGroup.measure( + View.MeasureSpec.makeMeasureSpec(screenWidth, View.MeasureSpec.AT_MOST), + View.MeasureSpec.makeMeasureSpec(screenHeight, View.MeasureSpec.AT_MOST)); positionAtCursor(); } @@ -9171,23 +9166,12 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener // Vertical clipping if (coords[1] + height > screenHeight) { - // Try to position above current line instead - // TODO use top layout instead, reverse suggestion order, - // try full screen vertical down if it still does not fit. TBD with designers. - - // Update dimensions from new view - contentView = mContainer.getContentView(); - width = contentView.getMeasuredWidth(); - height = contentView.getMeasuredHeight(); - - final int lineTop = mLayout.getLineTop(line); - final int lineHeight = lineBottom - lineTop; - coords[1] -= height + lineHeight; + coords[1] = screenHeight - height; } // Horizontal clipping - coords[0] = Math.max(0, coords[0]); coords[0] = Math.min(displayMetrics.widthPixels - width, coords[0]); + coords[0] = Math.max(0, coords[0]); mContainer.showAtLocation(TextView.this, Gravity.NO_GRAVITY, coords[0], coords[1]); } diff --git a/core/java/com/android/internal/app/AlertController.java b/core/java/com/android/internal/app/AlertController.java index 8d6caa1..2061c90 100644 --- a/core/java/com/android/internal/app/AlertController.java +++ b/core/java/com/android/internal/app/AlertController.java @@ -438,7 +438,7 @@ public class AlertController { LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); - topPanel.addView(mCustomTitleView, lp); + topPanel.addView(mCustomTitleView, 0, lp); // Hide the title template View titleTemplate = mWindow.findViewById(R.id.title_template); diff --git a/core/java/com/android/internal/statusbar/IStatusBarService.aidl b/core/java/com/android/internal/statusbar/IStatusBarService.aidl index a9e5057..07430e7 100644 --- a/core/java/com/android/internal/statusbar/IStatusBarService.aidl +++ b/core/java/com/android/internal/statusbar/IStatusBarService.aidl @@ -27,7 +27,7 @@ interface IStatusBarService void expand(); void collapse(); void disable(int what, IBinder token, String pkg); - void setIcon(String slot, String iconPackage, int iconId, int iconLevel); + void setIcon(String slot, String iconPackage, int iconId, int iconLevel, String contentDescription); void setIconVisibility(String slot, boolean visible); void removeIcon(String slot); void topAppWindowChanged(boolean menuVisible); diff --git a/core/java/com/android/internal/statusbar/StatusBarIcon.java b/core/java/com/android/internal/statusbar/StatusBarIcon.java index ae2cac2..3333c82 100644 --- a/core/java/com/android/internal/statusbar/StatusBarIcon.java +++ b/core/java/com/android/internal/statusbar/StatusBarIcon.java @@ -19,42 +19,35 @@ package com.android.internal.statusbar; import android.os.Parcel; import android.os.Parcelable; -/** - * @hide - */ public class StatusBarIcon implements Parcelable { public String iconPackage; public int iconId; public int iconLevel; public boolean visible = true; public int number; + public CharSequence contentDescription; - private StatusBarIcon() { - } - - public StatusBarIcon(String iconPackage, int iconId, int iconLevel) { - this.iconPackage = iconPackage; - this.iconId = iconId; - this.iconLevel = iconLevel; - } - - public StatusBarIcon(String iconPackage, int iconId, int iconLevel, int number) { + public StatusBarIcon(String iconPackage, int iconId, int iconLevel, int number, + CharSequence contentDescription) { this.iconPackage = iconPackage; this.iconId = iconId; this.iconLevel = iconLevel; this.number = number; + this.contentDescription = contentDescription; } + @Override public String toString() { return "StatusBarIcon(pkg=" + this.iconPackage + " id=0x" + Integer.toHexString(this.iconId) + " level=" + this.iconLevel + " visible=" + visible + " num=" + this.number + " )"; } + @Override public StatusBarIcon clone() { - StatusBarIcon that = new StatusBarIcon(this.iconPackage, this.iconId, this.iconLevel); + StatusBarIcon that = new StatusBarIcon(this.iconPackage, this.iconId, this.iconLevel, + this.number, this.contentDescription); that.visible = this.visible; - that.number = this.number; return that; } @@ -71,6 +64,7 @@ public class StatusBarIcon implements Parcelable { this.iconLevel = in.readInt(); this.visible = in.readInt() != 0; this.number = in.readInt(); + this.contentDescription = in.readCharSequence(); } public void writeToParcel(Parcel out, int flags) { @@ -79,6 +73,7 @@ public class StatusBarIcon implements Parcelable { out.writeInt(this.iconLevel); out.writeInt(this.visible ? 1 : 0); out.writeInt(this.number); + out.writeCharSequence(this.contentDescription); } public int describeContents() { diff --git a/core/java/com/android/internal/textservice/ISpellCheckerService.aidl b/core/java/com/android/internal/textservice/ISpellCheckerService.aidl new file mode 100644 index 0000000..ff00492 --- /dev/null +++ b/core/java/com/android/internal/textservice/ISpellCheckerService.aidl @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.internal.textservice; + +import com.android.internal.textservice.ISpellCheckerSession; +import com.android.internal.textservice.ISpellCheckerSessionListener; + +/** + * Public interface to the global spell checker. + * @hide + */ +interface ISpellCheckerService { + ISpellCheckerSession getISpellCheckerSession( + String locale, ISpellCheckerSessionListener listener); +} diff --git a/core/java/com/android/internal/textservice/ISpellCheckerSession.aidl b/core/java/com/android/internal/textservice/ISpellCheckerSession.aidl new file mode 100644 index 0000000..79e43510c0 --- /dev/null +++ b/core/java/com/android/internal/textservice/ISpellCheckerSession.aidl @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.internal.textservice; + +import android.view.textservice.TextInfo; + +/** + * @hide + */ +oneway interface ISpellCheckerSession { + void getSuggestionsMultiple( + in TextInfo[] textInfos, int suggestionsLimit, boolean multipleWords); + void cancel(); +} diff --git a/core/java/com/android/internal/textservice/ISpellCheckerSessionListener.aidl b/core/java/com/android/internal/textservice/ISpellCheckerSessionListener.aidl new file mode 100644 index 0000000..796b06e --- /dev/null +++ b/core/java/com/android/internal/textservice/ISpellCheckerSessionListener.aidl @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.internal.textservice; + +import android.view.textservice.SuggestionsInfo; + +/** + * @hide + */ +oneway interface ISpellCheckerSessionListener { + void onGetSuggestions(in SuggestionsInfo[] results); +} diff --git a/core/java/com/android/internal/textservice/ITextServicesManager.aidl b/core/java/com/android/internal/textservice/ITextServicesManager.aidl new file mode 100644 index 0000000..2a045e3 --- /dev/null +++ b/core/java/com/android/internal/textservice/ITextServicesManager.aidl @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.internal.textservice; + +import com.android.internal.textservice.ISpellCheckerSessionListener; +import com.android.internal.textservice.ITextServicesSessionListener; + +import android.content.ComponentName; +import android.view.textservice.SpellCheckerInfo; + +/** + * Interface to the text service manager. + * @hide + */ +interface ITextServicesManager { + SpellCheckerInfo getCurrentSpellChecker(String locale); + oneway void getSpellCheckerService(in SpellCheckerInfo info, in String locale, + in ITextServicesSessionListener tsListener, + in ISpellCheckerSessionListener scListener); + oneway void finishSpellCheckerService(in ISpellCheckerSessionListener listener); + SpellCheckerInfo[] getEnabledSpellCheckers(); +} diff --git a/core/java/com/android/internal/textservice/ITextServicesSessionListener.aidl b/core/java/com/android/internal/textservice/ITextServicesSessionListener.aidl new file mode 100644 index 0000000..ecb6cd0 --- /dev/null +++ b/core/java/com/android/internal/textservice/ITextServicesSessionListener.aidl @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2011 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.internal.textservice; + +import com.android.internal.textservice.ISpellCheckerSession; + +import android.view.textservice.SpellCheckerInfo; + +/** + * Interface to the text service session. + * @hide + */ +interface ITextServicesSessionListener { + oneway void onServiceConnected(in ISpellCheckerSession spellCheckerSession); +} diff --git a/core/java/com/android/internal/util/Protocol.java b/core/java/com/android/internal/util/Protocol.java index 69b80d9..9ecd29f 100644 --- a/core/java/com/android/internal/util/Protocol.java +++ b/core/java/com/android/internal/util/Protocol.java @@ -41,6 +41,9 @@ public class Protocol { /** Non system protocols */ public static final int BASE_WIFI = 0x00020000; public static final int BASE_WIFI_WATCHDOG = 0x00021000; + public static final int BASE_WIFI_P2P_MANAGER = 0x00022000; + public static final int BASE_WIFI_P2P_SERVICE = 0x00023000; + public static final int BASE_WIFI_MONITOR = 0x00024000; public static final int BASE_DHCP = 0x00030000; public static final int BASE_DATA_CONNECTION = 0x00040000; public static final int BASE_DATA_CONNECTION_AC = 0x00041000; diff --git a/core/java/com/android/internal/view/menu/MenuBuilder.java b/core/java/com/android/internal/view/menu/MenuBuilder.java index 164d581..159b3da 100644 --- a/core/java/com/android/internal/view/menu/MenuBuilder.java +++ b/core/java/com/android/internal/view/menu/MenuBuilder.java @@ -50,6 +50,8 @@ public class MenuBuilder implements Menu { private static final String LOGTAG = "MenuBuilder"; private static final String PRESENTER_KEY = "android:menu:presenters"; + private static final String ACTION_VIEW_STATES_KEY = "android:menu:actionviewstates"; + private static final String EXPANDED_ACTION_VIEW_ID = "android:menu:expandedactionview"; private static final int[] sCategoryToOrder = new int[] { 1, /* No category */ @@ -308,6 +310,67 @@ public class MenuBuilder implements Menu { dispatchRestoreInstanceState(state); } + public void saveActionViewStates(Bundle outStates) { + SparseArray<Parcelable> viewStates = null; + + final int itemCount = size(); + for (int i = 0; i < itemCount; i++) { + final MenuItem item = getItem(i); + final View v = item.getActionView(); + if (v != null && v.getId() != View.NO_ID) { + if (viewStates == null) { + viewStates = new SparseArray<Parcelable>(); + } + v.saveHierarchyState(viewStates); + if (item.isActionViewExpanded()) { + outStates.putInt(EXPANDED_ACTION_VIEW_ID, item.getItemId()); + } + } + if (item.hasSubMenu()) { + final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu(); + subMenu.saveActionViewStates(outStates); + } + } + + if (viewStates != null) { + outStates.putSparseParcelableArray(getActionViewStatesKey(), viewStates); + } + } + + public void restoreActionViewStates(Bundle states) { + if (states == null) { + return; + } + + SparseArray<Parcelable> viewStates = states.getSparseParcelableArray( + getActionViewStatesKey()); + + final int itemCount = size(); + for (int i = 0; i < itemCount; i++) { + final MenuItem item = getItem(i); + final View v = item.getActionView(); + if (v != null && v.getId() != View.NO_ID) { + v.restoreHierarchyState(viewStates); + } + if (item.hasSubMenu()) { + final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu(); + subMenu.restoreActionViewStates(states); + } + } + + final int expandedId = states.getInt(EXPANDED_ACTION_VIEW_ID); + if (expandedId > 0) { + MenuItem itemToExpand = findItem(expandedId); + if (itemToExpand != null) { + itemToExpand.expandActionView(); + } + } + } + + protected String getActionViewStatesKey() { + return ACTION_VIEW_STATES_KEY; + } + public void setCallback(Callback cb) { mCallback = cb; } diff --git a/core/java/com/android/internal/view/menu/MenuItemImpl.java b/core/java/com/android/internal/view/menu/MenuItemImpl.java index 541d101..b0a002d 100644 --- a/core/java/com/android/internal/view/menu/MenuItemImpl.java +++ b/core/java/com/android/internal/view/menu/MenuItemImpl.java @@ -553,6 +553,9 @@ public final class MenuItemImpl implements MenuItem { public MenuItem setActionView(View view) { mActionView = view; mActionProvider = null; + if (view != null && view.getId() == View.NO_ID && mId > 0) { + view.setId(mId); + } mMenu.onItemActionRequestChanged(this); return this; } diff --git a/core/java/com/android/internal/view/menu/SubMenuBuilder.java b/core/java/com/android/internal/view/menu/SubMenuBuilder.java index fb1cd5e..92acf8c 100644 --- a/core/java/com/android/internal/view/menu/SubMenuBuilder.java +++ b/core/java/com/android/internal/view/menu/SubMenuBuilder.java @@ -121,4 +121,13 @@ public class SubMenuBuilder extends MenuBuilder implements SubMenu { public boolean collapseItemActionView(MenuItemImpl item) { return mParentMenu.collapseItemActionView(item); } + + @Override + public String getActionViewStatesKey() { + final int itemId = mItem != null ? mItem.getItemId() : 0; + if (itemId == 0) { + return null; + } + return super.getActionViewStatesKey() + ":" + itemId; + } } diff --git a/core/java/com/android/internal/widget/ActionBarView.java b/core/java/com/android/internal/widget/ActionBarView.java index e03858b..09262e0 100644 --- a/core/java/com/android/internal/widget/ActionBarView.java +++ b/core/java/com/android/internal/widget/ActionBarView.java @@ -42,6 +42,7 @@ import android.text.TextUtils; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; +import android.view.CollapsibleActionView; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; @@ -285,8 +286,11 @@ public class ActionBarView extends AbsActionBarView { public void setSplitActionBar(boolean splitActionBar) { if (mSplitActionBar != splitActionBar) { if (mMenuView != null) { + final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); + if (oldParent != null) { + oldParent.removeView(mMenuView); + } if (splitActionBar) { - removeView(mMenuView); if (mSplitView != null) { mSplitView.addView(mMenuView); } @@ -332,7 +336,10 @@ public class ActionBarView extends AbsActionBarView { MenuBuilder builder = (MenuBuilder) menu; mOptionsMenu = builder; if (mMenuView != null) { - removeView(mMenuView); + final ViewGroup oldParent = (ViewGroup) mMenuView.getParent(); + if (oldParent != null) { + oldParent.removeView(mMenuView); + } } if (mActionMenuPresenter == null) { mActionMenuPresenter = new ActionMenuPresenter(); @@ -351,6 +358,10 @@ public class ActionBarView extends AbsActionBarView { builder.addMenuPresenter(mActionMenuPresenter); builder.addMenuPresenter(mExpandedMenuPresenter); menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); + final ViewGroup oldParent = (ViewGroup) menuView.getParent(); + if (oldParent != null && oldParent != this) { + oldParent.removeView(menuView); + } addView(menuView, layoutParams); } else { mActionMenuPresenter.setExpandedActionViewsExclusive(false); @@ -365,6 +376,10 @@ public class ActionBarView extends AbsActionBarView { builder.addMenuPresenter(mExpandedMenuPresenter); menuView = (ActionMenuView) mActionMenuPresenter.getMenuView(this); if (mSplitView != null) { + final ViewGroup oldParent = (ViewGroup) menuView.getParent(); + if (oldParent != null && oldParent != mSplitView) { + oldParent.removeView(menuView); + } mSplitView.addView(menuView, layoutParams); } else { // We'll add this later if we missed it this time. @@ -1304,6 +1319,10 @@ public class ActionBarView extends AbsActionBarView { if (mCustomNavView != null) mCustomNavView.setVisibility(GONE); requestLayout(); item.setActionViewExpanded(true); + + if (mExpandedActionView instanceof CollapsibleActionView) { + ((CollapsibleActionView) mExpandedActionView).onActionViewExpanded(); + } return true; } @@ -1330,11 +1349,16 @@ public class ActionBarView extends AbsActionBarView { if (mCustomNavView != null && (mDisplayOptions & ActionBar.DISPLAY_SHOW_CUSTOM) != 0) { mCustomNavView.setVisibility(VISIBLE); } + View collapsedView = mExpandedActionView; mExpandedActionView = null; mExpandedHomeLayout.setIcon(null); mCurrentExpandedItem = null; requestLayout(); item.setActionViewExpanded(false); + + if (collapsedView instanceof CollapsibleActionView) { + ((CollapsibleActionView) collapsedView).onActionViewCollapsed(); + } return true; } diff --git a/core/jni/android_media_AudioRecord.cpp b/core/jni/android_media_AudioRecord.cpp index 50d9ca1..9be3779 100644 --- a/core/jni/android_media_AudioRecord.cpp +++ b/core/jni/android_media_AudioRecord.cpp @@ -127,7 +127,7 @@ static void recorderCallback(int event, void* user, void *info) { static int android_media_AudioRecord_setup(JNIEnv *env, jobject thiz, jobject weak_this, jint source, jint sampleRateInHertz, jint channels, - jint audioFormat, jint buffSizeInBytes) + jint audioFormat, jint buffSizeInBytes, jintArray jSession) { //LOGV(">> Entering android_media_AudioRecord_setup"); //LOGV("sampleRate=%d, audioFormat=%d, channels=%x, buffSizeInBytes=%d", @@ -162,6 +162,20 @@ android_media_AudioRecord_setup(JNIEnv *env, jobject thiz, jobject weak_this, return AUDIORECORD_ERROR_SETUP_INVALIDSOURCE; } + if (jSession == NULL) { + LOGE("Error creating AudioRecord: invalid session ID pointer"); + return AUDIORECORD_ERROR; + } + + jint* nSession = (jint *) env->GetPrimitiveArrayCritical(jSession, NULL); + if (nSession == NULL) { + LOGE("Error creating AudioRecord: Error retrieving session id pointer"); + return AUDIORECORD_ERROR; + } + int sessionId = nSession[0]; + env->ReleasePrimitiveArrayCritical(jSession, nSession, 0); + nSession = NULL; + audiorecord_callback_cookie *lpCallbackData = NULL; AudioRecord* lpRecorder = NULL; @@ -193,13 +207,24 @@ android_media_AudioRecord_setup(JNIEnv *env, jobject thiz, jobject weak_this, recorderCallback,// callback_t lpCallbackData,// void* user 0, // notificationFrames, - true); // threadCanCallJava) + true, // threadCanCallJava) + sessionId); if(lpRecorder->initCheck() != NO_ERROR) { LOGE("Error creating AudioRecord instance: initialization check failed."); goto native_init_failure; } + nSession = (jint *) env->GetPrimitiveArrayCritical(jSession, NULL); + if (nSession == NULL) { + LOGE("Error creating AudioRecord: Error retrieving session id pointer"); + goto native_init_failure; + } + // read the audio session ID back from AudioTrack in case a new session was created during set() + nSession[0] = lpRecorder->getSessionId(); + env->ReleasePrimitiveArrayCritical(jSession, nSession, 0); + nSession = NULL; + // save our newly created C++ AudioRecord in the "nativeRecorderInJavaObj" field // of the Java object env->SetIntField(thiz, javaAudioRecordFields.nativeRecorderInJavaObj, (int)lpRecorder); @@ -485,7 +510,7 @@ static JNINativeMethod gMethods[] = { // name, signature, funcPtr {"native_start", "()I", (void *)android_media_AudioRecord_start}, {"native_stop", "()V", (void *)android_media_AudioRecord_stop}, - {"native_setup", "(Ljava/lang/Object;IIIII)I", + {"native_setup", "(Ljava/lang/Object;IIIII[I)I", (void *)android_media_AudioRecord_setup}, {"native_finalize", "()V", (void *)android_media_AudioRecord_finalize}, {"native_release", "()V", (void *)android_media_AudioRecord_release}, diff --git a/core/jni/android_net_wifi_Wifi.cpp b/core/jni/android_net_wifi_Wifi.cpp index e930c5c..3cbd912 100644 --- a/core/jni/android_net_wifi_Wifi.cpp +++ b/core/jni/android_net_wifi_Wifi.cpp @@ -28,6 +28,9 @@ #define WIFI_PKG_NAME "android/net/wifi/WifiNative" #define BUF_SIZE 256 +//TODO: This file can be refactored to push a lot of the functionality to java +//with just a few JNI calls - doBoolean/doInt/doString + namespace android { static jboolean sScanModeActive = false; @@ -315,26 +318,56 @@ static jboolean android_net_wifi_stopDriverCommand(JNIEnv* env, jobject) return doBooleanCommand("OK", "DRIVER STOP"); } -static jboolean android_net_wifi_startPacketFiltering(JNIEnv* env, jobject) +/* + Multicast filtering rules work as follows: + + The driver can filter multicast (v4 and/or v6) and broadcast packets when in + a power optimized mode (typically when screen goes off). + + In order to prevent the driver from filtering the multicast/broadcast packets, we have to + add a DRIVER RXFILTER-ADD rule followed by DRIVER RXFILTER-START to make the rule effective + + DRIVER RXFILTER-ADD Num + where Num = 0 - Unicast, 1 - Broadcast, 2 - Mutil4 or 3 - Multi6 + + and DRIVER RXFILTER-START + + In order to stop the usage of these rules, we do + + DRIVER RXFILTER-STOP + DRIVER RXFILTER-REMOVE Num + where Num is as described for RXFILTER-ADD + + The SETSUSPENDOPT driver command overrides the filtering rules +*/ + +static jboolean android_net_wifi_startMultiV4Filtering(JNIEnv* env, jobject) { - return doBooleanCommand("OK", "DRIVER RXFILTER-ADD 0") - && doBooleanCommand("OK", "DRIVER RXFILTER-ADD 1") - && doBooleanCommand("OK", "DRIVER RXFILTER-ADD 3") + return doBooleanCommand("OK", "DRIVER RXFILTER-STOP") + && doBooleanCommand("OK", "DRIVER RXFILTER-REMOVE 2") && doBooleanCommand("OK", "DRIVER RXFILTER-START"); } -static jboolean android_net_wifi_stopPacketFiltering(JNIEnv* env, jobject) +static jboolean android_net_wifi_stopMultiV4Filtering(JNIEnv* env, jobject) { - jboolean result = doBooleanCommand("OK", "DRIVER RXFILTER-STOP"); - if (result) { - (void)doBooleanCommand("OK", "DRIVER RXFILTER-REMOVE 3"); - (void)doBooleanCommand("OK", "DRIVER RXFILTER-REMOVE 1"); - (void)doBooleanCommand("OK", "DRIVER RXFILTER-REMOVE 0"); - } + return doBooleanCommand("OK", "DRIVER RXFILTER-ADD 2") + && doBooleanCommand("OK", "DRIVER RXFILTER-START"); +} - return result; +static jboolean android_net_wifi_startMultiV6Filtering(JNIEnv* env, jobject) +{ + return doBooleanCommand("OK", "DRIVER RXFILTER-STOP") + && doBooleanCommand("OK", "DRIVER RXFILTER-REMOVE 3") + && doBooleanCommand("OK", "DRIVER RXFILTER-START"); +} + +static jboolean android_net_wifi_stopMultiV6Filtering(JNIEnv* env, jobject) +{ + return doBooleanCommand("OK", "DRIVER RXFILTER-ADD 3") + && doBooleanCommand("OK", "DRIVER RXFILTER-START"); } + static jint android_net_wifi_getRssiHelper(const char *cmd) { char reply[BUF_SIZE]; @@ -507,6 +540,35 @@ static void android_net_wifi_setScanIntervalCommand(JNIEnv* env, jobject, jint s } +static jboolean android_net_wifi_doBooleanCommand(JNIEnv* env, jobject, jstring javaCommand) +{ + ScopedUtfChars command(env, javaCommand); + if (command.c_str() == NULL) { + return JNI_FALSE; + } + return doBooleanCommand("OK", "%s", command.c_str()); +} + +static jint android_net_wifi_doIntCommand(JNIEnv* env, jobject, jstring javaCommand) +{ + ScopedUtfChars command(env, javaCommand); + if (command.c_str() == NULL) { + return -1; + } + return doIntCommand("%s", command.c_str()); +} + +static jstring android_net_wifi_doStringCommand(JNIEnv* env, jobject, jstring javaCommand) +{ + ScopedUtfChars command(env, javaCommand); + if (command.c_str() == NULL) { + return NULL; + } + return doStringCommand(env, "%s", command.c_str()); +} + + + // ---------------------------------------------------------------------------- /* @@ -545,8 +607,10 @@ static JNINativeMethod gWifiMethods[] = { { "setScanModeCommand", "(Z)Z", (void*) android_net_wifi_setScanModeCommand }, { "startDriverCommand", "()Z", (void*) android_net_wifi_startDriverCommand }, { "stopDriverCommand", "()Z", (void*) android_net_wifi_stopDriverCommand }, - { "startPacketFiltering", "()Z", (void*) android_net_wifi_startPacketFiltering }, - { "stopPacketFiltering", "()Z", (void*) android_net_wifi_stopPacketFiltering }, + { "startFilteringMulticastV4Packets", "()Z", (void*) android_net_wifi_startMultiV4Filtering}, + { "stopFilteringMulticastV4Packets", "()Z", (void*) android_net_wifi_stopMultiV4Filtering}, + { "startFilteringMulticastV6Packets", "()Z", (void*) android_net_wifi_startMultiV6Filtering}, + { "stopFilteringMulticastV6Packets", "()Z", (void*) android_net_wifi_stopMultiV6Filtering}, { "setPowerModeCommand", "(I)Z", (void*) android_net_wifi_setPowerModeCommand }, { "getPowerModeCommand", "()I", (void*) android_net_wifi_getPowerModeCommand }, { "setBandCommand", "(I)Z", (void*) android_net_wifi_setBandCommand}, @@ -576,6 +640,9 @@ static JNINativeMethod gWifiMethods[] = { (void*) android_net_wifi_setCountryCodeCommand}, { "enableBackgroundScanCommand", "(Z)V", (void*) android_net_wifi_enableBackgroundScanCommand}, { "setScanIntervalCommand", "(I)V", (void*) android_net_wifi_setScanIntervalCommand}, + { "doBooleanCommand", "(Ljava/lang/String;)Z", (void*) android_net_wifi_doBooleanCommand}, + { "doIntCommand", "(Ljava/lang/String;)I", (void*) android_net_wifi_doIntCommand}, + { "doStringCommand", "(Ljava/lang/String;)Ljava/lang/String;", (void*) android_net_wifi_doStringCommand}, }; int register_android_net_wifi_WifiManager(JNIEnv* env) diff --git a/core/jni/android_view_GLES20Canvas.cpp b/core/jni/android_view_GLES20Canvas.cpp index b0c2f2c..b06de9d 100644 --- a/core/jni/android_view_GLES20Canvas.cpp +++ b/core/jni/android_view_GLES20Canvas.cpp @@ -576,18 +576,18 @@ static void android_view_GLES20Canvas_drawTextRun(JNIEnv* env, jobject clazz, // ---------------------------------------------------------------------------- static DisplayList* android_view_GLES20Canvas_getDisplayList(JNIEnv* env, - jobject clazz, DisplayListRenderer* renderer) { - return renderer->getDisplayList(); + jobject clazz, DisplayListRenderer* renderer, DisplayList* displayList) { + return renderer->getDisplayList(displayList); +} + +static OpenGLRenderer* android_view_GLES20Canvas_createDisplayListRenderer(JNIEnv* env, + jobject clazz) { + return new DisplayListRenderer; } -static OpenGLRenderer* android_view_GLES20Canvas_getDisplayListRenderer(JNIEnv* env, +static void android_view_GLES20Canvas_resetDisplayListRenderer(JNIEnv* env, jobject clazz, DisplayListRenderer* renderer) { - if (renderer == NULL) { - renderer = new DisplayListRenderer; - } else { - renderer->reset(); - } - return renderer; + renderer->reset(); } static void android_view_GLES20Canvas_destroyDisplayList(JNIEnv* env, @@ -812,9 +812,10 @@ static JNINativeMethod gMethods[] = { { "nGetClipBounds", "(ILandroid/graphics/Rect;)Z", (void*) android_view_GLES20Canvas_getClipBounds }, - { "nGetDisplayList", "(I)I", (void*) android_view_GLES20Canvas_getDisplayList }, + { "nGetDisplayList", "(II)I", (void*) android_view_GLES20Canvas_getDisplayList }, { "nDestroyDisplayList", "(I)V", (void*) android_view_GLES20Canvas_destroyDisplayList }, - { "nGetDisplayListRenderer", "(I)I", (void*) android_view_GLES20Canvas_getDisplayListRenderer }, + { "nCreateDisplayListRenderer", "()I", (void*) android_view_GLES20Canvas_createDisplayListRenderer }, + { "nResetDisplayListRenderer", "(I)V", (void*) android_view_GLES20Canvas_resetDisplayListRenderer }, { "nDrawDisplayList", "(IIIILandroid/graphics/Rect;)Z", (void*) android_view_GLES20Canvas_drawDisplayList }, { "nOutputDisplayList", "(II)V", (void*) android_view_GLES20Canvas_outputDisplayList }, diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml index 103a326..91003d1 100644 --- a/core/res/AndroidManifest.xml +++ b/core/res/AndroidManifest.xml @@ -1120,6 +1120,13 @@ android:description="@string/permdesc_bindInputMethod" android:protectionLevel="signature" /> + <!-- Must be required by a TextService (e.g. SpellCheckerService) + to ensure that only the system can bind to it. --> + <permission android:name="android.permission.BIND_TEXT_SERVICE" + android:label="@string/permlab_bindTextService" + android:description="@string/permdesc_bindTextService" + android:protectionLevel="signature" /> + <!-- Must be required by a {@link android.service.wallpaper.WallpaperService}, to ensure that only the system can bind to it. --> <permission android:name="android.permission.BIND_WALLPAPER" @@ -1197,7 +1204,7 @@ <permission android:name="android.permission.READ_FRAME_BUFFER" android:label="@string/permlab_readFrameBuffer" android:description="@string/permdesc_readFrameBuffer" - android:protectionLevel="signature" /> + android:protectionLevel="signatureOrSystem" /> <!-- Required to be able to disable the device (very dangerous!). --> <permission android:name="android.permission.BRICK" diff --git a/core/res/res/anim/screen_rotate_minus_90_enter.xml b/core/res/res/anim/screen_rotate_minus_90_enter.xml index 30518e0..61aa72a 100644 --- a/core/res/res/anim/screen_rotate_minus_90_enter.xml +++ b/core/res/res/anim/screen_rotate_minus_90_enter.xml @@ -19,11 +19,6 @@ <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false"> - <scale android:fromXScale="100%p" android:toXScale="100%" - android:fromYScale="100%p" android:toYScale="100%" - android:pivotX="50%" android:pivotY="50%" - android:interpolator="@interpolator/decelerate_quint" - android:duration="@android:integer/config_mediumAnimTime" /> <rotate android:fromDegrees="-90" android:toDegrees="0" android:pivotX="50%" android:pivotY="50%" android:interpolator="@interpolator/decelerate_quint" diff --git a/core/res/res/anim/screen_rotate_plus_90_enter.xml b/core/res/res/anim/screen_rotate_plus_90_enter.xml index 20943c8..53b0ccd 100644 --- a/core/res/res/anim/screen_rotate_plus_90_enter.xml +++ b/core/res/res/anim/screen_rotate_plus_90_enter.xml @@ -19,11 +19,6 @@ <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false"> - <scale android:fromXScale="100%p" android:toXScale="100%" - android:fromYScale="100%p" android:toYScale="100%" - android:pivotX="50%" android:pivotY="50%" - android:interpolator="@interpolator/decelerate_quint" - android:duration="@android:integer/config_mediumAnimTime" /> <rotate android:fromDegrees="90" android:toDegrees="0" android:pivotX="50%" android:pivotY="50%" android:interpolator="@interpolator/decelerate_quint" diff --git a/core/res/res/drawable-hdpi/text_edit_suggestions_top_window.9.png b/core/res/res/drawable-hdpi/text_edit_suggestions_top_window.9.png Binary files differdeleted file mode 100644 index ff6b34a..0000000 --- a/core/res/res/drawable-hdpi/text_edit_suggestions_top_window.9.png +++ /dev/null diff --git a/core/res/res/drawable-hdpi/text_edit_suggestions_bottom_window.9.png b/core/res/res/drawable-hdpi/text_edit_suggestions_window.9.png Binary files differindex c97514f..c97514f 100644 --- a/core/res/res/drawable-hdpi/text_edit_suggestions_bottom_window.9.png +++ b/core/res/res/drawable-hdpi/text_edit_suggestions_window.9.png diff --git a/core/res/res/drawable-mdpi/text_edit_suggestions_top_window.9.png b/core/res/res/drawable-mdpi/text_edit_suggestions_top_window.9.png Binary files differdeleted file mode 100644 index 41886eb..0000000 --- a/core/res/res/drawable-mdpi/text_edit_suggestions_top_window.9.png +++ /dev/null diff --git a/core/res/res/drawable-mdpi/text_edit_suggestions_bottom_window.9.png b/core/res/res/drawable-mdpi/text_edit_suggestions_window.9.png Binary files differindex 88be6e1..88be6e1 100644 --- a/core/res/res/drawable-mdpi/text_edit_suggestions_bottom_window.9.png +++ b/core/res/res/drawable-mdpi/text_edit_suggestions_window.9.png diff --git a/core/res/res/layout/text_edit_suggestion_item.xml b/core/res/res/layout/text_edit_suggestion_item.xml index ef537d9..082c5ec 100644 --- a/core/res/res/layout/text_edit_suggestion_item.xml +++ b/core/res/res/layout/text_edit_suggestion_item.xml @@ -22,6 +22,8 @@ android:paddingTop="8dip" android:paddingBottom="8dip" android:layout_gravity="left|center_vertical" + android:singleLine="true" + android:ellipsize="marquee" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@android:color/dim_foreground_light" /> diff --git a/core/res/res/layout/text_edit_suggestions_top_window.xml b/core/res/res/layout/text_edit_suggestions_window.xml index 67faa37..824025e 100644 --- a/core/res/res/layout/text_edit_suggestions_top_window.xml +++ b/core/res/res/layout/text_edit_suggestions_window.xml @@ -18,6 +18,6 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" - android:background="@android:drawable/text_edit_suggestions_top_window"> + android:background="@android:drawable/text_edit_suggestions_window"> </LinearLayout> diff --git a/core/res/res/layout/text_edit_suggestions_bottom_window.xml b/core/res/res/layout/wifi_p2p_go_negotiation_request_alert.xml index 588bfbd..41ca657 100644 --- a/core/res/res/layout/text_edit_suggestions_bottom_window.xml +++ b/core/res/res/layout/wifi_p2p_go_negotiation_request_alert.xml @@ -4,9 +4,9 @@ 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. @@ -16,8 +16,11 @@ <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:orientation="vertical" - android:background="@android:drawable/text_edit_suggestions_bottom_window"> + android:layout_height="wrap_content"> + <EditText android:id="@+id/wifi_p2p_wps_pin" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:inputType="textPassword" + /> </LinearLayout> diff --git a/core/res/res/values/attrs.xml b/core/res/res/values/attrs.xml index 082284a..7d7aea9 100755 --- a/core/res/res/values/attrs.xml +++ b/core/res/res/values/attrs.xml @@ -713,10 +713,7 @@ <!-- Layout of a the view that is used to create the text suggestions popup window in an EditText. This window will be displayed below the text line. --> - <attr name="textEditSuggestionsBottomWindowLayout" format="reference" /> - <!-- Same as textEditSuggestionsBottomWindowLayout, but used when the popup is displayed - above the current line of text instead of below. --> - <attr name="textEditSuggestionsTopWindowLayout" format="reference" /> + <attr name="textEditSuggestionsWindowLayout" format="reference" /> <!-- Layout of the TextView item that will populate the suggestion popup window. --> <attr name="textEditSuggestionItemLayout" format="reference" /> @@ -3082,10 +3079,7 @@ <!-- Layout of a the view that is used to create the text suggestions popup window in an EditText. This window will be displayed below the text line. --> - <attr name="textEditSuggestionsBottomWindowLayout" /> - <!-- Same as textEditSuggestionsBottomWindowLayout, but used when the popup is displayed - above the current line of text instead of below. --> - <attr name="textEditSuggestionsTopWindowLayout" /> + <attr name="textEditSuggestionsWindowLayout" /> <!-- Layout of the TextView item that will populate the suggestion popup window. --> <attr name="textEditSuggestionItemLayout" /> diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml index 215700c..2b2f356 100755 --- a/core/res/res/values/config.xml +++ b/core/res/res/values/config.xml @@ -182,6 +182,9 @@ <!-- Boolean indicating whether the wifi chipset has dual frequency band support --> <bool translatable="false" name="config_wifi_dual_band_support">false</bool> + <!-- Boolean indicating whether the wifi chipset has p2p support --> + <bool translatable="false" name="config_wifi_p2p_support">false</bool> + <!-- Boolean indicating whether the wifi chipset supports background scanning mechanism. This mechanism allows the host to remain in suspend state and the dongle to actively scan and wake the host when a configured SSID is detected by the dongle. This chipset diff --git a/core/res/res/values/public.xml b/core/res/res/values/public.xml index 75f0c4e..b2b7025 100644 --- a/core/res/res/values/public.xml +++ b/core/res/res/values/public.xml @@ -1715,8 +1715,7 @@ <public type="attr" name="switchPreferenceStyle" /> <public type="attr" name="textSuggestionsWindowStyle" /> - <public type="attr" name="textEditSuggestionsBottomWindowLayout" /> - <public type="attr" name="textEditSuggestionsTopWindowLayout" /> + <public type="attr" name="textEditSuggestionsWindowLayout" /> <public type="attr" name="textEditSuggestionItemLayout" /> <public type="attr" name="suggestionsEnabled" /> diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml index 419734a..e1a31f4 100755 --- a/core/res/res/values/strings.xml +++ b/core/res/res/values/strings.xml @@ -705,6 +705,12 @@ interface of an input method. Should never be needed for normal applications.</string> <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. --> + <string name="permlab_bindTextService">bind to a text service</string> + <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. --> + <string name="permdesc_bindTextService">Allows the holder to bind to the top-level + interface of a text service(e.g. SpellCheckerService). Should never be needed for normal applications.</string> + + <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. --> <string name="permlab_bindWallpaper">bind to a wallpaper</string> <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. --> <string name="permdesc_bindWallpaper">Allows the holder to bind to the top-level @@ -2568,9 +2574,23 @@ <item quantity="one">Open Wi-Fi network available</item> <item quantity="other">Open Wi-Fi networks available</item> </plurals> + + <!-- A notification is shown the first time a wireless network is disabled due to bad connectivity. This is the notification's title / ticker. --> + <string name="wifi_watchdog_network_disabled">A Wi-Fi network was disabled</string> + <!-- A notification is shown the first time a wireless network is disabled due to bad connectivity. This is the notification's message which leads to the settings pane --> + <string name="wifi_watchdog_network_disabled_detailed">A Wi-Fi network was temporarily disabled due to bad connectivity.</string> + <!-- Do not translate. Default access point SSID used for tethering --> <string name="wifi_tether_configure_ssid_default" translatable="false">AndroidAP</string> + <!-- Wi-Fi p2p dialog title--> + <string name="wifi_p2p_dialog_title">Wi-Fi Direct</string> + <string name="wifi_p2p_turnon_message">Start Wi-Fi Direct operation. This will turn off Wi-Fi client/hotspot operation.</string> + <string name="wifi_p2p_failed_message">Failed to start Wi-Fi Direct</string> + <string name="wifi_p2p_pbc_go_negotiation_request_message">Wi-Fi Direct connection setup request from <xliff:g id="p2p_device_address">%1$s</xliff:g>. Click OK to accept. </string> + <string name="wifi_p2p_pin_go_negotiation_request_message">Wi-Fi Direct connection setup request from <xliff:g id="p2p_device_address">%1$s</xliff:g>. Enter pin to proceed. </string> + <string name="wifi_p2p_pin_display_message">WPS pin <xliff:g id="p2p_wps_pin">%1$s</xliff:g> needs to be entered on the peer device <xliff:g id="p2p_client_address">%2$s</xliff:g> for connection setup to proceed </string> + <!-- Name of the dialog that lets the user choose an accented character to insert --> <string name="select_character">Insert character</string> @@ -2669,12 +2689,14 @@ <!-- USB_STORAGE_ERROR dialog ok button--> <string name="dlg_ok">OK</string> - <!-- USB_PREFERENCES: Notification for wehen the user connects the phone to a computer via USB in MTP mode. This is the title --> + <!-- USB_PREFERENCES: Notification for when the user connects the phone to a computer via USB in MTP mode. This is the title --> <string name="usb_mtp_notification_title">Connected as a media device</string> - <!-- USB_PREFERENCES: Notification for wehen the user connects the phone to a computer via USB in PTP mode. This is the title --> + <!-- USB_PREFERENCES: Notification for when the user connects the phone to a computer via USB in PTP mode. This is the title --> <string name="usb_ptp_notification_title">Connected as a camera</string> - <!-- USB_PREFERENCES: Notification for wehen the user connects the phone to a computer via USB in mass storage mode (for installer CD image). This is the title --> + <!-- USB_PREFERENCES: Notification for when the user connects the phone to a computer via USB in mass storage mode (for installer CD image). This is the title --> <string name="usb_cd_installer_notification_title">Connected as an installer</string> + <!-- USB_PREFERENCES: Notification for when a USB accessory is attached. This is the title --> + <string name="usb_accessory_notification_title">Connected to a USB accessory</string> <!-- See USB_PREFERENCES. This is the message. --> <string name="usb_notification_message">Touch for other USB options</string> @@ -3050,4 +3072,9 @@ <!-- Title for a dialog showing possible activities for sharing in ShareActionProvider [CHAR LIMIT=25] --> <string name="share_action_provider_share_with">Share with...</string> + <!-- Status Bar icon descriptions --> + + <!-- Description of for the status bar's icon that the device is locked for accessibility. [CHAR LIMIT=NONE] --> + <string name="status_bar_device_locked">Device locked.</string> + </resources> diff --git a/core/res/res/values/styles.xml b/core/res/res/values/styles.xml index d647467..9b6c442 100644 --- a/core/res/res/values/styles.xml +++ b/core/res/res/values/styles.xml @@ -423,8 +423,7 @@ <item name="android:textEditNoPasteWindowLayout">?android:attr/textEditNoPasteWindowLayout</item> <item name="android:textEditSidePasteWindowLayout">?android:attr/textEditSidePasteWindowLayout</item> <item name="android:textEditSideNoPasteWindowLayout">?android:attr/textEditSideNoPasteWindowLayout</item> - <item name="android:textEditSuggestionsBottomWindowLayout">?android:attr/textEditSuggestionsBottomWindowLayout</item> - <item name="android:textEditSuggestionsTopWindowLayout">?android:attr/textEditSuggestionsTopWindowLayout</item> + <item name="android:textEditSuggestionsWindowLayout">?android:attr/textEditSuggestionsWindowLayout</item> <item name="android:textEditSuggestionItemLayout">?android:attr/textEditSuggestionItemLayout</item> <item name="android:textCursorDrawable">?android:attr/textCursorDrawable</item> </style> diff --git a/core/res/res/values/themes.xml b/core/res/res/values/themes.xml index 90f3602..93ccfe3 100644 --- a/core/res/res/values/themes.xml +++ b/core/res/res/values/themes.xml @@ -190,8 +190,7 @@ <item name="textEditSidePasteWindowLayout">@android:layout/text_edit_side_paste_window</item> <item name="textEditSideNoPasteWindowLayout">@android:layout/text_edit_side_no_paste_window</item> <item name="textSuggestionsWindowStyle">@android:style/Widget.TextSuggestions</item> - <item name="textEditSuggestionsBottomWindowLayout">@android:layout/text_edit_suggestions_bottom_window</item> - <item name="textEditSuggestionsTopWindowLayout">@android:layout/text_edit_suggestions_top_window</item> + <item name="textEditSuggestionsWindowLayout">@android:layout/text_edit_suggestions_window</item> <item name="textEditSuggestionItemLayout">@android:layout/text_edit_suggestion_item</item> <item name="textCursorDrawable">@null</item> |