diff options
Diffstat (limited to 'core/java/android')
195 files changed, 11834 insertions, 3268 deletions
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java index 4dc4b6a..8236943 100644 --- a/core/java/android/app/Activity.java +++ b/core/java/android/app/Activity.java @@ -53,6 +53,7 @@ import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; +import android.view.ViewManager; import android.view.Window; import android.view.WindowManager; import android.view.ContextMenu.ContextMenuInfo; @@ -93,11 +94,11 @@ import java.util.HashMap; * {@link android.R.styleable#AndroidManifestActivity <activity>} * declaration in their package's <code>AndroidManifest.xml</code>.</p> * - * <p>The Activity class is an important part of an - * <a href="{@docRoot}intro/lifecycle.html">application's overall lifecycle</a>, + * <p>The Activity class is an important part of an application's overall lifecycle, * and the way activities are launched and put together is a fundamental - * part of the platform's - * <a href="{@docRoot}intro/appmodel.html">application model</a>.</p> + * part of the platform's application model. For a detailed perspective on the structure of + * Android applications and lifecycles, please read the <em>Dev Guide</em> document on + * <a href="{@docRoot}guide/topics/fundamentals.html">Application Fundamentals</a>.</p> * * <p>Topics covered here: * <ol> @@ -527,7 +528,7 @@ import java.util.HashMap; * {@link android.R.styleable#AndroidManifestUsesPermission <uses-permission>} * element in their own manifest to be able to start that activity. * - * <p>See the <a href="{@docRoot}devel/security.html">Security Model</a> + * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a> * document for more information on permissions and security in general. * * <a name="ProcessLifecycle"></a> @@ -629,6 +630,9 @@ public class Activity extends ContextThemeWrapper private WindowManager mWindowManager; /*package*/ View mDecor = null; + /*package*/ boolean mWindowAdded = false; + /*package*/ boolean mVisibleFromServer = false; + /*package*/ boolean mVisibleFromClient = true; private CharSequence mTitle; private int mTitleColor = 0; @@ -779,6 +783,8 @@ public class Activity extends ContextThemeWrapper * @see #onPostCreate */ protected void onCreate(Bundle savedInstanceState) { + mVisibleFromClient = mWindow.getWindowStyle().getBoolean( + com.android.internal.R.styleable.Window_windowNoDisplay, true); mCalled = true; } @@ -1134,12 +1140,19 @@ public class Activity extends ContextThemeWrapper /** * Called as part of the activity lifecycle when an activity is about to go * into the background as the result of user choice. For example, when the - * user presses the Home key, {@link #onUserLeaving} will be called, but + * user presses the Home key, {@link #onUserLeaveHint} will be called, but * when an incoming phone call causes the in-call Activity to be automatically - * brought to the foreground, {@link #onUserLeaving} will not be called on - * the activity being interrupted. + * brought to the foreground, {@link #onUserLeaveHint} will not be called on + * the activity being interrupted. In cases when it is invoked, this method + * is called right before the activity's {@link #onPause} callback. + * + * <p>This callback and {@link #onUserInteraction} are intended to help + * activities manage status bar notifications intelligently; specifically, + * for helping activities determine the proper time to cancel a notfication. + * + * @see #onUserInteraction() */ - protected void onUserLeaving() { + protected void onUserLeaveHint() { } /** @@ -1443,7 +1456,6 @@ public class Activity extends ContextThemeWrapper * @return The Cursor that was returned by query(). * * @see ContentResolver#query(android.net.Uri , String[], String, String[], String) - * @see #managedCommitUpdates * @see #startManagingCursor * @hide */ @@ -1475,7 +1487,6 @@ public class Activity extends ContextThemeWrapper * @return The Cursor that was returned by query(). * * @see ContentResolver#query(android.net.Uri , String[], String, String[], String) - * @see #managedCommitUpdates * @see #startManagingCursor */ public final Cursor managedQuery(Uri uri, @@ -1863,6 +1874,28 @@ public class Activity extends ContextThemeWrapper return false; } + /** + * Called whenever a key, touch, or trackball event is dispatched to the + * activity. Implement this method if you wish to know that the user has + * interacted with the device in some way while your activity is running. + * This callback and {@link #onUserLeaveHint} are intended to help + * activities manage status bar notifications intelligently; specifically, + * for helping activities determine the proper time to cancel a notfication. + * + * <p>All calls to your activity's {@link #onUserLeaveHint} callback will + * be accompanied by calls to {@link #onUserInteraction}. This + * ensures that your activity will be told of relevant user activity such + * as pulling down the notification pane and touching an item there. + * + * <p>Note that this callback will be invoked for the touch down action + * that begins a touch gesture, but may not be invoked for the touch-moved + * and touch-up actions that follow. + * + * @see #onUserLeaveHint() + */ + public void onUserInteraction() { + } + public void onWindowAttributesChanged(WindowManager.LayoutParams params) { // Update window manager if: we have a view, that view is // attached to its parent (which will be a RootView), and @@ -1935,6 +1968,7 @@ public class Activity extends ContextThemeWrapper * @return boolean Return true if this event was consumed. */ public boolean dispatchKeyEvent(KeyEvent event) { + onUserInteraction(); if (getWindow().superDispatchKeyEvent(event)) { return true; } @@ -1952,6 +1986,9 @@ public class Activity extends ContextThemeWrapper * @return boolean Return true if this event was consumed. */ public boolean dispatchTouchEvent(MotionEvent ev) { + if (ev.getAction() == MotionEvent.ACTION_DOWN) { + onUserInteraction(); + } if (getWindow().superDispatchTouchEvent(ev)) { return true; } @@ -1969,6 +2006,7 @@ public class Activity extends ContextThemeWrapper * @return boolean Return true if this event was consumed. */ public boolean dispatchTrackballEvent(MotionEvent ev) { + onUserInteraction(); if (getWindow().superDispatchTrackballEvent(ev)) { return true; } @@ -2865,6 +2903,35 @@ public class Activity extends ContextThemeWrapper } /** + * Control whether this activity's main window is visible. This is intended + * only for the special case of an activity that is not going to show a + * UI itself, but can't just finish prior to onResume() because it needs + * to wait for a service binding or such. Setting this to false allows + * you to prevent your UI from being shown during that time. + * + * <p>The default value for this is taken from the + * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme. + */ + public void setVisible(boolean visible) { + if (mVisibleFromClient != visible) { + mVisibleFromClient = visible; + if (mVisibleFromServer) { + if (visible) makeVisible(); + else mDecor.setVisibility(View.INVISIBLE); + } + } + } + + void makeVisible() { + if (!mWindowAdded) { + ViewManager wm = getWindowManager(); + wm.addView(mDecor, getWindow().getAttributes()); + mWindowAdded = true; + } + mDecor.setVisibility(View.VISIBLE); + } + + /** * Check to see whether this activity is in the process of finishing, * either because you called {@link #finish} on it or someone else * has requested that it finished. This is often used in @@ -3482,7 +3549,8 @@ public class Activity extends ContextThemeWrapper } final void performUserLeaving() { - onUserLeaving(); + onUserInteraction(); + onUserLeaveHint(); } final void performStop() { diff --git a/core/java/android/app/ActivityManager.java b/core/java/android/app/ActivityManager.java index f9b9221..07520c9d 100644 --- a/core/java/android/app/ActivityManager.java +++ b/core/java/android/app/ActivityManager.java @@ -19,16 +19,14 @@ package android.app; import android.content.ComponentName; import android.content.Context; import android.content.Intent; +import android.content.pm.ConfigurationInfo; import android.content.pm.IPackageDataObserver; import android.graphics.Bitmap; import android.os.RemoteException; import android.os.Handler; -import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; -import android.os.Parcelable.Creator; import android.text.TextUtils; -import android.util.Log; import java.util.List; /** @@ -617,7 +615,59 @@ public class ActivityManager { public String pkgList[]; + /** + * Constant for {@link #importance}: this process is running the + * foreground UI. + */ + public static final int IMPORTANCE_FOREGROUND = 100; + + /** + * Constant for {@link #importance}: this process is running something + * that is considered to be actively visible to the user. + */ + public static final int IMPORTANCE_VISIBLE = 200; + + /** + * Constant for {@link #importance}: this process is contains services + * that should remain running. + */ + public static final int IMPORTANCE_SERVICE = 300; + + /** + * Constant for {@link #importance}: this process process contains + * background code that is expendable. + */ + public static final int IMPORTANCE_BACKGROUND = 400; + + /** + * Constant for {@link #importance}: this process is empty of any + * actively running code. + */ + public static final int IMPORTANCE_EMPTY = 500; + + /** + * The relative importance level that the system places on this + * process. May be one of {@link #IMPORTANCE_FOREGROUND}, + * {@link #IMPORTANCE_VISIBLE}, {@link #IMPORTANCE_SERVICE}, + * {@link #IMPORTANCE_BACKGROUND}, or {@link #IMPORTANCE_EMPTY}. These + * constants are numbered so that "more important" values are always + * smaller than "less important" values. + */ + public int importance; + + /** + * An additional ordering within a particular {@link #importance} + * category, providing finer-grained information about the relative + * utility of processes within a category. This number means nothing + * except that a smaller values are more recently used (and thus + * more important). Currently an LRU value is only maintained for + * the {@link #IMPORTANCE_BACKGROUND} category, though others may + * be maintained in the future. + */ + public int lru; + public RunningAppProcessInfo() { + importance = IMPORTANCE_FOREGROUND; } public RunningAppProcessInfo(String pProcessName, int pPid, String pArr[]) { @@ -634,12 +684,16 @@ public class ActivityManager { dest.writeString(processName); dest.writeInt(pid); dest.writeStringArray(pkgList); + dest.writeInt(importance); + dest.writeInt(lru); } public void readFromParcel(Parcel source) { processName = source.readString(); pid = source.readInt(); pkgList = source.readStringArray(); + importance = source.readInt(); + lru = source.readInt(); } public static final Creator<RunningAppProcessInfo> CREATOR = @@ -671,4 +725,37 @@ public class ActivityManager { return null; } } + + /** + * Have the system perform a force stop of everything associated with + * the given application package. All processes that share its uid + * will be killed, all services it has running stopped, all activities + * removed, etc. In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED} + * broadcast will be sent, so that any of its registered alarms can + * be stopped, notifications removed, etc. + * + * <p>You must hold the permission + * {@link android.Manifest.permission#RESTART_PACKAGES} to be able to + * call this method. + * + * @param packageName The name of the package to be stopped. + */ + public void restartPackage(String packageName) { + try { + ActivityManagerNative.getDefault().restartPackage(packageName); + } catch (RemoteException e) { + } + } + + /** + * Get the device configuration attributes. + */ + public ConfigurationInfo getDeviceConfigurationInfo() { + try { + return ActivityManagerNative.getDefault().getDeviceConfigurationInfo(); + } catch (RemoteException e) { + } + return null; + } + } diff --git a/core/java/android/app/ActivityManagerNative.java b/core/java/android/app/ActivityManagerNative.java index ae9f3bf..f11dbec 100644 --- a/core/java/android/app/ActivityManagerNative.java +++ b/core/java/android/app/ActivityManagerNative.java @@ -20,6 +20,7 @@ import android.content.ComponentName; import android.content.ContentResolver; import android.content.Intent; import android.content.IntentFilter; +import android.content.pm.ConfigurationInfo; import android.content.pm.IPackageDataObserver; import android.content.res.Configuration; import android.graphics.Bitmap; @@ -83,6 +84,17 @@ public abstract class ActivityManagerNative extends Binder implements IActivityM } /** + * Convenience for checking whether the system is ready. For internal use only. + */ + static public boolean isSystemReady() { + if (!sSystemReady) { + sSystemReady = getDefault().testIsSystemReady(); + } + return sSystemReady; + } + static boolean sSystemReady = false; + + /** * Convenience for sending a sticky broadcast. For internal use only. * If you don't care about permission, use null. */ @@ -959,6 +971,23 @@ public abstract class ActivityManagerNative extends Binder implements IActivityM return true; } + case GET_DEVICE_CONFIGURATION_TRANSACTION: { + data.enforceInterface(IActivityManager.descriptor); + ConfigurationInfo config = getDeviceConfigurationInfo(); + reply.writeNoException(); + config.writeToParcel(reply, 0); + return true; + } + + case PEEK_SERVICE_TRANSACTION: { + data.enforceInterface(IActivityManager.descriptor); + Intent service = Intent.CREATOR.createFromParcel(data); + String resolvedType = data.readString(); + IBinder binder = peekService(service, resolvedType); + reply.writeNoException(); + reply.writeStrongBinder(binder); + return true; + } } return super.onTransact(code, data, reply, flags); @@ -1604,6 +1633,20 @@ class ActivityManagerProxy implements IActivityManager data.recycle(); reply.recycle(); } + + public IBinder peekService(Intent service, String resolvedType) throws RemoteException { + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + data.writeInterfaceToken(IActivityManager.descriptor); + service.writeToParcel(data, 0); + data.writeString(resolvedType); + mRemote.transact(PEEK_SERVICE_TRANSACTION, data, reply, 0); + reply.readException(); + IBinder binder = reply.readStrongBinder(); + reply.recycle(); + data.recycle(); + return binder; + } public boolean startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher) @@ -2028,6 +2071,11 @@ class ActivityManagerProxy implements IActivityManager data.recycle(); reply.recycle(); } + public boolean testIsSystemReady() + { + /* this base class version is never called */ + return true; + } public int handleApplicationError(IBinder app, int flags, String tag, String shortMsg, String longMsg, byte[] crashData) throws RemoteException @@ -2071,5 +2119,17 @@ class ActivityManagerProxy implements IActivityManager reply.recycle(); } + public ConfigurationInfo getDeviceConfigurationInfo() throws RemoteException + { + Parcel data = Parcel.obtain(); + Parcel reply = Parcel.obtain(); + data.writeInterfaceToken(IActivityManager.descriptor); + mRemote.transact(GET_DEVICE_CONFIGURATION_TRANSACTION, data, reply, 0); + reply.readException(); + ConfigurationInfo res = ConfigurationInfo.CREATOR.createFromParcel(reply); + reply.recycle(); + data.recycle(); + return res; + } private IBinder mRemote; } diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java index e4c1057..bf5616e 100644 --- a/core/java/android/app/ActivityThread.java +++ b/core/java/android/app/ActivityThread.java @@ -144,13 +144,19 @@ public final class ActivityThread { return sPackageManager; } - DisplayMetrics getDisplayMetricsLocked() { + DisplayMetrics getDisplayMetricsLocked(boolean forceUpdate) { + if (mDisplayMetrics != null && !forceUpdate) { + return mDisplayMetrics; + } if (mDisplay == null) { WindowManager wm = WindowManagerImpl.getDefault(); mDisplay = wm.getDefaultDisplay(); } - DisplayMetrics metrics = new DisplayMetrics(); + DisplayMetrics metrics = mDisplayMetrics = new DisplayMetrics(); mDisplay.getMetrics(metrics); + //Log.i("foo", "New metrics: w=" + metrics.widthPixels + " h=" + // + metrics.heightPixels + " den=" + metrics.density + // + " xdpi=" + metrics.xdpi + " ydpi=" + metrics.ydpi); return metrics; } @@ -173,7 +179,7 @@ public final class ActivityThread { if (assets.addAssetPath(appDir) == 0) { return null; } - DisplayMetrics metrics = getDisplayMetricsLocked(); + DisplayMetrics metrics = getDisplayMetricsLocked(false); r = new Resources(assets, metrics, getConfiguration()); //Log.i(TAG, "Created app resources " + r + ": " + r.getConfiguration()); // XXX need to remove entries when weak references go away @@ -235,7 +241,7 @@ public final class ActivityThread { ApplicationContext.createSystemContext(mainThread); mSystemContext.getResources().updateConfiguration( mainThread.getConfiguration(), - mainThread.getDisplayMetricsLocked()); + mainThread.getDisplayMetricsLocked(false)); //Log.i(TAG, "Created system resources " // + mSystemContext.getResources() + ": " // + mSystemContext.getResources().getConfiguration()); @@ -1205,7 +1211,10 @@ public final class ActivityThread { private static final String HEAP_COLUMN = "%17s %8s %8s %8s %8s"; private static final String ONE_COUNT_COLUMN = "%17s %8d"; private static final String TWO_COUNT_COLUMNS = "%17s %8d %17s %8d"; - + + // Formatting for checkin service - update version if row format changes + private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 1; + public final void schedulePauseActivity(IBinder token, boolean finished, boolean userLeaving, int configChanges) { queueOrSendMessage( @@ -1462,7 +1471,101 @@ public final class ActivityThread { long dalvikMax = runtime.totalMemory() / 1024; long dalvikFree = runtime.freeMemory() / 1024; long dalvikAllocated = dalvikMax - dalvikFree; - + long viewInstanceCount = ViewDebug.getViewInstanceCount(); + long viewRootInstanceCount = ViewDebug.getViewRootInstanceCount(); + long appContextInstanceCount = ApplicationContext.getInstanceCount(); + long activityInstanceCount = Activity.getInstanceCount(); + int globalAssetCount = AssetManager.getGlobalAssetCount(); + int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount(); + int binderLocalObjectCount = Debug.getBinderLocalObjectCount(); + int binderProxyObjectCount = Debug.getBinderProxyObjectCount(); + int binderDeathObjectCount = Debug.getBinderDeathObjectCount(); + int openSslSocketCount = OpenSSLSocketImpl.getInstanceCount(); + long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024; + SQLiteDebug.PagerStats stats = new SQLiteDebug.PagerStats(); + SQLiteDebug.getPagerStats(stats); + + // Check to see if we were called by checkin server. If so, print terse format. + boolean doCheckinFormat = false; + if (args != null) { + for (String arg : args) { + if ("-c".equals(arg)) doCheckinFormat = true; + } + } + + // For checkin, we print one long comma-separated list of values + if (doCheckinFormat) { + // NOTE: if you change anything significant below, also consider changing + // ACTIVITY_THREAD_CHECKIN_VERSION. + String processName = (mBoundApplication != null) + ? mBoundApplication.processName : "unknown"; + + // Header + pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(','); + pw.print(Process.myPid()); pw.print(','); + pw.print(processName); pw.print(','); + + // Heap info - max + pw.print(nativeMax); pw.print(','); + pw.print(dalvikMax); pw.print(','); + pw.print("N/A,"); + pw.print(nativeMax + dalvikMax); pw.print(','); + + // Heap info - allocated + pw.print(nativeAllocated); pw.print(','); + pw.print(dalvikAllocated); pw.print(','); + pw.print("N/A,"); + pw.print(nativeAllocated + dalvikAllocated); pw.print(','); + + // Heap info - free + pw.print(nativeFree); pw.print(','); + pw.print(dalvikFree); pw.print(','); + pw.print("N/A,"); + pw.print(nativeFree + dalvikFree); pw.print(','); + + // Heap info - proportional set size + pw.print(memInfo.nativePss); pw.print(','); + pw.print(memInfo.dalvikPss); pw.print(','); + pw.print(memInfo.otherPss); pw.print(','); + pw.print(memInfo.nativePss + memInfo.dalvikPss + memInfo.otherPss); pw.print(','); + + // Heap info - shared + pw.print(nativeShared); pw.print(','); + pw.print(dalvikShared); pw.print(','); + pw.print(otherShared); pw.print(','); + pw.print(nativeShared + dalvikShared + otherShared); pw.print(','); + + // Heap info - private + pw.print(nativePrivate); pw.print(','); + pw.print(dalvikPrivate); pw.print(','); + pw.print(otherPrivate); pw.print(','); + pw.print(nativePrivate + dalvikPrivate + otherPrivate); pw.print(','); + + // Object counts + pw.print(viewInstanceCount); pw.print(','); + pw.print(viewRootInstanceCount); pw.print(','); + pw.print(appContextInstanceCount); pw.print(','); + pw.print(activityInstanceCount); pw.print(','); + + pw.print(globalAssetCount); pw.print(','); + pw.print(globalAssetManagerCount); pw.print(','); + pw.print(binderLocalObjectCount); pw.print(','); + pw.print(binderProxyObjectCount); pw.print(','); + + pw.print(binderDeathObjectCount); pw.print(','); + pw.print(openSslSocketCount); pw.print(','); + + // SQL + pw.print(sqliteAllocated); pw.print(','); + pw.print(stats.databaseBytes / 1024); pw.print(','); + pw.print(stats.numPagers); pw.print(','); + pw.print((stats.totalBytes - stats.referencedBytes) / 1024); pw.print(','); + pw.print(stats.referencedBytes / 1024); pw.print('\n'); + + return; + } + + // otherwise, show human-readable format printRow(pw, HEAP_COLUMN, "", "native", "dalvik", "other", "total"); printRow(pw, HEAP_COLUMN, "size:", nativeMax, dalvikMax, "N/A", nativeMax + dalvikMax); printRow(pw, HEAP_COLUMN, "allocated:", nativeAllocated, dalvikAllocated, "N/A", @@ -1480,26 +1583,22 @@ public final class ActivityThread { pw.println(" "); pw.println(" Objects"); - printRow(pw, TWO_COUNT_COLUMNS, "Views:", ViewDebug.getViewInstanceCount(), "ViewRoots:", - ViewDebug.getViewRootInstanceCount()); - - printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", ApplicationContext.getInstanceCount(), - "Activities:", Activity.getInstanceCount()); + printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRoots:", + viewRootInstanceCount); - printRow(pw, TWO_COUNT_COLUMNS, "Assets:", AssetManager.getGlobalAssetCount(), - "AssetManagers:", AssetManager.getGlobalAssetManagerCount()); + printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount, + "Activities:", activityInstanceCount); - printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", Debug.getBinderLocalObjectCount(), - "Proxy Binders:", Debug.getBinderProxyObjectCount()); - printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", Debug.getBinderDeathObjectCount()); + printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount, + "AssetManagers:", globalAssetManagerCount); - printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", OpenSSLSocketImpl.getInstanceCount()); + printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount, + "Proxy Binders:", binderProxyObjectCount); + printRow(pw, ONE_COUNT_COLUMN, "Death Recipients:", binderDeathObjectCount); + printRow(pw, ONE_COUNT_COLUMN, "OpenSSL Sockets:", openSslSocketCount); + // SQLite mem info - long sqliteAllocated = SQLiteDebug.getHeapAllocatedSize() / 1024; - SQLiteDebug.PagerStats stats = new SQLiteDebug.PagerStats(); - SQLiteDebug.getPagerStats(stats); - pw.println(" "); pw.println(" SQL"); printRow(pw, TWO_COUNT_COLUMNS, "heap:", sqliteAllocated, "dbFiles:", @@ -1751,6 +1850,7 @@ public final class ActivityThread { final HashMap<String, WeakReference<PackageInfo>> mResourcePackages = new HashMap<String, WeakReference<PackageInfo>>(); Display mDisplay = null; + DisplayMetrics mDisplayMetrics = null; HashMap<String, WeakReference<Resources> > mActiveResources = new HashMap<String, WeakReference<Resources> >(); @@ -1918,7 +2018,7 @@ public final class ActivityThread { PackageInfo info = new PackageInfo(this, "android", context); context.init(info, null, this); context.getResources().updateConfiguration( - getConfiguration(), getDisplayMetricsLocked()); + getConfiguration(), getDisplayMetricsLocked(false)); mSystemContext = context; //Log.i(TAG, "Created system resources " + context.getResources() // + ": " + context.getResources().getConfiguration()); @@ -2557,7 +2657,10 @@ public final class ActivityThread { a.mDecor = decor; l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION; l.softInputMode |= forwardBit; - wm.addView(decor, l); + if (a.mVisibleFromClient) { + a.mWindowAdded = true; + wm.addView(decor, l); + } // If the window has already been added, but during resume // we started another activity, then don't yet make the @@ -2576,7 +2679,8 @@ public final class ActivityThread { performConfigurationChanged(r.activity, r.newConfig); r.newConfig = null; } - Log.v(TAG, "Resuming " + r + " with isForward=" + isForward); + if (localLOGV) Log.v(TAG, "Resuming " + r + " with isForward=" + + isForward); WindowManager.LayoutParams l = r.window.getAttributes(); if ((l.softInputMode & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) @@ -2588,8 +2692,11 @@ public final class ActivityThread { View decor = r.window.getDecorView(); wm.updateViewLayout(decor, l); } - r.activity.mDecor.setVisibility(View.VISIBLE); + r.activity.mVisibleFromServer = true; mNumVisibleActivities++; + if (r.activity.mVisibleFromClient) { + r.activity.makeVisible(); + } } r.nextIdle = mNewActivities; @@ -2800,18 +2907,22 @@ public final class ActivityThread { View v = r.activity.mDecor; if (v != null) { if (show) { - if (v.getVisibility() != View.VISIBLE) { - v.setVisibility(View.VISIBLE); + if (!r.activity.mVisibleFromServer) { + r.activity.mVisibleFromServer = true; mNumVisibleActivities++; + if (r.activity.mVisibleFromClient) { + r.activity.makeVisible(); + } } if (r.newConfig != null) { performConfigurationChanged(r.activity, r.newConfig); r.newConfig = null; } } else { - if (v.getVisibility() == View.VISIBLE) { - v.setVisibility(View.INVISIBLE); + if (r.activity.mVisibleFromServer) { + r.activity.mVisibleFromServer = false; mNumVisibleActivities--; + v.setVisibility(View.INVISIBLE); } } } @@ -3037,11 +3148,13 @@ public final class ActivityThread { WindowManager wm = r.activity.getWindowManager(); View v = r.activity.mDecor; if (v != null) { - if (v.getVisibility() == View.VISIBLE) { + if (r.activity.mVisibleFromServer) { mNumVisibleActivities--; } IBinder wtoken = v.getWindowToken(); - wm.removeViewImmediate(v); + if (r.activity.mWindowAdded) { + wm.removeViewImmediate(v); + } if (wtoken != null) { WindowManagerImpl.getDefault().closeAll(wtoken, r.activity.getClass().getName(), "Activity"); @@ -3271,6 +3384,7 @@ public final class ActivityThread { mConfiguration = new Configuration(); } mConfiguration.updateFrom(config); + DisplayMetrics dm = getDisplayMetricsLocked(true); // set it for java, this also affects newly created Resources if (config.locale != null) { @@ -3290,7 +3404,7 @@ public final class ActivityThread { WeakReference<Resources> v = it.next(); Resources r = v.get(); if (r != null) { - r.updateConfiguration(config, null); + r.updateConfiguration(config, dm); //Log.i(TAG, "Updated app resources " + v.getKey() // + " " + r + ": " + r.getConfiguration()); } else { diff --git a/core/java/android/app/ApplicationContext.java b/core/java/android/app/ApplicationContext.java index 4236a00..394b8e3 100644 --- a/core/java/android/app/ApplicationContext.java +++ b/core/java/android/app/ApplicationContext.java @@ -1630,6 +1630,15 @@ class ApplicationContext extends Context { } @Override + public String[] getSystemSharedLibraryNames() { + try { + return mPM.getSystemSharedLibraryNames(); + } catch (RemoteException e) { + throw new RuntimeException("Package manager has died", e); + } + } + + @Override public int checkPermission(String permName, String pkgName) { try { return mPM.checkPermission(permName, pkgName); @@ -1974,6 +1983,18 @@ class ApplicationContext extends Context { getApplicationInfo(appPackageName, 0)); } + int mCachedSafeMode = -1; + @Override public boolean isSafeMode() { + try { + if (mCachedSafeMode < 0) { + mCachedSafeMode = mPM.isSafeMode() ? 1 : 0; + } + return mCachedSafeMode != 0; + } catch (RemoteException e) { + throw new RuntimeException("Package manager has died", e); + } + } + static void configurationChanged() { synchronized (sSync) { sIconCache.clear(); diff --git a/core/java/android/app/Dialog.java b/core/java/android/app/Dialog.java index 951b48d..b09a57f 100644 --- a/core/java/android/app/Dialog.java +++ b/core/java/android/app/Dialog.java @@ -122,7 +122,7 @@ public class Dialog implements DialogInterface, Window.Callback, * uses the window manager and theme from this context to * present its UI. * @param theme A style resource describing the theme to use for the - * window. See <a href="{@docRoot}reference/available-resources.html#stylesandthemes">Style + * window. See <a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">Style * and Theme Resources</a> for more information about defining and using * styles. This theme is applied on top of the current theme in * <var>context</var>. If 0, the default dialog theme will be used. @@ -518,7 +518,7 @@ public class Dialog implements DialogInterface, Window.Callback, private boolean isOutOfBounds(MotionEvent event) { final int x = (int) event.getX(); final int y = (int) event.getY(); - final int slop = ViewConfiguration.getWindowTouchSlop(); + final int slop = ViewConfiguration.get(mContext).getScaledWindowTouchSlop(); final View decorView = getWindow().getDecorView(); return (x < -slop) || (y < -slop) || (x > (decorView.getWidth()+slop)) diff --git a/core/java/android/app/IActivityManager.java b/core/java/android/app/IActivityManager.java index 353500e..cd3701f 100644 --- a/core/java/android/app/IActivityManager.java +++ b/core/java/android/app/IActivityManager.java @@ -22,6 +22,7 @@ import android.content.ContentProviderNative; import android.content.IContentProvider; import android.content.Intent; import android.content.IntentFilter; +import android.content.pm.ConfigurationInfo; import android.content.pm.IPackageDataObserver; import android.content.pm.ProviderInfo; import android.content.res.Configuration; @@ -127,7 +128,8 @@ public interface IActivityManager extends IInterface { boolean doRebind) throws RemoteException; /* oneway */ public void serviceDoneExecuting(IBinder token) throws RemoteException; - + public IBinder peekService(Intent service, String resolvedType) throws RemoteException; + public boolean startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher) throws RemoteException; @@ -216,6 +218,13 @@ public interface IActivityManager extends IInterface { // Retrieve running application processes in the system public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() throws RemoteException; + // Get device configuration + public ConfigurationInfo getDeviceConfigurationInfo() throws RemoteException; + + /* + * Private non-Binder interfaces + */ + /* package */ boolean testIsSystemReady(); /** Information you can retrieve about a particular application. */ public static class ContentProviderHolder implements Parcelable { @@ -354,4 +363,6 @@ public interface IActivityManager extends IInterface { int GET_SERVICES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+80; int REPORT_PSS_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+81; int GET_RUNNING_APP_PROCESSES_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+82; + int GET_DEVICE_CONFIGURATION_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+83; + int PEEK_SERVICE_TRANSACTION = IBinder.FIRST_CALL_TRANSACTION+84; } diff --git a/core/java/android/app/Instrumentation.java b/core/java/android/app/Instrumentation.java index f96d787..f6a28b2 100644 --- a/core/java/android/app/Instrumentation.java +++ b/core/java/android/app/Instrumentation.java @@ -1267,7 +1267,7 @@ public class Instrumentation { } /** - * Perform calling of an activity's {@link Activity#onUserLeaving} method. + * Perform calling of an activity's {@link Activity#onUserLeaveHint} method. * The default implementation simply calls through to that method. * * @param activity The activity being notified that the user has navigated away diff --git a/core/java/android/app/LauncherActivity.java b/core/java/android/app/LauncherActivity.java index 8f0a4f5..c363f04 100644 --- a/core/java/android/app/LauncherActivity.java +++ b/core/java/android/app/LauncherActivity.java @@ -21,11 +21,23 @@ import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; +import android.content.res.Resources; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.PaintFlagsDrawFilter; +import android.graphics.PixelFormat; +import android.graphics.Rect; +import android.graphics.drawable.BitmapDrawable; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.PaintDrawable; +import android.os.AsyncTask; import android.os.Bundle; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.view.Window; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; @@ -43,33 +55,59 @@ import java.util.List; * */ public abstract class LauncherActivity extends ListActivity { + + Intent mIntent; + PackageManager mPackageManager; /** + * An item in the list + */ + public static class ListItem { + public CharSequence label; + //public CharSequence description; + public Drawable icon; + public String packageName; + public String className; + + ListItem(PackageManager pm, ResolveInfo resolveInfo, IconResizer resizer) { + label = resolveInfo.loadLabel(pm); + if (label == null && resolveInfo.activityInfo != null) { + label = resolveInfo.activityInfo.name; + } + + /* + if (resolveInfo.activityInfo != null && + resolveInfo.activityInfo.applicationInfo != null) { + description = resolveInfo.activityInfo.applicationInfo.loadDescription(pm); + } + */ + + icon = resizer.createIconThumbnail(resolveInfo.loadIcon(pm)); + packageName = resolveInfo.activityInfo.applicationInfo.packageName; + className = resolveInfo.activityInfo.name; + } + + public ListItem() { + } + } + + /** * Adapter which shows the set of activities that can be performed for a given intent. */ private class ActivityAdapter extends BaseAdapter implements Filterable { private final Object lock = new Object(); - private ArrayList<ResolveInfo> mOriginalValues; + private ArrayList<ListItem> mOriginalValues; - protected final Context mContext; - protected final Intent mIntent; protected final LayoutInflater mInflater; - protected List<ResolveInfo> mActivitiesList; + protected List<ListItem> mActivitiesList; private Filter mFilter; - - public ActivityAdapter(Context context, Intent intent) { - mContext = context; - mIntent = new Intent(intent); - mIntent.setComponent(null); - mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - - PackageManager pm = context.getPackageManager(); - mActivitiesList = pm.queryIntentActivities(intent, 0); - if (mActivitiesList != null) { - Collections.sort(mActivitiesList, new ResolveInfo.DisplayNameComparator(pm)); - } + + public ActivityAdapter() { + mInflater = (LayoutInflater) LauncherActivity.this.getSystemService( + Context.LAYOUT_INFLATER_SERVICE); + mActivitiesList = makeListItems(); } public Intent intentForPosition(int position) { @@ -78,8 +116,8 @@ public abstract class LauncherActivity extends ListActivity { } Intent intent = new Intent(mIntent); - ActivityInfo ai = mActivitiesList.get(position).activityInfo; - intent.setClassName(ai.applicationInfo.packageName, ai.name); + ListItem item = mActivitiesList.get(position); + intent.setClassName(item.packageName, item.className); return intent; } @@ -99,7 +137,7 @@ public abstract class LauncherActivity extends ListActivity { View view; if (convertView == null) { view = mInflater.inflate( - com.android.internal.R.layout.simple_list_item_1, parent, false); + com.android.internal.R.layout.activity_list_item_2, parent, false); } else { view = convertView; } @@ -108,7 +146,7 @@ public abstract class LauncherActivity extends ListActivity { } private char getCandidateLetter(ResolveInfo info) { - PackageManager pm = mContext.getPackageManager(); + PackageManager pm = LauncherActivity.this.getPackageManager(); CharSequence label = info.loadLabel(pm); if (label == null) { @@ -118,24 +156,22 @@ public abstract class LauncherActivity extends ListActivity { return Character.toLowerCase(label.charAt(0)); } - private void bindView(View view, ResolveInfo info) { - TextView text = (TextView) view.findViewById(com.android.internal.R.id.text1); - - PackageManager pm = mContext.getPackageManager(); - CharSequence label = info.loadLabel(pm); - text.setText(label != null ? label : info.activityInfo.name); + private void bindView(View view, ListItem item) { + TextView text = (TextView) view; + text.setText(item.label); + text.setCompoundDrawablesWithIntrinsicBounds(item.icon, null, null, null); } - + public Filter getFilter() { if (mFilter == null) { mFilter = new ArrayFilter(); } return mFilter; } - + /** - * <p>An array filters constrains the content of the array adapter with a prefix. Each item that - * does not start with the supplied prefix is removed from the list.</p> + * An array filters constrains the content of the array adapter with a prefix. Each + * item that does not start with the supplied prefix is removed from the list. */ private class ArrayFilter extends Filter { @Override @@ -144,39 +180,36 @@ public abstract class LauncherActivity extends ListActivity { if (mOriginalValues == null) { synchronized (lock) { - mOriginalValues = new ArrayList<ResolveInfo>(mActivitiesList); + mOriginalValues = new ArrayList<ListItem>(mActivitiesList); } } if (prefix == null || prefix.length() == 0) { synchronized (lock) { - ArrayList<ResolveInfo> list = new ArrayList<ResolveInfo>(mOriginalValues); + ArrayList<ListItem> list = new ArrayList<ListItem>(mOriginalValues); results.values = list; results.count = list.size(); } } else { - final PackageManager pm = mContext.getPackageManager(); + final PackageManager pm = LauncherActivity.this.getPackageManager(); final String prefixString = prefix.toString().toLowerCase(); - ArrayList<ResolveInfo> values = mOriginalValues; + ArrayList<ListItem> values = mOriginalValues; int count = values.size(); - ArrayList<ResolveInfo> newValues = new ArrayList<ResolveInfo>(count); + ArrayList<ListItem> newValues = new ArrayList<ListItem>(count); for (int i = 0; i < count; i++) { - ResolveInfo value = values.get(i); - - final CharSequence label = value.loadLabel(pm); - final CharSequence name = label != null ? label : value.activityInfo.name; + ListItem item = values.get(i); - String[] words = name.toString().toLowerCase().split(" "); + String[] words = item.label.toString().toLowerCase().split(" "); int wordCount = words.length; for (int k = 0; k < wordCount; k++) { final String word = words[k]; if (word.startsWith(prefixString)) { - newValues.add(value); + newValues.add(item); break; } } @@ -192,7 +225,7 @@ public abstract class LauncherActivity extends ListActivity { @Override protected void publishResults(CharSequence constraint, FilterResults results) { //noinspection unchecked - mActivitiesList = (List<ResolveInfo>) results.values; + mActivitiesList = (List<ListItem>) results.values; if (results.count > 0) { notifyDataSetChanged(); } else { @@ -201,19 +234,121 @@ public abstract class LauncherActivity extends ListActivity { } } } - - + + /** + * Utility class to resize icons to match default icon size. + */ + public class IconResizer { + // Code is borrowed from com.android.launcher.Utilities. + private int mIconWidth = -1; + private int mIconHeight = -1; + + private final Paint mPaint = new Paint(); + private final Rect mBounds = new Rect(); + private final Rect mOldBounds = new Rect(); + private Canvas mCanvas = new Canvas(); + + public IconResizer() { + mCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG, + Paint.FILTER_BITMAP_FLAG)); + + final Resources resources = LauncherActivity.this.getResources(); + mIconWidth = mIconHeight = (int) resources.getDimension( + android.R.dimen.app_icon_size); + } + + /** + * Returns a Drawable representing the thumbnail of the specified Drawable. + * The size of the thumbnail is defined by the dimension + * android.R.dimen.launcher_application_icon_size. + * + * This method is not thread-safe and should be invoked on the UI thread only. + * + * @param icon The icon to get a thumbnail of. + * + * @return A thumbnail for the specified icon or the icon itself if the + * thumbnail could not be created. + */ + public Drawable createIconThumbnail(Drawable icon) { + int width = mIconWidth; + int height = mIconHeight; + + final int iconWidth = icon.getIntrinsicWidth(); + final int iconHeight = icon.getIntrinsicHeight(); + + if (icon instanceof PaintDrawable) { + PaintDrawable painter = (PaintDrawable) icon; + painter.setIntrinsicWidth(width); + painter.setIntrinsicHeight(height); + } + + if (width > 0 && height > 0) { + if (width < iconWidth || height < iconHeight) { + final float ratio = (float) iconWidth / iconHeight; + + if (iconWidth > iconHeight) { + height = (int) (width / ratio); + } else if (iconHeight > iconWidth) { + width = (int) (height * ratio); + } + + final Bitmap.Config c = icon.getOpacity() != PixelFormat.OPAQUE ? + Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565; + final Bitmap thumb = Bitmap.createBitmap(mIconWidth, mIconHeight, c); + final Canvas canvas = mCanvas; + canvas.setBitmap(thumb); + // Copy the old bounds to restore them later + // If we were to do oldBounds = icon.getBounds(), + // the call to setBounds() that follows would + // change the same instance and we would lose the + // old bounds + mOldBounds.set(icon.getBounds()); + final int x = (mIconWidth - width) / 2; + final int y = (mIconHeight - height) / 2; + icon.setBounds(x, y, x + width, y + height); + icon.draw(canvas); + icon.setBounds(mOldBounds); + icon = new BitmapDrawable(thumb); + } else if (iconWidth < width && iconHeight < height) { + final Bitmap.Config c = Bitmap.Config.ARGB_8888; + final Bitmap thumb = Bitmap.createBitmap(mIconWidth, mIconHeight, c); + final Canvas canvas = mCanvas; + canvas.setBitmap(thumb); + mOldBounds.set(icon.getBounds()); + final int x = (width - iconWidth) / 2; + final int y = (height - iconHeight) / 2; + icon.setBounds(x, y, x + iconWidth, y + iconHeight); + icon.draw(canvas); + icon.setBounds(mOldBounds); + icon = new BitmapDrawable(thumb); + } + } + + return icon; + } + } + @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + protected void onCreate(Bundle icicle) { + super.onCreate(icicle); + + mPackageManager = getPackageManager(); + + requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); + setProgressBarIndeterminateVisibility(true); + setContentView(com.android.internal.R.layout.activity_list); - mAdapter = new ActivityAdapter(this, getTargetIntent()); + + mIntent = new Intent(getTargetIntent()); + mIntent.setComponent(null); + mAdapter = new ActivityAdapter(); setListAdapter(mAdapter); getListView().setTextFilterEnabled(true); + + setProgressBarIndeterminateVisibility(false); } - @Override protected void onListItemClick(ListView l, View v, int position, long id) { Intent intent = ((ActivityAdapter)mAdapter).intentForPosition(position); @@ -221,6 +356,42 @@ public abstract class LauncherActivity extends ListActivity { startActivity(intent); } - protected abstract Intent getTargetIntent(); - + /** + * Return the actual Intent for a specific position in our + * {@link android.widget.ListView}. + * @param position The item whose Intent to return + */ + protected Intent intentForPosition(int position) { + ActivityAdapter adapter = (ActivityAdapter) mAdapter; + return adapter.intentForPosition(position); + } + + /** + * Get the base intent to use when running + * {@link PackageManager#queryIntentActivities(Intent, int)}. + */ + protected Intent getTargetIntent() { + return new Intent(); + } + + /** + * Perform the query to determine which results to show and return a list of them. + */ + public List<ListItem> makeListItems() { + // Load all matching activities and sort correctly + List<ResolveInfo> list = mPackageManager.queryIntentActivities(mIntent, + /* no flags */ 0); + Collections.sort(list, new ResolveInfo.DisplayNameComparator(mPackageManager)); + + IconResizer resizer = new IconResizer(); + + ArrayList<ListItem> result = new ArrayList<ListItem>(list.size()); + int listSize = list.size(); + for (int i = 0; i < listSize; i++) { + ResolveInfo resolveInfo = list.get(i); + result.add(new ListItem(mPackageManager, resolveInfo, resizer)); + } + + return result; + } } diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java index ea67cdb..51fddb1 100644 --- a/core/java/android/app/Notification.java +++ b/core/java/android/app/Notification.java @@ -90,8 +90,9 @@ public class Notification implements Parcelable * The intent to execute when the expanded status entry is clicked. If * this is an activity, it must include the * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires - * that you take care of task management as described in the - * <a href="{@docRoot}intro/appmodel.html">application model</a> document. + * that you take care of task management as described in the <em>Activities and Tasks</em> + * section of the <a href="{@docRoot}guide/topics/fundamentals.html#acttask">Application + * Fundamentals</a> document. */ public PendingIntent contentIntent; @@ -420,8 +421,8 @@ public class Notification implements Parcelable * @param contentIntent The intent to launch when the user clicks the expanded notification. * If this is an activity, it must include the * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires - * that you take care of task management as described in the - * <a href="{@docRoot}intro/appmodel.html">application model</a> document. + * that you take care of task management as described in + * <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Application Fundamentals: Activities and Tasks</a>. */ public void setLatestEventInfo(Context context, CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) { diff --git a/core/java/android/app/SearchDialog.java b/core/java/android/app/SearchDialog.java index 2e2a1a1..64f1ba2 100644 --- a/core/java/android/app/SearchDialog.java +++ b/core/java/android/app/SearchDialog.java @@ -16,11 +16,14 @@ package android.app; +import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.Resources.NotFoundException; @@ -34,6 +37,7 @@ import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.server.search.SearchableInfo; +import android.speech.RecognizerIntent; import android.text.Editable; import android.text.InputType; import android.text.TextUtils; @@ -50,6 +54,7 @@ import android.widget.AdapterView; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.CursorAdapter; +import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; @@ -59,6 +64,7 @@ import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import java.lang.ref.WeakReference; +import java.util.List; import java.util.concurrent.atomic.AtomicLong; /** @@ -94,6 +100,7 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS private TextView mBadgeLabel; private AutoCompleteTextView mSearchTextField; private Button mGoButton; + private ImageButton mVoiceButton; // interaction with searchable application private ComponentName mLaunchComponent; @@ -115,6 +122,10 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS private Uri mSuggestionData = null; private String mSuggestionQuery = null; + // For voice searching + private Intent mVoiceWebSearchIntent; + private Intent mVoiceAppSearchIntent; + // support for AutoCompleteTextView suggestions display private SuggestionsAdapter mSuggestionsAdapter; @@ -153,12 +164,15 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS mSearchTextField = (AutoCompleteTextView) findViewById(com.android.internal.R.id.search_src_text); mGoButton = (Button) findViewById(com.android.internal.R.id.search_go_btn); + mVoiceButton = (ImageButton) findViewById(com.android.internal.R.id.search_voice_btn); // attach listeners mSearchTextField.addTextChangedListener(mTextWatcher); mSearchTextField.setOnKeyListener(mTextKeyListener); mGoButton.setOnClickListener(mGoButtonClickListener); mGoButton.setOnKeyListener(mButtonsKeyListener); + mVoiceButton.setOnClickListener(mVoiceButtonClickListener); + mVoiceButton.setOnKeyListener(mButtonsKeyListener); // pre-hide all the extraneous elements mBadgeLabel.setVisibility(View.GONE); @@ -169,13 +183,19 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS setCanceledOnTouchOutside(true); // Set up broadcast filters - mCloseDialogsFilter = new - IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); + mCloseDialogsFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); mPackageFilter = new IntentFilter(); mPackageFilter.addAction(Intent.ACTION_PACKAGE_ADDED); mPackageFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); mPackageFilter.addAction(Intent.ACTION_PACKAGE_CHANGED); mPackageFilter.addDataScheme("package"); + + // Save voice intent for later queries/launching + mVoiceWebSearchIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); + mVoiceWebSearchIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, + RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH); + + mVoiceAppSearchIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); } /** @@ -261,16 +281,15 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS } /** - * Dismiss the search dialog. + * The search dialog is being dismissed, so handle all of the local shutdown operations. * - * This function is designed to be idempotent so it can be safely called at any time + * This function is designed to be idempotent so that dismiss() can be safely called at any time * (even if already closed) and more likely to really dump any memory. No leaks! */ @Override - public void dismiss() { - if (isShowing()) { - super.dismiss(); - } + public void onStop() { + super.onStop(); + setOnCancelListener(null); setOnDismissListener(null); @@ -281,6 +300,11 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS // This is OK - it just means we didn't have any registered } + // close any leftover cursor + if (mSuggestionsAdapter != null) { + mSuggestionsAdapter.changeCursor(null); + } + // dump extra memory we're hanging on to mLaunchComponent = null; mAppSearchData = null; @@ -408,6 +432,7 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS updateSearchButton(); updateSearchBadge(); updateQueryHint(); + updateVoiceButton(); // In order to properly configure the input method (if one is being used), we // need to let it know if we'll be providing suggestions. Although it would be @@ -500,6 +525,30 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS } /** + * Update the visibility of the voice button. There are actually two voice search modes, + * either of which will activate the button. + */ + private void updateVoiceButton() { + int visibility = View.GONE; + if (mSearchable.getVoiceSearchEnabled()) { + Intent testIntent = null; + if (mSearchable.getVoiceSearchLaunchWebSearch()) { + testIntent = mVoiceWebSearchIntent; + } else if (mSearchable.getVoiceSearchLaunchRecognizer()) { + testIntent = mVoiceAppSearchIntent; + } + if (testIntent != null) { + List<ResolveInfo> list = getContext().getPackageManager(). + queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY); + if (list.size() > 0) { + visibility = View.VISIBLE; + } + } + } + mVoiceButton.setVisibility(visibility); + } + + /** * Listeners of various types */ @@ -642,11 +691,97 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS }; /** + * React to a click in the voice search button. + */ + View.OnClickListener mVoiceButtonClickListener = new View.OnClickListener() { + public void onClick(View v) { + try { + if (mSearchable.getVoiceSearchLaunchWebSearch()) { + getContext().startActivity(mVoiceWebSearchIntent); + dismiss(); + } else if (mSearchable.getVoiceSearchLaunchRecognizer()) { + Intent appSearchIntent = createVoiceAppSearchIntent(mVoiceAppSearchIntent); + getContext().startActivity(appSearchIntent); + dismiss(); + } + } catch (ActivityNotFoundException e) { + // Should not happen, since we check the availability of + // voice search before showing the button. But just in case... + Log.w(LOG_TAG, "Could not find voice search activity"); + } + } + }; + + /** + * Create and return an Intent that can launch the voice search activity, perform a specific + * voice transcription, and forward the results to the searchable activity. + * + * @param baseIntent The voice app search intent to start from + * @return A completely-configured intent ready to send to the voice search activity + */ + private Intent createVoiceAppSearchIntent(Intent baseIntent) { + // create the necessary intent to set up a search-and-forward operation + // in the voice search system. We have to keep the bundle separate, + // because it becomes immutable once it enters the PendingIntent + Intent queryIntent = new Intent(Intent.ACTION_SEARCH); + queryIntent.setComponent(mSearchable.mSearchActivity); + PendingIntent pending = PendingIntent.getActivity( + getContext(), 0, queryIntent, PendingIntent.FLAG_ONE_SHOT); + + // Now set up the bundle that will be inserted into the pending intent + // when it's time to do the search. We always build it here (even if empty) + // because the voice search activity will always need to insert "QUERY" into + // it anyway. + Bundle queryExtras = new Bundle(); + if (mAppSearchData != null) { + queryExtras.putBundle(SearchManager.APP_DATA, mAppSearchData); + } + + // Now build the intent to launch the voice search. Add all necessary + // extras to launch the voice recognizer, and then all the necessary extras + // to forward the results to the searchable activity + Intent voiceIntent = new Intent(baseIntent); + + // Add all of the configuration options supplied by the searchable's metadata + String languageModel = RecognizerIntent.LANGUAGE_MODEL_FREE_FORM; + String prompt = null; + String language = null; + int maxResults = 1; + Resources resources = mActivityContext.getResources(); + if (mSearchable.getVoiceLanguageModeId() != 0) { + languageModel = resources.getString(mSearchable.getVoiceLanguageModeId()); + } + if (mSearchable.getVoicePromptTextId() != 0) { + prompt = resources.getString(mSearchable.getVoicePromptTextId()); + } + if (mSearchable.getVoiceLanguageId() != 0) { + language = resources.getString(mSearchable.getVoiceLanguageId()); + } + if (mSearchable.getVoiceMaxResults() != 0) { + maxResults = mSearchable.getVoiceMaxResults(); + } + voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel); + voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt); + voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language); + voiceIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults); + + // Add the values that configure forwarding the results + voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending); + voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras); + + return voiceIntent; + } + + /** * React to the user typing "enter" or other hardwired keys while typing in the search box. * This handles these special keys while the edit box has focus. */ View.OnKeyListener mTextKeyListener = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + cancel(); + return true; + } // also guard against possible race conditions (late arrival after dismiss) if (mSearchable != null && TextUtils.getTrimmedLength(mSearchTextField.getText()) > 0) { @@ -793,24 +928,6 @@ public class SearchDialog extends Dialog implements OnItemClickListener, OnItemS }; /** - * UI-thread handling of dialog dismiss. Called by mBroadcastReceiver.onReceive(). - * - * TODO: This is a really heavyweight solution for something that should be so simple. - * For example, we already have a handler, in our superclass, why aren't we sharing that? - * I think we need to investigate simplifying this entire methodology, or perhaps boosting - * it up into the Dialog class. - */ - private static final int MESSAGE_DISMISS = 0; - private Handler mDismissHandler = new Handler() { - @Override - public void handleMessage(Message msg) { - if (msg.what == MESSAGE_DISMISS) { - dismiss(); - } - } - }; - - /** * Various ways to launch searches */ diff --git a/core/java/android/app/SearchManager.java b/core/java/android/app/SearchManager.java index 0a37e81..2cc6de9 100644 --- a/core/java/android/app/SearchManager.java +++ b/core/java/android/app/SearchManager.java @@ -168,7 +168,8 @@ import android.view.KeyEvent; * <p><b>Managing focus and knowing if Search is active.</b> The search UI is not a separate * activity, and when the UI is invoked or dismissed, your activity will not typically be paused, * resumed, or otherwise notified by the methods defined in - * <a href="android.app.Activity#ActivityLifecycle">Activity Lifecycle</a>. The search UI is + * <a href="{@docRoot}guide/topics/fundamentals.html#actlife">Application Fundamentals: + * Activity Lifecycle</a>. The search UI is * handled in the same way as other system UI elements which may appear from time to time, such as * notifications, screen locks, or other system alerts: * <p>When the search UI appears, your activity will lose input focus. @@ -212,11 +213,11 @@ import android.view.KeyEvent; * {@link #QUERY getStringExtra(SearchManager.QUERY)}.</li> * <li>To identify and support your searchable activity, you'll need to * provide an XML file providing searchability configuration parameters, a reference to that - * in your searchable activity's <a href="../../../devel/bblocks-manifest.html">manifest</a> + * in your searchable activity's <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a> * entry, and an intent-filter declaring that you can * receive ACTION_SEARCH intents. This is described in more detail in the * <a href="#SearchabilityMetadata">Searchability Metadata</a> section.</li> - * <li>Your <a href="../../../devel/bblocks-manifest.html">manifest</a> also needs a metadata entry + * <li>Your <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a> also needs a metadata entry * providing a global reference to the searchable activity. This is the "glue" directing the search * UI, when invoked from any of your <i>other</i> activities, to use your application as the * default search context. This is also described in more detail in the @@ -359,7 +360,7 @@ import android.view.KeyEvent; * <li>Implement a Content Provider that provides suggestions. If you already have one, and it * has access to your suggestions data. If not, you'll have to create one. * You'll also provide information about your Content Provider in your - * package's <a href="../../../devel/bblocks-manifest.html">manifest</a>.</li> + * package's <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a>.</li> * <li>Update your searchable activity's XML configuration file. There are two categories of * information used for suggestions: * <ul><li>The first is (required) data that the search manager will @@ -634,7 +635,7 @@ import android.view.KeyEvent; * * <p><b>Metadata for searchable activity.</b> As with your search implementations described * above, you must first identify which of your activities is searchable. In the - * <a href="../../../devel/bblocks-manifest.html">manifest</a> entry for this activity, you must + * <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a> entry for this activity, you must * provide two elements: * <ul><li>An intent-filter specifying that you can receive and process the * {@link android.content.Intent#ACTION_SEARCH ACTION_SEARCH} {@link android.content.Intent Intent}. @@ -643,7 +644,7 @@ import android.view.KeyEvent; * remaining configuration information for how your application implements search.</li></ul> * * <p>Here is a snippet showing the necessary elements in the - * <a href="../../../devel/bblocks-manifest.html">manifest</a> entry for your searchable activity. + * <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a> entry for your searchable activity. * <pre class="prettyprint"> * <!-- Search Activity - searchable --> * <activity android:name="MySearchActivity" @@ -765,9 +766,8 @@ import android.view.KeyEvent; * <li>.../res/values/strings.xml</li></ul> * * <p>For more complete documentation on this capability, see - * <a href="../../../devel/resources-i18n.html#AlternateResources">Resources and - * Internationalization: Supporting Alternate Resources for Alternate Languages and Configurations - * </a>. + * <a href="{@docRoot}guide/topics/resources/resources-i18n.html#AlternateResources">Resources and + * Internationalization: Alternate Resources</a>. * * <p><b>Metadata for non-searchable activities.</b> Activities which are part of a searchable * application, but don't implement search itself, require a bit of "glue" in order to cause @@ -775,7 +775,7 @@ import android.view.KeyEvent; * provided, then searches from these activities will use the system default search context. * * <p>The simplest way to specify this is to add a <i>search reference</i> element to the - * application entry in the <a href="../../../devel/bblocks-manifest.html">manifest</a> file. + * application entry in the <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a> file. * The value of this reference can be either of: * <ul><li>The name of your searchable activity. * It is typically prefixed by '.' to indicate that it's in the same package.</li> @@ -803,7 +803,7 @@ import android.view.KeyEvent; * to generate search suggestions, you'll need to publish it to the system, and you'll need to * provide a bit of additional XML metadata in order to configure communications with it. * - * <p>First, in your <a href="../../../devel/bblocks-manifest.html">manifest</a>, you'll add the + * <p>First, in your <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a>, you'll add the * following lines. * <pre class="prettyprint"> * <!-- Content provider for search suggestions --> @@ -832,7 +832,7 @@ import android.view.KeyEvent; * <tbody> * <tr><th>android:searchSuggestAuthority</th> * <td>This value must match the authority string provided in the <i>provider</i> section - * of your <a href="../../../devel/bblocks-manifest.html">manifest</a>.</td> + * of your <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest</a>.</td> * <td align="center">Yes</td> * </tr> * diff --git a/core/java/android/app/Service.java b/core/java/android/app/Service.java index 6c08e75..72692f4 100644 --- a/core/java/android/app/Service.java +++ b/core/java/android/app/Service.java @@ -42,12 +42,12 @@ import java.io.PrintWriter; * thread of their hosting process. This means that, if your service is going * to do any CPU intensive (such as MP3 playback) or blocking (such as * networking) operations, it should spawn its own thread in which to do that - * work. More information on this can be found in the - * <a href="{@docRoot}intro/appmodel.html#Threads">Threading section of the - * Application Model overview</a>.</p> + * work. More information on this can be found in + * <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals: + * Processes and Threads</a>.</p> * * <p>The Service class is an important part of an - * <a href="{@docRoot}intro/lifecycle.html">application's overall lifecycle</a>.</p> + * <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">application's overall lifecycle</a>.</p> * * <p>Topics covered here: * <ol> @@ -79,7 +79,7 @@ import java.io.PrintWriter; * to the service. The service will remain running as long as the connection * is established (whether or not the client retains a reference on the * service's IBinder). Usually the IBinder returned is for a complex - * interface that has been <a href="{@docRoot}reference/aidl.html">written + * interface that has been <a href="{@docRoot}guide/developing/tools/aidl.html">written * in aidl</a>. * * <p>A service can be both started and have connections bound to it. In such @@ -106,7 +106,7 @@ import java.io.PrintWriter; * {@link #checkCallingPermission} * method before executing the implementation of that call. * - * <p>See the <a href="{@docRoot}devel/security.html">Security Model</a> + * <p>See the <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a> * document for more information on permissions and security in general. * * <a name="ProcessLifecycle"></a> @@ -201,14 +201,14 @@ public abstract class Service extends ContextWrapper implements ComponentCallbac * Return the communication channel to the service. May return null if * clients can not bind to the service. The returned * {@link android.os.IBinder} is usually for a complex interface - * that has been <a href="{@docRoot}reference/aidl.html">described using + * that has been <a href="{@docRoot}guide/developing/tools/aidl.html">described using * aidl</a>. * * <p><em>Note that unlike other application components, calls on to the * IBinder interface returned here may not happen on the main thread * of the process</em>. More information about this can be found - * in the <a href="{@docRoot}intro/appmodel.html#Threads">Threading section - * of the Application Model overview</a>.</p> + * in <a href="{@docRoot}guide/topics/fundamentals.html#procthread">Application Fundamentals: + * Processes and Threads</a>.</p> * * @param intent The Intent that was used to bind to this service, * as given to {@link android.content.Context#bindService diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java index d613e1c..56b231f 100644 --- a/core/java/android/bluetooth/BluetoothDevice.java +++ b/core/java/android/bluetooth/BluetoothDevice.java @@ -31,10 +31,15 @@ import java.io.UnsupportedEncodingException; * @hide */ public class BluetoothDevice { - public static final int MODE_UNKNOWN = -1; - public static final int MODE_OFF = 0; - public static final int MODE_CONNECTABLE = 1; - public static final int MODE_DISCOVERABLE = 2; + /** Inquiry scan and page scan are both off. + * Device is neither discoverable nor connectable */ + public static final int SCAN_MODE_NONE = 0; + /** Page scan is on, inquiry scan is off. + * Device is connectable, but not discoverable */ + public static final int SCAN_MODE_CONNECTABLE = 1; + /** Page scan and inquiry scan are on. + * Device is connectable and discoverable */ + public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 3; public static final int RESULT_FAILURE = -1; public static final int RESULT_SUCCESS = 0; @@ -54,10 +59,10 @@ public class BluetoothDevice { /** A bond attempt failed because the other side explicilty rejected * bonding */ public static final int UNBOND_REASON_AUTH_REJECTED = 2; - /** A bond attempt failed because we cancelled the bonding process */ - public static final int UNBOND_REASON_CANCELLED = 3; + /** A bond attempt failed because we canceled the bonding process */ + public static final int UNBOND_REASON_AUTH_CANCELED = 3; /** A bond attempt failed because we could not contact the remote device */ - public static final int UNBOND_REASON_AUTH_REMOTE_DEVICE_DOWN = 4; + public static final int UNBOND_REASON_REMOTE_DEVICE_DOWN = 4; /** An existing bond was explicitly revoked */ public static final int UNBOND_REASON_REMOVED = 5; @@ -174,18 +179,6 @@ public class BluetoothDevice { return false; } - public String getMajorClass() { - try { - return mService.getMajorClass(); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } - public String getMinorClass() { - try { - return mService.getMinorClass(); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } public String getVersion() { try { return mService.getVersion(); @@ -211,15 +204,26 @@ public class BluetoothDevice { return null; } - public int getMode() { + /** + * Get the current scan mode. + * Used to determine if the local device is connectable and/or discoverable + * @return Scan mode, one of SCAN_MODE_* or an error code + */ + public int getScanMode() { try { - return mService.getMode(); + return mService.getScanMode(); } catch (RemoteException e) {Log.e(TAG, "", e);} - return MODE_UNKNOWN; + return BluetoothError.ERROR_IPC; } - public void setMode(int mode) { + + /** + * Set the current scan mode. + * Used to make the local device connectable and/or discoverable + * @param scanMode One of SCAN_MODE_* + */ + public void setScanMode(int scanMode) { try { - mService.setMode(mode); + mService.setScanMode(scanMode); } catch (RemoteException e) {Log.e(TAG, "", e);} } @@ -435,24 +439,6 @@ public class BluetoothDevice { return null; } - public String getRemoteAlias(String address) { - try { - return mService.getRemoteAlias(address); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } - public boolean setRemoteAlias(String address, String alias) { - try { - return mService.setRemoteAlias(address, alias); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return false; - } - public boolean clearRemoteAlias(String address) { - try { - return mService.clearRemoteAlias(address); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return false; - } public String getRemoteVersion(String address) { try { return mService.getRemoteVersion(address); @@ -477,24 +463,6 @@ public class BluetoothDevice { } catch (RemoteException e) {Log.e(TAG, "", e);} return null; } - public String getRemoteMajorClass(String address) { - try { - return mService.getRemoteMajorClass(address); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } - public String getRemoteMinorClass(String address) { - try { - return mService.getRemoteMinorClass(address); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } - public String[] getRemoteServiceClasses(String address) { - try { - return mService.getRemoteServiceClasses(address); - } catch (RemoteException e) {Log.e(TAG, "", e);} - return null; - } /** * Returns the RFCOMM channel associated with the 16-byte UUID on @@ -512,12 +480,19 @@ public class BluetoothDevice { return false; } + /** + * Get the major, minor and servics classes of a remote device. + * These classes are encoded as a 32-bit integer. See BluetoothClass. + * @param address remote device + * @return 32-bit class suitable for use with BluetoothClass. + */ public int getRemoteClass(String address) { try { return mService.getRemoteClass(address); } catch (RemoteException e) {Log.e(TAG, "", e);} return BluetoothClass.ERROR; } + public byte[] getRemoteFeatures(String address) { try { return mService.getRemoteFeatures(address); @@ -576,8 +551,8 @@ public class BluetoothDevice { } - /* Sanity check a bluetooth address, such as "00:43:A8:23:10:F0" */ private static final int ADDRESS_LENGTH = 17; + /** Sanity check a bluetooth address, such as "00:43:A8:23:10:F0" */ public static boolean checkBluetoothAddress(String address) { if (address == null || address.length() != ADDRESS_LENGTH) { return false; diff --git a/core/java/android/bluetooth/BluetoothHeadset.java b/core/java/android/bluetooth/BluetoothHeadset.java index c315271..34196bf 100644 --- a/core/java/android/bluetooth/BluetoothHeadset.java +++ b/core/java/android/bluetooth/BluetoothHeadset.java @@ -69,8 +69,8 @@ public class BluetoothHeadset { public static final int RESULT_FAILURE = 0; public static final int RESULT_SUCCESS = 1; - /** Connection cancelled before completetion. */ - public static final int RESULT_CANCELLED = 2; + /** Connection canceled before completetion. */ + public static final int RESULT_CANCELED = 2; /** Default priority for headsets that should be auto-connected */ public static final int PRIORITY_AUTO = 100; @@ -318,6 +318,12 @@ public class BluetoothHeadset { * @return True if this device might support HSP or HFP. */ public static boolean doesClassMatch(int btClass) { + // The render service class is required by the spec for HFP, so is a + // pretty good signal + if (BluetoothClass.Service.hasService(btClass, BluetoothClass.Service.RENDER)) { + return true; + } + // Just in case they forgot the render service class switch (BluetoothClass.Device.getDevice(btClass)) { case BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE: case BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET: diff --git a/core/java/android/bluetooth/BluetoothIntent.java b/core/java/android/bluetooth/BluetoothIntent.java index 57c46f9..b66b06e 100644 --- a/core/java/android/bluetooth/BluetoothIntent.java +++ b/core/java/android/bluetooth/BluetoothIntent.java @@ -29,8 +29,8 @@ import android.annotation.SdkConstant.SdkConstantType; * @hide */ public interface BluetoothIntent { - public static final String MODE = - "android.bluetooth.intent.MODE"; + public static final String SCAN_MODE = + "android.bluetooth.intent.SCAN_MODE"; public static final String ADDRESS = "android.bluetooth.intent.ADDRESS"; public static final String NAME = @@ -62,9 +62,14 @@ public interface BluetoothIntent { @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String NAME_CHANGED_ACTION = "android.bluetooth.intent.action.NAME_CHANGED"; + + /** + * Broadcast when the scan mode changes. Always contains an int extra + * named SCAN_MODE that contains the new scan mode. + */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) - public static final String MODE_CHANGED_ACTION = - "android.bluetooth.intent.action.MODE_CHANGED"; + public static final String SCAN_MODE_CHANGED_ACTION = + "android.bluetooth.intent.action.SCAN_MODE_CHANGED"; @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String DISCOVERY_STARTED_ACTION = @@ -104,12 +109,6 @@ public interface BluetoothIntent { @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String REMOTE_NAME_FAILED_ACTION = "android.bluetooth.intent.action.REMOTE_NAME_FAILED"; - @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) - public static final String REMOTE_ALIAS_CHANGED_ACTION = - "android.bluetooth.intent.action.REMOTE_ALIAS_CHANGED"; - @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) - public static final String REMOTE_ALIAS_CLEARED_ACTION = - "android.bluetooth.intent.action.REMOTE_ALIAS_CLEARED"; /** * Broadcast when the bond state of a remote device changes. diff --git a/core/java/android/bluetooth/HeadsetBase.java b/core/java/android/bluetooth/HeadsetBase.java index bce3388..fd2d2ab 100644 --- a/core/java/android/bluetooth/HeadsetBase.java +++ b/core/java/android/bluetooth/HeadsetBase.java @@ -21,13 +21,10 @@ import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.util.Log; -import java.io.IOException; -import java.lang.Thread; - /** * The Android Bluetooth API is not finalized, and *will* change. Use at your * own risk. - * + * * The base RFCOMM (service) connection for a headset or handsfree device. * * In the future this class will be removed. @@ -90,7 +87,7 @@ public class HeadsetBase { /* Create from an already exisiting rfcomm connection */ public HeadsetBase(PowerManager pm, BluetoothDevice bluetooth, String address, int socketFd, - int rfcommChannel, Handler handler) { + int rfcommChannel, Handler handler) { mDirection = DIRECTION_INCOMING; mConnectTimestamp = System.currentTimeMillis(); mBluetooth = bluetooth; @@ -132,30 +129,8 @@ public class HeadsetBase { */ protected void initializeAtParser() { mAtParser = new AtParser(); - - // Microphone Gain - mAtParser.register("+VGM", new AtCommandHandler() { - @Override - public AtCommandResult handleSetCommand(Object[] args) { - // AT+VGM=<gain> in range [0,15] - // Headset/Handsfree is reporting its current gain setting - //TODO: sync to android UI - //TODO: Send unsolicited +VGM when volume changed on AG - return new AtCommandResult(AtCommandResult.OK); - } - }); - - // Speaker Gain - mAtParser.register("+VGS", new AtCommandHandler() { - @Override - public AtCommandResult handleSetCommand(Object[] args) { - // AT+VGS=<gain> in range [0,15] - // Headset/Handsfree is reporting its current gain to Android - //TODO: sync to AG UI - //TODO: Send unsolicited +VGS when volume changed on AG - return new AtCommandResult(AtCommandResult.OK); - } - }); + //TODO(): Get rid of this as there are no parsers registered. But because of dependencies, + //it needs to be done as part of refactoring HeadsetBase and BluetoothHandsfree } public AtParser getAtParser() { diff --git a/core/java/android/bluetooth/IBluetoothDevice.aidl b/core/java/android/bluetooth/IBluetoothDevice.aidl index 59f679f..4351d2e 100644 --- a/core/java/android/bluetooth/IBluetoothDevice.aidl +++ b/core/java/android/bluetooth/IBluetoothDevice.aidl @@ -32,15 +32,13 @@ interface IBluetoothDevice String getAddress(); String getName(); boolean setName(in String name); - String getMajorClass(); - String getMinorClass(); String getVersion(); String getRevision(); String getManufacturer(); String getCompany(); - int getMode(); - boolean setMode(int mode); + int getScanMode(); + boolean setScanMode(int mode); int getDiscoverableTimeout(); boolean setDiscoverableTimeout(int timeout); @@ -64,17 +62,11 @@ interface IBluetoothDevice int getBondState(in String address); String getRemoteName(in String address); - String getRemoteAlias(in String address); - boolean setRemoteAlias(in String address, in String alias); - boolean clearRemoteAlias(in String address); String getRemoteVersion(in String address); String getRemoteRevision(in String address); int getRemoteClass(in String address); String getRemoteManufacturer(in String address); String getRemoteCompany(in String address); - String getRemoteMajorClass(in String address); - String getRemoteMinorClass(in String address); - String[] getRemoteServiceClasses(in String address); boolean getRemoteServiceChannel(in String address, int uuid16, in IBluetoothDeviceCallback callback); byte[] getRemoteFeatures(in String adddress); String lastSeen(in String address); diff --git a/core/java/android/content/AsyncQueryHandler.java b/core/java/android/content/AsyncQueryHandler.java index 2d651a7..ac851cc 100644 --- a/core/java/android/content/AsyncQueryHandler.java +++ b/core/java/android/content/AsyncQueryHandler.java @@ -146,6 +146,20 @@ public abstract class AsyncQueryHandler extends Handler { * @param token A token passed into {@link #onQueryComplete} to identify * the query. * @param cookie An object that gets passed into {@link #onQueryComplete} + * @param uri The URI, using the content:// scheme, for the content to + * retrieve. + * @param projection A list of which columns to return. Passing null will + * return all columns, which is discouraged to prevent reading data + * from storage that isn't going to be used. + * @param selection A filter declaring which rows to return, formatted as an + * SQL WHERE clause (excluding the WHERE itself). Passing null will + * return all rows for the given URI. + * @param selectionArgs You may include ?s in selection, which will be + * replaced by the values from selectionArgs, in the order that they + * appear in the selection. The values will be bound as Strings. + * @param orderBy How to order the rows, formatted as an SQL ORDER BY + * clause (excluding the ORDER BY itself). Passing null will use the + * default sort order, which may be unordered. */ public void startQuery(int token, Object cookie, Uri uri, String[] projection, String selection, String[] selectionArgs, diff --git a/core/java/android/content/BroadcastReceiver.java b/core/java/android/content/BroadcastReceiver.java index cd92002..ee08eea 100644 --- a/core/java/android/content/BroadcastReceiver.java +++ b/core/java/android/content/BroadcastReceiver.java @@ -16,7 +16,11 @@ package android.content; +import android.app.ActivityManagerNative; +import android.app.IActivityManager; import android.os.Bundle; +import android.os.IBinder; +import android.os.RemoteException; import android.util.Log; /** @@ -175,7 +179,9 @@ public abstract class BroadcastReceiver { * return a result to you asynchronously -- in particular, for interacting * with services, you should use * {@link Context#startService(Intent)} instead of - * {@link Context#bindService(Intent, ServiceConnection, int)}. + * {@link Context#bindService(Intent, ServiceConnection, int)}. If you wish + * to interact with a service that is already running, you can use + * {@link #peekService}. * * @param context The Context in which the receiver is running. * @param intent The Intent being received. @@ -183,6 +189,26 @@ public abstract class BroadcastReceiver { public abstract void onReceive(Context context, Intent intent); /** + * Provide a binder to an already-running service. This method is synchronous + * and will not start the target service if it is not present, so it is safe + * to call from {@link #onReceive}. + * + * @param myContext The Context that had been passed to {@link #onReceive(Context, Intent)} + * @param service The Intent indicating the service you wish to use. See {@link + * Context#startService(Intent)} for more information. + */ + public IBinder peekService(Context myContext, Intent service) { + IActivityManager am = ActivityManagerNative.getDefault(); + IBinder binder = null; + try { + binder = am.peekService(service, service.resolveTypeIfNeeded( + myContext.getContentResolver())); + } catch (RemoteException e) { + } + return binder; + } + + /** * Change the current result code of this broadcast; only works with * broadcasts sent through * {@link Context#sendOrderedBroadcast(Intent, String) diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java index 3908aa1..e0fe533 100644 --- a/core/java/android/content/Context.java +++ b/core/java/android/content/Context.java @@ -127,7 +127,7 @@ public abstract class Context { * current process. */ public abstract Context getApplicationContext(); - + /** * Return a localized, styled CharSequence from the application's package's * default string table. @@ -428,7 +428,7 @@ public abstract class Context { * cursor when query is called. * * @return The contents of a newly created database with the given name. - * @throws SQLiteException if the database file could not be opened. + * @throws android.database.sqlite.SQLiteException if the database file could not be opened. * * @see #MODE_PRIVATE * @see #MODE_WORLD_READABLE @@ -1064,7 +1064,7 @@ public abstract class Context { * @see #AUDIO_SERVICE * @see android.media.AudioManager * @see #TELEPHONY_SERVICE - * @see android.internal.TelephonyManager + * @see android.telephony.TelephonyManager * @see #INPUT_METHOD_SERVICE * @see android.view.inputmethod.InputMethodManager */ diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java index e2d3576..52aae0d 100644 --- a/core/java/android/content/Intent.java +++ b/core/java/android/content/Intent.java @@ -504,6 +504,8 @@ import java.util.Set; * <li> {@link #ACTION_PACKAGE_ADDED} * <li> {@link #ACTION_PACKAGE_CHANGED} * <li> {@link #ACTION_PACKAGE_REMOVED} + * <li> {@link #ACTION_PACKAGE_RESTARTED} + * <li> {@link #ACTION_PACKAGE_DATA_CLEARED} * <li> {@link #ACTION_UID_REMOVED} * <li> {@link #ACTION_BATTERY_CHANGED} * </ul> @@ -1107,6 +1109,10 @@ public class Intent implements Parcelable { /** * Broadcast Action: A new application package has been installed on the * device. The data contains the name of the package. + * <p>My include the following extras: + * <ul> + * <li> {@link #EXTRA_UID} containing the integer uid assigned to the new package. + * </ul> */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_PACKAGE_ADDED = "android.intent.action.PACKAGE_ADDED"; @@ -1114,23 +1120,49 @@ public class Intent implements Parcelable { * Broadcast Action: An existing application package has been removed from * the device. The data contains the name of the package. The package * that is being installed does <em>not</em> receive this Intent. + * <ul> + * <li> {@link #EXTRA_UID} containing the integer uid previously assigned + * to the package. + * <li> {@link #EXTRA_DATA_REMOVED} is set to true if the entire + * application -- data and code -- is being removed. + * <li> {@link #EXTRA_REPLACING} is set to true if this will be followed + * by an {@link #ACTION_PACKAGE_ADDED} broadcast for the same package. + * </ul> */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_PACKAGE_REMOVED = "android.intent.action.PACKAGE_REMOVED"; /** * Broadcast Action: An existing application package has been changed (e.g. a component has been * enabled or disabled. The data contains the name of the package. + * <ul> + * <li> {@link #EXTRA_UID} containing the integer uid assigned to the package. + * </ul> */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_PACKAGE_CHANGED = "android.intent.action.PACKAGE_CHANGED"; /** - * Broadcast Action: The user has restarted a package, all runtime state + * Broadcast Action: The user has restarted a package, and all of its + * processes have been killed. All runtime state * associated with it (processes, alarms, notifications, etc) should - * be remove. The data contains the name of the package. + * be removed. The data contains the name of the package. + * <ul> + * <li> {@link #EXTRA_UID} containing the integer uid assigned to the package. + * </ul> */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_PACKAGE_RESTARTED = "android.intent.action.PACKAGE_RESTARTED"; /** + * Broadcast Action: The user has cleared the data of a package. This should + * be preceded by {@link #ACTION_PACKAGE_RESTARTED}, after which all of + * its persistent data is erased and this broadcast sent. The data contains + * the name of the package. + * <ul> + * <li> {@link #EXTRA_UID} containing the integer uid assigned to the package. + * </ul> + */ + @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) + public static final String ACTION_PACKAGE_DATA_CLEARED = "android.intent.action.PACKAGE_DATA_CLEARED"; + /** * Broadcast Action: A user ID has been removed from the system. The user * ID number is stored in the extra data under {@link #EXTRA_UID}. */ @@ -1227,7 +1259,6 @@ public class Intent implements Parcelable { /** * Broadcast Action: External media is present, and being disk-checked * The path to the mount point for the checking media is contained in the Intent.mData field. - * @hide */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_MEDIA_CHECKING = "android.intent.action.MEDIA_CHECKING"; @@ -1235,7 +1266,6 @@ public class Intent implements Parcelable { /** * Broadcast Action: External media is present, but is using an incompatible fs (or is blank) * The path to the mount point for the checking media is contained in the Intent.mData field. - * @hide */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_MEDIA_NOFS = "android.intent.action.MEDIA_NOFS"; @@ -1656,6 +1686,22 @@ public class Intent implements Parcelable { public static final String EXTRA_UID = "android.intent.extra.UID"; /** + * Used as a boolean extra field in {@link android.content.Intent#ACTION_PACKAGE_REMOVED} + * intents to indicate whether this represents a full uninstall (removing + * both the code and its data) or a partial uninstall (leaving its data, + * implying that this is an update). + */ + public static final String EXTRA_DATA_REMOVED = "android.intent.extra.DATA_REMOVED"; + + /** + * Used as a boolean extra field in {@link android.content.Intent#ACTION_PACKAGE_REMOVED} + * intents to indicate that this is a replacement of the package, so this + * broadcast will immediately be followed by an add broadcast for a + * different version of the same package. + */ + public static final String EXTRA_REPLACING = "android.intent.extra.REPLACING"; + + /** * Used as an int extra field in {@link android.app.AlarmManager} intents * to tell the application being invoked how many pending alarms are being * delievered with the intent. For one-shot alarms this will always be 1. @@ -1770,8 +1816,8 @@ public class Intent implements Parcelable { * Intent, resulting in the stack now being: A, B. * * <p>The currently running instance of task B in the above example will - * either receiving the new intent you are starting here in its - * onNewIntent() method, or be itself finished and restarting with the + * either receive the new intent you are starting here in its + * onNewIntent() method, or be itself finished and restarted with the * new intent. If it has declared its launch mode to be "multiple" (the * default) it will be finished and re-created; for all other launch modes * it will receive the Intent in the current instance. @@ -1855,7 +1901,7 @@ public class Intent implements Parcelable { */ public static final int FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET = 0x00080000; /** - * If set, this flag will prevent the normal {@link android.app.Activity#onUserLeaving} + * If set, this flag will prevent the normal {@link android.app.Activity#onUserLeaveHint} * callback from occurring on the current frontmost activity before it is * paused as the newly-started activity is brought to the front. * @@ -1871,12 +1917,39 @@ public class Intent implements Parcelable { * activity does not think the user has acknowledged its notification. */ public static final int FLAG_ACTIVITY_NO_USER_ACTION = 0x00040000; - + /** + * If set in an Intent passed to {@link Context#startActivity Context.startActivity()}, + * this flag will cause the launched activity to be brought to the front of its + * task's history stack if it is already running. + * + * <p>For example, consider a task consisting of four activities: A, B, C, D. + * If D calls startActivity() with an Intent that resolves to the component + * of activity B, then B will be brought to the front of the history stack, + * with this resulting order: A, C, D, B. + * + * This flag will be ignored if {@link #FLAG_ACTIVITY_CLEAR_TOP} is also + * specified. + */ + public static final int FLAG_ACTIVITY_REORDER_TO_FRONT = 0X00020000; /** * If set, when sending a broadcast only registered receivers will be * called -- no BroadcastReceiver components will be launched. */ public static final int FLAG_RECEIVER_REGISTERED_ONLY = 0x40000000; + /** + * If set, when sending a broadcast <i>before boot has completed</i> only + * registered receivers will be called -- no BroadcastReceiver components + * will be launched. Sticky intent state will be recorded properly even + * if no receivers wind up being called. If {@link #FLAG_RECEIVER_REGISTERED_ONLY} + * is specified in the broadcast intent, this flag is unnecessary. + * + * <p>This flag is only for use by system sevices as a convenience to + * avoid having to implement a more complex mechanism around detection + * of boot completion. + * + * @hide + */ + public static final int FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT = 0x20000000; // --------------------------------------------------------------------- diff --git a/core/java/android/content/SyncManager.java b/core/java/android/content/SyncManager.java index 6bc3774..96470c3 100644 --- a/core/java/android/content/SyncManager.java +++ b/core/java/android/content/SyncManager.java @@ -123,7 +123,7 @@ class SyncManager { private static final String SYNC_WAKE_LOCK = "SyncManagerSyncWakeLock"; private static final String HANDLE_SYNC_ALARM_WAKE_LOCK = "SyncManagerHandleSyncAlarmWakeLock"; - + private Context mContext; private ContentResolver mContentResolver; @@ -249,7 +249,7 @@ class SyncManager { mSyncQueue = new SyncQueue(mSyncStorageEngine); mContext = context; - + mSyncThread = new HandlerThread("SyncHandlerThread", Process.THREAD_PRIORITY_BACKGROUND); mSyncThread.start(); mSyncHandler = new SyncHandler(mSyncThread.getLooper()); @@ -489,7 +489,7 @@ class SyncManager { // Require the precise value "yes" to discourage accidental activation. return "yes".equals(SystemProperties.get("ro.config.sync")); } - + /** * Initiate a sync. This can start a sync for all providers * (pass null to url, set onlyTicklable to false), only those @@ -515,7 +515,7 @@ class SyncManager { * syncs of a specific provider. Can be null. Is ignored * if the url is null. * @param delay how many milliseconds in the future to wait before performing this - * sync. -1 means to make this the next sync to perform. + * sync. -1 means to make this the next sync to perform. */ public void scheduleSync(Uri url, Bundle extras, long delay) { boolean isLoggable = Log.isLoggable(TAG, Log.VERBOSE); @@ -694,7 +694,7 @@ class SyncManager { class SyncHandlerMessagePayload { public final ActiveSyncContext activeSyncContext; public final SyncResult syncResult; - + SyncHandlerMessagePayload(ActiveSyncContext syncContext, SyncResult syncResult) { this.activeSyncContext = syncContext; this.syncResult = syncResult; @@ -740,7 +740,7 @@ class SyncManager { if (newDelayInMs > maxSyncRetryTimeInSeconds * 1000) { newDelayInMs = maxSyncRetryTimeInSeconds * 1000; } - + SyncOperation rescheduledSyncOperation = new SyncOperation(syncOperation); rescheduledSyncOperation.setDelay(newDelayInMs); scheduleSyncOperation(rescheduledSyncOperation); @@ -786,7 +786,7 @@ class SyncManager { // key than the one we are scheduling. if (!activeIsExpedited && !hasSameKey) { rescheduleImmediately(activeSyncContext.mSyncOperation); - sendSyncFinishedOrCanceledMessage(activeSyncContext, + sendSyncFinishedOrCanceledMessage(activeSyncContext, null /* no result since this is a cancel */); } } @@ -1323,7 +1323,7 @@ class SyncManager { public SyncHandler(Looper looper) { super(looper); } - + public void handleMessage(Message msg) { handleSyncHandlerMessage(msg); } @@ -1462,6 +1462,9 @@ class SyncManager { // start it, otherwise just get out. SyncOperation syncOperation; final Sync.Settings.QueryMap syncSettings = getSyncSettings(); + final ConnectivityManager connManager = (ConnectivityManager) + mContext.getSystemService(Context.CONNECTIVITY_SERVICE); + final boolean backgroundDataSetting = connManager.getBackgroundDataSetting(); synchronized (mSyncQueue) { while (true) { syncOperation = mSyncQueue.head(); @@ -1484,10 +1487,10 @@ class SyncManager { // skip the sync if it isn't a force and the settings are off for this provider final boolean force = syncOperation.extras.getBoolean( ContentResolver.SYNC_EXTRAS_FORCE, false); - if (!force && (!syncSettings.getBackgroundData() + if (!force && (!backgroundDataSetting || !syncSettings.getListenForNetworkTickles() || !syncSettings.getSyncProviderAutomatically( - syncOperation.authority))) { + syncOperation.authority))) { if (isLoggable) { Log.v(TAG, "runStateIdle: sync off, dropping " + syncOperation); } @@ -1669,7 +1672,7 @@ class SyncManager { * @param syncResult the SyncResult from which to read * @return the most "serious" error set in the SyncResult * @throws IllegalStateException if the SyncResult does not indicate any errors. - * If SyncResult.error() is true then it is safe to call this. + * If SyncResult.error() is true then it is safe to call this. */ private int syncResultToErrorNumber(SyncResult syncResult) { if (syncResult.syncAlreadyInProgress) return History.ERROR_SYNC_ALREADY_IN_PROGRESS; @@ -1679,7 +1682,8 @@ class SyncManager { if (syncResult.stats.numConflictDetectedExceptions > 0) return History.ERROR_CONFLICT; if (syncResult.tooManyDeletions) return History.ERROR_TOO_MANY_DELETIONS; if (syncResult.tooManyRetries) return History.ERROR_TOO_MANY_RETRIES; - throw new IllegalStateException("we are not in an error state, " + toString()); + if (syncResult.databaseError) return History.ERROR_INTERNAL; + throw new IllegalStateException("we are not in an error state, " + syncResult); } private void manageSyncNotification() { @@ -1717,7 +1721,7 @@ class SyncManager { if (mSyncNotificationInfo.isActive) { shouldInstall = shouldCancel; } else { - final boolean timeToShowNotification = + final boolean timeToShowNotification = now > mSyncNotificationInfo.startTime + SYNC_NOTIFICATION_DELAY; final boolean syncIsForced = syncOperation.extras .getBoolean(ContentResolver.SYNC_EXTRAS_FORCE, false); @@ -1769,7 +1773,7 @@ class SyncManager { if (!mDataConnectionIsConnected) return; if (mAccounts == null) return; if (mStorageIsLow) return; - + // Compute the alarm fire time: // - not syncing: time of the next sync operation // - syncing, no notification: time from sync start to notification create time @@ -1850,12 +1854,12 @@ class SyncManager { clickIntent.putExtra("account", account); clickIntent.putExtra("provider", authority); clickIntent.putExtra("numDeletes", numDeletes); - + if (!isActivityAvailable(clickIntent)) { Log.w(TAG, "No activity found to handle too many deletes."); return; } - + final PendingIntent pendingIntent = PendingIntent .getActivity(mContext, 0, clickIntent, PendingIntent.FLAG_CANCEL_CURRENT); @@ -1877,7 +1881,7 @@ class SyncManager { /** * Checks whether an activity exists on the system image for the given intent. - * + * * @param intent The intent for an activity. * @return Whether or not an activity exists. */ @@ -1892,10 +1896,10 @@ class SyncManager { return true; } } - + return false; } - + public long insertStartSyncEvent(SyncOperation syncOperation) { final int source = syncOperation.syncSource; final long now = System.currentTimeMillis(); diff --git a/core/java/android/content/TempProviderSyncAdapter.java b/core/java/android/content/TempProviderSyncAdapter.java index 78510aa..eb3a5da 100644 --- a/core/java/android/content/TempProviderSyncAdapter.java +++ b/core/java/android/content/TempProviderSyncAdapter.java @@ -1,11 +1,11 @@ package android.content; -import com.google.android.net.NetStats; - import android.database.SQLException; import android.os.Bundle; import android.os.Debug; +import android.os.NetStat; import android.os.Parcelable; +import android.os.Process; import android.os.SystemProperties; import android.text.TextUtils; import android.util.Config; @@ -177,7 +177,8 @@ public abstract class TempProviderSyncAdapter extends SyncAdapter { private final Bundle mExtras; private final SyncContext mSyncContext; private volatile boolean mIsCanceled = false; - private long[] mNetStats; + private long mInitialTxBytes; + private long mInitialRxBytes; private final SyncResult mResult; SyncThread(SyncContext syncContext, String account, Bundle extras) { @@ -193,15 +194,18 @@ public abstract class TempProviderSyncAdapter extends SyncAdapter { if (mAdapterSyncStarted) onSyncCanceled(); if (mProviderSyncStarted) mProvider.onSyncCanceled(); // We may lose the last few sync events when canceling. Oh well. - long[] newNetStats = NetStats.getStats(); - logSyncDetails(newNetStats[0] - mNetStats[0], newNetStats[1] - mNetStats[1], mResult); + int uid = Process.myUid(); + logSyncDetails(NetStat.getUidTxBytes(uid) - mInitialTxBytes, + NetStat.getUidRxBytes(uid) - mInitialRxBytes, mResult); } @Override public void run() { - android.os.Process.setThreadPriority(android.os.Process.myTid(), - android.os.Process.THREAD_PRIORITY_BACKGROUND); - mNetStats = NetStats.getStats(); + Process.setThreadPriority(Process.myTid(), + Process.THREAD_PRIORITY_BACKGROUND); + int uid = Process.myUid(); + mInitialTxBytes = NetStat.getUidTxBytes(uid); + mInitialRxBytes = NetStat.getUidRxBytes(uid); try { sync(mSyncContext, mAccount, mExtras); } catch (SQLException e) { @@ -210,8 +214,8 @@ public abstract class TempProviderSyncAdapter extends SyncAdapter { } finally { mSyncThread = null; if (!mIsCanceled) { - long[] newNetStats = NetStats.getStats(); - logSyncDetails(newNetStats[0] - mNetStats[0], newNetStats[1] - mNetStats[1], mResult); + logSyncDetails(NetStat.getUidTxBytes(uid) - mInitialTxBytes, + NetStat.getUidRxBytes(uid) - mInitialRxBytes, mResult); mSyncContext.onFinished(mResult); } } diff --git a/core/java/android/content/pm/ConfigurationInfo.java b/core/java/android/content/pm/ConfigurationInfo.java index 9115225..dcc7463 100755 --- a/core/java/android/content/pm/ConfigurationInfo.java +++ b/core/java/android/content/pm/ConfigurationInfo.java @@ -16,7 +16,6 @@ package android.content.pm; -import android.content.res.Configuration; import android.os.Parcel; import android.os.Parcelable; @@ -60,12 +59,12 @@ public class ConfigurationInfo implements Parcelable { /** * Value for {@link #reqInputFeatures}: if set, indicates that the application - * requires a hard keyboard + * requires a five way navigation device */ public static final int INPUT_FEATURE_FIVE_WAY_NAV = 0x00000002; /** - * Flags associated with the application. Any combination of + * Flags associated with the input features. Any combination of * {@link #INPUT_FEATURE_HARD_KEYBOARD}, * {@link #INPUT_FEATURE_FIVE_WAY_NAV} */ diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl index ea86188..d3f6f3c 100644 --- a/core/java/android/content/pm/IPackageManager.aidl +++ b/core/java/android/content/pm/IPackageManager.aidl @@ -255,8 +255,15 @@ interface IPackageManager { * retrieval of information is complete. */ void getPackageSizeInfo(in String packageName, IPackageStatsObserver observer); + + /** + * Get a list of shared libraries that are available on the + * system. + */ + String[] getSystemSharedLibraryNames(); void enterSafeMode(); + boolean isSafeMode(); void systemReady(); boolean hasSystemUidErrors(); } diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java index 4b902e9..698f27f 100644 --- a/core/java/android/content/pm/PackageManager.java +++ b/core/java/android/content/pm/PackageManager.java @@ -851,6 +851,16 @@ public abstract class PackageManager { * @see #GET_UNINSTALLED_PACKAGES */ public abstract List<ApplicationInfo> getInstalledApplications(int flags); + + /** + * Get a list of shared libraries that are available on the + * system. + * + * @return An array of shared library names that are + * available on the system, or null if none are installed. + * + */ + public abstract String[] getSystemSharedLibraryNames(); /** * Determine the best action to perform for a given Intent. This is how @@ -1608,4 +1618,9 @@ public abstract class PackageManager { * the manifest as found in {@link ComponentInfo}. */ public abstract int getApplicationEnabledSetting(String packageName); + + /** + * Return whether the device has been booted into safe mode. + */ + public abstract boolean isSafeMode(); } diff --git a/core/java/android/content/res/ColorStateList.java b/core/java/android/content/res/ColorStateList.java index 4b1e678..17cb687 100644 --- a/core/java/android/content/res/ColorStateList.java +++ b/core/java/android/content/res/ColorStateList.java @@ -304,6 +304,11 @@ public class ColorStateList implements Parcelable { } public void writeToParcel(Parcel dest, int flags) { + final int N = mStateSpecs.length; + dest.writeInt(N); + for (int i=0; i<N; i++) { + dest.writeIntArray(mStateSpecs[i]); + } dest.writeArray(mStateSpecs); dest.writeIntArray(mColors); } @@ -315,14 +320,11 @@ public class ColorStateList implements Parcelable { } public ColorStateList createFromParcel(Parcel source) { - Object[] o = source.readArray( - ColorStateList.class.getClassLoader()); - int[][] stateSpecs = new int[o.length][]; - - for (int i = 0; i < o.length; i++) { - stateSpecs[i] = (int[]) o[i]; + final int N = source.readInt(); + int[][] stateSpecs = new int[N][]; + for (int i=0; i<N; i++) { + stateSpecs[i] = source.createIntArray(); } - int[] colors = source.createIntArray(); return new ColorStateList(stateSpecs, colors); } diff --git a/core/java/android/content/res/Resources.java b/core/java/android/content/res/Resources.java index 10eced6..5a0daea 100644 --- a/core/java/android/content/res/Resources.java +++ b/core/java/android/content/res/Resources.java @@ -22,7 +22,6 @@ import com.android.internal.util.XmlUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; -import android.content.Intent; import android.graphics.Movie; import android.graphics.drawable.Drawable; import android.graphics.drawable.ColorDrawable; @@ -399,7 +398,6 @@ public class Resources { * * @throws NotFoundException Throws NotFoundException if the given ID does not exist. * - * @return CharSequence The string data associated with the resource, plus * @see #getDimensionPixelOffset * @see #getDimensionPixelSize */ @@ -432,7 +430,6 @@ public class Resources { * * @throws NotFoundException Throws NotFoundException if the given ID does not exist. * - * @return CharSequence The string data associated with the resource, plus * @see #getDimension * @see #getDimensionPixelSize */ @@ -467,7 +464,6 @@ public class Resources { * * @throws NotFoundException Throws NotFoundException if the given ID does not exist. * - * @return CharSequence The string data associated with the resource, plus * @see #getDimension * @see #getDimensionPixelOffset */ @@ -486,6 +482,36 @@ public class Resources { } /** + * Retrieve a fractional unit for a particular resource ID. + * + * @param id The desired resource identifier, as generated by the aapt + * tool. This integer encodes the package, type, and resource + * entry. The value 0 is an invalid identifier. + * @param base The base value of this fraction. In other words, a + * standard fraction is multiplied by this value. + * @param pbase The parent base value of this fraction. In other + * words, a parent fraction (nn%p) is multiplied by this + * value. + * + * @return Attribute fractional value multiplied by the appropriate + * base value. + * + * @throws NotFoundException Throws NotFoundException if the given ID does not exist. + */ + public float getFraction(int id, int base, int pbase) { + synchronized (mTmpValue) { + TypedValue value = mTmpValue; + getValue(id, value, true); + if (value.type == TypedValue.TYPE_FRACTION) { + return TypedValue.complexToFraction(value.data, base, pbase); + } + throw new NotFoundException( + "Resource ID #0x" + Integer.toHexString(id) + " type #0x" + + Integer.toHexString(value.type) + " is not valid"); + } + } + + /** * Return a drawable object associated with a particular resource ID. * Various types of objects will be returned depending on the underlying * resource -- for example, a solid color, PNG image, scalable image, etc. @@ -721,22 +747,36 @@ public class Resources { */ public InputStream openRawResource(int id) throws NotFoundException { synchronized (mTmpValue) { - TypedValue value = mTmpValue; - getValue(id, value, true); + return openRawResource(id, mTmpValue); + } + } - try { - return mAssets.openNonAsset( - value.assetCookie, value.string.toString(), - AssetManager.ACCESS_STREAMING); - } catch (Exception e) { - NotFoundException rnf = new NotFoundException( - "File " + value.string.toString() - + " from drawable resource ID #0x" - + Integer.toHexString(id)); - rnf.initCause(e); - throw rnf; - } + /** + * Open a data stream for reading a raw resource. This can only be used + * with resources whose value is the name of an asset files -- that is, it can be + * used to open drawable, sound, and raw resources; it will fail on string + * and color resources. + * + * @param id The resource identifier to open, as generated by the appt tool. + * @param value The TypedValue object to hold the resource information. + * + * @return InputStream Access to the resource data. + * + * @throws NotFoundException Throws NotFoundException if the given ID does not exist. + * + * @hide Pending API council approval + */ + public InputStream openRawResource(int id, TypedValue value) throws NotFoundException { + getValue(id, value, true); + try { + return mAssets.openNonAsset(value.assetCookie, value.string.toString(), + AssetManager.ACCESS_STREAMING); + } catch (Exception e) { + NotFoundException rnf = new NotFoundException("File " + value.string.toString() + + " from drawable resource ID #0x" + Integer.toHexString(id)); + rnf.initCause(e); + throw rnf; } } @@ -1588,7 +1628,7 @@ public class Resources { InputStream is = mAssets.openNonAsset( value.assetCookie, file, AssetManager.ACCESS_BUFFER); // System.out.println("Opened file " + file + ": " + is); - dr = Drawable.createFromStream(is, file); + dr = Drawable.createFromResourceStream(this, value, is, file); is.close(); // System.out.println("Created stream: " + dr); } catch (Exception e) { diff --git a/core/java/android/database/sqlite/SQLiteDatabase.java b/core/java/android/database/sqlite/SQLiteDatabase.java index fa062c8..87bb277 100644 --- a/core/java/android/database/sqlite/SQLiteDatabase.java +++ b/core/java/android/database/sqlite/SQLiteDatabase.java @@ -25,6 +25,7 @@ import android.os.SystemClock; import android.text.TextUtils; import android.util.Config; import android.util.Log; +import android.util.EventLog; import java.io.File; import java.util.HashMap; @@ -51,7 +52,8 @@ import java.util.concurrent.locks.ReentrantLock; * is the Unicode Collation Algorithm and not tailored to the current locale. */ public class SQLiteDatabase extends SQLiteClosable { - private final static String TAG = "Database"; + private static final String TAG = "Database"; + private static final int DB_OPERATION_EVENT = 52000; /** * Algorithms used in ON CONFLICT clause @@ -207,6 +209,11 @@ public class SQLiteDatabase extends SQLiteClosable { private WeakHashMap<SQLiteClosable, Object> mPrograms; private final RuntimeException mLeakedException; + + // package visible, since callers will access directly to minimize overhead in the case + // that logging is not enabled. + /* package */ final boolean mLogStats; + /** * @param closable */ @@ -436,7 +443,14 @@ public class SQLiteDatabase extends SQLiteClosable { if (mTransactionIsSuccessful) { execSQL("COMMIT;"); } else { - execSQL("ROLLBACK;"); + try { + execSQL("ROLLBACK;"); + } catch (SQLException e) { + if (Config.LOGD) { + Log.d(TAG, "exception during rollback, maybe the DB previously " + + "performed an auto-rollback"); + } + } } } finally { unlockForced(); @@ -1472,10 +1486,8 @@ public class SQLiteDatabase extends SQLiteClosable { * @throws SQLException If the SQL string is invalid for some reason */ public void execSQL(String sql) throws SQLException { - long timeStart = 0; - if (Config.LOGV) { - timeStart = System.currentTimeMillis(); - } + boolean logStats = mLogStats; + long timeStart = logStats ? SystemClock.elapsedRealtime() : 0; lock(); try { native_execSQL(sql); @@ -1485,9 +1497,8 @@ public class SQLiteDatabase extends SQLiteClosable { } finally { unlock(); } - if (Config.LOGV) { - long timeEnd = System.currentTimeMillis(); - Log.v(TAG, "Executed (" + (timeEnd - timeStart) + " ms):" + sql); + if (logStats) { + logTimeStat(false /* not a read */, timeStart, SystemClock.elapsedRealtime()); } } @@ -1504,10 +1515,9 @@ public class SQLiteDatabase extends SQLiteClosable { if (bindArgs == null) { throw new IllegalArgumentException("Empty bindArgs"); } - long timeStart = 0; - if (Config.LOGV) { - timeStart = System.currentTimeMillis(); - } + + boolean logStats = mLogStats; + long timeStart = logStats ? SystemClock.elapsedRealtime() : 0; lock(); SQLiteStatement statement = null; try { @@ -1528,9 +1538,8 @@ public class SQLiteDatabase extends SQLiteClosable { } unlock(); } - if (Config.LOGV) { - long timeEnd = System.currentTimeMillis(); - Log.v(TAG, "Executed (" + (timeEnd - timeStart) + " ms):" + sql); + if (logStats) { + logTimeStat(false /* not a read */, timeStart, SystemClock.elapsedRealtime()); } } @@ -1550,7 +1559,7 @@ public class SQLiteDatabase extends SQLiteClosable { } /** - * Private constructor. See {@link createDatabase} and {@link openDatabase}. + * Private constructor. See {@link #create} and {@link #openDatabase}. * * @param path The full path to the database * @param factory The factory to use when creating cursors, may be NULL. @@ -1563,6 +1572,8 @@ public class SQLiteDatabase extends SQLiteClosable { } mFlags = flags; mPath = path; + mLogStats = "1".equals(android.os.SystemProperties.get("db.logstats")); + mLeakedException = new IllegalStateException(path + " SQLiteDatabase created and never closed"); mFactory = factory; @@ -1605,6 +1616,10 @@ public class SQLiteDatabase extends SQLiteClosable { return mPath; } + /* package */ void logTimeStat(boolean read, long begin, long end) { + EventLog.writeEvent(DB_OPERATION_EVENT, mPath, read ? 0 : 1, end - begin); + } + /** * Sets the locale for this database. Does nothing if this database has * the NO_LOCALIZED_COLLATORS flag set or was opened read only. @@ -1629,7 +1644,7 @@ public class SQLiteDatabase extends SQLiteClosable { private native void dbopen(String path, int flags); /** - * Native call to execute a raw SQL statement. {@link mLock} must be held + * Native call to execute a raw SQL statement. {@link #lock} must be held * when calling this method. * * @param sql The raw SQL string @@ -1638,7 +1653,7 @@ public class SQLiteDatabase extends SQLiteClosable { /* package */ native void native_execSQL(String sql) throws SQLException; /** - * Native call to set the locale. {@link mLock} must be held when calling + * Native call to set the locale. {@link #lock} must be held when calling * this method. * @throws SQLException */ diff --git a/core/java/android/database/sqlite/SQLiteOpenHelper.java b/core/java/android/database/sqlite/SQLiteOpenHelper.java index 35bf645..52aac3a 100644 --- a/core/java/android/database/sqlite/SQLiteOpenHelper.java +++ b/core/java/android/database/sqlite/SQLiteOpenHelper.java @@ -26,6 +26,8 @@ import android.util.Log; * optionally {@link #onOpen}, and this class takes care of opening the database * if it exists, creating it if it does not, and upgrading it as necessary. * Transactions are used to make sure the database is always in a sensible state. + * <p>For an example, see the NotePadProvider class in the NotePad sample application, + * in the <em>samples/</em> directory of the SDK.</p> */ public abstract class SQLiteOpenHelper { private static final String TAG = SQLiteOpenHelper.class.getSimpleName(); diff --git a/core/java/android/database/sqlite/SQLiteQuery.java b/core/java/android/database/sqlite/SQLiteQuery.java index 22c53ab..5bfa0e8 100644 --- a/core/java/android/database/sqlite/SQLiteQuery.java +++ b/core/java/android/database/sqlite/SQLiteQuery.java @@ -17,6 +17,7 @@ package android.database.sqlite; import android.database.CursorWindow; +import android.os.SystemClock; /** * A SQLite program that represents a query that reads the resulting rows into a CursorWindow. @@ -55,12 +56,14 @@ public class SQLiteQuery extends SQLiteProgram { * Reads rows into a buffer. This method acquires the database lock. * * @param window The window to fill into - * @param startPos The position to start reading rows from * @return number of total rows in the query */ /* package */ int fillWindow(CursorWindow window, int maxRead, int lastPos) { mDatabase.lock(); + + boolean logStats = mDatabase.mLogStats; + long startTime = logStats ? SystemClock.elapsedRealtime() : 0; try { acquireReference(); try { @@ -68,8 +71,13 @@ public class SQLiteQuery extends SQLiteProgram { // if the start pos is not equal to 0, then most likely window is // too small for the data set, loading by another thread // is not safe in this situation. the native code will ignore maxRead - return native_fill_window(window, window.getStartPosition(), mOffsetIndex, + int numRows = native_fill_window(window, window.getStartPosition(), mOffsetIndex, maxRead, lastPos); + if (logStats) { + mDatabase.logTimeStat(true /* read */, startTime, + SystemClock.elapsedRealtime()); + } + return numRows; } catch (IllegalStateException e){ // simply ignore it return 0; diff --git a/core/java/android/database/sqlite/SQLiteStatement.java b/core/java/android/database/sqlite/SQLiteStatement.java index bf9361d..d169259 100644 --- a/core/java/android/database/sqlite/SQLiteStatement.java +++ b/core/java/android/database/sqlite/SQLiteStatement.java @@ -16,6 +16,8 @@ package android.database.sqlite; +import android.os.SystemClock; + /** * A pre-compiled statement against a {@link SQLiteDatabase} that can be reused. * The statement cannot return multiple rows, but 1x1 result sets are allowed. @@ -43,10 +45,16 @@ public class SQLiteStatement extends SQLiteProgram */ public void execute() { mDatabase.lock(); + boolean logStats = mDatabase.mLogStats; + long startTime = logStats ? SystemClock.elapsedRealtime() : 0; + acquireReference(); try { native_execute(); - } finally { + if (logStats) { + mDatabase.logTimeStat(false /* write */, startTime, SystemClock.elapsedRealtime()); + } + } finally { releaseReference(); mDatabase.unlock(); } @@ -64,9 +72,15 @@ public class SQLiteStatement extends SQLiteProgram */ public long executeInsert() { mDatabase.lock(); + boolean logStats = mDatabase.mLogStats; + long startTime = logStats ? SystemClock.elapsedRealtime() : 0; + acquireReference(); try { native_execute(); + if (logStats) { + mDatabase.logTimeStat(false /* write */, startTime, SystemClock.elapsedRealtime()); + } return mDatabase.lastInsertRow(); } finally { releaseReference(); @@ -84,9 +98,16 @@ public class SQLiteStatement extends SQLiteProgram */ public long simpleQueryForLong() { mDatabase.lock(); + boolean logStats = mDatabase.mLogStats; + long startTime = logStats ? SystemClock.elapsedRealtime() : 0; + acquireReference(); try { - return native_1x1_long(); + long retValue = native_1x1_long(); + if (logStats) { + mDatabase.logTimeStat(false /* write */, startTime, SystemClock.elapsedRealtime()); + } + return retValue; } finally { releaseReference(); mDatabase.unlock(); @@ -103,9 +124,16 @@ public class SQLiteStatement extends SQLiteProgram */ public String simpleQueryForString() { mDatabase.lock(); + boolean logStats = mDatabase.mLogStats; + long startTime = logStats ? SystemClock.elapsedRealtime() : 0; + acquireReference(); try { - return native_1x1_string(); + String retValue = native_1x1_string(); + if (logStats) { + mDatabase.logTimeStat(false /* write */, startTime, SystemClock.elapsedRealtime()); + } + return retValue; } finally { releaseReference(); mDatabase.unlock(); diff --git a/core/java/android/database/sqlite/package.html b/core/java/android/database/sqlite/package.html index c03a8dc..ff0f9f5 100644 --- a/core/java/android/database/sqlite/package.html +++ b/core/java/android/database/sqlite/package.html @@ -6,7 +6,7 @@ classes that an application would use to manage its own private database. Applications use these classes to maange private databases. If creating a content provider, you will probably have to use these classes to create and manage your own database to store content. See <a -href="{@docRoot}devel/data.html">Storing, Retrieving and Exposing Data</a> to learn +href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a> to learn the conventions for implementing a content provider. See the NotePadProvider class in the NotePad sample application in the SDK for an example of a content provider. Android ships with SQLite version 3.4.0 diff --git a/core/java/android/gadget/GadgetHost.java b/core/java/android/gadget/GadgetHost.java index 418f2aa..9176d18 100644 --- a/core/java/android/gadget/GadgetHost.java +++ b/core/java/android/gadget/GadgetHost.java @@ -17,14 +17,67 @@ package android.gadget; import android.content.Context; +import android.os.Handler; +import android.os.IBinder; +import android.os.Message; +import android.os.RemoteException; +import android.os.ServiceManager; import android.widget.RemoteViews; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import com.android.internal.gadget.IGadgetHost; +import com.android.internal.gadget.IGadgetService; + /** * GadgetHost provides the interaction with the Gadget Service for apps, * like the home screen, that want to embed gadgets in their UI. */ public class GadgetHost { + + static final int HANDLE_UPDATE = 1; + + static Object sServiceLock = new Object(); + static IGadgetService sService; + + Context mContext; + String mPackageName; + + class Callbacks extends IGadgetHost.Stub { + public void updateGadget(int gadgetId, RemoteViews views) { + Message msg = mHandler.obtainMessage(HANDLE_UPDATE); + msg.arg1 = gadgetId; + msg.obj = views; + msg.sendToTarget(); + } + } + + Handler mHandler = new Handler() { + public void handleMessage(Message msg) { + switch (msg.what) { + case HANDLE_UPDATE: { + updateGadgetView(msg.arg1, (RemoteViews)msg.obj); + break; + } + } + } + }; + + int mHostId; + Callbacks mCallbacks = new Callbacks(); + HashMap<Integer,GadgetHostView> mViews = new HashMap(); + public GadgetHost(Context context, int hostId) { + mContext = context; + mHostId = hostId; + synchronized (sServiceLock) { + if (sService == null) { + IBinder b = ServiceManager.getService(Context.GADGET_SERVICE); + sService = IGadgetService.Stub.asInterface(b); + } + } } /** @@ -32,6 +85,23 @@ public class GadgetHost { * becomes visible, i.e. from onStart() in your Activity. */ public void startListening() { + int[] updatedIds = null; + ArrayList<RemoteViews> updatedViews = new ArrayList(); + + try { + if (mPackageName == null) { + mPackageName = mContext.getPackageName(); + } + updatedIds = sService.startListening(mCallbacks, mPackageName, mHostId, updatedViews); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + + final int N = updatedIds.length; + for (int i=0; i<N; i++) { + updateGadgetView(updatedIds[i], updatedViews.get(i)); + } } /** @@ -39,25 +109,93 @@ public class GadgetHost { * no longer visible, i.e. from onStop() in your Activity. */ public void stopListening() { + try { + sService.stopListening(mHostId); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } } /** - * Stop listening to changes for this gadget. + * Get a gadgetId for a host in the calling process. + * + * @return a gadgetId */ - public void gadgetRemoved(int gadgetId) { + public int allocateGadgetId() { + try { + if (mPackageName == null) { + mPackageName = mContext.getPackageName(); + } + return sService.allocateGadgetId(mPackageName, mHostId); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } } /** - * Remove all records about gadget instances from the gadget manager. Call this when - * initializing your database, as it might be because of a data wipe. + * Stop listening to changes for this gadget. */ - public void clearGadgets() { + public void deleteGadgetId(int gadgetId) { + synchronized (mViews) { + mViews.remove(gadgetId); + try { + sService.deleteGadgetId(gadgetId); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + } + } + + /** + * Remove all records about this host from the gadget manager. + * <ul> + * <li>Call this when initializing your database, as it might be because of a data wipe.</li> + * <li>Call this to have the gadget manager release all resources associated with your + * host. Any future calls about this host will cause the records to be re-allocated.</li> + * </ul> + */ + public void deleteHost() { + try { + sService.deleteHost(mHostId); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + } + + /** + * Remove all records about all hosts for your package. + * <ul> + * <li>Call this when initializing your database, as it might be because of a data wipe.</li> + * <li>Call this to have the gadget manager release all resources associated with your + * host. Any future calls about this host will cause the records to be re-allocated.</li> + * </ul> + */ + public static void deleteAllHosts() { + try { + sService.deleteAllHosts(); + } + catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } } public final GadgetHostView createView(Context context, int gadgetId, GadgetInfo gadget) { GadgetHostView view = onCreateView(context, gadgetId, gadget); view.setGadget(gadgetId, gadget); - view.updateGadget(null); + synchronized (mViews) { + mViews.put(gadgetId, view); + } + RemoteViews views = null; + try { + views = sService.getGadgetViews(gadgetId); + } catch (RemoteException e) { + throw new RuntimeException("system server dead?", e); + } + view.updateGadget(views); return view; } @@ -68,5 +206,16 @@ public class GadgetHost { protected GadgetHostView onCreateView(Context context, int gadgetId, GadgetInfo gadget) { return new GadgetHostView(context); } + + void updateGadgetView(int gadgetId, RemoteViews views) { + GadgetHostView v; + synchronized (mViews) { + v = mViews.get(gadgetId); + } + if (v != null) { + v.updateGadget(views); + } + } } + diff --git a/core/java/android/gadget/GadgetHostView.java b/core/java/android/gadget/GadgetHostView.java index e2bef8c..d92c123 100644 --- a/core/java/android/gadget/GadgetHostView.java +++ b/core/java/android/gadget/GadgetHostView.java @@ -19,16 +19,21 @@ package android.gadget; import android.content.Context; import android.content.pm.PackageManager; import android.gadget.GadgetInfo; -import android.util.AttributeSet; +import android.graphics.Color; +import android.util.Config; import android.util.Log; +import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; +import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.RemoteViews; import android.widget.TextView; +import android.widget.ViewAnimator; -public class GadgetHostView extends FrameLayout { +public class GadgetHostView extends ViewAnimator { static final String TAG = "GadgetHostView"; + static final boolean LOGD = Config.LOGD || true; // When we're inflating the initialLayout for a gadget, we only allow // views that are allowed in RemoteViews. @@ -40,63 +45,139 @@ public class GadgetHostView extends FrameLayout { int mGadgetId; GadgetInfo mInfo; - View mContentView; + View mActiveView; + View mStaleView; + + protected int mDefaultGravity = Gravity.CENTER; public GadgetHostView(Context context) { super(context); } public void setGadget(int gadgetId, GadgetInfo info) { + if (LOGD) Log.d(TAG, "setGadget is incoming with info=" + info); if (mInfo != null) { // TODO: remove the old view, or whatever } mGadgetId = gadgetId; mInfo = info; + + View defaultView = getDefaultView(); + flipUpdate(defaultView); + } + + /** + * Trigger actual animation between current and new content in the + * {@link ViewAnimator}. + */ + protected void flipUpdate(View newContent) { + if (LOGD) Log.d(TAG, "pushing an update to surface"); + + // Take requested dimensions from parent, but apply default gravity. + ViewGroup.LayoutParams requested = newContent.getLayoutParams(); + if (requested == null) { + requested = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, + LayoutParams.FILL_PARENT); + } + + FrameLayout.LayoutParams params = + new FrameLayout.LayoutParams(requested.width, requested.height); + params.gravity = mDefaultGravity; + newContent.setLayoutParams(params); + + // Add new content and animate to it + addView(newContent); + showNext(); + + // Dispose old stale view + removeView(mStaleView); + mStaleView = mActiveView; + mActiveView = newContent; } + /** + * Process a set of {@link RemoteViews} coming in as an update from the + * gadget provider. Will animate into these new views as needed. + */ public void updateGadget(RemoteViews remoteViews) { - Context context = getContext(); - - View contentView = null; + if (LOGD) Log.d(TAG, "updateGadget() with remoteViews = " + remoteViews); + + View newContent = null; Exception exception = null; + try { if (remoteViews == null) { // there is no remoteViews (yet), so use the initial layout - Context theirContext = context.createPackageContext(mInfo.provider.getPackageName(), - 0); - LayoutInflater inflater = (LayoutInflater)theirContext.getSystemService( - Context.LAYOUT_INFLATER_SERVICE); - inflater = inflater.cloneInContext(theirContext); - inflater.setFilter(sInflaterFilter); - contentView = inflater.inflate(mInfo.initialLayout, this, false); + newContent = getDefaultView(); } else { // use the RemoteViews - contentView = remoteViews.apply(mContext, this); + // TODO: try applying RemoteViews to existing staleView if available + newContent = remoteViews.apply(mContext, this); } - } - catch (PackageManager.NameNotFoundException e) { + } catch (RuntimeException e) { exception = e; } - catch (RuntimeException e) { - exception = e; - } - if (contentView == null) { + + if (exception != null && LOGD) { Log.w(TAG, "Error inflating gadget " + mInfo, exception); + } + + if (newContent == null) { // TODO: Should we throw an exception here for the host activity to catch? // Maybe we should show a generic error widget. - TextView tv = new TextView(context); - tv.setText("Error inflating gadget"); - contentView = tv; + if (LOGD) Log.d(TAG, "updateGadget couldn't find any view, so inflating error"); + newContent = getErrorView(); } - FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( - FrameLayout.LayoutParams.WRAP_CONTENT, - FrameLayout.LayoutParams.WRAP_CONTENT); - - mContentView = contentView; - this.addView(contentView, lp); - - // TODO: do an animation (maybe even one provided by the gadget). + flipUpdate(newContent); + } + + /** + * Inflate and return the default layout requested by gadget provider. + */ + protected View getDefaultView() { + View defaultView = null; + Exception exception = null; + + try { + if (mInfo != null) { + Context theirContext = mContext.createPackageContext( + mInfo.provider.getPackageName(), 0 /* no flags */); + LayoutInflater inflater = (LayoutInflater) + theirContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + inflater = inflater.cloneInContext(theirContext); + inflater.setFilter(sInflaterFilter); + defaultView = inflater.inflate(mInfo.initialLayout, this, false); + } else { + Log.w(TAG, "can't inflate defaultView because mInfo is missing"); + } + } catch (PackageManager.NameNotFoundException e) { + exception = e; + } catch (RuntimeException e) { + exception = e; + } + + if (exception != null && LOGD) { + Log.w(TAG, "Error inflating gadget " + mInfo, exception); + } + + if (defaultView == null) { + if (LOGD) Log.d(TAG, "getDefaultView couldn't find any view, so inflating error"); + defaultView = getErrorView(); + } + + return defaultView; + } + + /** + * Inflate and return a view that represents an error state. + */ + protected View getErrorView() { + TextView tv = new TextView(mContext); + // TODO: move this error string and background color into resources + tv.setText("Error inflating gadget"); + tv.setBackgroundColor(Color.argb(127, 0, 0, 0)); + return tv; } } diff --git a/core/java/android/gadget/GadgetInfo.java b/core/java/android/gadget/GadgetInfo.java index 1a7a9a0..5ac3da9 100644 --- a/core/java/android/gadget/GadgetInfo.java +++ b/core/java/android/gadget/GadgetInfo.java @@ -58,6 +58,16 @@ public class GadgetInfo implements Parcelable { */ public ComponentName configure; + /** + * The label to display to the user. + */ + public String label; + + /** + * The icon to display for this gadget in the picker list. + */ + public int icon; + public GadgetInfo() { } @@ -75,6 +85,8 @@ public class GadgetInfo implements Parcelable { if (0 != in.readInt()) { this.configure = new ComponentName(in); } + this.label = in.readString(); + this.icon = in.readInt(); } @@ -95,6 +107,8 @@ public class GadgetInfo implements Parcelable { } else { out.writeInt(0); } + out.writeString(this.label); + out.writeInt(this.icon); } public int describeContents() { diff --git a/core/java/android/gadget/GadgetManager.java b/core/java/android/gadget/GadgetManager.java index 088dc86..20f4014 100644 --- a/core/java/android/gadget/GadgetManager.java +++ b/core/java/android/gadget/GadgetManager.java @@ -30,6 +30,10 @@ import java.lang.ref.WeakReference; import java.util.List; import java.util.WeakHashMap; +/** + * Updates gadget state; gets information about installed gadget providers and other + * gadget related state. + */ public class GadgetManager { static final String TAG = "GadgetManager"; @@ -40,9 +44,8 @@ public class GadgetManager { * The system will respond with an onActivityResult call with the following extras in * the intent: * <ul> - * <li><b>gadgetId</b></li> - * <li><b>gadgetId</b></li> - * <li><b>gadgetId</b></li> + * <li><b>gadgetIds</b></li> + * <li><b>hostId</b></li> * </ul> * TODO: Add constants for these. * TODO: Where does this go? @@ -50,21 +53,42 @@ public class GadgetManager { public static final String GADGET_PICK_ACTION = "android.gadget.action.PICK_GADGET"; public static final String EXTRA_GADGET_ID = "gadgetId"; + public static final String EXTRA_GADGET_IDS = "gadgetIds"; + public static final String EXTRA_HOST_ID = "hostId"; /** * Sent when it is time to update your gadget. + * + * <p>This may be sent in response to a new instance for this gadget provider having + * been instantiated, the requested {@link GadgetInfo#updatePeriodMillis update interval} + * having lapsed, or the system booting. */ public static final String GADGET_UPDATE_ACTION = "android.gadget.action.GADGET_UPDATE"; /** - * Sent when the gadget is added to a host for the first time. TODO: Maybe we don't want this. + * Sent when it is time to configure your gadget. This action is not sent as a broadcast + * to the gadget provider, but as a startActivity to the activity specified in the + * {@link GadgetInfo GadgetInfo meta-data}. + * + * <p>The {@link #EXTRA_GADGET_ID} extra contains the gadget ID. + */ + public static final String GADGET_CONFIGURE_ACTION = "android.gadget.action.GADGET_CONFIGURE"; + + /** + * Sent when the gadget is added to a host for the first time. This broadcast is sent at + * boot time if there is a gadget host installed with an instance for this provider. + */ + public static final String GADGET_ENABLED_ACTION = "android.gadget.action.GADGET_ENABLED"; + + /** + * Sent when an instances of a gadget is deleted from the host. */ - public static final String GADGET_ENABLE_ACTION = "android.gadget.action.GADGET_ENABLE"; + public static final String GADGET_DELETED_ACTION = "android.gadget.action.GADGET_DELETED"; /** - * Sent when the gadget is removed from the last host. TODO: Maybe we don't want this. + * Sent when the gadget is removed from the last host. */ - public static final String GADGET_DISABLE_ACTION = "android.gadget.action.GADGET_DISABLE"; + public static final String GADGET_DISABLED_ACTION = "android.gadget.action.GADGET_DISABLED"; /** * Field for the manifest meta-data tag. @@ -106,18 +130,12 @@ public class GadgetManager { * <p> * This method will only work when called from the uid that owns the gadget provider. * - * @param gadgetId The gadget instance for which to set the RemoteViews. + * @param gadgetIds The gadget instances for which to set the RemoteViews. * @param views The RemoteViews object to show. */ - public void updateGadget(int gadgetId, RemoteViews views) { - } - - /** - * Return a list of the gadget providers that are currently installed. - */ - public List<GadgetInfo> getInstalledProviders() { + public void updateGadget(int[] gadgetIds, RemoteViews views) { try { - return sService.getInstalledProviders(); + sService.updateGadgetIds(gadgetIds, views); } catch (RemoteException e) { throw new RuntimeException("system server dead?", e); @@ -125,14 +143,19 @@ public class GadgetManager { } /** - * Get the available info about the gadget. If the gadgetId has not been bound yet, - * this method will return null. + * Call this with the new RemoteViews for your gadget whenever you need to. * - * TODO: throws GadgetNotFoundException ??? if not valid + * <p> + * This method will only work when called from the uid that owns the gadget provider. + * + * @param provider The {@link ComponentName} for the {@link + * android.content.BroadcastReceiver BroadcastReceiver} provider + * for your gadget. + * @param views The RemoteViews object to show. */ - public GadgetInfo getGadgetInfo(int gadgetId) { + public void updateGadget(ComponentName provider, RemoteViews views) { try { - return sService.getGadgetInfo(gadgetId); + sService.updateGadgetProvider(provider, views); } catch (RemoteException e) { throw new RuntimeException("system server dead?", e); @@ -140,13 +163,11 @@ public class GadgetManager { } /** - * Get a gadgetId for a host in the calling process. - * - * @return a gadgetId + * Return a list of the gadget providers that are currently installed. */ - public int allocateGadgetId(String hostPackage) { + public List<GadgetInfo> getInstalledProviders() { try { - return sService.allocateGadgetId(hostPackage); + return sService.getInstalledProviders(); } catch (RemoteException e) { throw new RuntimeException("system server dead?", e); @@ -154,11 +175,14 @@ public class GadgetManager { } /** - * Delete the gadgetId. Same as removeGadget on GadgetHost. + * Get the available info about the gadget. If the gadgetId has not been bound yet, + * this method will return null. + * + * TODO: throws GadgetNotFoundException ??? if not valid */ - public void deleteGadgetId(int gadgetId) { + public GadgetInfo getGadgetInfo(int gadgetId) { try { - sService.deleteGadgetId(gadgetId); + return sService.getGadgetInfo(gadgetId); } catch (RemoteException e) { throw new RuntimeException("system server dead?", e); diff --git a/core/java/android/gadget/GadgetProvider.java b/core/java/android/gadget/GadgetProvider.java new file mode 100755 index 0000000..1ddfe3f --- /dev/null +++ b/core/java/android/gadget/GadgetProvider.java @@ -0,0 +1,175 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * 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.gadget; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; + +/** + * A conveience class to aid in implementing a gadget provider. + * Everything you can do with GadgetProvider, you can do with a regular {@link BroadcastReceiver}. + * GadgetProvider merely parses the relevant fields out of the Intent that is received in + * {@link #onReceive(Context,Intent) onReceive(Context,Intent)}, and calls hook methods + * with the received extras. + * + * <p>Extend this class and override one or more of the {@link #onUpdate}, {@link #onDeleted}, + * {@link #onEnabled} or {@link #onDisabled} methods to implement your own gadget functionality. + * + * <h3>Sample Code</h3> + * For an example of how to write a gadget provider, see the + * <a href="{@toroot}reference/android/gadget/package-descr.html#providers">android.gadget + * package overview</a>. + */ +public class GadgetProvider extends BroadcastReceiver { + /** + * Constructor to initialize GadgetProvider. + */ + public GadgetProvider() { + } + + /** + * Implements {@link BroadcastReceiver#onReceive} to dispatch calls to the various + * other methods on GadgetProvider. + * + * @param context The Context in which the receiver is running. + * @param intent The Intent being received. + */ + // BEGIN_INCLUDE(onReceive) + public void onReceive(Context context, Intent intent) { + // Protect against rogue update broadcasts (not really a security issue, + // just filter bad broacasts out so subclasses are less likely to crash). + String action = intent.getAction(); + if (GadgetManager.GADGET_UPDATE_ACTION.equals(action)) { + Bundle extras = intent.getExtras(); + if (extras != null) { + int[] gadgetIds = extras.getIntArray(GadgetManager.EXTRA_GADGET_IDS); + if (gadgetIds != null && gadgetIds.length > 0) { + this.onUpdate(context, GadgetManager.getInstance(context), gadgetIds); + } + } + } + else if (GadgetManager.GADGET_DELETED_ACTION.equals(action)) { + Bundle extras = intent.getExtras(); + if (extras != null) { + int[] gadgetIds = extras.getIntArray(GadgetManager.EXTRA_GADGET_IDS); + if (gadgetIds != null && gadgetIds.length > 0) { + this.onDeleted(context, gadgetIds); + } + } + } + else if (GadgetManager.GADGET_ENABLED_ACTION.equals(action)) { + this.onEnabled(context); + } + else if (GadgetManager.GADGET_DISABLED_ACTION.equals(action)) { + this.onDisabled(context); + } + } + // END_INCLUDE(onReceive) + + /** + * Called in response to the {@link GadgetManager#GADGET_UPDATE_ACTION} broadcast when + * this gadget provider is being asked to provide {@link android.widget.RemoteViews RemoteViews} + * for a set of gadgets. Override this method to implement your own gadget functionality. + * + * {@more} + * <p class="note">If you want this method called, you must declare in an intent-filter in + * your AndroidManifest.xml file that you accept the GADGET_UPDATE_ACTION intent action. + * For example: + * <font color=red>TODO: SAMPLE CODE GOES HERE</font> + * </p> + * + * @param context The {@link android.content.Context Context} in which this receiver is + * running. + * @param gadgetManager A {@link GadgetManager} object you can call {@link + * GadgetManager#updateGadgets} on. + * @param gadgetIds The gadgetsIds for which an update is needed. Note that this + * may be all of the gadget instances for this provider, or just + * a subset of them. + * + * @see GadgetManager#GADGET_UPDATE_ACTION + */ + public void onUpdate(Context context, GadgetManager gadgetManager, int[] gadgetIds) { + } + + /** + * Called in response to the {@link GadgetManager#GADGET_DELETED_ACTION} broadcast when + * one or more gadget instances have been deleted. Override this method to implement + * your own gadget functionality. + * + * {@more} + * <p class="note">If you want this method called, you must declare in an intent-filter in + * your AndroidManifest.xml file that you accept the GADGET_DELETED_ACTION intent action. + * For example: + * <font color=red>TODO: SAMPLE CODE GOES HERE</font> + * </p> + * + * @param context The {@link android.content.Context Context} in which this receiver is + * running. + * @param gadgetIds The gadgetsIds that have been deleted from their host. + * + * @see GadgetManager#GADGET_DELETED_ACTION + */ + public void onDeleted(Context context, int[] gadgetIds) { + } + + /** + * Called in response to the {@link GadgetManager#GADGET_ENABLED_ACTION} broadcast when + * the a gadget for this provider is instantiated. Override this method to implement your + * own gadget functionality. + * + * {@more} + * When the last gadget for this provider is deleted, + * {@link GadgetManager#GADGET_DISABLED_ACTION} is sent and {@link #onDisabled} + * is called. If after that, a gadget for this provider is created again, onEnabled() will + * be called again. + * + * <p class="note">If you want this method called, you must declare in an intent-filter in + * your AndroidManifest.xml file that you accept the GADGET_ENABLED_ACTION intent action. + * For example: + * <font color=red>TODO: SAMPLE CODE GOES HERE</font> + * </p> + * + * @param context The {@link android.content.Context Context} in which this receiver is + * running. + * + * @see GadgetManager#GADGET_ENABLED_ACTION + */ + public void onEnabled(Context context) { + } + + /** + * Called in response to the {@link GadgetManager#GADGET_DISABLED_ACTION} broadcast, which + * is sent when the last gadget instance for this provider is deleted. Override this method + * to implement your own gadget functionality. + * + * {@more} + * <p class="note">If you want this method called, you must declare in an intent-filter in + * your AndroidManifest.xml file that you accept the GADGET_DISABLED_ACTION intent action. + * For example: + * <font color=red>TODO: SAMPLE CODE GOES HERE</font> + * </p> + * + * @param context The {@link android.content.Context Context} in which this receiver is + * running. + * + * @see GadgetManager#GADGET_DISABLED_ACTION + */ + public void onDisabled(Context context) { + } +} diff --git a/core/java/android/gadget/package.html b/core/java/android/gadget/package.html index 280ccfb..4b8b9d9 100644 --- a/core/java/android/gadget/package.html +++ b/core/java/android/gadget/package.html @@ -1,4 +1,51 @@ <body> -@hide +{@hide} +<p>Android allows applications to publish views to be embedded in other applications. These +views are called gadgets, and are published by "gadget providers." The component that can +contain gadgets is called a "gadget host." See the links below for more information. +</p> +<h3><a href="{@toroot}reference/android/gadget/package-descr.html#providers">Gadget Providers</a></h3> +<ul> + <li><a href="{@toroot}reference/android/gadget/package-descr.html#provider_manifest">Declaring a gadget in the AndroidManifest</a></li> + <li><a href="{@toroot}reference/android/gadget/package-descr.html#provider_meta_data">Adding the {@link android.gadget.GadgetInfo GadgetInfo} meta-data</a></li> + <li><a href="{@toroot}reference/android/gadget/package-descr.html#provider_GadgetProvider">Using the {@link android.gadget.GadgetProvider GadgetProvider} class</a></li> + <li><a href="{@toroot}reference/android/gadget/package-descr.html#provider_configuration">Gadget Configuration UI</a></li> + <li><a href="{@toroot}reference/android/gadget/package-descr.html#provider_broadcasts">Gadget Broadcast Intents</a></li> +</ul> +<h3><a href="{@toroot}reference/android/gadget/package-descr.html#">Gadget Hosts</a></h3> +<ul> + <li><a href="{@toroot}reference/android/gadget/package-descr.html#">asdf</a></li> +</ul> +{@more} +<h2><a name="providers"></a>Gadget Providers</h2> +<p>Any application can publish gadgets. All an application needs to do to publish a gadget is +to have a {@link android.content.BroadcastReceiver} that receives the {@link +android.gadget.GadgetManager#GADGET_UPDATE_ACTION GadgetManager.GADGET_UPDATE_ACTION} intent, +and provide some meta-data about the gadget. + +<h3><a name="provider_manifest"></a>Declaring a gadget in the AndroidManifest</h3> + +<h3><a name="provider_meta_data"></a>Adding the {@link android.gadget.GadgetInfo GadgetInfo} meta-data</h3> + +<h3><a name="provider_GadgetProvider"></a>Using the {@link android.gadget.GadgetProvider GadgetProvider} class</h3> + +<h3><a name="provider_configuration"></a>Gadget Configuration UI</h3> + +<h3><a name="providers_broadcasts"></a>Gadget Broadcast Intents</h3> + +<p>{@link GadgetProvider} is just a convenience class. If you would like to receive the +gadget broadcasts directly, you can. By way of example, the implementation of +{@link GadgetProvider.onReceive} is quite simple:</p> + +{@sample frameworks/base/core/java/android/gadget/GadgetProvider.java onReceive} + + +<h2>Gadget Hosts</h3> +<p>Gadget hosts are the containers in which gadgets can be placed. Most of the look and feel +details are left up to the gadget hosts. For example, the home screen has one way of viewing +gadgets, but the lock screen could also contain gadgets, and it would have a different way of +adding, removing and otherwise managing gadgets.</p> +<p>For more information on implementing your own gadget host, see the +{@link android.gadget.GadgetHost GadgetHost} class.</p> </body> diff --git a/core/java/android/hardware/GeomagneticField.java b/core/java/android/hardware/GeomagneticField.java new file mode 100644 index 0000000..b4c04b1 --- /dev/null +++ b/core/java/android/hardware/GeomagneticField.java @@ -0,0 +1,409 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.hardware; + +import java.util.GregorianCalendar; + +/** + * This class is used to estimated estimate magnetic field at a given point on + * Earth, and in particular, to compute the magnetic declination from true + * north. + * + * <p>This uses the World Magnetic Model produced by the United States National + * Geospatial-Intelligence Agency. More details about the model can be found at + * <a href="http://www.ngdc.noaa.gov/geomag/WMM/DoDWMM.shtml">http://www.ngdc.noaa.gov/geomag/WMM/DoDWMM.shtml</a>. + * This class currently uses WMM-2005 which is valid until 2010, but should + * produce acceptable results for several years after that. + */ +public class GeomagneticField { + // The magnetic field at a given point, in nonoteslas in geodetic + // coordinates. + private float mX; + private float mY; + private float mZ; + + // Geocentric coordinates -- set by computeGeocentricCoordinates. + private float mGcLatitudeRad; + private float mGcLongitudeRad; + private float mGcRadiusKm; + + // Constants from WGS84 (the coordinate system used by GPS) + static private final float EARTH_SEMI_MAJOR_AXIS_KM = 6378.137f; + static private final float EARTH_SEMI_MINOR_AXIS_KM = 6356.7523f; + static private final float EARTH_REFERENCE_RADIUS_KM = 6371.2f; + + // These coefficients and the formulae used below are from: + // NOAA Technical Report: The US/UK World Magnetic Model for 2005-2010 + static private final float[][] G_COEFF = new float[][] { + { 0f }, + { -29556.8f, -1671.7f }, + { -2340.6f, 3046.9f, 1657.0f }, + { 1335.4f, -2305.1f, 1246.7f, 674.0f }, + { 919.8f, 798.1f, 211.3f, -379.4f, 100.0f }, + { -227.4f, 354.6f, 208.7f, -136.5f, -168.3f, -14.1f }, + { 73.2f, 69.7f, 76.7f, -151.2f, -14.9f, 14.6f, -86.3f }, + { 80.1f, -74.5f, -1.4f, 38.5f, 12.4f, 9.5f, 5.7f, 1.8f }, + { 24.9f, 7.7f, -11.6f, -6.9f, -18.2f, 10.0f, 9.2f, -11.6f, -5.2f }, + { 5.6f, 9.9f, 3.5f, -7.0f, 5.1f, -10.8f, -1.3f, 8.8f, -6.7f, -9.1f }, + { -2.3f, -6.3f, 1.6f, -2.6f, 0.0f, 3.1f, 0.4f, 2.1f, 3.9f, -0.1f, -2.3f }, + { 2.8f, -1.6f, -1.7f, 1.7f, -0.1f, 0.1f, -0.7f, 0.7f, 1.8f, 0.0f, 1.1f, 4.1f }, + { -2.4f, -0.4f, 0.2f, 0.8f, -0.3f, 1.1f, -0.5f, 0.4f, -0.3f, -0.3f, -0.1f, + -0.3f, -0.1f } }; + + static private final float[][] H_COEFF = new float[][] { + { 0f }, + { 0.0f, 5079.8f }, + { 0.0f, -2594.7f, -516.7f }, + { 0.0f, -199.9f, 269.3f, -524.2f }, + { 0.0f, 281.5f, -226.0f, 145.8f, -304.7f }, + { 0.0f, 42.4f, 179.8f, -123.0f, -19.5f, 103.6f }, + { 0.0f, -20.3f, 54.7f, 63.6f, -63.4f, -0.1f, 50.4f }, + { 0.0f, -61.5f, -22.4f, 7.2f, 25.4f, 11.0f, -26.4f, -5.1f }, + { 0.0f, 11.2f, -21.0f, 9.6f, -19.8f, 16.1f, 7.7f, -12.9f, -0.2f }, + { 0.0f, -20.1f, 12.9f, 12.6f, -6.7f, -8.1f, 8.0f, 2.9f, -7.9f, 6.0f }, + { 0.0f, 2.4f, 0.2f, 4.4f, 4.8f, -6.5f, -1.1f, -3.4f, -0.8f, -2.3f, -7.9f }, + { 0.0f, 0.3f, 1.2f, -0.8f, -2.5f, 0.9f, -0.6f, -2.7f, -0.9f, -1.3f, -2.0f, -1.2f }, + { 0.0f, -0.4f, 0.3f, 2.4f, -2.6f, 0.6f, 0.3f, 0.0f, 0.0f, 0.3f, -0.9f, -0.4f, + 0.8f } }; + + static private final float[][] DELTA_G = new float[][] { + { 0f }, + { 8.0f, 10.6f }, + { -15.1f, -7.8f, -0.8f }, + { 0.4f, -2.6f, -1.2f, -6.5f }, + { -2.5f, 2.8f, -7.0f, 6.2f, -3.8f }, + { -2.8f, 0.7f, -3.2f, -1.1f, 0.1f, -0.8f }, + { -0.7f, 0.4f, -0.3f, 2.3f, -2.1f, -0.6f, 1.4f }, + { 0.2f, -0.1f, -0.3f, 1.1f, 0.6f, 0.5f, -0.4f, 0.6f }, + { 0.1f, 0.3f, -0.4f, 0.3f, -0.3f, 0.2f, 0.4f, -0.7f, 0.4f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f } }; + + static private final float[][] DELTA_H = new float[][] { + { 0f }, + { 0.0f, -20.9f }, + { 0.0f, -23.2f, -14.6f }, + { 0.0f, 5.0f, -7.0f, -0.6f }, + { 0.0f, 2.2f, 1.6f, 5.8f, 0.1f }, + { 0.0f, 0.0f, 1.7f, 2.1f, 4.8f, -1.1f }, + { 0.0f, -0.6f, -1.9f, -0.4f, -0.5f, -0.3f, 0.7f }, + { 0.0f, 0.6f, 0.4f, 0.2f, 0.3f, -0.8f, -0.2f, 0.1f }, + { 0.0f, -0.2f, 0.1f, 0.3f, 0.4f, 0.1f, -0.2f, 0.4f, 0.4f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }, + { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f } }; + + static private final long BASE_TIME = + new GregorianCalendar(2005, 1, 1).getTimeInMillis(); + + // The ratio between the Gauss-normalized associated Legendre functions and + // the Schmid quasi-normalized ones. Compute these once staticly since they + // don't depend on input variables at all. + static private final float[][] SCHMIDT_QUASI_NORM_FACTORS = + computeSchmidtQuasiNormFactors(G_COEFF.length); + + /** + * Estimate the magnetic field at a given point and time. + * + * @param gdLatitudeDeg + * Latitude in WGS84 geodetic coordinates -- positive is east. + * @param gdLongitudeDeg + * Longitude in WGS84 geodetic coordinates -- positive is north. + * @param altitudeMeters + * Altitude in WGS84 geodetic coordinates, in meters. + * @param timeMillis + * Time at which to evaluate the declination, in milliseconds + * since January 1, 1970. (approximate is fine -- the declination + * changes very slowly). + */ + public GeomagneticField(float gdLatitudeDeg, + float gdLongitudeDeg, + float altitudeMeters, + long timeMillis) { + final int MAX_N = G_COEFF.length; // Maximum degree of the coefficients. + + // We don't handle the north and south poles correctly -- pretend that + // we're not quite at them to avoid crashing. + gdLatitudeDeg = Math.min(90.0f - 1e-5f, + Math.max(-90.0f + 1e-5f, gdLatitudeDeg)); + computeGeocentricCoordinates(gdLatitudeDeg, + gdLongitudeDeg, + altitudeMeters); + + assert G_COEFF.length == H_COEFF.length; + + // Note: LegendreTable computes associated Legendre functions for + // cos(theta). We want the associated Legendre functions for + // sin(latitude), which is the same as cos(PI/2 - latitude), except the + // derivate will be negated. + LegendreTable legendre = + new LegendreTable(MAX_N - 1, + (float) (Math.PI / 2.0 - mGcLatitudeRad)); + + // Compute a table of (EARTH_REFERENCE_RADIUS_KM / radius)^n for i in + // 0..MAX_N-2 (this is much faster than calling Math.pow MAX_N+1 times). + float[] relativeRadiusPower = new float[MAX_N + 2]; + relativeRadiusPower[0] = 1.0f; + relativeRadiusPower[1] = EARTH_REFERENCE_RADIUS_KM / mGcRadiusKm; + for (int i = 2; i < relativeRadiusPower.length; ++i) { + relativeRadiusPower[i] = relativeRadiusPower[i - 1] * + relativeRadiusPower[1]; + } + + // Compute tables of sin(lon * m) and cos(lon * m) for m = 0..MAX_N -- + // this is much faster than calling Math.sin and Math.com MAX_N+1 times. + float[] sinMLon = new float[MAX_N]; + float[] cosMLon = new float[MAX_N]; + sinMLon[0] = 0.0f; + cosMLon[0] = 1.0f; + sinMLon[1] = (float) Math.sin(mGcLongitudeRad); + cosMLon[1] = (float) Math.cos(mGcLongitudeRad); + + for (int m = 2; m < MAX_N; ++m) { + // Standard expansions for sin((m-x)*theta + x*theta) and + // cos((m-x)*theta + x*theta). + int x = m >> 1; + sinMLon[m] = sinMLon[m-x] * cosMLon[x] + cosMLon[m-x] * sinMLon[x]; + cosMLon[m] = cosMLon[m-x] * cosMLon[x] - sinMLon[m-x] * sinMLon[x]; + } + + float inverseCosLatitude = 1.0f / (float) Math.cos(mGcLatitudeRad); + float yearsSinceBase = + (timeMillis - BASE_TIME) / (365f * 24f * 60f * 60f * 1000f); + + // We now compute the magnetic field strength given the geocentric + // location. The magnetic field is the derivative of the potential + // function defined by the model. See NOAA Technical Report: The US/UK + // World Magnetic Model for 2005-2010 for the derivation. + float gcX = 0.0f; // Geocentric northwards component. + float gcY = 0.0f; // Geocentric eastwards component. + float gcZ = 0.0f; // Geocentric downwards component. + + for (int n = 1; n < MAX_N; n++) { + for (int m = 0; m <= n; m++) { + // Adjust the coefficients for the current date. + float g = G_COEFF[n][m] + yearsSinceBase * DELTA_G[n][m]; + float h = H_COEFF[n][m] + yearsSinceBase * DELTA_H[n][m]; + + // Negative derivative with respect to latitude, divided by + // radius. This looks like the negation of the version in the + // NOAA Techincal report because that report used + // P_n^m(sin(theta)) and we use P_n^m(cos(90 - theta)), so the + // derivative with respect to theta is negated. + gcX += relativeRadiusPower[n+2] + * (g * cosMLon[m] + h * sinMLon[m]) + * legendre.mPDeriv[n][m] + * SCHMIDT_QUASI_NORM_FACTORS[n][m]; + + // Negative derivative with respect to longitude, divided by + // radius. + gcY += relativeRadiusPower[n+2] * m + * (g * sinMLon[m] - h * cosMLon[m]) + * legendre.mP[n][m] + * SCHMIDT_QUASI_NORM_FACTORS[n][m] + * inverseCosLatitude; + + // Negative derivative with respect to radius. + gcZ -= (n + 1) * relativeRadiusPower[n+2] + * (g * cosMLon[m] + h * sinMLon[m]) + * legendre.mP[n][m] + * SCHMIDT_QUASI_NORM_FACTORS[n][m]; + } + } + + // Convert back to geodetic coordinates. This is basically just a + // rotation around the Y-axis by the difference in latitudes between the + // geocentric frame and the geodetic frame. + double latDiffRad = Math.toRadians(gdLatitudeDeg) - mGcLatitudeRad; + mX = (float) (gcX * Math.cos(latDiffRad) + + gcZ * Math.sin(latDiffRad)); + mY = gcY; + mZ = (float) (- gcX * Math.sin(latDiffRad) + + gcZ * Math.cos(latDiffRad)); + } + + /** + * @return The X (northward) component of the magnetic field in nanoteslas. + */ + public float getX() { + return mX; + } + + /** + * @return The Y (eastward) component of the magnetic field in nanoteslas. + */ + public float getY() { + return mY; + } + + /** + * @return The Z (downward) component of the magnetic field in nanoteslas. + */ + public float getZ() { + return mZ; + } + + /** + * @return The declination of the horizontal component of the magnetic + * field from true north, in degrees (i.e. positive means the + * magnetic field is rotated east that much from true north). + */ + public float getDeclination() { + return (float) Math.toDegrees(Math.atan2(mY, mX)); + } + + /** + * @return The inclination of the magnetic field in degrees -- positive + * means the magnetic field is rotated downwards. + */ + public float getInclination() { + return (float) Math.toDegrees(Math.atan2(mZ, + getHorizontalStrength())); + } + + /** + * @return Horizontal component of the field strength in nonoteslas. + */ + public float getHorizontalStrength() { + return (float) Math.sqrt(mX * mX + mY * mY); + } + + /** + * @return Total field strength in nanoteslas. + */ + public float getFieldStrength() { + return (float) Math.sqrt(mX * mX + mY * mY + mZ * mZ); + } + + /** + * @param gdLatitudeDeg + * Latitude in WGS84 geodetic coordinates. + * @param gdLongitudeDeg + * Longitude in WGS84 geodetic coordinates. + * @param altitudeMeters + * Altitude above sea level in WGS84 geodetic coordinates. + * @return Geocentric latitude (i.e. angle between closest point on the + * equator and this point, at the center of the earth. + */ + private void computeGeocentricCoordinates(float gdLatitudeDeg, + float gdLongitudeDeg, + float altitudeMeters) { + float altitudeKm = altitudeMeters / 1000.0f; + float a2 = EARTH_SEMI_MAJOR_AXIS_KM * EARTH_SEMI_MAJOR_AXIS_KM; + float b2 = EARTH_SEMI_MINOR_AXIS_KM * EARTH_SEMI_MINOR_AXIS_KM; + double gdLatRad = Math.toRadians(gdLatitudeDeg); + float clat = (float) Math.cos(gdLatRad); + float slat = (float) Math.sin(gdLatRad); + float tlat = slat / clat; + float latRad = + (float) Math.sqrt(a2 * clat * clat + b2 * slat * slat); + + mGcLatitudeRad = (float) Math.atan(tlat * (latRad * altitudeKm + b2) + / (latRad * altitudeKm + a2)); + + mGcLongitudeRad = (float) Math.toRadians(gdLongitudeDeg); + + float radSq = altitudeKm * altitudeKm + + 2 * altitudeKm * (float) Math.sqrt(a2 * clat * clat + + b2 * slat * slat) + + (a2 * a2 * clat * clat + b2 * b2 * slat * slat) + / (a2 * clat * clat + b2 * slat * slat); + mGcRadiusKm = (float) Math.sqrt(radSq); + } + + + /** + * Utility class to compute a table of Gauss-normalized associated Legendre + * functions P_n^m(cos(theta)) + */ + static private class LegendreTable { + // These are the Gauss-normalized associated Legendre functions -- that + // is, they are normal Legendre functions multiplied by + // (n-m)!/(2n-1)!! (where (2n-1)!! = 1*3*5*...*2n-1) + public final float[][] mP; + + // Derivative of mP, with respect to theta. + public final float[][] mPDeriv; + + /** + * @param maxN + * The maximum n- and m-values to support + * @param thetaRad + * Returned functions will be Gauss-normalized + * P_n^m(cos(thetaRad)), with thetaRad in radians. + */ + public LegendreTable(int maxN, float thetaRad) { + // Compute the table of Gauss-normalized associated Legendre + // functions using standard recursion relations. Also compute the + // table of derivatives using the derivative of the recursion + // relations. + float cos = (float) Math.cos(thetaRad); + float sin = (float) Math.sin(thetaRad); + + mP = new float[maxN + 1][]; + mPDeriv = new float[maxN + 1][]; + mP[0] = new float[] { 1.0f }; + mPDeriv[0] = new float[] { 0.0f }; + for (int n = 1; n <= maxN; n++) { + mP[n] = new float[n + 1]; + mPDeriv[n] = new float[n + 1]; + for (int m = 0; m <= n; m++) { + if (n == m) { + mP[n][m] = sin * mP[n - 1][m - 1]; + mPDeriv[n][m] = cos * mP[n - 1][m - 1] + + sin * mPDeriv[n - 1][m - 1]; + } else if (n == 1 || m == n - 1) { + mP[n][m] = cos * mP[n - 1][m]; + mPDeriv[n][m] = -sin * mP[n - 1][m] + + cos * mPDeriv[n - 1][m]; + } else { + assert n > 1 && m < n - 1; + float k = ((n - 1) * (n - 1) - m * m) + / (float) ((2 * n - 1) * (2 * n - 3)); + mP[n][m] = cos * mP[n - 1][m] - k * mP[n - 2][m]; + mPDeriv[n][m] = -sin * mP[n - 1][m] + + cos * mPDeriv[n - 1][m] - k * mPDeriv[n - 2][m]; + } + } + } + } + } + + /** + * Compute the ration between the Gauss-normalized associated Legendre + * functions and the Schmidt quasi-normalized version. This is equivalent to + * sqrt((m==0?1:2)*(n-m)!/(n+m!))*(2n-1)!!/(n-m)! + */ + private static float[][] computeSchmidtQuasiNormFactors(int maxN) { + float[][] schmidtQuasiNorm = new float[maxN + 1][]; + schmidtQuasiNorm[0] = new float[] { 1.0f }; + for (int n = 1; n <= maxN; n++) { + schmidtQuasiNorm[n] = new float[n + 1]; + schmidtQuasiNorm[n][0] = + schmidtQuasiNorm[n - 1][0] * (2 * n - 1) / (float) n; + for (int m = 1; m <= n; m++) { + schmidtQuasiNorm[n][m] = schmidtQuasiNorm[n][m - 1] + * (float) Math.sqrt((n - m + 1) * (m == 1 ? 2 : 1) + / (float) (n + m)); + } + } + return schmidtQuasiNorm; + } +}
\ No newline at end of file diff --git a/core/java/android/hardware/ISensorService.aidl b/core/java/android/hardware/ISensorService.aidl index 8aad9b4..04af2ae 100644 --- a/core/java/android/hardware/ISensorService.aidl +++ b/core/java/android/hardware/ISensorService.aidl @@ -25,5 +25,5 @@ import android.os.ParcelFileDescriptor; interface ISensorService { ParcelFileDescriptor getDataChanel(); - boolean enableSensor(IBinder listener, int sensor, int enable); + boolean enableSensor(IBinder listener, String name, int sensor, int enable); } diff --git a/core/java/android/hardware/SensorManager.java b/core/java/android/hardware/SensorManager.java index f02094e..3981f27 100644 --- a/core/java/android/hardware/SensorManager.java +++ b/core/java/android/hardware/SensorManager.java @@ -741,7 +741,7 @@ public class SensorManager extends IRotationWatcher.Stub */ @Deprecated public void unregisterListener(SensorListener listener) { - unregisterListener(listener, SENSOR_ALL); + unregisterListener(listener, SENSOR_ALL | SENSOR_ORIENTATION_RAW); } /** @@ -829,9 +829,11 @@ public class SensorManager extends IRotationWatcher.Stub } } + String name = sensor.getName(); + int handle = sensor.getHandle(); if (l == null) { l = new ListenerDelegate(listener, sensor, handler); - result = mSensorService.enableSensor(l, sensor.getHandle(), delay); + result = mSensorService.enableSensor(l, name, handle, delay); if (result) { sListeners.add(l); sListeners.notify(); @@ -840,7 +842,7 @@ public class SensorManager extends IRotationWatcher.Stub sSensorThread.startLocked(mSensorService); } } else { - result = mSensorService.enableSensor(l, sensor.getHandle(), delay); + result = mSensorService.enableSensor(l, name, handle, delay); if (result) { l.addSensor(sensor); } @@ -861,8 +863,9 @@ public class SensorManager extends IRotationWatcher.Stub ListenerDelegate l = sListeners.get(i); if (l.getListener() == listener) { // disable these sensors + String name = sensor.getName(); int handle = sensor.getHandle(); - mSensorService.enableSensor(l, handle, SENSOR_DISABLE); + mSensorService.enableSensor(l, name, handle, SENSOR_DISABLE); // if we have no more sensors enabled on this listener, // take it off the list. if (l.removeSensor(sensor) == 0) { @@ -886,7 +889,9 @@ public class SensorManager extends IRotationWatcher.Stub if (l.getListener() == listener) { // disable all sensors for this listener for (Sensor sensor : l.getSensors()) { - mSensorService.enableSensor(l, sensor.getHandle(), SENSOR_DISABLE); + String name = sensor.getName(); + int handle = sensor.getHandle(); + mSensorService.enableSensor(l, name, handle, SENSOR_DISABLE); } sListeners.remove(i); break; diff --git a/core/java/android/inputmethodservice/AbstractInputMethodService.java b/core/java/android/inputmethodservice/AbstractInputMethodService.java index 7d02f65..eedcc35 100644 --- a/core/java/android/inputmethodservice/AbstractInputMethodService.java +++ b/core/java/android/inputmethodservice/AbstractInputMethodService.java @@ -24,6 +24,9 @@ import android.view.MotionEvent; import android.view.inputmethod.InputMethod; import android.view.inputmethod.InputMethodSession; +import java.io.FileDescriptor; +import java.io.PrintWriter; + /** * AbstractInputMethodService provides a abstract base class for input methods. * Normal input method implementations will not derive from this directly, @@ -156,6 +159,13 @@ public abstract class AbstractInputMethodService extends Service */ public abstract AbstractInputMethodSessionImpl onCreateInputMethodSessionInterface(); + /** + * Implement this to handle {@link android.os.Binder#dump Binder.dump()} + * calls on your input method. + */ + protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { + } + @Override final public IBinder onBind(Intent intent) { if (mInputMethod == null) { diff --git a/core/java/android/inputmethodservice/ExtractEditText.java b/core/java/android/inputmethodservice/ExtractEditText.java index e59f38b..d9f10a9 100644 --- a/core/java/android/inputmethodservice/ExtractEditText.java +++ b/core/java/android/inputmethodservice/ExtractEditText.java @@ -2,6 +2,7 @@ package android.inputmethodservice; import android.content.Context; import android.util.AttributeSet; +import android.view.inputmethod.ExtractedText; import android.widget.EditText; /*** @@ -9,6 +10,9 @@ import android.widget.EditText; * extracted text in a full-screen input method. */ public class ExtractEditText extends EditText { + private InputMethodService mIME; + private int mSettingExtractedText; + public ExtractEditText(Context context) { super(context, null); } @@ -20,4 +24,101 @@ public class ExtractEditText extends EditText { public ExtractEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } + + void setIME(InputMethodService ime) { + mIME = ime; + } + + /** + * Start making changes that will not be reported to the client. That + * is, {@link #onSelectionChanged(int, int)} will not result in sending + * the new selection to the client + */ + public void startInternalChanges() { + mSettingExtractedText += 1; + } + + /** + * Finish making changes that will not be reported to the client. That + * is, {@link #onSelectionChanged(int, int)} will not result in sending + * the new selection to the client + */ + public void finishInternalChanges() { + mSettingExtractedText -= 1; + } + + /** + * Implement just to keep track of when we are setting text from the + * client (vs. seeing changes in ourself from the user). + */ + @Override public void setExtractedText(ExtractedText text) { + try { + mSettingExtractedText++; + super.setExtractedText(text); + } finally { + mSettingExtractedText--; + } + } + + /** + * Report to the underlying text editor about selection changes. + */ + @Override protected void onSelectionChanged(int selStart, int selEnd) { + if (mSettingExtractedText == 0 && mIME != null && selStart >= 0 && selEnd >= 0) { + mIME.onExtractedSelectionChanged(selStart, selEnd); + } + } + + /** + * Redirect clicks to the IME for handling there. First allows any + * on click handler to run, though. + */ + @Override public boolean performClick() { + if (!super.performClick() && mIME != null) { + mIME.onExtractedTextClicked(); + return true; + } + return false; + } + + @Override public boolean onTextContextMenuItem(int id) { + if (mIME != null) { + if (mIME.onExtractTextContextMenuItem(id)) { + return true; + } + } + return super.onTextContextMenuItem(id); + } + + /** + * We are always considered to be an input method target. + */ + public boolean isInputMethodTarget() { + return true; + } + + /** + * Pretend like the window this view is in always has focus, so its + * highlight and cursor will be displayed. + */ + @Override public boolean hasWindowFocus() { + return true; + } + + /** + * Pretend like this view always has focus, so its + * highlight and cursor will be displayed. + */ + @Override public boolean isFocused() { + return true; + } + + /** + * Pretend like this view always has focus, so its + * highlight and cursor will be displayed. + */ + @Override public boolean hasFocus() { + return true; + } + } diff --git a/core/java/android/inputmethodservice/IInputMethodWrapper.java b/core/java/android/inputmethodservice/IInputMethodWrapper.java index 9abc23b..a2c75b5 100644 --- a/core/java/android/inputmethodservice/IInputMethodWrapper.java +++ b/core/java/android/inputmethodservice/IInputMethodWrapper.java @@ -8,6 +8,8 @@ import com.android.internal.view.IInputMethodSession; import com.android.internal.view.InputConnectionWrapper; import android.content.Context; +import android.content.pm.PackageManager; +import android.os.Binder; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; @@ -18,6 +20,11 @@ import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethod; import android.view.inputmethod.InputMethodSession; +import java.io.FileDescriptor; +import java.io.PrintWriter; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + /** * Implements the internal IInputMethod interface to convert incoming calls * on to it back to calls on the public InputMethod interface, scheduling @@ -28,6 +35,7 @@ class IInputMethodWrapper extends IInputMethod.Stub private static final String TAG = "InputMethodWrapper"; private static final boolean DEBUG = false; + private static final int DO_DUMP = 1; private static final int DO_ATTACH_TOKEN = 10; private static final int DO_SET_INPUT_CONTEXT = 20; private static final int DO_UNSET_INPUT_CONTEXT = 30; @@ -39,9 +47,14 @@ class IInputMethodWrapper extends IInputMethod.Stub private static final int DO_SHOW_SOFT_INPUT = 60; private static final int DO_HIDE_SOFT_INPUT = 70; + final AbstractInputMethodService mTarget; final HandlerCaller mCaller; final InputMethod mInputMethod; + static class Notifier { + boolean notified; + } + // NOTE: we should have a cache of these. static class InputMethodSessionCallbackWrapper implements InputMethod.SessionCallback { final Context mContext; @@ -64,7 +77,9 @@ class IInputMethodWrapper extends IInputMethod.Stub } } - public IInputMethodWrapper(Context context, InputMethod inputMethod) { + public IInputMethodWrapper(AbstractInputMethodService context, + InputMethod inputMethod) { + mTarget = context; mCaller = new HandlerCaller(context, this); mInputMethod = inputMethod; } @@ -75,6 +90,20 @@ class IInputMethodWrapper extends IInputMethod.Stub public void executeMessage(Message msg) { switch (msg.what) { + case DO_DUMP: { + HandlerCaller.SomeArgs args = (HandlerCaller.SomeArgs)msg.obj; + try { + mTarget.dump((FileDescriptor)args.arg1, + (PrintWriter)args.arg2, (String[])args.arg3); + } catch (RuntimeException e) { + ((PrintWriter)args.arg2).println("Exception: " + e); + } + synchronized (args.arg4) { + ((CountDownLatch)args.arg4).countDown(); + } + return; + } + case DO_ATTACH_TOKEN: { mInputMethod.attachToken((IBinder)msg.obj); return; @@ -86,12 +115,22 @@ class IInputMethodWrapper extends IInputMethod.Stub case DO_UNSET_INPUT_CONTEXT: mInputMethod.unbindInput(); return; - case DO_START_INPUT: - mInputMethod.startInput((EditorInfo)msg.obj); + case DO_START_INPUT: { + HandlerCaller.SomeArgs args = (HandlerCaller.SomeArgs)msg.obj; + IInputContext inputContext = (IInputContext)args.arg1; + InputConnection ic = inputContext != null + ? new InputConnectionWrapper(inputContext) : null; + mInputMethod.startInput(ic, (EditorInfo)args.arg2); return; - case DO_RESTART_INPUT: - mInputMethod.restartInput((EditorInfo)msg.obj); + } + case DO_RESTART_INPUT: { + HandlerCaller.SomeArgs args = (HandlerCaller.SomeArgs)msg.obj; + IInputContext inputContext = (IInputContext)args.arg1; + InputConnection ic = inputContext != null + ? new InputConnectionWrapper(inputContext) : null; + mInputMethod.restartInput(ic, (EditorInfo)args.arg2); return; + } case DO_CREATE_SESSION: { mInputMethod.createSession(new InputMethodSessionCallbackWrapper( mCaller.mContext, (IInputMethodCallback)msg.obj)); @@ -105,8 +144,7 @@ class IInputMethodWrapper extends IInputMethod.Stub mInputMethod.revokeSession((InputMethodSession)msg.obj); return; case DO_SHOW_SOFT_INPUT: - mInputMethod.showSoftInput( - msg.arg1 != 0 ? InputMethod.SHOW_EXPLICIT : 0); + mInputMethod.showSoftInput(msg.arg1); return; case DO_HIDE_SOFT_INPUT: mInputMethod.hideSoftInput(); @@ -115,6 +153,28 @@ class IInputMethodWrapper extends IInputMethod.Stub Log.w(TAG, "Unhandled message code: " + msg.what); } + @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { + if (mTarget.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) + != PackageManager.PERMISSION_GRANTED) { + + fout.println("Permission Denial: can't dump InputMethodManager from from pid=" + + Binder.getCallingPid() + + ", uid=" + Binder.getCallingUid()); + return; + } + + CountDownLatch latch = new CountDownLatch(1); + mCaller.executeOrSendMessage(mCaller.obtainMessageOOOO(DO_DUMP, + fd, fout, args, latch)); + try { + if (!latch.await(5, TimeUnit.SECONDS)) { + fout.println("Timeout waiting for dump"); + } + } catch (InterruptedException e) { + fout.println("Interrupted waiting for dump"); + } + } + public void attachToken(IBinder token) { mCaller.executeOrSendMessage(mCaller.obtainMessageO(DO_ATTACH_TOKEN, token)); } @@ -130,12 +190,14 @@ class IInputMethodWrapper extends IInputMethod.Stub mCaller.executeOrSendMessage(mCaller.obtainMessage(DO_UNSET_INPUT_CONTEXT)); } - public void startInput(EditorInfo attribute) { - mCaller.executeOrSendMessage(mCaller.obtainMessageO(DO_START_INPUT, attribute)); + public void startInput(IInputContext inputContext, EditorInfo attribute) { + mCaller.executeOrSendMessage(mCaller.obtainMessageOO(DO_START_INPUT, + inputContext, attribute)); } - public void restartInput(EditorInfo attribute) { - mCaller.executeOrSendMessage(mCaller.obtainMessageO(DO_RESTART_INPUT, attribute)); + public void restartInput(IInputContext inputContext, EditorInfo attribute) { + mCaller.executeOrSendMessage(mCaller.obtainMessageOO(DO_RESTART_INPUT, + inputContext, attribute)); } public void createSession(IInputMethodCallback callback) { @@ -163,9 +225,9 @@ class IInputMethodWrapper extends IInputMethod.Stub } } - public void showSoftInput(boolean explicit) { + public void showSoftInput(int flags) { mCaller.executeOrSendMessage(mCaller.obtainMessageI(DO_SHOW_SOFT_INPUT, - explicit ? 1 : 0)); + flags)); } public void hideSoftInput() { diff --git a/core/java/android/inputmethodservice/InputMethodService.java b/core/java/android/inputmethodservice/InputMethodService.java index 3a9b26a..ea5f741 100644 --- a/core/java/android/inputmethodservice/InputMethodService.java +++ b/core/java/android/inputmethodservice/InputMethodService.java @@ -26,7 +26,13 @@ import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.IBinder; +import android.provider.Settings; +import android.text.Layout; +import android.text.Spannable; +import android.text.method.MovementMethod; import android.util.Log; +import android.util.PrintWriterPrinter; +import android.util.Printer; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; @@ -45,12 +51,31 @@ import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.EditorInfo; import android.widget.FrameLayout; +import java.io.FileDescriptor; +import java.io.PrintWriter; + /** * InputMethodService provides a standard implementation of an InputMethod, * which final implementations can derive from and customize. See the * base class {@link AbstractInputMethodService} and the {@link InputMethod} * interface for more information on the basics of writing input methods. * + * <p>In addition to the normal Service lifecycle methods, this class + * introduces some new specific callbacks that most subclasses will want + * to make use of:</p> + * <ul> + * <li> {@link #onInitializeInterface()} for user-interface initialization, + * in particular to deal with configuration changes while the service is + * running. + * <li> {@link #onBindInput} to find out about switching to a new client. + * <li> {@link #onStartInput} to deal with an input session starting with + * the client. + * <li> {@link #onCreateInputView()}, {@link #onCreateCandidatesView()}, + * and {@link #onCreateExtractTextView()} for non-demand generation of the UI. + * <li> {@link #onStartInputView(EditorInfo, boolean)} to deal with input + * starting within the input area of the IME. + * </ul> + * * <p>An input method has significant discretion in how it goes about its * work: the {@link android.inputmethodservice.InputMethodService} provides * a basic framework for standard UI elements (input view, candidates view, @@ -184,6 +209,7 @@ public class InputMethodService extends AbstractInputMethodService { LayoutInflater mInflater; View mRootView; SoftInputWindow mWindow; + boolean mInitialized; boolean mWindowCreated; boolean mWindowAdded; boolean mWindowVisible; @@ -196,11 +222,16 @@ public class InputMethodService extends AbstractInputMethodService { InputBinding mInputBinding; InputConnection mInputConnection; boolean mInputStarted; + boolean mInputViewStarted; + boolean mCandidatesViewStarted; + InputConnection mStartedInputConnection; EditorInfo mInputEditorInfo; boolean mShowInputRequested; boolean mLastShowInputRequested; - boolean mShowCandidatesRequested; + int mCandidatesVisibility; + + boolean mShowInputForced; boolean mFullscreenApplied; boolean mIsFullscreen; @@ -262,6 +293,7 @@ public class InputMethodService extends AbstractInputMethodService { mInputConnection = binding.getConnection(); if (DEBUG) Log.v(TAG, "bindInput(): binding=" + binding + " ic=" + mInputConnection); + initialize(); onBindInput(); } @@ -277,14 +309,14 @@ public class InputMethodService extends AbstractInputMethodService { mInputConnection = null; } - public void startInput(EditorInfo attribute) { + public void startInput(InputConnection ic, EditorInfo attribute) { if (DEBUG) Log.v(TAG, "startInput(): editor=" + attribute); - doStartInput(attribute, false); + doStartInput(ic, attribute, false); } - public void restartInput(EditorInfo attribute) { + public void restartInput(InputConnection ic, EditorInfo attribute) { if (DEBUG) Log.v(TAG, "restartInput(): editor=" + attribute); - doStartInput(attribute, true); + doStartInput(ic, attribute, true); } /** @@ -293,6 +325,7 @@ public class InputMethodService extends AbstractInputMethodService { public void hideSoftInput() { if (DEBUG) Log.v(TAG, "hideSoftInput()"); mShowInputRequested = false; + mShowInputForced = false; hideWindow(); } @@ -316,8 +349,7 @@ public class InputMethodService extends AbstractInputMethodService { return; } if (DEBUG) Log.v(TAG, "finishInput() in " + this); - onFinishInput(); - mInputStarted = false; + doFinishInput(); } /** @@ -444,17 +476,37 @@ public class InputMethodService extends AbstractInputMethodService { mWindow.getWindow().setLayout(FILL_PARENT, WRAP_CONTENT); } + /** + * This is a hook that subclasses can use to perform initialization of + * their interface. It is called for you prior to any of your UI objects + * being created, both after the service is first created and after a + * configuration change happens. + */ + public void onInitializeInterface() { + } + + void initialize() { + if (!mInitialized) { + mInitialized = true; + onInitializeInterface(); + } + } + void initViews() { - mWindowVisible = false; + mInitialized = false; mWindowCreated = false; mShowInputRequested = false; - mShowCandidatesRequested = false; + mShowInputForced = false; mRootView = mInflater.inflate( com.android.internal.R.layout.input_method, null); mWindow.setContentView(mRootView); mRootView.getViewTreeObserver().addOnComputeInternalInsetsListener(mInsetsComputer); - + if (Settings.System.getInt(getContentResolver(), + Settings.System.FANCY_IME_ANIMATIONS, 0) != 0) { + mWindow.getWindow().setWindowAnimations( + com.android.internal.R.style.Animation_InputMethodFancy); + } mExtractFrame = (FrameLayout)mRootView.findViewById(android.R.id.extractArea); mExtractView = null; mExtractEditText = null; @@ -466,7 +518,8 @@ public class InputMethodService extends AbstractInputMethodService { mIsInputViewShown = false; mExtractFrame.setVisibility(View.GONE); - mCandidatesFrame.setVisibility(View.INVISIBLE); + mCandidatesVisibility = getCandidatesHiddenVisibility(); + mCandidatesFrame.setVisibility(mCandidatesVisibility); mInputFrame.setVisibility(View.GONE); } @@ -486,19 +539,36 @@ public class InputMethodService extends AbstractInputMethodService { * regenerating the input method UI as a result of the configuration * change, so you can rely on your {@link #onCreateInputView} and * other methods being called as appropriate due to a configuration change. + * + * <p>When a configuration change does happen, + * {@link #onInitializeInterface()} is guaranteed to be called the next + * time prior to any of the other input or UI creation callbacks. The + * following will be called immediately depending if appropriate for current + * state: {@link #onStartInput} if input is active, and + * {@link #onCreateInputView} and {@link #onStartInputView} and related + * appropriate functions if the UI is displayed. */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); boolean visible = mWindowVisible; boolean showingInput = mShowInputRequested; - boolean showingCandidates = mShowCandidatesRequested; + boolean showingForced = mShowInputForced; + boolean showingCandidates = mCandidatesVisibility == View.VISIBLE; initViews(); + mInputViewStarted = false; + mCandidatesViewStarted = false; + if (mInputStarted) { + doStartInput(getCurrentInputConnection(), + getCurrentInputEditorInfo(), true); + } if (visible) { - if (showingCandidates) { - setCandidatesViewShown(true); - } - if (showingInput) { + if (showingForced) { + // If we are showing the full soft keyboard, then go through + // this path to take care of current decisions about fullscreen + // etc. + onShowRequested(InputMethod.SHOW_FORCED|InputMethod.SHOW_EXPLICIT); + } else if (showingInput) { // If we are showing the full soft keyboard, then go through // this path to take care of current decisions about fullscreen // etc. @@ -507,6 +577,9 @@ public class InputMethodService extends AbstractInputMethodService { // Otherwise just put it back for its candidates. showWindow(false); } + if (showingCandidates) { + setCandidatesViewShown(true); + } } } @@ -568,6 +641,10 @@ public class InputMethodService extends AbstractInputMethodService { * the input method, or null if there is none. */ public InputConnection getCurrentInputConnection() { + InputConnection ic = mStartedInputConnection; + if (ic != null) { + return ic; + } return mInputConnection; } @@ -594,6 +671,7 @@ public class InputMethodService extends AbstractInputMethodService { changed = true; mIsFullscreen = isFullscreen; mFullscreenApplied = true; + initialize(); Drawable bg = onCreateBackgroundDrawable(); if (bg == null) { // We need to give the window a real drawable, so that it @@ -708,6 +786,7 @@ public class InputMethodService extends AbstractInputMethodService { mIsInputViewShown = isShown; mInputFrame.setVisibility(isShown ? View.VISIBLE : View.GONE); if (mInputView == null) { + initialize(); View v = onCreateInputView(); if (v != null) { setInputView(v); @@ -717,12 +796,19 @@ public class InputMethodService extends AbstractInputMethodService { } /** + * Returns true if we have been asked to show our input view. + */ + public boolean isShowInputRequested() { + return mShowInputRequested; + } + + /** * Return whether the soft input view is <em>currently</em> shown to the * user. This is the state that was last determined and * applied by {@link #updateInputViewShown()}. */ public boolean isInputViewShown() { - return mIsInputViewShown; + return mIsInputViewShown && mWindowVisible; } /** @@ -744,9 +830,10 @@ public class InputMethodService extends AbstractInputMethodService { * it is hidden. */ public void setCandidatesViewShown(boolean shown) { - if (mShowCandidatesRequested != shown) { - mCandidatesFrame.setVisibility(shown ? View.VISIBLE : View.INVISIBLE); - mShowCandidatesRequested = shown; + int vis = shown ? View.VISIBLE : getCandidatesHiddenVisibility(); + if (mCandidatesVisibility != vis) { + mCandidatesFrame.setVisibility(vis); + mCandidatesVisibility = vis; } if (!mShowInputRequested && mWindowVisible != shown) { // If we are being asked to show the candidates view while the app @@ -760,10 +847,24 @@ public class InputMethodService extends AbstractInputMethodService { } } + /** + * Returns the visibility mode (either {@link View#INVISIBLE View.INVISIBLE} + * or {@link View#GONE View.GONE}) of the candidates view when it is not + * shown. The default implementation returns GONE when in fullscreen mode, + * otherwise VISIBLE. Be careful if you change this to return GONE in + * other situations -- if showing or hiding the candidates view causes + * your window to resize, this can cause temporary drawing artifacts as + * the resize takes place. + */ + public int getCandidatesHiddenVisibility() { + return isFullscreenMode() ? View.GONE : View.INVISIBLE; + } + public void setStatusIcon(int iconResId) { mStatusIcon = iconResId; - if (mInputConnection != null && mWindowVisible) { - mInputConnection.showStatusIcon(getPackageName(), iconResId); + InputConnection ic = getCurrentInputConnection(); + if (ic != null && mWindowVisible) { + ic.showStatusIcon(getPackageName(), iconResId); } } @@ -783,11 +884,12 @@ public class InputMethodService extends AbstractInputMethodService { mExtractFrame.removeAllViews(); mExtractFrame.addView(view, new FrameLayout.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, - ViewGroup.LayoutParams.WRAP_CONTENT)); + ViewGroup.LayoutParams.FILL_PARENT)); mExtractView = view; if (view != null) { mExtractEditText = (ExtractEditText)view.findViewById( com.android.internal.R.id.inputExtractEditText); + mExtractEditText.setIME(this); startExtractingText(); } else { mExtractEditText = null; @@ -890,6 +992,72 @@ public class InputMethodService extends AbstractInputMethodService { } /** + * Called when the input view is being hidden from the user. This will + * be called either prior to hiding the window, or prior to switching to + * another target for editing. + * + * <p>The default + * implementation uses the InputConnection to clear any active composing + * text; you can override this (not calling the base class implementation) + * to perform whatever behavior you would like. + * + * @boolean finishingInput If true, {@link #onFinishInput} will be + * called immediately after. + */ + public void onFinishInputView(boolean finishingInput) { + if (!finishingInput) { + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.finishComposingText(); + } + } + } + + /** + * Called when only the candidates view has been shown for showing + * processing as the user enters text through a hard keyboard. + * This will always be called after {@link #onStartInput}, + * allowing you to do your general setup there and just view-specific + * setup here. You are guaranteed that {@link #onCreateCandidatesView()} + * will have been called some time before this function is called. + * + * <p>Note that this will <em>not</em> be called when the input method + * is running in full editing mode, and thus receiving + * {@link #onStartInputView} to initiate that operation. This is only + * for the case when candidates are being shown while the input method + * editor is hidden but wants to show its candidates UI as text is + * entered through some other mechanism. + * + * @param info Description of the type of text being edited. + * @param restarting Set to true if we are restarting input on the + * same text field as before. + */ + public void onStartCandidatesView(EditorInfo info, boolean restarting) { + } + + /** + * Called when the candidates view is being hidden from the user. This will + * be called either prior to hiding the window, or prior to switching to + * another target for editing. + * + * <p>The default + * implementation uses the InputConnection to clear any active composing + * text; you can override this (not calling the base class implementation) + * to perform whatever behavior you would like. + * + * @boolean finishingInput If true, {@link #onFinishInput} will be + * called immediately after. + */ + public void onFinishCandidatesView(boolean finishingInput) { + if (!finishingInput) { + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.finishComposingText(); + } + } + } + + /** * The system has decided that it may be time to show your input method. * This is called due to a corresponding call to your * {@link InputMethod#showSoftInput(int) InputMethod.showSoftInput(int)} @@ -905,10 +1073,22 @@ public class InputMethodService extends AbstractInputMethodService { if (!onEvaluateInputViewShown()) { return; } - if ((flags&InputMethod.SHOW_EXPLICIT) == 0 && onEvaluateFullscreenMode()) { - // Don't show if this is not explicit requested by the user and - // the input method is fullscreen. That would be too disruptive. - return; + if ((flags&InputMethod.SHOW_EXPLICIT) == 0) { + if (onEvaluateFullscreenMode()) { + // Don't show if this is not explicitly requested by the user and + // the input method is fullscreen. That would be too disruptive. + return; + } + Configuration config = getResources().getConfiguration(); + if (config.keyboard != Configuration.KEYBOARD_NOKEYS) { + // And if the device has a hard keyboard, even if it is + // currently hidden, don't show the input method implicitly. + // These kinds of devices don't need it that much. + return; + } + } + if ((flags&InputMethod.SHOW_FORCED) != 0) { + mShowInputForced = true; } showWindow(true); } @@ -922,6 +1102,7 @@ public class InputMethodService extends AbstractInputMethodService { + " mInputStarted=" + mInputStarted); boolean doShowInput = false; boolean wasVisible = mWindowVisible; + boolean wasCreated = mWindowCreated; mWindowVisible = true; if (!mShowInputRequested) { if (mInputStarted) { @@ -935,41 +1116,66 @@ public class InputMethodService extends AbstractInputMethodService { } if (DEBUG) Log.v(TAG, "showWindow: updating UI"); + initialize(); updateFullscreenMode(); updateInputViewShown(); if (!mWindowAdded || !mWindowCreated) { mWindowAdded = true; mWindowCreated = true; + initialize(); + if (DEBUG) Log.v(TAG, "CALL: onCreateCandidatesView"); View v = onCreateCandidatesView(); if (DEBUG) Log.v(TAG, "showWindow: candidates=" + v); if (v != null) { setCandidatesView(v); } } - if (doShowInput) { - if (mInputStarted) { - if (DEBUG) Log.v(TAG, "showWindow: starting input view"); + if (mShowInputRequested) { + if (!mInputViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onStartInputView"); + mInputViewStarted = true; onStartInputView(mInputEditorInfo, false); } + } else if (!mCandidatesViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onStartCandidatesView"); + mCandidatesViewStarted = true; + onStartCandidatesView(mInputEditorInfo, false); + } + + if (doShowInput) { startExtractingText(); } if (!wasVisible) { if (DEBUG) Log.v(TAG, "showWindow: showing!"); mWindow.show(); - if (mInputConnection != null) { - mInputConnection.showStatusIcon(getPackageName(), mStatusIcon); + } + + if (!wasVisible || !wasCreated) { + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.showStatusIcon(getPackageName(), mStatusIcon); } } } public void hideWindow() { + if (mInputViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onFinishInputView"); + onFinishInputView(false); + } else if (mCandidatesViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onFinishCandidatesView"); + onFinishCandidatesView(false); + } + mInputViewStarted = false; + mCandidatesViewStarted = false; if (mWindowVisible) { mWindow.hide(); mWindowVisible = false; - if (mInputConnection != null) { - mInputConnection.hideStatusIcon(); + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.hideStatusIcon(); } } } @@ -1008,18 +1214,45 @@ public class InputMethodService extends AbstractInputMethodService { public void onStartInput(EditorInfo attribute, boolean restarting) { } - void doStartInput(EditorInfo attribute, boolean restarting) { - if (mInputStarted && !restarting) { + void doFinishInput() { + if (mInputViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onFinishInputView"); + onFinishInputView(true); + } else if (mCandidatesViewStarted) { + if (DEBUG) Log.v(TAG, "CALL: onFinishCandidatesView"); + onFinishCandidatesView(true); + } + mInputViewStarted = false; + mCandidatesViewStarted = false; + if (mInputStarted) { + if (DEBUG) Log.v(TAG, "CALL: onFinishInput"); onFinishInput(); } + mInputStarted = false; + mStartedInputConnection = null; + } + + void doStartInput(InputConnection ic, EditorInfo attribute, boolean restarting) { + if (!restarting) { + doFinishInput(); + } mInputStarted = true; + mStartedInputConnection = ic; mInputEditorInfo = attribute; + initialize(); + if (DEBUG) Log.v(TAG, "CALL: onStartInput"); onStartInput(attribute, restarting); if (mWindowVisible) { if (mShowInputRequested) { + if (DEBUG) Log.v(TAG, "CALL: onStartInputView"); + mInputViewStarted = true; onStartInputView(mInputEditorInfo, restarting); + startExtractingText(); + } else if (mCandidatesVisibility == View.VISIBLE) { + if (DEBUG) Log.v(TAG, "CALL: onStartCandidatesView"); + mCandidatesViewStarted = true; + onStartCandidatesView(mInputEditorInfo, restarting); } - startExtractingText(); } } @@ -1029,8 +1262,17 @@ public class InputMethodService extends AbstractInputMethodService { * {@link #onStartInput(EditorInfo, boolean)} to perform input in a * new editor, or the input method may be left idle. This method is * <em>not</em> called when input restarts in the same editor. + * + * <p>The default + * implementation uses the InputConnection to clear any active composing + * text; you can override this (not calling the base class implementation) + * to perform whatever behavior you would like. */ public void onFinishInput() { + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.finishComposingText(); + } } /** @@ -1073,9 +1315,12 @@ public class InputMethodService extends AbstractInputMethodService { public void onUpdateSelection(int oldSelStart, int oldSelEnd, int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { - if (mExtractEditText != null && mExtractedText != null) { + final ExtractEditText eet = mExtractEditText; + if (eet != null && mExtractedText != null) { final int off = mExtractedText.startOffset; - mExtractEditText.setSelection(newSelStart-off, newSelEnd-off); + eet.startInternalChanges(); + eet.setSelection(newSelStart-off, newSelEnd-off); + eet.finishInternalChanges(); } } @@ -1100,6 +1345,18 @@ public class InputMethodService extends AbstractInputMethodService { .hideSoftInputFromInputMethod(mToken, flags); } + /** + * Override this to intercept key down events before they are processed by the + * application. If you return true, the application will not itself + * process the event. If you return true, the normal application processing + * will occur as if the IME had not seen the event at all. + * + * <p>The default implementation intercepts {@link KeyEvent#KEYCODE_BACK + * KeyEvent.KEYCODE_BACK} to hide the current IME UI if it is shown. In + * additional, in fullscreen mode only, it will consume DPAD movement + * events to move the cursor in the extracted text view, not allowing + * them to perform navigation in the underlying application. + */ public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { @@ -1108,25 +1365,54 @@ public class InputMethodService extends AbstractInputMethodService { // consume the back key. dismissSoftInput(0); return true; - } - if (mShowCandidatesRequested) { - // If the candidates are shown, we just want to make sure - // they are now hidden but otherwise let the app execute - // the back. - // XXX this needs better interaction with the soft input - // implementation. - //setCandidatesViewShown(false); + } else if (mWindowVisible) { + if (mCandidatesVisibility == View.VISIBLE) { + // If we are showing candidates even if no input area, then + // hide them. + setCandidatesViewShown(false); + return true; + } else { + // If we have the window visible for some other reason -- + // most likely to show candidates -- then just get rid + // of it. This really shouldn't happen, but just in case... + hideWindow(); + return true; + } } } - return false; + + return doMovementKey(keyCode, event, MOVEMENT_DOWN); } + /** + * Override this to intercept special key multiple events before they are + * processed by the + * application. If you return true, the application will not itself + * process the event. If you return true, the normal application processing + * will occur as if the IME had not seen the event at all. + * + * <p>The default implementation always returns false, except when + * in fullscreen mode, where it will consume DPAD movement + * events to move the cursor in the extracted text view, not allowing + * them to perform navigation in the underlying application. + */ public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) { - return false; + return doMovementKey(keyCode, event, count); } + /** + * Override this to intercept key up events before they are processed by the + * application. If you return true, the application will not itself + * process the event. If you return true, the normal application processing + * will occur as if the IME had not seen the event at all. + * + * <p>The default implementation always returns false, except when + * in fullscreen mode, where it will consume DPAD movement + * events to move the cursor in the extracted text view, not allowing + * them to perform navigation in the underlying application. + */ public boolean onKeyUp(int keyCode, KeyEvent event) { - return false; + return doMovementKey(keyCode, event, MOVEMENT_UP); } public boolean onTrackballEvent(MotionEvent event) { @@ -1136,21 +1422,176 @@ public class InputMethodService extends AbstractInputMethodService { public void onAppPrivateCommand(String action, Bundle data) { } + static final int MOVEMENT_DOWN = -1; + static final int MOVEMENT_UP = -2; + + boolean doMovementKey(int keyCode, KeyEvent event, int count) { + final ExtractEditText eet = mExtractEditText; + if (isFullscreenMode() && isInputViewShown() && eet != null) { + // If we are in fullscreen mode, the cursor will move around + // the extract edit text, but should NOT cause focus to move + // to other fields. + MovementMethod movement = eet.getMovementMethod(); + Layout layout = eet.getLayout(); + if (movement != null && layout != null) { + // We want our own movement method to handle the key, so the + // cursor will properly move in our own word wrapping. + if (count == MOVEMENT_DOWN) { + if (movement.onKeyDown(eet, + (Spannable)eet.getText(), keyCode, event)) { + return true; + } + } else if (count == MOVEMENT_UP) { + if (movement.onKeyUp(eet, + (Spannable)eet.getText(), keyCode, event)) { + return true; + } + } else { + KeyEvent down = new KeyEvent(event, KeyEvent.ACTION_DOWN); + if (movement.onKeyDown(eet, + (Spannable)eet.getText(), keyCode, down)) { + KeyEvent up = new KeyEvent(event, KeyEvent.ACTION_UP); + movement.onKeyUp(eet, + (Spannable)eet.getText(), keyCode, up); + while (--count > 0) { + movement.onKeyDown(eet, + (Spannable)eet.getText(), keyCode, down); + movement.onKeyUp(eet, + (Spannable)eet.getText(), keyCode, up); + } + } + } + } + // Regardless of whether the movement method handled the key, + // we never allow DPAD navigation to the application. + switch (keyCode) { + case KeyEvent.KEYCODE_DPAD_LEFT: + case KeyEvent.KEYCODE_DPAD_RIGHT: + case KeyEvent.KEYCODE_DPAD_UP: + case KeyEvent.KEYCODE_DPAD_DOWN: + return true; + } + } + + return false; + } + + /** + * This is called when the user has moved the cursor in the extracted + * text view, when running in fullsreen mode. The default implementation + * performs the corresponding selection change on the underlying text + * editor. + */ + public void onExtractedSelectionChanged(int start, int end) { + InputConnection conn = getCurrentInputConnection(); + if (conn != null) { + conn.setSelection(start, end); + } + } + + /** + * This is called when the user has clicked on the extracted text view, + * when running in fullscreen mode. The default implementation hides + * the candidates view when this happens. Re-implement this to provide + * whatever behavior you want. + */ + public void onExtractedTextClicked() { + setCandidatesViewShown(false); + } + + /** + * This is called when the user has selected a context menu item from the + * extracted text view, when running in fullscreen mode. The default + * implementation sends this action to the current InputConnection's + * {@link InputConnection#performContextMenuAction(int)}, for it + * to be processed in underlying "real" editor. Re-implement this to + * provide whatever behavior you want. + */ + public boolean onExtractTextContextMenuItem(int id) { + InputConnection ic = getCurrentInputConnection(); + if (ic != null) { + ic.performContextMenuAction(id); + } + return true; + } + void startExtractingText() { - if (mExtractEditText != null && getCurrentInputStarted() + final ExtractEditText eet = mExtractEditText; + if (eet != null && getCurrentInputStarted() && isFullscreenMode()) { mExtractedToken++; ExtractedTextRequest req = new ExtractedTextRequest(); req.token = mExtractedToken; + req.flags = InputConnection.GET_TEXT_WITH_STYLES; req.hintMaxLines = 10; req.hintMaxChars = 10000; - mExtractedText = mInputConnection.getExtractedText(req, - InputConnection.EXTRACTED_TEXT_MONITOR); - if (mExtractedText != null) { - mExtractEditText.setExtractedText(mExtractedText); + mExtractedText = getCurrentInputConnection().getExtractedText(req, + InputConnection.GET_EXTRACTED_TEXT_MONITOR); + try { + eet.startInternalChanges(); + int inputType = getCurrentInputEditorInfo().inputType; + if ((inputType&EditorInfo.TYPE_MASK_CLASS) + == EditorInfo.TYPE_CLASS_TEXT) { + if ((inputType&EditorInfo.TYPE_TEXT_FLAG_IME_MULTI_LINE) != 0) { + inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; + } + } + eet.setInputType(inputType); + eet.setHint(mInputEditorInfo.hintText); + if (mExtractedText != null) { + eet.setExtractedText(mExtractedText); + } + } finally { + eet.finishInternalChanges(); } - mExtractEditText.setInputType(getCurrentInputEditorInfo().inputType); - mExtractEditText.setHint(mInputEditorInfo.hintText); } } + + /** + * Performs a dump of the InputMethodService's internal state. Override + * to add your own information to the dump. + */ + @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { + final Printer p = new PrintWriterPrinter(fout); + p.println("Input method service state for " + this + ":"); + p.println(" mWindowCreated=" + mWindowCreated + + " mWindowAdded=" + mWindowAdded + + " mWindowVisible=" + mWindowVisible); + p.println(" Configuration=" + getResources().getConfiguration()); + p.println(" mToken=" + mToken); + p.println(" mInputBinding=" + mInputBinding); + p.println(" mInputConnection=" + mInputConnection); + p.println(" mStartedInputConnection=" + mStartedInputConnection); + p.println(" mInputStarted=" + mInputStarted + + " mInputViewStarted=" + mInputViewStarted + + " mCandidatesViewStarted=" + mCandidatesViewStarted); + + if (mInputEditorInfo != null) { + p.println(" mInputEditorInfo:"); + mInputEditorInfo.dump(p, " "); + } else { + p.println(" mInputEditorInfo: null"); + } + + p.println(" mShowInputRequested=" + mShowInputRequested + + " mLastShowInputRequested=" + mLastShowInputRequested + + " mShowInputForced=" + mShowInputForced); + p.println(" mCandidatesVisibility=" + mCandidatesVisibility + + " mFullscreenApplied=" + mFullscreenApplied + + " mIsFullscreen=" + mIsFullscreen); + + if (mExtractedText != null) { + p.println(" mExtractedText:"); + p.println(" text=" + mExtractedText.text.length() + " chars" + + " startOffset=" + mExtractedText.startOffset); + p.println(" selectionStart=" + mExtractedText.selectionStart + + " selectionEnd=" + mExtractedText.selectionEnd + + " flags=0x" + Integer.toHexString(mExtractedText.flags)); + } else { + p.println(" mExtractedText: null"); + } + p.println(" mExtractedToken=" + mExtractedToken); + p.println(" mIsInputViewShown=" + mIsInputViewShown + + " mStatusIcon=" + mStatusIcon); + } } diff --git a/core/java/android/inputmethodservice/Keyboard.java b/core/java/android/inputmethodservice/Keyboard.java index cfd3188..228acbe 100755 --- a/core/java/android/inputmethodservice/Keyboard.java +++ b/core/java/android/inputmethodservice/Keyboard.java @@ -177,13 +177,13 @@ public class Keyboard { parent.mDisplayWidth, parent.mDefaultWidth); defaultHeight = getDimensionOrFraction(a, com.android.internal.R.styleable.Keyboard_keyHeight, - parent.mDisplayWidth, parent.mDefaultHeight); - defaultHorizontalGap = getDimensionOrFraction(a, + parent.mDisplayHeight, parent.mDefaultHeight); + defaultHorizontalGap = getDimensionOrFraction(a, com.android.internal.R.styleable.Keyboard_horizontalGap, parent.mDisplayWidth, parent.mDefaultHorizontalGap); verticalGap = getDimensionOrFraction(a, com.android.internal.R.styleable.Keyboard_verticalGap, - parent.mDisplayWidth, parent.mDefaultVerticalGap); + parent.mDisplayHeight, parent.mDefaultVerticalGap); a.recycle(); a = res.obtainAttributes(Xml.asAttributeSet(parser), com.android.internal.R.styleable.Keyboard_Row); @@ -540,7 +540,6 @@ public class Keyboard { row.defaultHorizontalGap = mDefaultHorizontalGap; row.verticalGap = mDefaultVerticalGap; row.rowEdgeFlags = EDGE_TOP | EDGE_BOTTOM; - final int maxColumns = columns == -1 ? Integer.MAX_VALUE : columns; for (int i = 0; i < characters.length(); i++) { char c = characters.charAt(i); diff --git a/core/java/android/inputmethodservice/KeyboardView.java b/core/java/android/inputmethodservice/KeyboardView.java index 2f3b54b..b2c74f2 100755 --- a/core/java/android/inputmethodservice/KeyboardView.java +++ b/core/java/android/inputmethodservice/KeyboardView.java @@ -149,6 +149,7 @@ public class KeyboardView extends View implements View.OnClickListener { private int mMiniKeyboardOffsetY; private Map<Key,View> mMiniKeyboardCache; private int[] mWindowOffset; + private Key[] mKeys; /** Listener for {@link OnKeyboardActionListener}. */ private OnKeyboardActionListener mKeyboardActionListener; @@ -163,7 +164,7 @@ public class KeyboardView extends View implements View.OnClickListener { private boolean mPreviewCentered = false; private boolean mShowPreview = true; - private boolean mShowTouchPoints = false; + private boolean mShowTouchPoints = true; private int mPopupPreviewX; private int mPopupPreviewY; @@ -334,7 +335,7 @@ public class KeyboardView extends View implements View.OnClickListener { } private void initGestureDetector() { - mGestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() { + mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) { @@ -386,6 +387,8 @@ public class KeyboardView extends View implements View.OnClickListener { showPreview(NOT_A_KEY); } mKeyboard = keyboard; + List<Key> keys = mKeyboard.getKeys(); + mKeys = keys.toArray(new Key[keys.size()]); requestLayout(); invalidate(); computeProximityThreshold(keyboard); @@ -521,16 +524,16 @@ public class KeyboardView extends View implements View.OnClickListener { */ private void computeProximityThreshold(Keyboard keyboard) { if (keyboard == null) return; - List<Key> keys = keyboard.getKeys(); + final Key[] keys = mKeys; if (keys == null) return; - int length = keys.size(); + int length = keys.length; int dimensionSum = 0; for (int i = 0; i < length; i++) { - Key key = keys.get(i); - dimensionSum += key.width + key.gap + key.height; + Key key = keys[i]; + dimensionSum += Math.min(key.width, key.height) + key.gap; } if (dimensionSum < 0 || length == 0) return; - mProximityThreshold = dimensionSum / (length * 2); + mProximityThreshold = (int) (dimensionSum * 1.5f / length); mProximityThreshold *= mProximityThreshold; // Square it } @@ -545,7 +548,7 @@ public class KeyboardView extends View implements View.OnClickListener { final Rect padding = mPadding; final int kbdPaddingLeft = mPaddingLeft; final int kbdPaddingTop = mPaddingTop; - final List<Key> keys = mKeyboard.getKeys(); + final Key[] keys = mKeys; final Key invalidKey = mInvalidatedKey; //canvas.translate(0, mKeyboardPaddingTop); paint.setAlpha(255); @@ -565,9 +568,9 @@ public class KeyboardView extends View implements View.OnClickListener { drawSingleKey = true; } } - final int keyCount = keys.size(); + final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { - final Key key = keys.get(i); + final Key key = keys[i]; if (drawSingleKey && invalidKey != key) { continue; } @@ -638,15 +641,15 @@ public class KeyboardView extends View implements View.OnClickListener { } private int getKeyIndices(int x, int y, int[] allKeys) { - final List<Key> keys = mKeyboard.getKeys(); + final Key[] keys = mKeys; final boolean shifted = mKeyboard.isShifted(); int primaryIndex = NOT_A_KEY; int closestKey = NOT_A_KEY; int closestKeyDist = mProximityThreshold + 1; java.util.Arrays.fill(mDistances, Integer.MAX_VALUE); - final int keyCount = keys.size(); + final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { - final Key key = keys.get(i); + final Key key = keys[i]; int dist = 0; boolean isInside = key.isInside(x,y); if (((mProximityCorrectOn @@ -694,7 +697,7 @@ public class KeyboardView extends View implements View.OnClickListener { private void detectAndSendKey(int x, int y, long eventTime) { int index = mCurrentKey; if (index != NOT_A_KEY) { - final Key key = mKeyboard.getKeys().get(index); + final Key key = mKeys[index]; if (key.text != null) { for (int i = 0; i < key.text.length(); i++) { mKeyboardActionListener.onKey(key.text.charAt(i), key.codes); @@ -743,14 +746,14 @@ public class KeyboardView extends View implements View.OnClickListener { mCurrentKeyIndex = keyIndex; // Release the old key and press the new key - final List<Key> keys = mKeyboard.getKeys(); + final Key[] keys = mKeys; if (oldKeyIndex != mCurrentKeyIndex) { - if (oldKeyIndex != NOT_A_KEY && keys.size() > oldKeyIndex) { - keys.get(oldKeyIndex).onReleased(mCurrentKeyIndex == NOT_A_KEY); + if (oldKeyIndex != NOT_A_KEY && keys.length > oldKeyIndex) { + keys[oldKeyIndex].onReleased(mCurrentKeyIndex == NOT_A_KEY); invalidateKey(oldKeyIndex); } - if (mCurrentKeyIndex != NOT_A_KEY && keys.size() > mCurrentKeyIndex) { - keys.get(mCurrentKeyIndex).onPressed(); + if (mCurrentKeyIndex != NOT_A_KEY && keys.length > mCurrentKeyIndex) { + keys[mCurrentKeyIndex].onPressed(); invalidateKey(mCurrentKeyIndex); } } @@ -764,7 +767,7 @@ public class KeyboardView extends View implements View.OnClickListener { } } if (keyIndex != NOT_A_KEY) { - Key key = keys.get(keyIndex); + Key key = keys[keyIndex]; if (key.icon != null) { mPreviewText.setCompoundDrawables(null, null, null, key.iconPreview != null ? key.iconPreview : key.icon); @@ -774,8 +777,10 @@ public class KeyboardView extends View implements View.OnClickListener { mPreviewText.setText(getPreviewText(key)); if (key.label.length() > 1 && key.codes.length < 2) { mPreviewText.setTextSize(mLabelTextSize); + mPreviewText.setTypeface(Typeface.DEFAULT_BOLD); } else { mPreviewText.setTextSize(mPreviewTextSizeLarge); + mPreviewText.setTypeface(Typeface.DEFAULT); } } mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), @@ -788,8 +793,6 @@ public class KeyboardView extends View implements View.OnClickListener { lp.width = popupWidth; lp.height = popupHeight; } - previewPopup.setWidth(popupWidth); - previewPopup.setHeight(popupHeight); if (!mPreviewCentered) { mPopupPreviewX = key.x - mPreviewText.getPaddingLeft() + mPaddingLeft; mPopupPreviewY = key.y - popupHeight + mPreviewOffset; @@ -809,25 +812,27 @@ public class KeyboardView extends View implements View.OnClickListener { mPreviewText.getBackground().setState( key.popupResId != 0 ? LONG_PRESSABLE_STATE_SET : EMPTY_STATE_SET); if (previewPopup.isShowing()) { - previewPopup.update(mPopupParent, mPopupPreviewX + mOffsetInWindow[0], + previewPopup.update(mPopupPreviewX + mOffsetInWindow[0], mPopupPreviewY + mOffsetInWindow[1], popupWidth, popupHeight); } else { + previewPopup.setWidth(popupWidth); + previewPopup.setHeight(popupHeight); previewPopup.showAtLocation(mPopupParent, Gravity.NO_GRAVITY, mPopupPreviewX + mOffsetInWindow[0], mPopupPreviewY + mOffsetInWindow[1]); } - mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SHOW_PREVIEW, keyIndex, 0), + mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SHOW_PREVIEW, keyIndex, 0), ViewConfiguration.getTapTimeout()); } } } private void invalidateKey(int keyIndex) { - if (keyIndex < 0 || keyIndex >= mKeyboard.getKeys().size()) { + if (keyIndex < 0 || keyIndex >= mKeys.length) { return; } - final Key key = mKeyboard.getKeys().get(keyIndex); + final Key key = mKeys[keyIndex]; mInvalidatedKey = key; invalidate(key.x + mPaddingLeft, key.y + mPaddingTop, key.x + key.width + mPaddingLeft, key.y + key.height + mPaddingTop); @@ -838,11 +843,11 @@ public class KeyboardView extends View implements View.OnClickListener { if (mPopupLayout == 0) { return false; } - if (mCurrentKey < 0 || mCurrentKey >= mKeyboard.getKeys().size()) { + if (mCurrentKey < 0 || mCurrentKey >= mKeys.length) { return false; } - Key popupKey = mKeyboard.getKeys().get(mCurrentKey); + Key popupKey = mKeys[mCurrentKey]; boolean result = onLongPress(popupKey); if (result) { mAbortKey = true; @@ -968,8 +973,8 @@ public class KeyboardView extends View implements View.OnClickListener { mLastMoveTime = mDownTime; checkMultiTap(eventTime, keyIndex); mKeyboardActionListener.onPress(keyIndex != NOT_A_KEY ? - mKeyboard.getKeys().get(keyIndex).codes[0] : 0); - if (mCurrentKey >= 0 && mKeyboard.getKeys().get(mCurrentKey).repeatable) { + mKeys[keyIndex].codes[0] : 0); + if (mCurrentKey >= 0 && mKeys[mCurrentKey].repeatable) { mRepeatKeyIndex = mCurrentKey; repeatKey(); Message msg = mHandler.obtainMessage(MSG_REPEAT); @@ -1054,7 +1059,7 @@ public class KeyboardView extends View implements View.OnClickListener { } private boolean repeatKey() { - Key key = mKeyboard.getKeys().get(mRepeatKeyIndex); + Key key = mKeys[mRepeatKeyIndex]; detectAndSendKey(key.x, key.y, mLastTapTime); return true; } @@ -1113,7 +1118,7 @@ public class KeyboardView extends View implements View.OnClickListener { private void checkMultiTap(long eventTime, int keyIndex) { if (keyIndex == NOT_A_KEY) return; - Key key = mKeyboard.getKeys().get(keyIndex); + Key key = mKeys[keyIndex]; if (key.codes.length > 1) { mInMultiTap = true; if (eventTime < mLastTapTime + MULTITAP_INTERVAL diff --git a/core/java/android/inputmethodservice/SoftInputWindow.java b/core/java/android/inputmethodservice/SoftInputWindow.java index 9ff1665..da67c6d 100644 --- a/core/java/android/inputmethodservice/SoftInputWindow.java +++ b/core/java/android/inputmethodservice/SoftInputWindow.java @@ -18,6 +18,7 @@ package android.inputmethodservice; import android.app.Dialog; import android.content.Context; +import android.content.pm.ActivityInfo; import android.os.IBinder; import android.view.Gravity; import android.view.WindowManager; @@ -139,6 +140,8 @@ class SoftInputWindow extends Dialog { lp.gravity = Gravity.BOTTOM; lp.width = -1; + // Let the input method window's orientation follow sensor based rotation + lp.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_USER; getWindow().setAttributes(lp); getWindow().setFlags( diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java index 213813a..1429bc1 100644 --- a/core/java/android/net/ConnectivityManager.java +++ b/core/java/android/net/ConnectivityManager.java @@ -16,6 +16,8 @@ package android.net; +import android.annotation.SdkConstant; +import android.annotation.SdkConstant.SdkConstantType; import android.os.RemoteException; /** @@ -100,6 +102,18 @@ public class ConnectivityManager */ public static final String EXTRA_EXTRA_INFO = "extraInfo"; + /** + * Broadcast Action: The setting for background data usage has changed + * values. Use {@link #getBackgroundDataSetting()} to get the current value. + * <p> + * If an application uses the network in the background, it should listen + * for this broadcast and stop using the background data if the value is + * false. + */ + @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) + public static final String ACTION_BACKGROUND_DATA_SETTING_CHANGED = + "android.net.conn.BACKGROUND_DATA_SETTING_CHANGED"; + public static final int TYPE_MOBILE = 0; public static final int TYPE_WIFI = 1; @@ -224,6 +238,43 @@ public class ConnectivityManager } /** + * Returns the value of the setting for background data usage. If false, + * applications should not use the network if the application is not in the + * foreground. Developers should respect this setting, and check the value + * of this before performing any background data operations. + * <p> + * All applications that have background services that use the network + * should listen to {@link #ACTION_BACKGROUND_DATA_SETTING_CHANGED}. + * + * @return Whether background data usage is allowed. + */ + public boolean getBackgroundDataSetting() { + try { + return mService.getBackgroundDataSetting(); + } catch (RemoteException e) { + // Err on the side of safety + return false; + } + } + + /** + * Sets the value of the setting for background data usage. + * + * @param allowBackgroundData Whether an application should use data while + * it is in the background. + * + * @attr ref android.Manifest.permission#CHANGE_BACKGROUND_DATA_SETTING + * @see #getBackgroundDataSetting() + * @hide + */ + public void setBackgroundDataSetting(boolean allowBackgroundData) { + try { + mService.setBackgroundDataSetting(allowBackgroundData); + } catch (RemoteException e) { + } + } + + /** * Don't allow use of default constructor. */ @SuppressWarnings({"UnusedDeclaration"}) diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl index e1d921f..de68598 100644 --- a/core/java/android/net/IConnectivityManager.aidl +++ b/core/java/android/net/IConnectivityManager.aidl @@ -44,4 +44,8 @@ interface IConnectivityManager int stopUsingNetworkFeature(int networkType, in String feature); boolean requestRouteToHost(int networkType, int hostAddress); + + boolean getBackgroundDataSetting(); + + void setBackgroundDataSetting(boolean allowBackgroundData); } diff --git a/core/java/android/net/Uri.java b/core/java/android/net/Uri.java index 32a26e4..c23df21 100644 --- a/core/java/android/net/Uri.java +++ b/core/java/android/net/Uri.java @@ -2235,12 +2235,13 @@ public abstract class Uri implements Parcelable, Comparable<Uri> { } /** - * Creates a new Uri by encoding and appending a path segment to a base Uri. + * Creates a new Uri by appending an already-encoded path segment to a + * base Uri. * * @param baseUri Uri to append path segment to - * @param pathSegment to encode and append - * @return a new Uri based on baseUri with the given segment encoded and - * appended to the path + * @param pathSegment encoded path segment to append + * @return a new Uri based on baseUri with the given segment appended to + * the path * @throws NullPointerException if baseUri is null */ public static Uri withAppendedPath(Uri baseUri, String pathSegment) { diff --git a/core/java/android/net/http/AndroidHttpClient.java b/core/java/android/net/http/AndroidHttpClient.java index 01442ae..4fb1499 100644 --- a/core/java/android/net/http/AndroidHttpClient.java +++ b/core/java/android/net/http/AndroidHttpClient.java @@ -26,7 +26,6 @@ import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.client.CookieStore; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.ClientProtocolException; @@ -56,7 +55,6 @@ import java.io.OutputStream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.net.URI; -import java.util.concurrent.atomic.AtomicInteger; import android.util.Log; import android.content.ContentResolver; @@ -347,6 +345,13 @@ public final class AndroidHttpClient implements HttpClient { } /** + * Returns true if auth logging is turned on for this configuration. + */ + private boolean isAuthLoggable() { + return Log.isLoggable(tag + "-auth", level); + } + + /** * Prints a message using this configuration. */ private void println(String message) { @@ -392,7 +397,8 @@ public final class AndroidHttpClient implements HttpClient { if (configuration != null && configuration.isLoggable() && request instanceof HttpUriRequest) { - configuration.println(toCurl((HttpUriRequest) request)); + configuration.println(toCurl((HttpUriRequest) request, + configuration.isAuthLoggable())); } } } @@ -400,12 +406,17 @@ public final class AndroidHttpClient implements HttpClient { /** * Generates a cURL command equivalent to the given request. */ - private static String toCurl(HttpUriRequest request) throws IOException { + private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException { StringBuilder builder = new StringBuilder(); builder.append("curl "); for (Header header: request.getAllHeaders()) { + if (!logAuthToken + && (header.getName().equals("Authorization") || + header.getName().equals("Cookie"))) { + continue; + } builder.append("--header \""); builder.append(header.toString().trim()); builder.append("\" "); diff --git a/core/java/android/net/http/RequestHandle.java b/core/java/android/net/http/RequestHandle.java index 65e6117..c4ee5b0 100644 --- a/core/java/android/net/http/RequestHandle.java +++ b/core/java/android/net/http/RequestHandle.java @@ -55,7 +55,7 @@ public class RequestHandle { private final static String AUTHORIZATION_HEADER = "Authorization"; private final static String PROXY_AUTHORIZATION_HEADER = "Proxy-Authorization"; - private final static int MAX_REDIRECT_COUNT = 16; + public final static int MAX_REDIRECT_COUNT = 16; /** * Creates a new request session. @@ -106,6 +106,14 @@ public class RequestHandle { return mRedirectCount >= MAX_REDIRECT_COUNT; } + public int getRedirectCount() { + return mRedirectCount; + } + + public void setRedirectCount(int count) { + mRedirectCount = count; + } + /** * Create and queue a redirect request. * diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java index ed7c366..017b14d 100644 --- a/core/java/android/os/BatteryStats.java +++ b/core/java/android/os/BatteryStats.java @@ -15,19 +15,26 @@ import android.util.SparseArray; public abstract class BatteryStats { /** - * A constant indicating a partial wake lock. + * A constant indicating a partial wake lock timer. */ public static final int WAKE_TYPE_PARTIAL = 0; /** - * A constant indicating a full wake lock. + * A constant indicating a full wake lock timer. */ public static final int WAKE_TYPE_FULL = 1; /** - * A constant indicating a window wake lock. + * A constant indicating a window wake lock timer. */ public static final int WAKE_TYPE_WINDOW = 2; + + /** + * A constant indicating a sensor timer. + * + * {@hide} + */ + public static final int SENSOR = 3; /** * Include all of the data in the stats, including previously saved data. @@ -48,6 +55,21 @@ public abstract class BatteryStats { * Include only the run since the last time the device was unplugged in the stats. */ public static final int STATS_UNPLUGGED = 3; + + /** + * Bump the version on this if the checkin format changes. + */ + private static final int BATTERY_STATS_CHECKIN_VERSION = 1; + + // TODO: Update this list if you add/change any stats above. + private static final String[] STAT_NAMES = { "total", "last", "current", "unplugged" }; + + private static final String APK_DATA = "apk"; + private static final String PROCESS_DATA = "process"; + private static final String SENSOR_DATA = "sensor"; + private static final String WAKELOCK_DATA = "wakelock"; + private static final String NETWORK_DATA = "network"; + private static final String BATTERY_DATA = "battery"; private final StringBuilder mFormatBuilder = new StringBuilder(8); private final Formatter mFormatter = new Formatter(mFormatBuilder); @@ -115,8 +137,28 @@ public abstract class BatteryStats { * @return a Map from Strings to Uid.Pkg objects. */ public abstract Map<String, ? extends Pkg> getPackageStats(); + + /** + * {@hide} + */ + public abstract int getUid(); + + /** + * {@hide} + */ + public abstract long getTcpBytesReceived(int which); + + /** + * {@hide} + */ + public abstract long getTcpBytesSent(int which); public static abstract class Sensor { + /** + * {@hide} + */ + public abstract String getName(); + public abstract Timer getSensorTime(); } @@ -200,6 +242,22 @@ public abstract class BatteryStats { * Returns the number of times the device has been started. */ public abstract int getStartCount(); + + /** + * Returns the time in milliseconds that the screen has been on while the device was + * running on battery. + * + * {@hide} + */ + public abstract long getBatteryScreenOnTime(); + + /** + * Returns the time in milliseconds that the screen has been on while the device was + * plugged in. + * + * {@hide} + */ + public abstract long getPluggedScreenOnTime(); /** * Returns a SparseArray containing the statistics for each uid. @@ -318,11 +376,14 @@ public abstract class BatteryStats { * @param linePrefix a String to be prepended to each line of output. * @return the line prefix */ - private final String printWakeLock(StringBuilder sb, Timer timer, long now, + private static final String printWakeLock(StringBuilder sb, Timer timer, long now, String name, int which, String linePrefix) { + if (timer != null) { // Convert from microseconds to milliseconds with rounding - long totalTimeMillis = (timer.getTotalTime(now, which) + 500) / 1000; + long totalTimeMicros = timer.getTotalTime(now, which); + long totalTimeMillis = (totalTimeMicros + 500) / 1000; + int count = timer.getCount(which); if (totalTimeMillis != 0) { sb.append(linePrefix); @@ -337,6 +398,184 @@ public abstract class BatteryStats { } return linePrefix; } + + /** + * Checkin version of wakelock printer. Prints simple comma-separated list. + * + * @param sb a StringBuilder object. + * @param timer a Timer object contining the wakelock times. + * @param now the current time in microseconds. + * @param name the name of the wakelock. + * @param which which one of STATS_TOTAL, STATS_LAST, or STATS_CURRENT. + * @param linePrefix a String to be prepended to each line of output. + * @return the line prefix + */ + private static final String printWakeLockCheckin(StringBuilder sb, Timer timer, long now, + String name, int which, String linePrefix) { + long totalTimeMicros = 0; + int count = 0; + if (timer != null) { + totalTimeMicros = timer.getTotalTime(now, which); + count = timer.getCount(which); + } + sb.append(linePrefix); + sb.append((totalTimeMicros + 500) / 1000); // microseconds to milliseconds with rounding + sb.append(','); + sb.append(name); + sb.append(','); + sb.append(count); + return ","; + } + + /** + * Dump a comma-separated line of values for terse checkin mode. + * + * @param pw the PageWriter to dump log to + * @param category category of data (e.g. "total", "last", "unplugged", "current" ) + * @param type type of data (e.g. "wakelock", "sensor", "process", "apk" , "process", "network") + * @param args type-dependent data arguments + */ + private static final void dumpLine(PrintWriter pw, int uid, String category, String type, + Object... args ) { + pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(','); + pw.print(uid); pw.print(','); + pw.print(category); pw.print(','); + pw.print(type); + + for (Object arg : args) { + pw.print(','); + pw.print(arg); + } + pw.print('\n'); + } + + /** + * Checkin server version of dump to produce more compact, computer-readable log. + * + * NOTE: all times are expressed in 'ms'. + * @param fd + * @param pw + * @param which + */ + private final void dumpCheckinLocked(FileDescriptor fd, PrintWriter pw, int which) { + long uSecTime = SystemClock.elapsedRealtime() * 1000; + final long uSecNow = getBatteryUptime(uSecTime); + + StringBuilder sb = new StringBuilder(128); + long batteryUptime = computeBatteryUptime(uSecNow, which); + long batteryRealtime = computeBatteryRealtime(getBatteryRealtime(uSecTime), which); + long elapsedRealtime = computeRealtime(uSecTime, which); + long uptime = computeUptime(SystemClock.uptimeMillis() * 1000, which); + + String category = STAT_NAMES[which]; + + // Dump "battery" stat + dumpLine(pw, 0 /* uid */, category, BATTERY_DATA, + which == STATS_TOTAL ? getStartCount() : "N/A", + batteryUptime / 1000, + formatRatioLocked(batteryUptime, elapsedRealtime), + batteryRealtime / 1000, + formatRatioLocked(batteryRealtime, elapsedRealtime), + uptime / 1000, + elapsedRealtime / 1000); + + SparseArray<? extends Uid> uidStats = getUidStats(); + final int NU = uidStats.size(); + for (int iu = 0; iu < NU; iu++) { + final int uid = uidStats.keyAt(iu); + Uid u = uidStats.valueAt(iu); + // Dump Network stats per uid, if any + long rx = u.getTcpBytesReceived(which); + long tx = u.getTcpBytesSent(which); + if (rx > 0 || tx > 0) dumpLine(pw, uid, category, NETWORK_DATA, rx, tx); + + Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats(); + if (wakelocks.size() > 0) { + for (Map.Entry<String, ? extends BatteryStats.Uid.Wakelock> ent + : wakelocks.entrySet()) { + Uid.Wakelock wl = ent.getValue(); + String linePrefix = ""; + sb.setLength(0); + linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_FULL), uSecNow, + "full", which, linePrefix); + linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_PARTIAL), uSecNow, + "partial", which, linePrefix); + linePrefix = printWakeLockCheckin(sb, wl.getWakeTime(WAKE_TYPE_WINDOW), uSecNow, + "window", which, linePrefix); + + // Only log if we had at lease one wakelock... + if (sb.length() > 0) { + dumpLine(pw, uid, category, WAKELOCK_DATA, ent.getKey(), sb.toString()); + } + } + } + + Map<Integer, ? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats(); + if (sensors.size() > 0) { + for (Map.Entry<Integer, ? extends BatteryStats.Uid.Sensor> ent + : sensors.entrySet()) { + Uid.Sensor se = ent.getValue(); + int sensorNumber = ent.getKey(); + Timer timer = se.getSensorTime(); + if (timer != null) { + // Convert from microseconds to milliseconds with rounding + long totalTime = (timer.getTotalTime(uSecNow, which) + 500) / 1000; + int count = timer.getCount(which); + if (totalTime != 0) { + dumpLine(pw, uid, category, SENSOR_DATA, sensorNumber, totalTime, count); + } + } + } + } + + Map<String, ? extends BatteryStats.Uid.Proc> processStats = u.getProcessStats(); + if (processStats.size() > 0) { + for (Map.Entry<String, ? extends BatteryStats.Uid.Proc> ent + : processStats.entrySet()) { + Uid.Proc ps = ent.getValue(); + + long userTime = ps.getUserTime(which); + long systemTime = ps.getSystemTime(which); + int starts = ps.getStarts(which); + + if (userTime != 0 || systemTime != 0 || starts != 0) { + dumpLine(pw, uid, category, PROCESS_DATA, + ent.getKey(), // proc + userTime * 10, // cpu time in ms + systemTime * 10, // user time in ms + starts); // process starts + } + } + } + + Map<String, ? extends BatteryStats.Uid.Pkg> packageStats = u.getPackageStats(); + if (packageStats.size() > 0) { + for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg> ent + : packageStats.entrySet()) { + + Uid.Pkg ps = ent.getValue(); + int wakeups = ps.getWakeups(which); + Map<String, ? extends Uid.Pkg.Serv> serviceStats = ps.getServiceStats(); + for (Map.Entry<String, ? extends BatteryStats.Uid.Pkg.Serv> sent + : serviceStats.entrySet()) { + BatteryStats.Uid.Pkg.Serv ss = sent.getValue(); + long startTime = ss.getStartTime(uSecNow, which); + int starts = ss.getStarts(which); + int launches = ss.getLaunches(which); + if (startTime != 0 || starts != 0 || launches != 0) { + dumpLine(pw, uid, category, APK_DATA, + wakeups, // wakeup alarms + ent.getKey(), // Apk + sent.getKey(), // service + startTime / 1000, // time spent started, in ms + starts, + launches); + } + } + } + } + } + } @SuppressWarnings("unused") private final void dumpLocked(FileDescriptor fd, PrintWriter pw, String prefix, int which) { @@ -344,13 +583,22 @@ public abstract class BatteryStats { final long uSecNow = getBatteryUptime(uSecTime); StringBuilder sb = new StringBuilder(128); - if (which == STATS_TOTAL) { - pw.println(prefix + "Current and Historic Battery Usage Statistics:"); - pw.println(prefix + " System starts: " + getStartCount()); - } else if (which == STATS_LAST) { - pw.println(prefix + "Last Battery Usage Statistics:"); - } else { - pw.println(prefix + "Current Battery Usage Statistics:"); + switch (which) { + case STATS_TOTAL: + pw.println(prefix + "Current and Historic Battery Usage Statistics:"); + pw.println(prefix + " System starts: " + getStartCount()); + break; + case STATS_LAST: + pw.println(prefix + "Last Battery Usage Statistics:"); + break; + case STATS_UNPLUGGED: + pw.println(prefix + "Last Unplugged Battery Usage Statistics:"); + break; + case STATS_CURRENT: + pw.println(prefix + "Current Battery Usage Statistics:"); + break; + default: + throw new IllegalArgumentException("which = " + which); } long batteryUptime = computeBatteryUptime(uSecNow, which); long batteryRealtime = computeBatteryRealtime(getBatteryRealtime(uSecTime), which); @@ -359,7 +607,7 @@ public abstract class BatteryStats { pw.println(prefix + " On battery: " + formatTimeMs(batteryUptime / 1000) + "(" - + formatRatioLocked(batteryUptime, batteryRealtime) + + formatRatioLocked(batteryUptime, elapsedRealtime) + ") uptime, " + formatTimeMs(batteryRealtime / 1000) + "(" + formatRatioLocked(batteryRealtime, elapsedRealtime) @@ -380,6 +628,9 @@ public abstract class BatteryStats { Uid u = uidStats.valueAt(iu); pw.println(prefix + " #" + uid + ":"); boolean uidActivity = false; + + pw.println(prefix + " Network: " + u.getTcpBytesReceived(which) + " bytes received, " + + u.getTcpBytesSent(which) + " bytes sent"); Map<String, ? extends BatteryStats.Uid.Wakelock> wakelocks = u.getWakelockStats(); if (wakelocks.size() > 0) { @@ -512,12 +763,30 @@ public abstract class BatteryStats { */ @SuppressWarnings("unused") public void dumpLocked(FileDescriptor fd, PrintWriter pw, String[] args) { + boolean isCheckin = false; + if (args != null) { + for (String arg : args) { + if ("-c".equals(arg)) { + isCheckin = true; + break; + } + } + } synchronized (this) { - dumpLocked(fd, pw, "", STATS_TOTAL); - pw.println(""); - dumpLocked(fd, pw, "", STATS_LAST); - pw.println(""); - dumpLocked(fd, pw, "", STATS_CURRENT); + if (isCheckin) { + dumpCheckinLocked(fd, pw, STATS_TOTAL); + dumpCheckinLocked(fd, pw, STATS_LAST); + dumpCheckinLocked(fd, pw, STATS_UNPLUGGED); + dumpCheckinLocked(fd, pw, STATS_CURRENT); + } else { + dumpLocked(fd, pw, "", STATS_TOTAL); + pw.println(""); + dumpLocked(fd, pw, "", STATS_LAST); + pw.println(""); + dumpLocked(fd, pw, "", STATS_UNPLUGGED); + pw.println(""); + dumpLocked(fd, pw, "", STATS_CURRENT); + } } } } diff --git a/core/java/android/os/Binder.java b/core/java/android/os/Binder.java index 528e6bd..df10c6a 100644 --- a/core/java/android/os/Binder.java +++ b/core/java/android/os/Binder.java @@ -33,7 +33,7 @@ import java.lang.reflect.Modifier; * the standard support creating a local implementation of such an object. * * <p>Most developers will not implement this class directly, instead using the - * <a href="{@docRoot}reference/aidl.html">aidl</a> tool to describe the desired + * <a href="{@docRoot}guide/developing/tools/aidl.html">aidl</a> tool to describe the desired * interface, having it generate the appropriate Binder subclass. You can, * however, derive directly from Binder to implement your own custom RPC * protocol or simply instantiate a raw Binder object directly to use as a @@ -194,18 +194,15 @@ public class Binder implements IBinder { return true; } else if (code == DUMP_TRANSACTION) { ParcelFileDescriptor fd = data.readFileDescriptor(); - FileOutputStream fout = fd != null - ? new FileOutputStream(fd.getFileDescriptor()) : null; - PrintWriter pw = fout != null ? new PrintWriter(fout) : null; - if (pw != null) { - String[] args = data.readStringArray(); - dump(fd.getFileDescriptor(), pw, args); - pw.flush(); - } + String[] args = data.readStringArray(); if (fd != null) { try { - fd.close(); - } catch (IOException e) { + dump(fd.getFileDescriptor(), args); + } finally { + try { + fd.close(); + } catch (IOException e) { + } } } return true; @@ -214,6 +211,20 @@ public class Binder implements IBinder { } /** + * Implemented to call the more convenient version + * {@link #dump(FileDescriptor, PrintWriter, String[])}. + */ + public void dump(FileDescriptor fd, String[] args) { + FileOutputStream fout = new FileOutputStream(fd); + PrintWriter pw = new PrintWriter(fout); + try { + dump(fd, pw, args); + } finally { + pw.flush(); + } + } + + /** * Print the object's state into the given stream. * * @param fd The raw file descriptor that the dump is being sent to. @@ -302,6 +313,17 @@ final class BinderProxy implements IBinder { throws RemoteException; public native boolean unlinkToDeath(DeathRecipient recipient, int flags); + public void dump(FileDescriptor fd, String[] args) throws RemoteException { + Parcel data = Parcel.obtain(); + data.writeFileDescriptor(fd); + data.writeStringArray(args); + try { + transact(DUMP_TRANSACTION, data, null, 0); + } finally { + data.recycle(); + } + } + BinderProxy() { mSelf = new WeakReference(this); } diff --git a/core/java/android/os/Build.java b/core/java/android/os/Build.java index cdf907b..467c17f 100644 --- a/core/java/android/os/Build.java +++ b/core/java/android/os/Build.java @@ -26,6 +26,9 @@ public class Build { /** Either a changelist number, or a label like "M4-rc20". */ public static final String ID = getString("ro.build.id"); + /** A build ID string meant for displaying to the user */ + public static final String DISPLAY = getString("ro.build.display.id"); + /** The name of the overall product. */ public static final String PRODUCT = getString("ro.product.name"); diff --git a/core/java/android/os/Debug.java b/core/java/android/os/Debug.java index 5f7f91f..950bb09 100644 --- a/core/java/android/os/Debug.java +++ b/core/java/android/os/Debug.java @@ -17,6 +17,7 @@ package android.os; import java.io.FileOutputStream; +import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; @@ -28,12 +29,13 @@ import dalvik.bytecode.Opcodes; import dalvik.system.VMDebug; -/** Provides various debugging functions for Android applications, including +/** + * Provides various debugging functions for Android applications, including * tracing and allocation counts. * <p><strong>Logging Trace Files</strong></p> * <p>Debug can create log files that give details about an application, such as * a call stack and start/stop times for any running methods. See <a -href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Program</a> for +href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for * information about reading trace files. To start logging trace files, call one * of the startMethodTracing() methods. To stop tracing, call * {@link #stopMethodTracing()}. @@ -285,7 +287,7 @@ public final class Debug /** * Start method tracing with default log name and buffer size. See <a -href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Program</a> for +href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for * information about reading these files. Call stopMethodTracing() to stop * tracing. */ @@ -297,7 +299,7 @@ href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Progra * Start method tracing, specifying the trace log file name. The trace * file will be put under "/sdcard" unless an absolute path is given. * See <a - href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Program</a> for + href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for * information about reading trace files. * * @param traceName Name for the trace log file to create. @@ -313,7 +315,7 @@ href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Progra * Start method tracing, specifying the trace log file name and the * buffer size. The trace files will be put under "/sdcard" unless an * absolute path is given. See <a - href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Program</a> for + href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for * information about reading trace files. * @param traceName Name for the trace log file to create. * If no name argument is given, this value defaults to "/sdcard/dmtrace.trace". @@ -330,7 +332,7 @@ href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Progra * Start method tracing, specifying the trace log file name and the * buffer size. The trace files will be put under "/sdcard" unless an * absolute path is given. See <a - href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Program</a> for + href="{@docRoot}guide/developing/tools/traceview.html">Traceview: A Graphical Log Viewer</a> for * information about reading trace files. * * <p> @@ -581,6 +583,18 @@ href="{@docRoot}reference/traceview.html">Running the Traceview Debugging Progra } /** + * Dump "hprof" data to the specified file. This will cause a GC. + * + * @param fileName Full pathname of output file (e.g. "/sdcard/dump.hprof"). + * @throws UnsupportedOperationException if the VM was built without + * HPROF support. + * @throws IOException if an error occurs while opening or writing files. + */ + public static void dumpHprofData(String fileName) throws IOException { + VMDebug.dumpHprofData(fileName); + } + + /** * Returns the number of sent transactions from this process. * @return The number of sent transactions or -1 if it could not read t. */ diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java index e37b551..f761e8e 100644 --- a/core/java/android/os/Environment.java +++ b/core/java/android/os/Environment.java @@ -75,6 +75,18 @@ public class Environment { public static final String MEDIA_UNMOUNTED = "unmounted"; /** + * getExternalStorageState() returns MEDIA_CHECKING if the media is present + * and being disk-checked + */ + public static final String MEDIA_CHECKING = "checking"; + + /** + * getExternalStorageState() returns MEDIA_NOFS if the media is present + * but is blank or is using an unsupported filesystem + */ + public static final String MEDIA_NOFS = "nofs"; + + /** * getExternalStorageState() returns MEDIA_MOUNTED if the media is present * and mounted at its mount point with read/write access. */ diff --git a/core/java/android/os/IBinder.java b/core/java/android/os/IBinder.java index 3ec0e9b..5c40c9a0 100644 --- a/core/java/android/os/IBinder.java +++ b/core/java/android/os/IBinder.java @@ -16,6 +16,9 @@ package android.os; +import java.io.FileDescriptor; +import java.io.PrintWriter; + /** * Base interface for a remotable object, the core part of a lightweight * remote procedure call mechanism designed for high performance when @@ -145,6 +148,14 @@ public interface IBinder { public IInterface queryLocalInterface(String descriptor); /** + * Print the object's state into the given stream. + * + * @param fd The raw file descriptor that the dump is being sent to. + * @param args additional arguments to the dump request. + */ + public void dump(FileDescriptor fd, String[] args) throws RemoteException; + + /** * Perform a generic operation with the object. * * @param code The action to perform. This should diff --git a/core/java/android/os/ICheckinService.aidl b/core/java/android/os/ICheckinService.aidl index 70ad28e..11becc4 100644 --- a/core/java/android/os/ICheckinService.aidl +++ b/core/java/android/os/ICheckinService.aidl @@ -26,6 +26,9 @@ import android.os.IParentalControlCallback; * {@hide} */ interface ICheckinService { + /** Synchronously attempt a checkin with the server, return true on success. */ + boolean checkin(); + /** Direct submission of crash data; returns after writing the crash. */ void reportCrashSync(in byte[] crashData); diff --git a/core/java/android/os/IMountService.aidl b/core/java/android/os/IMountService.aidl index 0397446..88dae85 100644 --- a/core/java/android/os/IMountService.aidl +++ b/core/java/android/os/IMountService.aidl @@ -48,4 +48,19 @@ interface IMountService * Safely unmount external storage at given mount point. */ void unmountMedia(String mountPoint); + + /** + * Format external storage given a mount point + */ + void formatMedia(String mountPoint); + + /** + * Returns true if media notification sounds are enabled. + */ + boolean getPlayNotificationSounds(); + + /** + * Sets whether or not media notification sounds are played. + */ + void setPlayNotificationSounds(boolean value); } diff --git a/core/java/android/os/INetStatService.aidl b/core/java/android/os/INetStatService.aidl index fb840d8..a8f3de0 100644 --- a/core/java/android/os/INetStatService.aidl +++ b/core/java/android/os/INetStatService.aidl @@ -17,14 +17,19 @@ package android.os; /** - * Retrieves packet and byte counts for the phone data interface. + * Retrieves packet and byte counts for the phone data interface, + * and for all interfaces. * Used for the data activity icon and the phone status in Settings. * * {@hide} */ interface INetStatService { - int getTxPackets(); - int getRxPackets(); - int getTxBytes(); - int getRxBytes(); + long getMobileTxPackets(); + long getMobileRxPackets(); + long getMobileTxBytes(); + long getMobileRxBytes(); + long getTotalTxPackets(); + long getTotalRxPackets(); + long getTotalTxBytes(); + long getTotalRxBytes(); } diff --git a/core/java/android/os/NetStat.java b/core/java/android/os/NetStat.java index 7312236..733137a 100644 --- a/core/java/android/os/NetStat.java +++ b/core/java/android/os/NetStat.java @@ -16,36 +16,197 @@ package android.os; +import android.util.Log; + +import java.io.File; +import java.io.RandomAccessFile; +import java.io.IOException; + /** @hide */ public class NetStat{ /** - * Get total number of tx packets sent through ppp0 + * Get total number of tx packets sent through rmnet0 or ppp0 * - * @return number of Tx packets through ppp0 + * @return number of Tx packets through rmnet0 or ppp0 */ - - public native static int netStatGetTxPkts(); + public static long getMobileTxPkts() { + return getMobileStat("tx_packets"); + } /** - * Get total number of rx packets received through ppp0 + * Get total number of rx packets received through rmnet0 or ppp0 * - * @return number of Rx packets through ppp0 + * @return number of Rx packets through rmnet0 or ppp0 */ - public native static int netStatGetRxPkts(); + public static long getMobileRxPkts() { + return getMobileStat("rx_packets"); + } /** - * Get total number of tx bytes received through ppp0 + * Get total number of tx bytes received through rmnet0 or ppp0 + * + * @return number of Tx bytes through rmnet0 or ppp0 + */ + public static long getMobileTxBytes() { + return getMobileStat("tx_bytes"); + } + + /** + * Get total number of rx bytes received through rmnet0 or ppp0 + * + * @return number of Rx bytes through rmnet0 or ppp0 + */ + public static long getMobileRxBytes() { + return getMobileStat("rx_bytes"); + } + + /** + * Get the total number of packets sent through all network interfaces. + * + * @return the number of packets sent through all network interfaces + */ + public static long getTotalTxPkts() { + return getTotalStat("tx_packets"); + } + + /** + * Get the total number of packets received through all network interfaces. + * + * @return the number of packets received through all network interfaces + */ + public static long getTotalRxPkts() { + return getTotalStat("rx_packets"); + } + + /** + * Get the total number of bytes sent through all network interfaces. + * + * @return the number of bytes sent through all network interfaces + */ + public static long getTotalTxBytes() { + return getTotalStat("tx_bytes"); + } + + /** + * Get the total number of bytes received through all network interfaces. + * + * @return the number of bytes received through all network interfaces + */ + public static long getTotalRxBytes() { + return getTotalStat("rx_bytes"); + } + + /** + * Gets network bytes sent for this UID. + * The statistics are across all interfaces. + * The statistics come from /proc/uid_stat. * - * @return number of Tx bytes through ppp0 + * {@see android.os.Process#myUid()}. + * + * @param uid + * @return byte count */ - public native static int netStatGetTxBytes(); + public static long getUidTxBytes(int uid) { + return getNumberFromFilePath("/proc/uid_stat/" + uid + "/tcp_snd"); + } /** - * Get total number of rx bytes received through ppp0 + * Gets network bytes received for this UID. + * The statistics are across all interfaces. + * The statistics come from /proc/uid_stat. * - * @return number of Rx bytes through ppp0 + * {@see android.os.Process#myUid()}. + * + * @param uid + * @return byte count */ - public native static int netStatGetRxBytes(); + public static long getUidRxBytes(int uid) { + return getNumberFromFilePath("/proc/uid_stat/" + uid + "/tcp_rcv"); + } + + private static String TAG = "netstat"; + private static final byte[] buf = new byte[16]; + + private static long getTotalStat(String whatStat) { + File netdir = new File("/sys/class/net"); + + File[] nets = netdir.listFiles(); + if (nets == null) { + return 0; + } + long total = 0; + StringBuffer strbuf = new StringBuffer(); + for (File net : nets) { + strbuf.append(net.getPath()).append(File.separator).append("statistics") + .append(File.separator).append(whatStat); + total += getNumberFromFilePath(strbuf.toString()); + strbuf.setLength(0); + } + return total; + } + + private static long getMobileStat(String whatStat) { + String filename = "/sys/class/net/rmnet0/statistics/" + whatStat; + RandomAccessFile raf = getFile(filename); + if (raf == null) { + filename = "/sys/class/net/ppp0/statistics/" + whatStat; + raf = getFile(filename); + } + if (raf == null) { + return 0L; + } + return getNumberFromFile(raf, filename); + } + + // File will have format <number><newline> + private static long getNumberFromFilePath(String filename) { + RandomAccessFile raf = getFile(filename); + if (raf == null) { + return 0L; + } + return getNumberFromFile(raf, filename); + } + + private static synchronized long getNumberFromFile(RandomAccessFile raf, String filename) { + try { + raf.read(buf); + raf.close(); + } catch (IOException e) { + Log.w(TAG, "Exception getting TCP bytes from " + filename, e); + return 0L; + } finally { + if (raf != null) { + try { + raf.close(); + } catch (IOException e) { + Log.w(TAG, "Exception closing " + filename, e); + } + } + } + + long num = 0L; + for (int i = 0; i < buf.length; i++) { + if (buf[i] < '0' || buf[i] > '9') { + break; + } + num *= 10; + num += buf[i] - '0'; + } + return num; + } + + private static RandomAccessFile getFile(String filename) { + File f = new File(filename); + if (!f.canRead()) { + return null; + } + try { + return new RandomAccessFile(f, "r"); + } catch (IOException e) { + Log.w(TAG, "Exception opening TCP statistics file " + filename, e); + return null; + } + } } diff --git a/core/java/android/package.html b/core/java/android/package.html index b6d2999..1f1be2d 100644 --- a/core/java/android/package.html +++ b/core/java/android/package.html @@ -5,6 +5,6 @@ Contains the resource classes used by standard Android applications. This package contains the resource classes that Android defines to be used in Android applications. Third party developers can use many of them also for their applications. To learn more about how to use these classes, and what a -resource is, see <a href="{@docRoot}devel/resources-i18n.html">Resources</a>. +resource is, see <a href="{@docRoot}guide/topics/resources/index.html">Resources and Assets</a>. </BODY> </HTML> diff --git a/core/java/android/preference/PreferenceActivity.java b/core/java/android/preference/PreferenceActivity.java index 95970ea..837ce91 100644 --- a/core/java/android/preference/PreferenceActivity.java +++ b/core/java/android/preference/PreferenceActivity.java @@ -103,8 +103,6 @@ public abstract class PreferenceActivity extends ListActivity implements protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - requestWindowFeature(Window.FEATURE_NO_TITLE); - setContentView(com.android.internal.R.layout.preference_list_content); mPreferenceManager = onCreatePreferenceManager(); @@ -214,6 +212,11 @@ public abstract class PreferenceActivity extends ListActivity implements public void setPreferenceScreen(PreferenceScreen preferenceScreen) { if (mPreferenceManager.setPreferences(preferenceScreen) && preferenceScreen != null) { postBindPreferences(); + CharSequence title = getPreferenceScreen().getTitle(); + // Set the title of the activity + if (title != null) { + setTitle(title); + } } } diff --git a/core/java/android/preference/PreferenceGroup.java b/core/java/android/preference/PreferenceGroup.java index 4258b41..d008fd6 100644 --- a/core/java/android/preference/PreferenceGroup.java +++ b/core/java/android/preference/PreferenceGroup.java @@ -25,6 +25,7 @@ import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.os.Parcelable; +import android.text.TextUtils; import android.util.AttributeSet; /** @@ -223,6 +224,9 @@ public abstract class PreferenceGroup extends Preference implements GenericInfla * @return The {@link Preference} with the key, or null. */ public Preference findPreference(CharSequence key) { + if (TextUtils.equals(getKey(), key)) { + return this; + } final int preferenceCount = getPreferenceCount(); for (int i = 0; i < preferenceCount; i++) { final Preference preference = getPreference(i); diff --git a/core/java/android/provider/Checkin.java b/core/java/android/provider/Checkin.java index ef5eded..5767c65 100644 --- a/core/java/android/provider/Checkin.java +++ b/core/java/android/provider/Checkin.java @@ -30,10 +30,13 @@ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; /** - * Contract class for {@link android.server.checkin.CheckinProvider}. + * Contract class for the checkin provider, used to store events and + * statistics that will be uploaded to a checkin server eventually. * Describes the exposed database schema, and offers methods to add * events and statistics to be uploaded. * + * TODO: Move this to vendor/google when we have a home for it. + * * @hide */ public final class Checkin { @@ -56,6 +59,12 @@ public final class Checkin { /** Valid tag values. Extend as necessary for your needs. */ public enum Tag { + AUTOTEST_FAILURE, + AUTOTEST_SEQUENCE_BEGIN, + AUTOTEST_SUITE_BEGIN, + AUTOTEST_TEST_BEGIN, + AUTOTEST_TEST_FAILURE, + AUTOTEST_TEST_SUCCESS, BROWSER_BUG_REPORT, CARRIER_BUG_REPORT, CHECKIN_FAILURE, @@ -195,8 +204,11 @@ public final class Checkin { values.put(Events.TAG, tag.toString()); if (value != null) values.put(Events.VALUE, value); return resolver.insert(Events.CONTENT_URI, values); + } catch (IllegalArgumentException e) { // thrown when provider is unavailable. + Log.w(TAG, "Can't log event " + tag + ": " + e); + return null; } catch (SQLException e) { - Log.e(TAG, "Can't log event: " + tag, e); // Database errors are not fatal. + Log.e(TAG, "Can't log event " + tag, e); // Database errors are not fatal. return null; } } @@ -218,8 +230,11 @@ public final class Checkin { if (count != 0) values.put(Stats.COUNT, count); if (sum != 0.0) values.put(Stats.SUM, sum); return resolver.insert(Stats.CONTENT_URI, values); + } catch (IllegalArgumentException e) { // thrown when provider is unavailable. + Log.w(TAG, "Can't update stat " + tag + ": " + e); + return null; } catch (SQLException e) { - Log.e(TAG, "Can't update stat: " + tag, e); // Database errors are not fatal. + Log.e(TAG, "Can't update stat " + tag, e); // Database errors are not fatal. return null; } } @@ -285,4 +300,3 @@ public final class Checkin { } } } - diff --git a/core/java/android/provider/Contacts.java b/core/java/android/provider/Contacts.java index 085c095..3bffaec 100644 --- a/core/java/android/provider/Contacts.java +++ b/core/java/android/provider/Contacts.java @@ -932,27 +932,33 @@ public class Contacts { } /** - * This looks up the provider category defined in - * {@link android.provider.Im.ProviderCategories} from the predefined IM protocol id. + * This looks up the provider name defined in + * {@link android.provider.Im.ProviderNames} from the predefined IM protocol id. * This is used for interacting with the IM application. - * + * * @param protocol the protocol ID - * @return the provider category the IM app uses for the given protocol, or null if no + * @return the provider name the IM app uses for the given protocol, or null if no * provider is defined for the given protocol * @hide */ - public static String lookupProviderCategoryFromId(int protocol) { + public static String lookupProviderNameFromId(int protocol) { switch (protocol) { case PROTOCOL_GOOGLE_TALK: - return Im.ProviderCategories.GTALK; + return Im.ProviderNames.GTALK; case PROTOCOL_AIM: - return Im.ProviderCategories.AIM; + return Im.ProviderNames.AIM; case PROTOCOL_MSN: - return Im.ProviderCategories.MSN; + return Im.ProviderNames.MSN; case PROTOCOL_YAHOO: - return Im.ProviderCategories.YAHOO; + return Im.ProviderNames.YAHOO; case PROTOCOL_ICQ: - return Im.ProviderCategories.ICQ; + return Im.ProviderNames.ICQ; + case PROTOCOL_JABBER: + return Im.ProviderNames.JABBER; + case PROTOCOL_SKYPE: + return Im.ProviderNames.SKYPE; + case PROTOCOL_QQ: + return Im.ProviderNames.QQ; } return null; } diff --git a/core/java/android/provider/Downloads.java b/core/java/android/provider/Downloads.java index a5a30b9..4c58e0d 100644 --- a/core/java/android/provider/Downloads.java +++ b/core/java/android/provider/Downloads.java @@ -471,34 +471,40 @@ public final class Downloads implements BaseColumns { public static final int STATUS_UNHANDLED_REDIRECT = 493; /** - * This download couldn't be completed because there were - * too many redirects. + * This download couldn't be completed because of an + * unspecified unhandled HTTP code. */ - public static final int STATUS_TOO_MANY_REDIRECTS = 494; + public static final int STATUS_UNHANDLED_HTTP_CODE = 494; /** * This download couldn't be completed because of an - * unspecified unhandled HTTP code. + * error receiving or processing data at the HTTP level. */ - public static final int STATUS_UNHANDLED_HTTP_CODE = 495; + public static final int STATUS_HTTP_DATA_ERROR = 495; /** * This download couldn't be completed because of an - * error receiving or processing data at the HTTP level. + * HttpException while setting up the request. */ - public static final int STATUS_HTTP_DATA_ERROR = 496; + public static final int STATUS_HTTP_EXCEPTION = 496; /** - * This download is visible and shows in the notifications while - * in progress and after completion. + * This download couldn't be completed because there were + * too many redirects. */ - public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 0; + public static final int STATUS_TOO_MANY_REDIRECTS = 497; /** * This download is visible but only shows in the notifications * while it's in progress. */ - public static final int VISIBILITY_VISIBLE = 1; + public static final int VISIBILITY_VISIBLE = 0; + + /** + * This download is visible and shows in the notifications while + * in progress and after completion. + */ + public static final int VISIBILITY_VISIBLE_NOTIFY_COMPLETED = 1; /** * This download doesn't show in the UI or in the notifications. diff --git a/core/java/android/provider/Gmail.java b/core/java/android/provider/Gmail.java index 325f19d..253dd4a 100644 --- a/core/java/android/provider/Gmail.java +++ b/core/java/android/provider/Gmail.java @@ -370,6 +370,25 @@ public final class Gmail { "maxAttachmentSize"; } + /** + * These flags can be included as Selection Arguments when + * querying the provider. + */ + public static class SelectionArguments { + private SelectionArguments() { + // forbid instantiation + } + + /** + * Specifies that you do NOT wish the returned cursor to + * become the Active Network Cursor. If you do not include + * this flag as a selectionArg, the new cursor will become the + * Active Network Cursor by default. + */ + public static final String DO_NOT_BECOME_ACTIVE_NETWORK_CURSOR = + "SELECTION_ARGUMENT_DO_NOT_BECOME_ACTIVE_NETWORK_CURSOR"; + } + // These are the projections that we need when getting cursors from the // content provider. private static String[] CONVERSATION_PROJECTION = { @@ -436,6 +455,28 @@ public final class Gmail { } /** + * Behavior for a new cursor: should it become the Active Network + * Cursor? This could potentially lead to bad behavior if someone + * else is using the Active Network Cursor, since theirs will stop + * being the Active Network Cursor. + */ + public static enum BecomeActiveNetworkCursor { + /** + * The new cursor should become the one and only Active + * Network Cursor. Any other cursor that might already be the + * Active Network Cursor will cease to be so. + */ + YES, + + /** + * The new cursor should not become the Active Network + * Cursor. Any other cursor that might already be the Active + * Network Cursor will continue to be so. + */ + NO + } + + /** * Wraps a Cursor in a ConversationCursor * * @param account the account the cursor is associated with @@ -450,6 +491,20 @@ public final class Gmail { } /** + * Creates an array of SelectionArguments suitable for passing to the provider's query. + * Currently this only handles one flag, but it could be expanded in the future. + */ + private static String[] getSelectionArguments( + BecomeActiveNetworkCursor becomeActiveNetworkCursor) { + if (BecomeActiveNetworkCursor.NO == becomeActiveNetworkCursor) { + return new String[] {SelectionArguments.DO_NOT_BECOME_ACTIVE_NETWORK_CURSOR}; + } else { + // Default behavior; no args required. + return null; + } + } + + /** * Asynchronously gets a cursor over all conversations matching a query. The * query is in Gmail's query syntax. When the operation is complete the handler's * onQueryComplete() method is called with the resulting Cursor. @@ -458,14 +513,17 @@ public final class Gmail { * @param handler An AsyncQueryHanlder that will be used to run the query * @param token The token to pass to startQuery, which will be passed back to onQueryComplete * @param query a query in Gmail's query syntax + * @param becomeActiveNetworkCursor whether or not the returned + * cursor should become the Active Network Cursor */ public void runQueryForConversations(String account, AsyncQueryHandler handler, int token, - String query) { + String query, BecomeActiveNetworkCursor becomeActiveNetworkCursor) { if (TextUtils.isEmpty(account)) { throw new IllegalArgumentException("account is empty"); } + String[] selectionArgs = getSelectionArguments(becomeActiveNetworkCursor); handler.startQuery(token, null, Uri.withAppendedPath(CONVERSATIONS_URI, account), - CONVERSATION_PROJECTION, query, null, null); + CONVERSATION_PROJECTION, query, selectionArgs, null); } /** @@ -474,11 +532,15 @@ public final class Gmail { * * @param account run the query on this account * @param query a query in Gmail's query syntax + * @param becomeActiveNetworkCursor whether or not the returned + * cursor should become the Active Network Cursor */ - public ConversationCursor getConversationCursorForQuery(String account, String query) { + public ConversationCursor getConversationCursorForQuery( + String account, String query, BecomeActiveNetworkCursor becomeActiveNetworkCursor) { + String[] selectionArgs = getSelectionArguments(becomeActiveNetworkCursor); Cursor cursor = mContentResolver.query( Uri.withAppendedPath(CONVERSATIONS_URI, account), CONVERSATION_PROJECTION, - query, null, null); + query, selectionArgs, null); return new ConversationCursor(this, account, cursor); } @@ -559,12 +621,10 @@ public final class Gmail { * server message id. * @param label the label to add or remove * @param add true to add the label, false to remove it - * @throws NonexistentLabelException thrown if the label does not exist */ public void addOrRemoveLabelOnConversation( String account, long conversationId, long maxServerMessageId, String label, - boolean add) - throws NonexistentLabelException { + boolean add) { if (TextUtils.isEmpty(account)) { throw new IllegalArgumentException("account is empty"); } @@ -599,7 +659,6 @@ public final class Gmail { * @param messageId the id of the message to whose labels should be changed * @param label the label to add or remove * @param add true to add the label, false to remove it - * @throws NonexistentLabelException thrown if the label does not exist */ public static void addOrRemoveLabelOnMessage(ContentResolver contentResolver, String account, long conversationId, long messageId, String label, boolean add) { @@ -1175,19 +1234,6 @@ public final class Gmail { } /** - * Thrown when an operation is requested with a label that does not exist. - * - * TODO: this is here because I wanted a checked exception. However, I don't - * think that that is appropriate. In fact, I don't think that we should - * throw an exception at all because the label might have been valid when - * the caller presented it to the user but removed as a result of a sync. - * Maybe we should kill this and eat the errors. - */ - public static class NonexistentLabelException extends Exception { - // TODO: Add label name? - } - - /** * A cursor over labels. */ public final class LabelCursor extends MailCursor { @@ -2021,10 +2067,8 @@ public final class Gmail { * * @param label the label to add or remove * @param add whether to add or remove the label - * @throws NonexistentLabelException thrown if the named label does not - * exist */ - public void addOrRemoveLabel(String label, boolean add) throws NonexistentLabelException { + public void addOrRemoveLabel(String label, boolean add) { addOrRemoveLabelOnMessage(mContentResolver, mAccount, getConversationId(), getMessageId(), label, add); } diff --git a/core/java/android/provider/Im.java b/core/java/android/provider/Im.java index 68b2acd..bea857f 100644 --- a/core/java/android/provider/Im.java +++ b/core/java/android/provider/Im.java @@ -78,21 +78,10 @@ public class Im { String MSN = "MSN"; String ICQ = "ICQ"; String AIM = "AIM"; - } - - /** - * The ProviderCategories definitions are used for the Intent category for the Intent - * - * Intent intent = new Intent(Intent.ACTION_SENDTO, - * Uri.fromParts("im", data, null)). - * addCategory(category); - */ - public interface ProviderCategories { - String GTALK = "com.android.im.category.GTALK"; - String AIM = "com.android.im.category.AIM"; - String MSN = "com.android.im.category.MSN"; - String YAHOO = "com.android.im.category.YAHOO"; - String ICQ = "com.android.im.category.ICQ"; + String XMPP = "XMPP"; + String JABBER = "JABBER"; + String SKYPE = "SKYPE"; + String QQ = "QQ"; } /** @@ -140,54 +129,6 @@ public class Im { return retVal; } - /** - * This returns the provider name given a provider category. - * - * @param providerCategory the provider category defined in {@link ProviderCategories}. - * @return the corresponding provider name defined in {@link ProviderNames}. - */ - public static String getProviderNameForCategory(String providerCategory) { - if (providerCategory != null) { - if (providerCategory.equalsIgnoreCase(ProviderCategories.GTALK)) { - return ProviderNames.GTALK; - } else if (providerCategory.equalsIgnoreCase(ProviderCategories.AIM)) { - return ProviderNames.AIM; - } else if (providerCategory.equalsIgnoreCase(ProviderCategories.MSN)) { - return ProviderNames.MSN; - } else if (providerCategory.equalsIgnoreCase(ProviderCategories.YAHOO)) { - return ProviderNames.YAHOO; - } else if (providerCategory.equalsIgnoreCase(ProviderCategories.ICQ)) { - return ProviderNames.ICQ; - } - } - - return null; - } - - /** - * This returns the provider category given a provider name. - * - * @param providername the provider name defined in {@link ProviderNames}. - * @return the provider category defined in {@link ProviderCategories}. - */ - public static String getProviderCategoryFromName(String providername) { - if (providername != null) { - if (providername.equalsIgnoreCase(Im.ProviderNames.GTALK)) { - return Im.ProviderCategories.GTALK; - } else if (providername.equalsIgnoreCase(Im.ProviderNames.AIM)) { - return Im.ProviderCategories.AIM; - } else if (providername.equalsIgnoreCase(Im.ProviderNames.MSN)) { - return Im.ProviderCategories.MSN; - } else if (providername.equalsIgnoreCase(Im.ProviderNames.YAHOO)) { - return Im.ProviderCategories.YAHOO; - } else if (providername.equalsIgnoreCase(Im.ProviderNames.ICQ)) { - return Im.ProviderCategories.ICQ; - } - } - - return null; - } - private static final String[] PROVIDER_PROJECTION = new String[] { _ID, NAME @@ -797,6 +738,13 @@ public class Im { String ETAG = "etag"; /** + * The OTR etag, computed by the server, stored on the client. There is one OTR etag + * per account roster. + * <P>Type: TEXT</P> + */ + String OTR_ETAG = "otr_etag"; + + /** * The account id for the etag. * <P> Type: INTEGER </P> */ @@ -837,12 +785,38 @@ public class Im { return retVal; } + public static final String getOtrEtag(ContentResolver resolver, long accountId) { + String retVal = null; + + Cursor c = resolver.query(CONTENT_URI, + CONTACT_OTR_ETAG_PROJECTION, + ACCOUNT + "=" + accountId, + null /* selection args */, + null /* sort order */); + + try { + if (c.moveToFirst()) { + retVal = c.getString(COLUMN_OTR_ETAG); + } + } finally { + c.close(); + } + + return retVal; + } + private static final String[] CONTACT_ETAG_PROJECTION = new String[] { Im.ContactsEtag.ETAG // 0 }; private static int COLUMN_ETAG = 0; + private static final String[] CONTACT_OTR_ETAG_PROJECTION = new String[] { + Im.ContactsEtag.OTR_ETAG // 0 + }; + + private static int COLUMN_OTR_ETAG = 0; + /** * The content:// style URL for this table */ @@ -1271,9 +1245,9 @@ public class Im { } /** - * Columns shared between the IM and contacts presence tables + * Common presence columns shared between the IM and contacts presence tables */ - interface CommonPresenceColumns { + public interface CommonPresenceColumns { /** * The priority, an integer, used by XMPP presence * <P>Type: INTEGER</P> diff --git a/core/java/android/provider/MediaStore.java b/core/java/android/provider/MediaStore.java index 87a02e6..2897b4e 100644 --- a/core/java/android/provider/MediaStore.java +++ b/core/java/android/provider/MediaStore.java @@ -91,14 +91,14 @@ public final class MediaStore public static final String EXTRA_SCREEN_ORIENTATION = "android.intent.extra.screenOrientation"; /** - * The name of the Intent-extra used to control the orientation of a ViewImage. + * The name of an Intent-extra used to control the UI of a ViewImage. * This is a boolean property that overrides the activity's default fullscreen state. * @hide */ public static final String EXTRA_FULL_SCREEN = "android.intent.extra.fullScreen"; /** - * The name of the Intent-extra used to control the orientation of a ViewImage. + * The name of an Intent-extra used to control the UI of a ViewImage. * This is a boolean property that specifies whether or not to show action icons. * @hide */ @@ -117,25 +117,36 @@ public final class MediaStore */ public static final String INTENT_ACTION_STILL_IMAGE_CAMERA = "android.media.action.STILL_IMAGE_CAMERA"; - /** * The name of the Intent action used to launch a camera in video mode. */ public static final String INTENT_ACTION_VIDEO_CAMERA = "android.media.action.VIDEO_CAMERA"; /** - * Standard Intent action that can be sent to have the media application - * capture an image and return it. The image is returned as a Bitmap - * object in the extra field. - * @hide + * Standard Intent action that can be sent to have the camera application + * capture an image and return it. + * <p> + * The caller may pass an extra EXTRA_OUTPUT to control where this image will be written. + * If the EXTRA_OUTPUT is not present, then a small sized image is returned as a Bitmap + * object in the extra field. This is useful for applications that only need a small image. + * If the EXTRA_OUTPUT is present, then the full-sized image will be written to the Uri + * value of EXTRA_OUTPUT. + * @see #EXTRA_OUTPUT + * @see #EXTRA_VIDEO_QUALITY */ public final static String ACTION_IMAGE_CAPTURE = "android.media.action.IMAGE_CAPTURE"; /** - * Standard Intent action that can be sent to have the media application - * capture an video and return it. The caller may pass in an extra EXTRA_VIDEO_QUALITY - * control the video quality. - * @hide + * Standard Intent action that can be sent to have the camera application + * capture an video and return it. + * <p> + * The caller may pass in an extra EXTRA_VIDEO_QUALITY to control the video quality. + * <p> + * The caller may pass in an extra EXTRA_OUTPUT to control + * where the video is written. If EXTRA_OUTPUT is not present the video will be + * written to the standard location for videos, and the Uri of that location will be + * returned in the data field of the Uri. + * @see #EXTRA_OUTPUT */ public final static String ACTION_VIDEO_CAPTURE = "android.media.action.VIDEO_CAPTURE"; @@ -143,14 +154,12 @@ public final class MediaStore * The name of the Intent-extra used to control the quality of a recorded video. This is an * integer property. Currently value 0 means low quality, suitable for MMS messages, and * value 1 means high quality. In the future other quality levels may be added. - * @hide */ public final static String EXTRA_VIDEO_QUALITY = "android.intent.extra.videoQuality"; /** - * The name of the Intent-extra used to indicate a Uri to be used to + * The name of the Intent-extra used to indicate a content resolver Uri to be used to * store the requested image or video. - * @hide */ public final static String EXTRA_OUTPUT = "output"; @@ -471,7 +480,7 @@ public final class MediaStore /** * The default sort order for this table */ - public static final String DEFAULT_SORT_ORDER = "name ASC"; + public static final String DEFAULT_SORT_ORDER = ImageColumns.BUCKET_DISPLAY_NAME; } public static class Thumbnails implements BaseColumns @@ -582,6 +591,14 @@ public final class MediaStore public static final String DURATION = "duration"; /** + * The position, in ms, playback was at when playback for this file + * was last stopped. + * <P>Type: INTEGER (long)</P> + * @hide + */ + public static final String BOOKMARK = "bookmark"; + + /** * The id of the artist who created the audio file, if any * <P>Type: INTEGER (long)</P> */ @@ -654,6 +671,13 @@ public final class MediaStore public static final String IS_MUSIC = "is_music"; /** + * Non-zero if the audio file is a podcast + * <P>Type: INTEGER (boolean)</P> + * @hide + */ + public static final String IS_PODCAST = "is_podcast"; + + /** * Non-zero id the audio file may be a ringtone * <P>Type: INTEGER (boolean)</P> */ @@ -1198,22 +1222,15 @@ public final class MediaStore } public static final class Video { - /** - * deprecated Replaced by DEFAULT_SORT_ORDER2 - * This variable is a mistake that is retained for backwards compatibility. - * (There is no "name" column in the Video table.) - */ - public static final String DEFAULT_SORT_ORDER = "name ASC"; /** - * The default sort order for this table - * @hide + * The default sort order for this table. */ - public static final String DEFAULT_SORT_ORDER2 = MediaColumns.DISPLAY_NAME; + public static final String DEFAULT_SORT_ORDER = MediaColumns.DISPLAY_NAME; public static final Cursor query(ContentResolver cr, Uri uri, String[] projection) { - return cr.query(uri, projection, null, null, DEFAULT_SORT_ORDER2); + return cr.query(uri, projection, null, null, DEFAULT_SORT_ORDER); } public interface VideoColumns extends MediaColumns { @@ -1316,7 +1333,6 @@ public final class MediaStore * video should start playing at the next time it is opened. If the value is null or * out of the range 0..DURATION-1 then the video should start playing from the * beginning. - * @hide * <P>Type: INTEGER</P> */ public static final String BOOKMARK = "bookmark"; diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java index abbfd5b..054da1d 100644 --- a/core/java/android/provider/Settings.java +++ b/core/java/android/provider/Settings.java @@ -235,6 +235,35 @@ public final class Settings { "android.settings.LOCALE_SETTINGS"; /** + * Activity Action: Show settings to configure input methods, in particular + * allowing the user to enable input methods. + * <p> + * In some cases, a matching Activity may not exist, so ensure you + * safeguard against this. + * <p> + * Input: Nothing. + * <p> + * Output: Nothing. + */ + @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) + public static final String ACTION_INPUT_METHOD_SETTINGS = + "android.settings.INPUT_METHOD_SETTINGS"; + + /** + * Activity Action: Show settings to manage the user input dictionary. + * <p> + * In some cases, a matching Activity may not exist, so ensure you + * safeguard against this. + * <p> + * Input: Nothing. + * <p> + * Output: Nothing. + */ + @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) + public static final String ACTION_USER_DICTIONARY_SETTINGS = + "android.settings.USER_DICTIONARY_SETTINGS"; + + /** * Activity Action: Show settings to allow configuration of application-related settings. * <p> * In some cases, a matching Activity may not exist, so ensure you @@ -1233,6 +1262,13 @@ public final class Settings { public static final String TRANSITION_ANIMATION_SCALE = "transition_animation_scale"; /** + * Scaling factor for normal window animations. Setting to 0 will disable window + * animations. + * @hide + */ + public static final String FANCY_IME_ANIMATIONS = "fancy_ime_animations"; + + /** * Control whether the accelerometer will be used to change screen * orientation. If 0, it will not be used unless explicitly requested * by the application; if 1, it will be used by default unless explicitly @@ -2008,6 +2044,14 @@ public final class Settings { */ public static final String WIFI_MOBILE_DATA_TRANSITION_WAKELOCK_TIMEOUT_MS = "wifi_mobile_data_transition_wakelock_timeout_ms"; + + /** + * Whether background data usage is allowed by the user. See + * ConnectivityManager for more info. + * + * @hide pending API council + */ + public static final String BACKGROUND_DATA = "background_data"; } /** @@ -2130,6 +2174,11 @@ public final class Settings { * Event tags from the kernel event log to upload during checkin. */ public static final String CHECKIN_EVENTS = "checkin_events"; + + /** + * Event tags for list of services to upload during checkin. + */ + public static final String CHECKIN_DUMPSYS_LIST = "checkin_dumpsys_list"; /** * The interval (in seconds) between periodic checkin attempts. @@ -2704,8 +2753,27 @@ public final class Settings { * Speech encoding used with voice search on WIFI networks. To be factored out of this class. */ public static final String VOICE_SEARCH_ENCODING_WIFI = "voice_search_encoding_wifi"; - - + + /** + * Prefix for rules that launch automatic instrumentation test cycles. + * The format is the InstrumentationTestRunner (or compatible) package and class, + * followed optionally by space-separated key value pairs to pass to it. + */ + public static final String AUTOTEST_PREFIX = "autotest:"; + + /** + * Interval between synchronous checkins forced by the automatic test runner. + * If you set this to a value smaller than CHECKIN_INTERVAL, then the test runner's + * frequent checkins will prevent asynchronous background checkins from interfering + * with any performance measurements. + */ + public static final String AUTOTEST_CHECKIN_SECONDS = "autotest_checkin_seconds"; + + /** + * Interval between reboots forced by the automatic test runner. + */ + public static final String AUTOTEST_REBOOT_SECONDS = "autotest_reboot_seconds"; + /** * @deprecated * @hide @@ -2912,9 +2980,10 @@ public final class Settings { * * @param context A context. * @param cursor A cursor pointing to the row whose title should be - * returned. The cursor must contain at least the - * {@link #TITLE} and {@link #INTENT} columns. - * @return A title that is localized and can be displayed to the user. + * returned. The cursor must contain at least the {@link #TITLE} + * and {@link #INTENT} columns. + * @return A title that is localized and can be displayed to the user, + * or the empty string if one could not be found. */ public static CharSequence getTitle(Context context, Cursor cursor) { int titleColumn = cursor.getColumnIndex(TITLE); @@ -2943,7 +3012,7 @@ public final class Settings { PackageManager packageManager = context.getPackageManager(); ResolveInfo info = packageManager.resolveActivity(intent, 0); - return info.loadLabel(packageManager); + return info != null ? info.loadLabel(packageManager) : ""; } } diff --git a/core/java/android/provider/Sync.java b/core/java/android/provider/Sync.java index 94bf807..628852f 100644 --- a/core/java/android/provider/Sync.java +++ b/core/java/android/provider/Sync.java @@ -273,6 +273,7 @@ public final class Sync { public static final int ERROR_CONFLICT = 5; public static final int ERROR_TOO_MANY_DELETIONS = 6; public static final int ERROR_TOO_MANY_RETRIES = 7; + public static final int ERROR_INTERNAL = 8; // The MESG column will contain one of these or one of the Error types. public static final String MESG_SUCCESS = "success"; @@ -292,6 +293,7 @@ public final class Sync { case ERROR_CONFLICT: return "conflict detected"; case ERROR_TOO_MANY_DELETIONS: return "too many deletions"; case ERROR_TOO_MANY_RETRIES: return "too many retries"; + case ERROR_INTERNAL: return "internal error"; default: return "unknown error"; } } @@ -491,11 +493,6 @@ public final class Sync { /** controls whether or not the device listens for sync tickles */ public static final String SETTING_LISTEN_FOR_TICKLES = "listen_for_tickles"; - /** controls whether or not the device connect to Google in background for various - * stuff, including GTalk, checkin, Market and data sync ... - */ - public static final String SETTING_BACKGROUND_DATA = "background_data"; - /** controls whether or not the individual provider is synced when tickles are received */ public static final String SETTING_SYNC_PROVIDER_PREFIX = "sync_provider_"; @@ -572,18 +569,6 @@ public final class Sync { putBoolean(contentResolver, SETTING_LISTEN_FOR_TICKLES, flag); } - /** - * A convenience method to set whether or not the device should connect to Google - * in background. - * - * @param contentResolver the ContentResolver to use to access the settings table - * @param flag true if it should connect. - */ - static public void setBackgroundData(ContentResolver contentResolver, - boolean flag) { - putBoolean(contentResolver, SETTING_BACKGROUND_DATA, flag); - } - public static class QueryMap extends ContentQueryMap { private ContentResolver mContentResolver; @@ -632,24 +617,6 @@ public final class Sync { } /** - * Set whether or not the device should connect to Google in background - * - * @param flag true if it should - */ - public void setBackgroundData(boolean flag) { - Settings.setBackgroundData(mContentResolver, flag); - } - - /** - * Check if the device should connect to Google in background. - - * @return true if it should - */ - public boolean getBackgroundData() { - return getBoolean(SETTING_BACKGROUND_DATA, true); - } - - /** * Convenience function for retrieving a single settings value * as a boolean. * diff --git a/core/java/android/provider/UserDictionary.java b/core/java/android/provider/UserDictionary.java index 58e5731..5a7ef85 100644 --- a/core/java/android/provider/UserDictionary.java +++ b/core/java/android/provider/UserDictionary.java @@ -25,10 +25,13 @@ import android.net.Uri; import android.text.TextUtils; /** - * - * @hide Pending API council approval + * A provider of user defined words for input methods to use for predictive text input. + * Applications and input methods may add words into the dictionary. Words can have associated + * frequency information and locale information. */ public class UserDictionary { + + /** Authority string for this provider. */ public static final String AUTHORITY = "user_dictionary"; /** @@ -39,7 +42,6 @@ public class UserDictionary { /** * Contains the user defined words. - * @hide Pending API council approval */ public static class Words implements BaseColumns { /** @@ -67,14 +69,14 @@ public class UserDictionary { public static final String WORD = "word"; /** - * The frequency column. A value between 1 and 255. + * The frequency column. A value between 1 and 255. Higher values imply higher frequency. * <p>TYPE: INTEGER</p> */ public static final String FREQUENCY = "frequency"; /** * The locale that this word belongs to. Null if it pertains to all - * locales. Locale is a 5 letter string such as <pre>en_US</pre>. + * locales. Locale is as defined by the string returned by Locale.toString(). * <p>TYPE: TEXT</p> */ public static final String LOCALE = "locale"; @@ -85,8 +87,10 @@ public class UserDictionary { */ public static final String APP_ID = "appid"; + /** The locale type to specify that the word is common to all locales. */ public static final int LOCALE_TYPE_ALL = 0; + /** The locale type to specify that the word is for the current locale. */ public static final int LOCALE_TYPE_CURRENT = 1; /** @@ -94,7 +98,14 @@ public class UserDictionary { */ public static final String DEFAULT_SORT_ORDER = FREQUENCY + " DESC"; - + /** Adds a word to the dictionary, with the given frequency and the specified + * specified locale type. + * @param context the current application context + * @param word the word to add to the dictionary. This should not be null or + * empty. + * @param localeType the locale type for this word. It should be one of + * {@link #LOCALE_TYPE_ALL} or {@link #LOCALE_TYPE_CURRENT}. + */ public static void addWord(Context context, String word, int frequency, int localeType) { final ContentResolver resolver = context.getContentResolver(); diff --git a/core/java/android/provider/package.html b/core/java/android/provider/package.html index a553592..055b037 100644 --- a/core/java/android/provider/package.html +++ b/core/java/android/provider/package.html @@ -6,6 +6,6 @@ Android. as contact informations, calendar information, and media files. These classes provide simplified methods of adding or retrieving data from these content providers. For information about how to use a content provider, see <a -href="{@docRoot}devel/data.html">Reading and Writing Persistent Data</a>. +href="{@docRoot}guide/topics/providers/content-providers.html">Content Providers</a>. </BODY> </HTML> diff --git a/core/java/android/server/BluetoothA2dpService.java b/core/java/android/server/BluetoothA2dpService.java index 8486e4b..58f9491 100644 --- a/core/java/android/server/BluetoothA2dpService.java +++ b/core/java/android/server/BluetoothA2dpService.java @@ -55,6 +55,7 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH; private static final String A2DP_SINK_ADDRESS = "a2dp_sink_address"; + private static final String BLUETOOTH_ENABLED = "bluetooth_enabled"; private final Context mContext; private final IntentFilter mIntentFilter; @@ -136,10 +137,28 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { BluetoothA2dp.STATE_DISCONNECTED)); } } + mAudioManager.setParameter(BLUETOOTH_ENABLED, "true"); } private synchronized void onBluetoothDisable() { - mAudioDevices = null; + if (mAudioDevices != null) { + for (String path : mAudioDevices.keySet()) { + switch (mAudioDevices.get(path).state) { + case BluetoothA2dp.STATE_CONNECTING: + case BluetoothA2dp.STATE_CONNECTED: + case BluetoothA2dp.STATE_PLAYING: + disconnectSinkNative(path); + updateState(path, BluetoothA2dp.STATE_DISCONNECTED); + break; + case BluetoothA2dp.STATE_DISCONNECTING: + updateState(path, BluetoothA2dp.STATE_DISCONNECTED); + break; + } + } + mAudioDevices = null; + } + mAudioManager.setBluetoothA2dpOn(false); + mAudioManager.setParameter(BLUETOOTH_ENABLED, "false"); } public synchronized int connectSink(String address) { @@ -289,6 +308,7 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { } } + updateState(path, BluetoothA2dp.STATE_CONNECTING); mAudioManager.setParameter(A2DP_SINK_ADDRESS, lookupAddress(path)); mAudioManager.setBluetoothA2dpOn(true); updateState(path, BluetoothA2dp.STATE_CONNECTED); @@ -309,6 +329,11 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { private synchronized final String lookupAddress(String path) { if (mAudioDevices == null) return null; + SinkState sink = mAudioDevices.get(path); + if (sink == null) { + Log.w(TAG, "lookupAddress() called for unknown device " + path); + updateState(path, BluetoothA2dp.STATE_DISCONNECTED); + } String address = mAudioDevices.get(path).address; if (address == null) Log.e(TAG, "Can't find address for " + path); return address; @@ -349,6 +374,15 @@ public class BluetoothA2dpService extends IBluetoothA2dp.Stub { intent.putExtra(BluetoothA2dp.SINK_PREVIOUS_STATE, prevState); intent.putExtra(BluetoothA2dp.SINK_STATE, state); mContext.sendBroadcast(intent, BLUETOOTH_PERM); + + if ((prevState == BluetoothA2dp.STATE_CONNECTED || + prevState == BluetoothA2dp.STATE_PLAYING) && + (state != BluetoothA2dp.STATE_CONNECTED && + state != BluetoothA2dp.STATE_PLAYING)) { + // disconnected + intent = new Intent(AudioManager.ACTION_AUDIO_BECOMING_NOISY); + mContext.sendBroadcast(intent); + } } } diff --git a/core/java/android/server/BluetoothDeviceService.java b/core/java/android/server/BluetoothDeviceService.java index 3ce34c3..d149761 100644 --- a/core/java/android/server/BluetoothDeviceService.java +++ b/core/java/android/server/BluetoothDeviceService.java @@ -91,8 +91,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { mIsDiscovering = false; mEventLoop = new BluetoothEventLoop(mContext, this); registerForAirplaneMode(); - - disableEsco(); // TODO: enable eSCO support once its fully supported } private native void initializeNativeDataNative(); @@ -130,10 +128,21 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } mEventLoop.stop(); disableNative(); + + // mark in progress bondings as cancelled + for (String address : mBondState.listInState(BluetoothDevice.BOND_BONDING)) { + mBondState.setBondState(address, BluetoothDevice.BOND_NOT_BONDED, + BluetoothDevice.UNBOND_REASON_AUTH_CANCELED); + } + // update mode + Intent intent = new Intent(BluetoothIntent.SCAN_MODE_CHANGED_ACTION); + intent.putExtra(BluetoothIntent.SCAN_MODE, BluetoothDevice.SCAN_MODE_NONE); + mContext.sendBroadcast(intent, BLUETOOTH_PERM); + mIsEnabled = false; - Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.BLUETOOTH_ON, 0); + persistBluetoothOnSetting(false); mIsDiscovering = false; - Intent intent = new Intent(BluetoothIntent.DISABLED_ACTION); + intent = new Intent(BluetoothIntent.DISABLED_ACTION); mContext.sendBroadcast(intent, BLUETOOTH_PERM); return true; } @@ -202,18 +211,27 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { if (res) { mIsEnabled = true; - Settings.Secure.putInt(mContext.getContentResolver(), - Settings.Secure.BLUETOOTH_ON, 1); + persistBluetoothOnSetting(true); mIsDiscovering = false; Intent intent = new Intent(BluetoothIntent.ENABLED_ACTION); mBondState.loadBondState(); mContext.sendBroadcast(intent, BLUETOOTH_PERM); mHandler.sendMessageDelayed(mHandler.obtainMessage(REGISTER_SDP_RECORDS), 3000); + + // Update mode + mEventLoop.onModeChanged(getModeNative()); } mEnableThread = null; } - }; + } + private void persistBluetoothOnSetting(boolean bluetoothOn) { + long origCallerIdentityToken = Binder.clearCallingIdentity(); + Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.BLUETOOTH_ON, + bluetoothOn ? 1 : 0); + Binder.restoreCallingIdentity(origCallerIdentityToken); + } + private native int enableNative(); private native int disableNative(); @@ -288,10 +306,10 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { return state.intValue(); } - public synchronized String[] listBonds() { + private synchronized String[] listInState(int state) { ArrayList<String> result = new ArrayList<String>(mState.size()); for (Map.Entry<String, Integer> e : mState.entrySet()) { - if (e.getValue().intValue() == BluetoothDevice.BOND_BONDED) { + if (e.getValue().intValue() == state) { result.add(e.getKey()); } } @@ -353,18 +371,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } private native boolean setNameNative(String name); - public synchronized String getMajorClass() { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return getMajorClassNative(); - } - private native String getMajorClassNative(); - - public synchronized String getMinorClass() { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return getMinorClassNative(); - } - private native String getMinorClassNative(); - /** * Returns the user-friendly name of a remote device. This value is * retrned from our local cache, which is updated during device discovery. @@ -386,24 +392,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { /* pacakge */ native String getAdapterPathNative(); - /** - * Initiate a remote-device-discovery procedure. This procedure may be - * canceled by calling {@link #stopDiscovery}. Remote-device discoveries - * are returned as intents - * <p> - * Typically, when a remote device is found, your - * android.bluetooth.DiscoveryEventNotifier#notifyRemoteDeviceFound - * method will be invoked, and subsequently, your - * android.bluetooth.RemoteDeviceEventNotifier#notifyRemoteNameUpdated - * will tell you the user-friendly name of the remote device. However, - * it is possible that the name update may fail for various reasons, so you - * should display the device's Bluetooth address as soon as you get a - * notifyRemoteDeviceFound event, and update the name when you get the - * remote name. - * - * @return true if discovery has started, - * false otherwise. - */ public synchronized boolean startDiscovery(boolean resolveNames) { mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); @@ -411,12 +399,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } private native boolean startDiscoveryNative(boolean resolveNames); - /** - * Cancel a remote-device discovery. - * - * Note: you may safely call this method even when discovery has not been - * started. - */ public synchronized boolean cancelDiscovery() { mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); @@ -492,171 +474,23 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } private native boolean isConnectedNative(String address); - /** - * Detetermines whether this device is connectable (that is, whether remote - * devices can connect to it.) - * <p> - * Note: A Bluetooth adapter has separate connectable and discoverable - * states, and you could have any combination of those. Although - * any combination is possible (such as discoverable but not - * connectable), we restrict the possible combinations to one of - * three possibilities: discoverable and connectable, connectable - * but not discoverable, and neither connectable nor discoverable. - * - * @return true if this adapter is connectable - * false otherwise - * - * @see #isDiscoverable - * @see #getMode - * @see #setMode - */ - public synchronized boolean isConnectable() { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return isConnectableNative(); - } - private native boolean isConnectableNative(); - - /** - * Detetermines whether this device is discoverable. - * - * Note: a Bluetooth adapter has separate connectable and discoverable - * states, and you could have any combination of those. Although - * any combination is possible (such as discoverable but not - * connectable), we restrict the possible combinations to one of - * three possibilities: discoverable and connectable, connectable - * but not discoverable, and neither connectable nor discoverable. - * - * @return true if this adapter is discoverable - * false otherwise - * - * @see #isConnectable - * @see #getMode - * @see #setMode - */ - public synchronized boolean isDiscoverable() { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return isDiscoverableNative(); - } - private native boolean isDiscoverableNative(); - - /** - * Determines which one of three modes this adapter is in: discoverable and - * connectable, not discoverable but connectable, or neither. - * - * @return Mode enumeration containing the current mode. - * - * @see #setMode - */ - public synchronized int getMode() { + public synchronized int getScanMode() { mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - String mode = getModeNative(); - if (mode == null) { - return BluetoothDevice.MODE_UNKNOWN; - } - if (mode.equalsIgnoreCase("off")) { - return BluetoothDevice.MODE_OFF; - } - else if (mode.equalsIgnoreCase("connectable")) { - return BluetoothDevice.MODE_CONNECTABLE; - } - else if (mode.equalsIgnoreCase("discoverable")) { - return BluetoothDevice.MODE_DISCOVERABLE; - } - else { - return BluetoothDevice.MODE_UNKNOWN; - } + return bluezStringToScanMode(getModeNative()); } private native String getModeNative(); - /** - * Set the discoverability and connectability mode of this adapter. The - * possibilities are discoverable and connectable (MODE_DISCOVERABLE), - * connectable but not discoverable (MODE_CONNECTABLE), and neither - * (MODE_OFF). - * - * Note: MODE_OFF does not mean that the adapter is physically off. It - * may be neither discoverable nor connectable, but it could still - * initiate outgoing connections, or could participate in a - * connection initiated by a remote device before its mode was set - * to MODE_OFF. - * - * @param mode the new mode - * @see #getMode - */ - public synchronized boolean setMode(int mode) { + public synchronized boolean setScanMode(int mode) { mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); - switch (mode) { - case BluetoothDevice.MODE_OFF: - return setModeNative("off"); - case BluetoothDevice.MODE_CONNECTABLE: - return setModeNative("connectable"); - case BluetoothDevice.MODE_DISCOVERABLE: - return setModeNative("discoverable"); + String bluezMode = scanModeToBluezString(mode); + if (bluezMode != null) { + return setModeNative(bluezMode); } return false; } private native boolean setModeNative(String mode); - /** - * Retrieves the alias of a remote device. The alias is a local feature, - * and allows us to associate a name with a remote device that is different - * from that remote device's user-friendly name. The remote device knows - * nothing about this. The alias can be changed with - * {@link #setRemoteAlias}, and it may be removed with - * {@link #clearRemoteAlias} - * - * @param address Bluetooth address of remote device. - * - * @return The alias of the remote device. - */ - public synchronized String getRemoteAlias(String address) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - if (!BluetoothDevice.checkBluetoothAddress(address)) { - return null; - } - return getRemoteAliasNative(address); - } - private native String getRemoteAliasNative(String address); - - /** - * Changes the alias of a remote device. The alias is a local feature, - * from that remote device's user-friendly name. The remote device knows - * nothing about this. The alias can be retrieved with - * {@link #getRemoteAlias}, and it may be removed with - * {@link #clearRemoteAlias}. - * - * @param address Bluetooth address of remote device - * @param alias Alias for the remote device - */ - public synchronized boolean setRemoteAlias(String address, String alias) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, - "Need BLUETOOTH_ADMIN permission"); - if (alias == null || !BluetoothDevice.checkBluetoothAddress(address)) { - return false; - } - return setRemoteAliasNative(address, alias); - } - private native boolean setRemoteAliasNative(String address, String alias); - - /** - * Removes the alias of a remote device. The alias is a local feature, - * from that remote device's user-friendly name. The remote device knows - * nothing about this. The alias can be retrieved with - * {@link #getRemoteAlias}. - * - * @param address Bluetooth address of remote device - */ - public synchronized boolean clearRemoteAlias(String address) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, - "Need BLUETOOTH_ADMIN permission"); - if (!BluetoothDevice.checkBluetoothAddress(address)) { - return false; - } - return clearRemoteAliasNative(address); - } - private native boolean clearRemoteAliasNative(String address); - public synchronized boolean disconnectRemoteDeviceAcl(String address) { mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH_ADMIN permission"); @@ -699,7 +533,7 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { } mBondState.setBondState(address, BluetoothDevice.BOND_NOT_BONDED, - BluetoothDevice.UNBOND_REASON_CANCELLED); + BluetoothDevice.UNBOND_REASON_AUTH_CANCELED); cancelBondingProcessNative(address); return true; } @@ -717,7 +551,7 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { public synchronized String[] listBonds() { mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return mBondState.listBonds(); + return mBondState.listInState(BluetoothDevice.BOND_BONDED); } public synchronized int getBondState(String address) { @@ -919,69 +753,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { private native String lastUsedNative(String address); /** - * Gets the major device class of the specified device. - * Example: "computer" - * - * Note: This is simply a string desciption of the major class of the - * device-class information, which is returned as a 32-bit value - * during device discovery. - * - * @param address The Bluetooth address of the remote device. - * - * @return remote-device major class - * - * @see #getRemoteClass - */ - public synchronized String getRemoteMajorClass(String address) { - if (!BluetoothDevice.checkBluetoothAddress(address)) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - return null; - } - return getRemoteMajorClassNative(address); - } - private native String getRemoteMajorClassNative(String address); - - /** - * Gets the minor device class of the specified device. - * Example: "laptop" - * - * Note: This is simply a string desciption of the minor class of the - * device-class information, which is returned as a 32-bit value - * during device discovery. - * - * @param address The Bluetooth address of the remote device. - * - * @return remote-device minor class - * - * @see #getRemoteClass - */ - public synchronized String getRemoteMinorClass(String address) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - if (!BluetoothDevice.checkBluetoothAddress(address)) { - return null; - } - return getRemoteMinorClassNative(address); - } - private native String getRemoteMinorClassNative(String address); - - /** - * Gets the service classes of the specified device. - * Example: ["networking", "object transfer"] - * - * @return a String array with the descriptions of the service classes. - * - * @see #getRemoteClass - */ - public synchronized String[] getRemoteServiceClasses(String address) { - mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); - if (!BluetoothDevice.checkBluetoothAddress(address)) { - return null; - } - return getRemoteServiceClassesNative(address); - } - private native String[] getRemoteServiceClassesNative(String address); - - /** * Gets the remote major, minor, and service classes encoded as a 32-bit * integer. * @@ -1188,16 +959,6 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { Settings.System.AIRPLANE_MODE_ON, 0) == 1; } - private static final String DISABLE_ESCO_PATH = "/sys/module/sco/parameters/disable_esco"; - private static void disableEsco() { - try { - FileWriter file = new FileWriter(DISABLE_ESCO_PATH); - file.write("Y"); - file.close(); - } catch (FileNotFoundException e) { - } catch (IOException e) {} - } - @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { if (mIsEnabled) { @@ -1248,6 +1009,34 @@ public class BluetoothDeviceService extends IBluetoothDevice.Stub { pw.println("\nmIsAirplaneSensitive = " + mIsAirplaneSensitive); } + /* package */ static int bluezStringToScanMode(String mode) { + if (mode == null) { + return BluetoothError.ERROR; + } + mode = mode.toLowerCase(); + if (mode.equals("off")) { + return BluetoothDevice.SCAN_MODE_NONE; + } else if (mode.equals("connectable")) { + return BluetoothDevice.SCAN_MODE_CONNECTABLE; + } else if (mode.equals("discoverable")) { + return BluetoothDevice.SCAN_MODE_CONNECTABLE_DISCOVERABLE; + } else { + return BluetoothError.ERROR; + } + } + + /* package */ static String scanModeToBluezString(int mode) { + switch (mode) { + case BluetoothDevice.SCAN_MODE_NONE: + return "off"; + case BluetoothDevice.SCAN_MODE_CONNECTABLE: + return "connectable"; + case BluetoothDevice.SCAN_MODE_CONNECTABLE_DISCOVERABLE: + return "discoverable"; + } + return null; + } + private static void log(String msg) { Log.d(TAG, msg); } diff --git a/core/java/android/server/BluetoothEventLoop.java b/core/java/android/server/BluetoothEventLoop.java index 4f63f98..0f60fae 100644 --- a/core/java/android/server/BluetoothEventLoop.java +++ b/core/java/android/server/BluetoothEventLoop.java @@ -16,6 +16,7 @@ package android.server; +import android.bluetooth.BluetoothA2dp; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothError; @@ -114,9 +115,7 @@ class BluetoothEventLoop { public synchronized void stop() { if (mThread != null) { - mInterrupted = true; - try { mThread.join(); mThread = null; @@ -130,104 +129,86 @@ class BluetoothEventLoop { return mThread != null; } - public void onModeChanged(String mode) { - Intent intent = new Intent(BluetoothIntent.MODE_CHANGED_ACTION); - int intMode = BluetoothDevice.MODE_UNKNOWN; - if (mode.equalsIgnoreCase("off")) { - intMode = BluetoothDevice.MODE_OFF; - } - else if (mode.equalsIgnoreCase("connectable")) { - intMode = BluetoothDevice.MODE_CONNECTABLE; - } - else if (mode.equalsIgnoreCase("discoverable")) { - intMode = BluetoothDevice.MODE_DISCOVERABLE; + /*package*/ void onModeChanged(String bluezMode) { + int mode = BluetoothDeviceService.bluezStringToScanMode(bluezMode); + if (mode >= 0) { + Intent intent = new Intent(BluetoothIntent.SCAN_MODE_CHANGED_ACTION); + intent.putExtra(BluetoothIntent.SCAN_MODE, mode); + mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - intent.putExtra(BluetoothIntent.MODE, intMode); - mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onDiscoveryStarted() { + private void onDiscoveryStarted() { mBluetoothService.setIsDiscovering(true); Intent intent = new Intent(BluetoothIntent.DISCOVERY_STARTED_ACTION); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onDiscoveryCompleted() { + private void onDiscoveryCompleted() { mBluetoothService.setIsDiscovering(false); Intent intent = new Intent(BluetoothIntent.DISCOVERY_COMPLETED_ACTION); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onPairingRequest() { + private void onPairingRequest() { Intent intent = new Intent(BluetoothIntent.PAIRING_REQUEST_ACTION); mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM); } - public void onPairingCancel() { + private void onPairingCancel() { Intent intent = new Intent(BluetoothIntent.PAIRING_CANCEL_ACTION); mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM); } - public void onRemoteDeviceFound(String address, int deviceClass, short rssi) { + private void onRemoteDeviceFound(String address, int deviceClass, short rssi) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_FOUND_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); intent.putExtra(BluetoothIntent.CLASS, deviceClass); intent.putExtra(BluetoothIntent.RSSI, rssi); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteDeviceDisappeared(String address) { + private void onRemoteDeviceDisappeared(String address) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_DISAPPEARED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteClassUpdated(String address, int deviceClass) { + private void onRemoteClassUpdated(String address, int deviceClass) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_CLASS_UPDATED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); intent.putExtra(BluetoothIntent.CLASS, deviceClass); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteDeviceConnected(String address) { + private void onRemoteDeviceConnected(String address) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_CONNECTED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteDeviceDisconnectRequested(String address) { + private void onRemoteDeviceDisconnectRequested(String address) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_DISCONNECT_REQUESTED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteDeviceDisconnected(String address) { + private void onRemoteDeviceDisconnected(String address) { Intent intent = new Intent(BluetoothIntent.REMOTE_DEVICE_DISCONNECTED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteNameUpdated(String address, String name) { + private void onRemoteNameUpdated(String address, String name) { Intent intent = new Intent(BluetoothIntent.REMOTE_NAME_UPDATED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); intent.putExtra(BluetoothIntent.NAME, name); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteNameFailed(String address) { + private void onRemoteNameFailed(String address) { Intent intent = new Intent(BluetoothIntent.REMOTE_NAME_FAILED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteNameChanged(String address, String name) { + private void onRemoteNameChanged(String address, String name) { Intent intent = new Intent(BluetoothIntent.REMOTE_NAME_UPDATED_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); intent.putExtra(BluetoothIntent.NAME, name); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onRemoteAliasChanged(String address, String alias) { - Intent intent = new Intent(BluetoothIntent.REMOTE_ALIAS_CHANGED_ACTION); - intent.putExtra(BluetoothIntent.ADDRESS, address); - intent.putExtra(BluetoothIntent.ALIAS, alias); - mContext.sendBroadcast(intent, BLUETOOTH_PERM); - } - public void onRemoteAliasCleared(String address) { - Intent intent = new Intent(BluetoothIntent.REMOTE_ALIAS_CLEARED_ACTION); - intent.putExtra(BluetoothIntent.ADDRESS, address); - mContext.sendBroadcast(intent, BLUETOOTH_PERM); - } private void onCreateBondingResult(String address, int result) { address = address.toUpperCase(); @@ -239,23 +220,23 @@ class BluetoothEventLoop { } } - public void onBondingCreated(String address) { + private void onBondingCreated(String address) { mBluetoothService.getBondState().setBondState(address.toUpperCase(), BluetoothDevice.BOND_BONDED); } - public void onBondingRemoved(String address) { + private void onBondingRemoved(String address) { mBluetoothService.getBondState().setBondState(address.toUpperCase(), BluetoothDevice.BOND_NOT_BONDED, BluetoothDevice.UNBOND_REASON_REMOVED); } - public void onNameChanged(String name) { + private void onNameChanged(String name) { Intent intent = new Intent(BluetoothIntent.NAME_CHANGED_ACTION); intent.putExtra(BluetoothIntent.NAME, name); mContext.sendBroadcast(intent, BLUETOOTH_PERM); } - public void onPasskeyAgentRequest(String address, int nativeData) { + private void onPasskeyAgentRequest(String address, int nativeData) { address = address.toUpperCase(); mPasskeyAgentRequestData.put(address, new Integer(nativeData)); @@ -284,14 +265,36 @@ class BluetoothEventLoop { mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM); } - public void onPasskeyAgentCancel(String address) { + private void onPasskeyAgentCancel(String address) { address = address.toUpperCase(); mPasskeyAgentRequestData.remove(address); Intent intent = new Intent(BluetoothIntent.PAIRING_CANCEL_ACTION); intent.putExtra(BluetoothIntent.ADDRESS, address); mContext.sendBroadcast(intent, BLUETOOTH_ADMIN_PERM); mBluetoothService.getBondState().setBondState(address, BluetoothDevice.BOND_NOT_BONDED, - BluetoothDevice.UNBOND_REASON_CANCELLED); + BluetoothDevice.UNBOND_REASON_AUTH_CANCELED); + } + + private boolean onAuthAgentAuthorize(String address, String service, String uuid) { + boolean authorized = false; + if (service.endsWith("service_audio")) { + BluetoothA2dp a2dp = new BluetoothA2dp(mContext); + authorized = a2dp.getSinkPriority(address) > BluetoothA2dp.PRIORITY_OFF; + if (authorized) { + Log.i(TAG, "Allowing incoming A2DP connection from " + address); + } else { + Log.i(TAG, "Rejecting incoming A2DP connection from " + address); + } + } else { + Log.i(TAG, "Rejecting incoming " + service + " connection from " + address); + } + return authorized; + } + + private void onAuthAgentCancel(String address, String service, String uuid) { + // We immediately response to DBUS Authorize() so this should not + // usually happen + log("onAuthAgentCancel(" + address + ", " + service + ", " + uuid + ")"); } private void onGetRemoteServiceChannelResult(String address, int channel) { diff --git a/core/java/android/server/checkin/CheckinProvider.java b/core/java/android/server/checkin/CheckinProvider.java deleted file mode 100644 index 86ece4a..0000000 --- a/core/java/android/server/checkin/CheckinProvider.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Copyright (C) 2006 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * 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.server.checkin; - -import android.content.ContentProvider; -import android.content.ContentUris; -import android.content.ContentValues; -import android.content.Context; -import android.content.pm.PackageManager; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteOpenHelper; -import android.database.sqlite.SQLiteQueryBuilder; -import android.net.Uri; -import android.os.Environment; -import android.provider.BaseColumns; -import android.provider.Checkin; -import android.util.Log; - -import java.io.File; - -/** - * Content provider for the database used to store events and statistics - * while they wait to be uploaded by the checkin service. - */ -public class CheckinProvider extends ContentProvider { - /** Class identifier for logging. */ - private static final String TAG = "CheckinProvider"; - - /** Filename of database (in /data directory). */ - private static final String DATABASE_FILENAME = "checkin.db"; - - /** Version of database schema. */ - private static final int DATABASE_VERSION = 1; - - /** Maximum number of events recorded. */ - private static final int EVENT_LIMIT = 1000; - - /** Maximum size of individual event data. */ - private static final int EVENT_SIZE = 8192; - - /** Maximum number of crashes recorded. */ - private static final int CRASH_LIMIT = 25; - - /** Maximum size of individual crashes recorded. */ - private static final int CRASH_SIZE = 16384; - - /** Permission required for access to the 'properties' database. */ - private static final String PROPERTIES_PERMISSION = - "android.permission.ACCESS_CHECKIN_PROPERTIES"; - - /** Lock for stats read-modify-write update cycle (see {@link #insert}). */ - private final Object mStatsLock = new Object(); - - /** The underlying SQLite database. */ - private SQLiteOpenHelper mOpenHelper; - - private static class OpenHelper extends SQLiteOpenHelper { - public OpenHelper(Context context) { - super(context, DATABASE_FILENAME, null, DATABASE_VERSION); - - // The database used to live in /data/checkin.db. - File oldLocation = Environment.getDataDirectory(); - File old = new File(oldLocation, DATABASE_FILENAME); - File file = context.getDatabasePath(DATABASE_FILENAME); - - // Try to move the file to the new location. - // TODO: Remove this code before shipping. - if (old.exists() && !file.exists() && !old.renameTo(file)) { - Log.e(TAG, "Can't rename " + old + " to " + file); - } - if (old.exists() && !old.delete()) { - // Clean up the old data file in any case. - Log.e(TAG, "Can't remove " + old); - } - } - - @Override - public void onCreate(SQLiteDatabase db) { - db.execSQL("CREATE TABLE " + Checkin.Events.TABLE_NAME + " (" + - BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + - Checkin.Events.TAG + " TEXT NOT NULL," + - Checkin.Events.VALUE + " TEXT DEFAULT \"\"," + - Checkin.Events.DATE + " INTEGER NOT NULL)"); - - db.execSQL("CREATE INDEX events_index ON " + - Checkin.Events.TABLE_NAME + " (" + - Checkin.Events.TAG + ")"); - - db.execSQL("CREATE TABLE " + Checkin.Stats.TABLE_NAME + " (" + - BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + - Checkin.Stats.TAG + " TEXT UNIQUE," + - Checkin.Stats.COUNT + " INTEGER DEFAULT 0," + - Checkin.Stats.SUM + " REAL DEFAULT 0.0)"); - - db.execSQL("CREATE TABLE " + Checkin.Crashes.TABLE_NAME + " (" + - BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + - Checkin.Crashes.DATA + " TEXT NOT NULL," + - Checkin.Crashes.LOGS + " TEXT)"); - - db.execSQL("CREATE TABLE " + Checkin.Properties.TABLE_NAME + " (" + - BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + - Checkin.Properties.TAG + " TEXT UNIQUE ON CONFLICT REPLACE," - + Checkin.Properties.VALUE + " TEXT DEFAULT \"\")"); - } - - @Override - public void onUpgrade(SQLiteDatabase db, int old, int version) { - db.execSQL("DROP TABLE IF EXISTS " + Checkin.Events.TABLE_NAME); - db.execSQL("DROP TABLE IF EXISTS " + Checkin.Stats.TABLE_NAME); - db.execSQL("DROP TABLE IF EXISTS " + Checkin.Crashes.TABLE_NAME); - db.execSQL("DROP TABLE IF EXISTS " + Checkin.Properties.TABLE_NAME); - onCreate(db); - } - } - - @Override public boolean onCreate() { - mOpenHelper = new OpenHelper(getContext()); - return true; - } - - @Override - public Cursor query(Uri uri, String[] select, - String where, String[] args, String sort) { - checkPermissions(uri); - SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); - qb.setTables(uri.getPathSegments().get(0)); - if (uri.getPathSegments().size() == 2) { - qb.appendWhere("_id=" + ContentUris.parseId(uri)); - } else if (uri.getPathSegments().size() != 1) { - throw new IllegalArgumentException("Invalid query URI: " + uri); - } - - SQLiteDatabase db = mOpenHelper.getReadableDatabase(); - Cursor cursor = qb.query(db, select, where, args, null, null, sort); - cursor.setNotificationUri(getContext().getContentResolver(), uri); - return cursor; - } - - @Override - public Uri insert(Uri uri, ContentValues values) { - checkPermissions(uri); - if (uri.getPathSegments().size() != 1) { - throw new IllegalArgumentException("Invalid insert URI: " + uri); - } - - long id; - String table = uri.getPathSegments().get(0); - if (Checkin.Events.TABLE_NAME.equals(table)) { - id = insertEvent(values); - } else if (Checkin.Stats.TABLE_NAME.equals(table)) { - id = insertStats(values); - } else if (Checkin.Crashes.TABLE_NAME.equals(table)) { - id = insertCrash(values); - } else { - id = mOpenHelper.getWritableDatabase().insert(table, null, values); - } - - if (id < 0) { - return null; - } else { - uri = ContentUris.withAppendedId(uri, id); - getContext().getContentResolver().notifyChange(uri, null); - return uri; - } - } - - /** - * Insert an entry into the events table. - * Trims old events from the table to keep the size bounded. - * @param values to insert - * @return the row ID of the new entry - */ - private long insertEvent(ContentValues values) { - String value = values.getAsString(Checkin.Events.VALUE); - if (value != null && value.length() > EVENT_SIZE) { - // Event values are readable text, so they can be truncated. - value = value.substring(0, EVENT_SIZE - 3) + "..."; - values.put(Checkin.Events.VALUE, value); - } - - if (!values.containsKey(Checkin.Events.DATE)) { - values.put(Checkin.Events.DATE, System.currentTimeMillis()); - } - - // TODO: Make this more efficient; don't do it on every insert. - // Also, consider keeping the most recent instance of every tag, - // and possibly update a counter when events are deleted. - - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - db.execSQL("DELETE FROM " + - Checkin.Events.TABLE_NAME + " WHERE " + - Checkin.Events._ID + " IN (SELECT " + - Checkin.Events._ID + " FROM " + - Checkin.Events.TABLE_NAME + " ORDER BY " + - Checkin.Events.DATE + " DESC LIMIT -1 OFFSET " + - (EVENT_LIMIT - 1) + ")"); - return db.insert(Checkin.Events.TABLE_NAME, null, values); - } - - /** - * Add an entry into the stats table. - * For statistics, instead of just inserting a row into the database, - * we add the count and sum values to the existing values (if any) - * for the specified tag. This must be done with a lock held, - * to avoid a race condition during the read-modify-write update. - * @param values to insert - * @return the row ID of the modified entry - */ - private long insertStats(ContentValues values) { - synchronized (mStatsLock) { - String tag = values.getAsString(Checkin.Stats.TAG); - if (tag == null) { - throw new IllegalArgumentException("Tag required:" + values); - } - - // Look for existing values with this tag. - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - Cursor cursor = db.query(false, - Checkin.Stats.TABLE_NAME, - new String[] { - Checkin.Stats._ID, - Checkin.Stats.COUNT, - Checkin.Stats.SUM - }, - Checkin.Stats.TAG + "=?", - new String[] { tag }, - null, null, null, null /* limit */); - - try { - if (cursor == null || !cursor.moveToNext()) { - // This is a new statistic, insert it directly. - return db.insert(Checkin.Stats.TABLE_NAME, null, values); - } else { - // Depend on SELECT column order to avoid getColumnIndex() - long id = cursor.getLong(0); - int count = cursor.getInt(1); - double sum = cursor.getDouble(2); - - Integer countAdd = values.getAsInteger(Checkin.Stats.COUNT); - if (countAdd != null) count += countAdd.intValue(); - - Double sumAdd = values.getAsDouble(Checkin.Stats.SUM); - if (sumAdd != null) sum += sumAdd.doubleValue(); - - if (count <= 0 && sum == 0.0) { - // Updated to nothing: delete the row! - cursor.deleteRow(); - getContext().getContentResolver().notifyChange( - ContentUris.withAppendedId(Checkin.Stats.CONTENT_URI, id), null); - return -1; - } else { - if (countAdd != null) cursor.updateInt(1, count); - if (sumAdd != null) cursor.updateDouble(2, sum); - cursor.commitUpdates(); - return id; - } - } - } finally { - // Always clean up the cursor. - if (cursor != null) cursor.close(); - } - } - } - - /** - * Add an entry into the crashes table. - * @param values to insert - * @return the row ID of the modified entry - */ - private long insertCrash(ContentValues values) { - try { - int crashSize = values.getAsString(Checkin.Crashes.DATA).length(); - if (crashSize > CRASH_SIZE) { - // The crash is too big. Don't report it, but do log a stat. - Checkin.updateStats(getContext().getContentResolver(), - Checkin.Stats.Tag.CRASHES_TRUNCATED, 1, 0.0); - throw new IllegalArgumentException("Too big: " + crashSize); - } - - // Count the number of crashes reported, even if they roll over. - Checkin.updateStats(getContext().getContentResolver(), - Checkin.Stats.Tag.CRASHES_REPORTED, 1, 0.0); - - // Trim the crashes database, if needed. - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - db.execSQL("DELETE FROM " + - Checkin.Crashes.TABLE_NAME + " WHERE " + - Checkin.Crashes._ID + " IN (SELECT " + - Checkin.Crashes._ID + " FROM " + - Checkin.Crashes.TABLE_NAME + " ORDER BY " + - Checkin.Crashes._ID + " DESC LIMIT -1 OFFSET " + - (CRASH_LIMIT - 1) + ")"); - - return db.insert(Checkin.Crashes.TABLE_NAME, null, values); - } catch (Throwable t) { - // To avoid an infinite crash-reporting loop, swallow the error. - Log.e("CheckinProvider", "Error inserting crash: " + t); - return -1; - } - } - - // TODO: optimize bulkInsert, especially for stats? - - @Override - public int update(Uri uri, ContentValues values, - String where, String[] args) { - checkPermissions(uri); - if (uri.getPathSegments().size() == 2) { - if (where != null && where.length() > 0) { - throw new UnsupportedOperationException( - "WHERE clause not supported for update: " + uri); - } - where = "_id=" + ContentUris.parseId(uri); - args = null; - } else if (uri.getPathSegments().size() != 1) { - throw new IllegalArgumentException("Invalid update URI: " + uri); - } - - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - int count = db.update(uri.getPathSegments().get(0), values, where, args); - getContext().getContentResolver().notifyChange(uri, null); - return count; - } - - @Override - public int delete(Uri uri, String where, String[] args) { - checkPermissions(uri); - if (uri.getPathSegments().size() == 2) { - if (where != null && where.length() > 0) { - throw new UnsupportedOperationException( - "WHERE clause not supported for delete: " + uri); - } - where = "_id=" + ContentUris.parseId(uri); - args = null; - } else if (uri.getPathSegments().size() != 1) { - throw new IllegalArgumentException("Invalid delete URI: " + uri); - } - - SQLiteDatabase db = mOpenHelper.getWritableDatabase(); - int count = db.delete(uri.getPathSegments().get(0), where, args); - getContext().getContentResolver().notifyChange(uri, null); - return count; - } - - @Override - public String getType(Uri uri) { - if (uri.getPathSegments().size() == 1) { - return "vnd.android.cursor.dir/" + uri.getPathSegments().get(0); - } else if (uri.getPathSegments().size() == 2) { - return "vnd.android.cursor.item/" + uri.getPathSegments().get(0); - } else { - throw new IllegalArgumentException("Invalid URI: " + uri); - } - } - - /** - * Make sure the caller has permission to the database. - * @param uri the caller is requesting access to - * @throws SecurityException if the caller is forbidden. - */ - private void checkPermissions(Uri uri) { - if (uri.getPathSegments().size() < 1) { - throw new IllegalArgumentException("Invalid query URI: " + uri); - } - - String table = uri.getPathSegments().get(0); - if (table.equals(Checkin.Properties.TABLE_NAME) && - getContext().checkCallingOrSelfPermission(PROPERTIES_PERMISSION) != - PackageManager.PERMISSION_GRANTED) { - throw new SecurityException("Cannot access checkin properties"); - } - } -} diff --git a/core/java/android/server/checkin/FallbackCheckinService.java b/core/java/android/server/checkin/FallbackCheckinService.java deleted file mode 100644 index 65921af..0000000 --- a/core/java/android/server/checkin/FallbackCheckinService.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.server.checkin; - -import android.os.ICheckinService; -import android.os.RemoteException; -import android.os.IParentalControlCallback; -import com.google.android.net.ParentalControlState; - -/** - * @hide - */ -public final class FallbackCheckinService extends ICheckinService.Stub { - public FallbackCheckinService() { - } - - public void reportCrashSync(byte[] crashData) throws RemoteException { - } - - public void reportCrashAsync(byte[] crashData) throws RemoteException { - } - - public void masterClear() throws RemoteException { - } - - public void getParentalControlState(IParentalControlCallback p) throws RemoteException { - ParentalControlState state = new ParentalControlState(); - state.isEnabled = false; - p.onResult(state); - } - - public void getParentalControlState(IParentalControlCallback p, String requestingApp) - throws android.os.RemoteException { - } -} diff --git a/core/java/android/server/checkin/package.html b/core/java/android/server/checkin/package.html deleted file mode 100644 index 1c9bf9d..0000000 --- a/core/java/android/server/checkin/package.html +++ /dev/null @@ -1,5 +0,0 @@ -<html> -<body> - {@hide} -</body> -</html> diff --git a/core/java/android/server/search/SearchableInfo.java b/core/java/android/server/search/SearchableInfo.java index c8f395e..c18675e 100644 --- a/core/java/android/server/search/SearchableInfo.java +++ b/core/java/android/server/search/SearchableInfo.java @@ -86,6 +86,16 @@ public final class SearchableInfo implements Parcelable { private String mSuggestProviderPackage = null; private Context mCacheActivityContext = null; // use during setup only - don't hold memory! + // Flag values for Searchable_voiceSearchMode + private static int VOICE_SEARCH_SHOW_BUTTON = 1; + private static int VOICE_SEARCH_LAUNCH_WEB_SEARCH = 2; + private static int VOICE_SEARCH_LAUNCH_RECOGNIZER = 4; + private int mVoiceSearchMode = 0; + private int mVoiceLanguageModeId; // voiceLanguageModel + private int mVoicePromptTextId; // voicePromptText + private int mVoiceLanguageId; // voiceLanguage + private int mVoiceMaxResults; // voiceMaxResults + /** * Set the default searchable activity (when none is specified). */ @@ -420,7 +430,7 @@ public final class SearchableInfo implements Parcelable { mSearchInputType = a.getInt(com.android.internal.R.styleable.Searchable_inputType, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_SEARCH | - InputType.TYPE_TEXT_VARIATION_SEARCH_STRING); + InputType.TYPE_TEXT_VARIATION_NORMAL); setSearchModeFlags(); if (DBG_INHIBIT_SUGGESTIONS == 0) { @@ -435,6 +445,18 @@ public final class SearchableInfo implements Parcelable { mSuggestIntentData = a.getString( com.android.internal.R.styleable.Searchable_searchSuggestIntentData); } + mVoiceSearchMode = + a.getInt(com.android.internal.R.styleable.Searchable_voiceSearchMode, 0); + // TODO this didn't work - came back zero from YouTube + mVoiceLanguageModeId = + a.getResourceId(com.android.internal.R.styleable.Searchable_voiceLanguageModel, 0); + mVoicePromptTextId = + a.getResourceId(com.android.internal.R.styleable.Searchable_voicePromptText, 0); + mVoiceLanguageId = + a.getResourceId(com.android.internal.R.styleable.Searchable_voiceLanguage, 0); + mVoiceMaxResults = + a.getInt(com.android.internal.R.styleable.Searchable_voiceMaxResults, 0); + a.recycle(); // get package info for suggestions provider (if any) @@ -462,11 +484,6 @@ public final class SearchableInfo implements Parcelable { * Convert searchmode to flags. */ private void setSearchModeFlags() { - // decompose searchMode attribute - // TODO How do I reconcile these hardcoded values with the flag bits defined in - // in attrs.xml? e.g. android.R.id.filterMode = 0x010200a4 instead of just "1" - /* mFilterMode = (0 != (mSearchMode & 1)); */ - /* mQuickStart = (0 != (mSearchMode & 2)); */ mBadgeLabel = (0 != (mSearchMode & 4)); mBadgeIcon = (0 != (mSearchMode & 8)) && (mIconId != 0); mQueryRewriteFromData = (0 != (mSearchMode & 0x10)); @@ -654,6 +671,59 @@ public final class SearchableInfo implements Parcelable { } /** + * @return true if android:voiceSearchMode="showVoiceSearchButton" + */ + public boolean getVoiceSearchEnabled() { + return 0 != (mVoiceSearchMode & VOICE_SEARCH_SHOW_BUTTON); + } + + /** + * @return true if android:voiceSearchMode="launchWebSearch" + */ + public boolean getVoiceSearchLaunchWebSearch() { + return 0 != (mVoiceSearchMode & VOICE_SEARCH_LAUNCH_WEB_SEARCH); + } + + /** + * @return true if android:voiceSearchMode="launchRecognizer" + */ + public boolean getVoiceSearchLaunchRecognizer() { + return 0 != (mVoiceSearchMode & VOICE_SEARCH_LAUNCH_RECOGNIZER); + } + + /** + * @return the resource Id of the language model string, if specified in the searchable + * activity's metadata, or 0 if not specified. + */ + public int getVoiceLanguageModeId() { + return mVoiceLanguageModeId; + } + + /** + * @return the resource Id of the voice prompt text string, if specified in the searchable + * activity's metadata, or 0 if not specified. + */ + public int getVoicePromptTextId() { + return mVoicePromptTextId; + } + + /** + * @return the resource Id of the spoken langauge, if specified in the searchable + * activity's metadata, or 0 if not specified. + */ + public int getVoiceLanguageId() { + return mVoiceLanguageId; + } + + /** + * @return the max results count, if specified in the searchable + * activity's metadata, or 0 if not specified. + */ + public int getVoiceMaxResults() { + return mVoiceMaxResults; + } + + /** * Return the resource Id of replacement text for the "Search" button. * * @return Returns the resource Id, or 0 if not specified by this package. @@ -727,6 +797,12 @@ public final class SearchableInfo implements Parcelable { } mSuggestProviderPackage = in.readString(); + + mVoiceSearchMode = in.readInt(); + mVoiceLanguageModeId = in.readInt(); + mVoicePromptTextId = in.readInt(); + mVoiceLanguageId = in.readInt(); + mVoiceMaxResults = in.readInt(); } public int describeContents() { @@ -764,5 +840,11 @@ public final class SearchableInfo implements Parcelable { } dest.writeString(mSuggestProviderPackage); + + dest.writeInt(mVoiceSearchMode); + dest.writeInt(mVoiceLanguageModeId); + dest.writeInt(mVoicePromptTextId); + dest.writeInt(mVoiceLanguageId); + dest.writeInt(mVoiceMaxResults); } } diff --git a/core/java/android/speech/RecognizerIntent.java b/core/java/android/speech/RecognizerIntent.java index abbf8a7..987e763 100644 --- a/core/java/android/speech/RecognizerIntent.java +++ b/core/java/android/speech/RecognizerIntent.java @@ -22,8 +22,6 @@ import android.content.Intent; /** * Constants for supporting speech recognition through starting an {@link Intent} - * - * @hide {pending API council review} */ public class RecognizerIntent { private RecognizerIntent() { @@ -32,7 +30,8 @@ public class RecognizerIntent { /** * Starts an activity that will prompt the user for speech and sends it through a - * speech recognizer. + * speech recognizer. The results will be returned via activity results, or forwarded + * via a PendingIntent if one is provided. * * <p>Required extras: * <ul> @@ -41,9 +40,11 @@ public class RecognizerIntent { * * <p>Optional extras: * <ul> - * <li>{@link Intent#EXTRA_PROMPT} + * <li>{@link #EXTRA_PROMPT} * <li>{@link #EXTRA_LANGUAGE} * <li>{@link #EXTRA_MAX_RESULTS} + * <li>{@link #EXTRA_RESULTS_PENDINGINTENT} + * <li>{@link #EXTRA_RESULTS_PENDINGINTENT_BUNDLE} * </ul> * * <p> Result extras: @@ -57,6 +58,32 @@ public class RecognizerIntent { public static final String ACTION_RECOGNIZE_SPEECH = "android.speech.action.RECOGNIZE_SPEECH"; /** + * Starts an activity that will prompt the user for speech, sends it through a + * speech recognizer, and invokes and displays a web search result. + * + * <p>Required extras: + * <ul> + * <li>{@link #EXTRA_LANGUAGE_MODEL} + * </ul> + * + * <p>Optional extras: + * <ul> + * <li>{@link #EXTRA_PROMPT} + * <li>{@link #EXTRA_LANGUAGE} + * <li>{@link #EXTRA_MAX_RESULTS} + * </ul> + * + * <p> Result extras: + * <ul> + * <li>{@link #EXTRA_RESULTS} + * </ul> + * + * <p>NOTE: There may not be any applications installed to handle this action, so you should + * make sure to catch {@link ActivityNotFoundException}. + */ + public static final String ACTION_WEB_SEARCH = "android.speech.action.WEB_SEARCH"; + + /** * Informs the recognizer which speech model to prefer when performing * {@link #ACTION_RECOGNIZE_SPEECH}. The recognizer uses this * information to fine tune the results. This extra is required. Activities implementing @@ -65,27 +92,51 @@ public class RecognizerIntent { * @see #LANGUAGE_MODEL_FREE_FORM * @see #LANGUAGE_MODEL_WEB_SEARCH */ - public static final String EXTRA_LANGUAGE_MODEL = "language_model"; + public static final String EXTRA_LANGUAGE_MODEL = "android.speech.extra.LANGUAGE_MODEL"; - /** Free form speech recognition */ + /** + * Use a language model based on free-form speech recognition. This is a value to use for + * {@link #EXTRA_LANGUAGE_MODEL}. + * @see #EXTRA_LANGUAGE_MODEL + */ public static final String LANGUAGE_MODEL_FREE_FORM = "free_form"; - /** Use a language model based on web search terms */ + /** + * Use a language model based on web search terms. This is a value to use for + * {@link #EXTRA_LANGUAGE_MODEL}. + * @see #EXTRA_LANGUAGE_MODEL + */ public static final String LANGUAGE_MODEL_WEB_SEARCH = "web_search"; /** Optional text prompt to show to the user when asking them to speak. */ - public static final String EXTRA_PROMPT = "prompt"; + public static final String EXTRA_PROMPT = "android.speech.extra.PROMPT"; /** * Optional language override to inform the recognizer that it should expect speech in * a language different than the one set in the {@link java.util.Locale#getDefault()}. */ - public static final String EXTRA_LANGUAGE = "lang"; + public static final String EXTRA_LANGUAGE = "android.speech.extra.LANGUAGE"; /** * Optional limit on the maximum number of results to return. If omitted the recognizer * will choose how many results to return. Must be an integer. */ - public static final String EXTRA_MAX_RESULTS = "max_results"; + public static final String EXTRA_MAX_RESULTS = "android.speech.extra.MAX_RESULTS"; + + /** + * When the intent is {@link #ACTION_RECOGNIZE_SPEECH}, the speech input activity will + * return results to you via the activity results mechanism. Alternatively, if you use this + * extra to supply a PendingIntent, the results will be added to its bundle and the + * PendingIntent will be sent to its target. + */ + public static final String EXTRA_RESULTS_PENDINGINTENT = + "android.speech.extra.RESULTS_PENDINGINTENT"; + /** + * If you use {@link #EXTRA_RESULTS_PENDINGINTENT} to supply a forwarding intent, you can + * also use this extra to supply additional extras for the final intent. The search results + * will be added to this bundle, and the combined bundle will be sent to the target. + */ + public static final String EXTRA_RESULTS_PENDINGINTENT_BUNDLE = + "android.speech.extra.RESULTS_PENDINGINTENT_BUNDLE"; /** Result code returned when no matches are found for the given speech */ public static final int RESULT_NO_MATCH = Activity.RESULT_FIRST_USER; @@ -102,5 +153,5 @@ public class RecognizerIntent { * An ArrayList<String> of the potential results when performing * {@link #ACTION_RECOGNIZE_SPEECH}. Only present when {@link Activity#RESULT_OK} is returned. */ - public static final String EXTRA_RESULTS = "results"; + public static final String EXTRA_RESULTS = "android.speech.extra.RESULTS"; } diff --git a/core/java/android/text/Annotation.java b/core/java/android/text/Annotation.java index a3812a8..dbc290b 100644 --- a/core/java/android/text/Annotation.java +++ b/core/java/android/text/Annotation.java @@ -16,20 +16,40 @@ package android.text; +import android.os.Parcel; + /** * Annotations are simple key-value pairs that are preserved across * TextView save/restore cycles and can be used to keep application-specific * data that needs to be maintained for regions of text. */ -public class Annotation { - private String mKey; - private String mValue; +public class Annotation implements ParcelableSpan { + private final String mKey; + private final String mValue; public Annotation(String key, String value) { mKey = key; mValue = value; } + public Annotation(Parcel src) { + mKey = src.readString(); + mValue = src.readString(); + } + + public int getSpanTypeId() { + return TextUtils.ANNOTATION; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mKey); + dest.writeString(mValue); + } + public String getKey() { return mKey; } diff --git a/core/java/android/text/Html.java b/core/java/android/text/Html.java index 90f5e4c..8495714 100644 --- a/core/java/android/text/Html.java +++ b/core/java/android/text/Html.java @@ -700,7 +700,41 @@ class HtmlToSpannedConverter implements ContentHandler { } public void characters(char ch[], int start, int length) throws SAXException { - mSpannableStringBuilder.append(CharBuffer.wrap(ch, start, length)); + StringBuilder sb = new StringBuilder(); + + /* + * Ignore whitespace that immediately follows other whitespace; + * newlines count as spaces. + */ + + for (int i = 0; i < length; i++) { + char c = ch[i + start]; + + if (c == ' ' || c == '\n') { + char pred; + int len = sb.length(); + + if (len == 0) { + len = mSpannableStringBuilder.length(); + + if (len == 0) { + pred = '\n'; + } else { + pred = mSpannableStringBuilder.charAt(len - 1); + } + } else { + pred = sb.charAt(len - 1); + } + + if (pred != ' ' && pred != '\n') { + sb.append(' '); + } + } else { + sb.append(c); + } + } + + mSpannableStringBuilder.append(sb); } public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { diff --git a/core/java/android/text/InputType.java b/core/java/android/text/InputType.java index bd86834..a073cf4 100644 --- a/core/java/android/text/InputType.java +++ b/core/java/android/text/InputType.java @@ -116,14 +116,22 @@ public interface InputType { /** * Flag for {@link #TYPE_CLASS_TEXT}: multiple lines of text can be - * entered into the field. + * entered into the field. If this flag is not set, the text field + * will be constrained to a single line. */ public static final int TYPE_TEXT_FLAG_MULTI_LINE = 0x00020000; /** + * Flag for {@link #TYPE_CLASS_TEXT}: the regular text view associated + * with this should not be multi-line, but when a fullscreen input method + * is providing text it should use multiple lines if it can. + */ + public static final int TYPE_TEXT_FLAG_IME_MULTI_LINE = 0x00040000; + + /** * Flag for {@link #TYPE_CLASS_TEXT}: flags any text being used as a search string */ - public static final int TYPE_TEXT_FLAG_SEARCH = 0x00040000; + public static final int TYPE_TEXT_FLAG_SEARCH = 0x00080000; // ---------------------------------------------------------------------- @@ -149,30 +157,31 @@ public interface InputType { public static final int TYPE_TEXT_VARIATION_EMAIL_SUBJECT = 0x00000030; /** - * Variation of {@link #TYPE_CLASS_TEXT}: entering the content of - * an e-mail. + * Variation of {@link #TYPE_CLASS_TEXT}: entering a short, possibly informal + * message such as an instant message or a text message. */ - public static final int TYPE_TEXT_VARIATION_EMAIL_CONTENT = 0x00000040; + public static final int TYPE_TEXT_VARIATION_SHORT_MESSAGE = 0x00000040; /** + * Variation of {@link #TYPE_CLASS_TEXT}: entering the content of a long, possibly + * formal message such as the body of an e-mail. + */ + public static final int TYPE_TEXT_VARIATION_LONG_MESSAGE = 0x00000050; + + /** * Variation of {@link #TYPE_CLASS_TEXT}: entering the name of a person. */ - public static final int TYPE_TEXT_VARIATION_PERSON_NAME = 0x00000050; + public static final int TYPE_TEXT_VARIATION_PERSON_NAME = 0x00000060; /** * Variation of {@link #TYPE_CLASS_TEXT}: entering a postal mailing address. */ - public static final int TYPE_TEXT_VARIATION_POSTAL_ADDRESS = 0x00000060; + public static final int TYPE_TEXT_VARIATION_POSTAL_ADDRESS = 0x00000070; /** * Variation of {@link #TYPE_CLASS_TEXT}: entering a password. */ - public static final int TYPE_TEXT_VARIATION_PASSWORD = 0x00000070; - - /** - * Variation of {@link #TYPE_CLASS_TEXT}: entering a simple text search (e.g. web search) - */ - public static final int TYPE_TEXT_VARIATION_SEARCH_STRING = 0x00000080; + public static final int TYPE_TEXT_VARIATION_PASSWORD = 0x00000080; /** * Variation of {@link #TYPE_CLASS_TEXT}: entering text inside of a web form. diff --git a/core/java/android/text/NoCopySpan.java b/core/java/android/text/NoCopySpan.java new file mode 100644 index 0000000..0855c0b --- /dev/null +++ b/core/java/android/text/NoCopySpan.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.text; + +/** + * This interface should be added to a span object that should not be copied + * into a new Spenned when performing a slice or copy operation on the original + * Spanned it was placed in. + */ +public interface NoCopySpan { + /** + * Convenience equivalent for when you would just want a new Object() for + * a span but want it to be no-copy. Use this instead. + */ + public class Concrete implements NoCopySpan { + } +} diff --git a/core/java/android/text/ParcelableSpan.java b/core/java/android/text/ParcelableSpan.java new file mode 100644 index 0000000..224511a --- /dev/null +++ b/core/java/android/text/ParcelableSpan.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.text; + +import android.os.Parcelable; + +/** + * A special kind of Parcelable for objects that will serve as text spans. + * This can only be used by code in the framework; it is not intended for + * applications to implement their own Parcelable spans. + */ +public interface ParcelableSpan extends Parcelable { + /** + * Return a special type identifier for this span class. + */ + public abstract int getSpanTypeId(); +} diff --git a/core/java/android/text/Selection.java b/core/java/android/text/Selection.java index 44469ec..bb98bce 100644 --- a/core/java/android/text/Selection.java +++ b/core/java/android/text/Selection.java @@ -72,7 +72,7 @@ public class Selection { if (ostart != start || oend != stop) { text.setSpan(SELECTION_START, start, start, - Spanned.SPAN_POINT_POINT); + Spanned.SPAN_POINT_POINT|Spanned.SPAN_INTERMEDIATE); text.setSpan(SELECTION_END, stop, stop, Spanned.SPAN_POINT_POINT); } @@ -417,8 +417,8 @@ public class Selection { } } - private static final class START { }; - private static final class END { }; + private static final class START implements NoCopySpan { }; + private static final class END implements NoCopySpan { }; /* * Public constants diff --git a/core/java/android/text/SpanWatcher.java b/core/java/android/text/SpanWatcher.java index f99882a..01e82c8 100644 --- a/core/java/android/text/SpanWatcher.java +++ b/core/java/android/text/SpanWatcher.java @@ -21,7 +21,7 @@ package android.text; * will be called to notify it that other markup objects have been * added, changed, or removed. */ -public interface SpanWatcher { +public interface SpanWatcher extends NoCopySpan { /** * This method is called to notify you that the specified object * has been attached to the specified range of the text. diff --git a/core/java/android/text/SpannableStringBuilder.java b/core/java/android/text/SpannableStringBuilder.java index 223ce2f..caaafa1 100644 --- a/core/java/android/text/SpannableStringBuilder.java +++ b/core/java/android/text/SpannableStringBuilder.java @@ -70,6 +70,10 @@ implements CharSequence, GetChars, Spannable, Editable, Appendable, Object[] spans = sp.getSpans(start, end, Object.class); for (int i = 0; i < spans.length; i++) { + if (spans[i] instanceof NoCopySpan) { + continue; + } + int st = sp.getSpanStart(spans[i]) - start; int en = sp.getSpanEnd(spans[i]) - start; int fl = sp.getSpanFlags(spans[i]); diff --git a/core/java/android/text/Spanned.java b/core/java/android/text/Spanned.java index bd0a16b..154497d 100644 --- a/core/java/android/text/Spanned.java +++ b/core/java/android/text/Spanned.java @@ -106,6 +106,14 @@ extends CharSequence public static final int SPAN_COMPOSING = 0x100; /** + * This flag will be set for intermediate span changes, meaning there + * is guaranteed to be another change following it. Typically it is + * used for {@link Selection} which automatically uses this with the first + * offset it sets when updating the selection. + */ + public static final int SPAN_INTERMEDIATE = 0x200; + + /** * The bits numbered SPAN_USER_SHIFT and above are available * for callers to use to store scalar data associated with their * span object. diff --git a/core/java/android/text/StaticLayout.java b/core/java/android/text/StaticLayout.java index ceb9f4f..0fef40b 100644 --- a/core/java/android/text/StaticLayout.java +++ b/core/java/android/text/StaticLayout.java @@ -576,7 +576,28 @@ extends Layout if (fmbottom > fitbottom) fitbottom = fmbottom; - if (c == ' ' || c == '\t') { + /* + * From the Unicode Line Breaking Algorithm: + * (at least approximately) + * + * .,:; are class IS: breakpoints + * except when adjacent to digits + * / is class SY: a breakpoint + * except when followed by a digit. + * - is class HY: a breakpoint + * except when followed by a digit. + * + * Ideographs are class ID: breakpoints when adjacent. + */ + + if (c == ' ' || c == '\t' || + ((c == '.' || c == ',' || c == ':' || c == ';') && + (j - 1 < here || !Character.isDigit(chs[j - 1 - start])) && + (j + 1 >= next || !Character.isDigit(chs[j + 1 - start]))) || + ((c == '/' || c == '-') && + (j + 1 >= next || !Character.isDigit(chs[j + 1 - start]))) || + (c >= FIRST_CJK && isIdeographic(c) && + j + 1 < next && isIdeographic(chs[j + 1 - start]))) { okwidth = w; ok = j + 1; @@ -592,6 +613,11 @@ extends Layout } else if (breakOnlyAtSpaces) { if (ok != here) { // Log.e("text", "output ok " + here + " to " +ok); + + while (ok < next && chs[ok - start] == ' ') { + ok++; + } + v = out(source, here, ok, okascent, okdescent, oktop, okbottom, @@ -623,6 +649,11 @@ extends Layout } else { if (ok != here) { // Log.e("text", "output ok " + here + " to " +ok); + + while (ok < next && chs[ok - start] == ' ') { + ok++; + } + v = out(source, here, ok, okascent, okdescent, oktop, okbottom, @@ -739,6 +770,51 @@ extends Layout } } + private static final char FIRST_CJK = '\u2E80'; + /** + * Returns true if the specified character is one of those specified + * as being Ideographic (class ID) by the Unicode Line Breaking Algorithm + * (http://www.unicode.org/unicode/reports/tr14/), and is therefore OK + * to break between a pair of. + */ + private static final boolean isIdeographic(char c) { + if (c >= '\u2E80' && c <= '\u2FFF') { + return true; // CJK, KANGXI RADICALS, DESCRIPTION SYMBOLS + } + if (c == '\u3000') { + return true; // IDEOGRAPHIC SPACE + } + if (c >= '\u3040' && c <= '\u309F') { + return true; // Hiragana (except small characters) + } + if (c >= '\u30A0' && c <= '\u30FF') { + return true; // Katakana (except small characters) + } + if (c >= '\u3400' && c <= '\u4DB5') { + return true; // CJK UNIFIED IDEOGRAPHS EXTENSION A + } + if (c >= '\u4E00' && c <= '\u9FBB') { + return true; // CJK UNIFIED IDEOGRAPHS + } + if (c >= '\uF900' && c <= '\uFAD9') { + return true; // CJK COMPATIBILITY IDEOGRAPHS + } + if (c >= '\uA000' && c <= '\uA48F') { + return true; // YI SYLLABLES + } + if (c >= '\uA490' && c <= '\uA4CF') { + return true; // YI RADICALS + } + if (c >= '\uFE62' && c <= '\uFE66') { + return true; // SMALL PLUS SIGN to SMALL EQUALS SIGN + } + if (c >= '\uFF10' && c <= '\uFF19') { + return true; // WIDE DIGITS + } + + return false; + } + /* private static void dump(byte[] data, int count, String label) { if (false) { diff --git a/core/java/android/text/TextUtils.java b/core/java/android/text/TextUtils.java index 405d934..5b4c380 100644 --- a/core/java/android/text/TextUtils.java +++ b/core/java/android/text/TextUtils.java @@ -236,6 +236,13 @@ public class TextUtils { return match; } + /** + * Create a new String object containing the given range of characters + * from the source string. This is different than simply calling + * {@link CharSequence#subSequence(int, int) CharSequence.subSequence} + * in that it does not preserve any style runs in the source sequence, + * allowing a more efficient implementation. + */ public static String substring(CharSequence source, int start, int end) { if (source instanceof String) return ((String) source).substring(start, end); @@ -447,13 +454,26 @@ public class TextUtils { /** * Returns true if a and b are equal, including if they are both null. - * + * <p><i>Note: In platform versions 1.1 and earlier, this method only worked well if + * both the arguments were instances of String.</i></p> * @param a first CharSequence to check * @param b second CharSequence to check * @return true if a and b are equal */ public static boolean equals(CharSequence a, CharSequence b) { - return a == b || (a != null && a.equals(b)); + if (a == b) return true; + int length; + if (a != null && b != null && (length = a.length()) == b.length()) { + if (a instanceof String && b instanceof String) { + return a.equals(b); + } else { + for (int i = 0; i < length; i++) { + if (a.charAt(i) != b.charAt(i)) return false; + } + return true; + } + } + return false; } // XXX currently this only reverses chars, not spans @@ -510,24 +530,42 @@ public class TextUtils { private int mEnd; } - private static final int ALIGNMENT_SPAN = 1; - private static final int FOREGROUND_COLOR_SPAN = 2; - private static final int RELATIVE_SIZE_SPAN = 3; - private static final int SCALE_X_SPAN = 4; - private static final int STRIKETHROUGH_SPAN = 5; - private static final int UNDERLINE_SPAN = 6; - private static final int STYLE_SPAN = 7; - private static final int BULLET_SPAN = 8; - private static final int QUOTE_SPAN = 9; - private static final int LEADING_MARGIN_SPAN = 10; - private static final int URL_SPAN = 11; - private static final int BACKGROUND_COLOR_SPAN = 12; - private static final int TYPEFACE_SPAN = 13; - private static final int SUPERSCRIPT_SPAN = 14; - private static final int SUBSCRIPT_SPAN = 15; - private static final int ABSOLUTE_SIZE_SPAN = 16; - private static final int TEXT_APPEARANCE_SPAN = 17; - private static final int ANNOTATION = 18; + /** @hide */ + public static final int ALIGNMENT_SPAN = 1; + /** @hide */ + public static final int FOREGROUND_COLOR_SPAN = 2; + /** @hide */ + public static final int RELATIVE_SIZE_SPAN = 3; + /** @hide */ + public static final int SCALE_X_SPAN = 4; + /** @hide */ + public static final int STRIKETHROUGH_SPAN = 5; + /** @hide */ + public static final int UNDERLINE_SPAN = 6; + /** @hide */ + public static final int STYLE_SPAN = 7; + /** @hide */ + public static final int BULLET_SPAN = 8; + /** @hide */ + public static final int QUOTE_SPAN = 9; + /** @hide */ + public static final int LEADING_MARGIN_SPAN = 10; + /** @hide */ + public static final int URL_SPAN = 11; + /** @hide */ + public static final int BACKGROUND_COLOR_SPAN = 12; + /** @hide */ + public static final int TYPEFACE_SPAN = 13; + /** @hide */ + public static final int SUPERSCRIPT_SPAN = 14; + /** @hide */ + public static final int SUBSCRIPT_SPAN = 15; + /** @hide */ + public static final int ABSOLUTE_SIZE_SPAN = 16; + /** @hide */ + public static final int TEXT_APPEARANCE_SPAN = 17; + /** @hide */ + public static final int ANNOTATION = 18; /** * Flatten a CharSequence and whatever styles can be copied across processes @@ -555,136 +593,10 @@ public class TextUtils { prop = ((CharacterStyle) prop).getUnderlying(); } - if (prop instanceof AlignmentSpan) { - p.writeInt(ALIGNMENT_SPAN); - p.writeString(((AlignmentSpan) prop).getAlignment().name()); - writeWhere(p, sp, o); - } - - if (prop instanceof ForegroundColorSpan) { - p.writeInt(FOREGROUND_COLOR_SPAN); - p.writeInt(((ForegroundColorSpan) prop).getForegroundColor()); - writeWhere(p, sp, o); - } - - if (prop instanceof RelativeSizeSpan) { - p.writeInt(RELATIVE_SIZE_SPAN); - p.writeFloat(((RelativeSizeSpan) prop).getSizeChange()); - writeWhere(p, sp, o); - } - - if (prop instanceof ScaleXSpan) { - p.writeInt(SCALE_X_SPAN); - p.writeFloat(((ScaleXSpan) prop).getScaleX()); - writeWhere(p, sp, o); - } - - if (prop instanceof StrikethroughSpan) { - p.writeInt(STRIKETHROUGH_SPAN); - writeWhere(p, sp, o); - } - - if (prop instanceof UnderlineSpan) { - p.writeInt(UNDERLINE_SPAN); - writeWhere(p, sp, o); - } - - if (prop instanceof StyleSpan) { - p.writeInt(STYLE_SPAN); - p.writeInt(((StyleSpan) prop).getStyle()); - writeWhere(p, sp, o); - } - - if (prop instanceof LeadingMarginSpan) { - if (prop instanceof BulletSpan) { - p.writeInt(BULLET_SPAN); - writeWhere(p, sp, o); - } else if (prop instanceof QuoteSpan) { - p.writeInt(QUOTE_SPAN); - p.writeInt(((QuoteSpan) prop).getColor()); - writeWhere(p, sp, o); - } else { - p.writeInt(LEADING_MARGIN_SPAN); - p.writeInt(((LeadingMarginSpan) prop). - getLeadingMargin(true)); - p.writeInt(((LeadingMarginSpan) prop). - getLeadingMargin(false)); - writeWhere(p, sp, o); - } - } - - if (prop instanceof URLSpan) { - p.writeInt(URL_SPAN); - p.writeString(((URLSpan) prop).getURL()); - writeWhere(p, sp, o); - } - - if (prop instanceof BackgroundColorSpan) { - p.writeInt(BACKGROUND_COLOR_SPAN); - p.writeInt(((BackgroundColorSpan) prop).getBackgroundColor()); - writeWhere(p, sp, o); - } - - if (prop instanceof TypefaceSpan) { - p.writeInt(TYPEFACE_SPAN); - p.writeString(((TypefaceSpan) prop).getFamily()); - writeWhere(p, sp, o); - } - - if (prop instanceof SuperscriptSpan) { - p.writeInt(SUPERSCRIPT_SPAN); - writeWhere(p, sp, o); - } - - if (prop instanceof SubscriptSpan) { - p.writeInt(SUBSCRIPT_SPAN); - writeWhere(p, sp, o); - } - - if (prop instanceof AbsoluteSizeSpan) { - p.writeInt(ABSOLUTE_SIZE_SPAN); - p.writeInt(((AbsoluteSizeSpan) prop).getSize()); - writeWhere(p, sp, o); - } - - if (prop instanceof TextAppearanceSpan) { - TextAppearanceSpan tas = (TextAppearanceSpan) prop; - p.writeInt(TEXT_APPEARANCE_SPAN); - - String tf = tas.getFamily(); - if (tf != null) { - p.writeInt(1); - p.writeString(tf); - } else { - p.writeInt(0); - } - - p.writeInt(tas.getTextStyle()); - p.writeInt(tas.getTextSize()); - - ColorStateList csl = tas.getTextColor(); - if (csl == null) { - p.writeInt(0); - } else { - p.writeInt(1); - csl.writeToParcel(p, parcelableFlags); - } - - csl = tas.getLinkTextColor(); - if (csl == null) { - p.writeInt(0); - } else { - p.writeInt(1); - csl.writeToParcel(p, parcelableFlags); - } - - writeWhere(p, sp, o); - } - - if (prop instanceof Annotation) { - p.writeInt(ANNOTATION); - p.writeString(((Annotation) prop).getKey()); - p.writeString(((Annotation) prop).getValue()); + if (prop instanceof ParcelableSpan) { + ParcelableSpan ps = (ParcelableSpan)prop; + p.writeInt(ps.getSpanTypeId()); + ps.writeToParcel(p, parcelableFlags); writeWhere(p, sp, o); } } @@ -707,8 +619,7 @@ public class TextUtils { } public static final Parcelable.Creator<CharSequence> CHAR_SEQUENCE_CREATOR - = new Parcelable.Creator<CharSequence>() - { + = new Parcelable.Creator<CharSequence>() { /** * Read and return a new CharSequence, possibly with styles, * from the parcel. @@ -729,89 +640,75 @@ public class TextUtils { switch (kind) { case ALIGNMENT_SPAN: - readSpan(p, sp, new AlignmentSpan.Standard( - Layout.Alignment.valueOf(p.readString()))); + readSpan(p, sp, new AlignmentSpan.Standard(p)); break; case FOREGROUND_COLOR_SPAN: - readSpan(p, sp, new ForegroundColorSpan(p.readInt())); + readSpan(p, sp, new ForegroundColorSpan(p)); break; case RELATIVE_SIZE_SPAN: - readSpan(p, sp, new RelativeSizeSpan(p.readFloat())); + readSpan(p, sp, new RelativeSizeSpan(p)); break; case SCALE_X_SPAN: - readSpan(p, sp, new ScaleXSpan(p.readFloat())); + readSpan(p, sp, new ScaleXSpan(p)); break; case STRIKETHROUGH_SPAN: - readSpan(p, sp, new StrikethroughSpan()); + readSpan(p, sp, new StrikethroughSpan(p)); break; case UNDERLINE_SPAN: - readSpan(p, sp, new UnderlineSpan()); + readSpan(p, sp, new UnderlineSpan(p)); break; case STYLE_SPAN: - readSpan(p, sp, new StyleSpan(p.readInt())); + readSpan(p, sp, new StyleSpan(p)); break; case BULLET_SPAN: - readSpan(p, sp, new BulletSpan()); + readSpan(p, sp, new BulletSpan(p)); break; case QUOTE_SPAN: - readSpan(p, sp, new QuoteSpan(p.readInt())); + readSpan(p, sp, new QuoteSpan(p)); break; case LEADING_MARGIN_SPAN: - readSpan(p, sp, new LeadingMarginSpan.Standard(p.readInt(), - p.readInt())); + readSpan(p, sp, new LeadingMarginSpan.Standard(p)); break; case URL_SPAN: - readSpan(p, sp, new URLSpan(p.readString())); + readSpan(p, sp, new URLSpan(p)); break; case BACKGROUND_COLOR_SPAN: - readSpan(p, sp, new BackgroundColorSpan(p.readInt())); + readSpan(p, sp, new BackgroundColorSpan(p)); break; case TYPEFACE_SPAN: - readSpan(p, sp, new TypefaceSpan(p.readString())); + readSpan(p, sp, new TypefaceSpan(p)); break; case SUPERSCRIPT_SPAN: - readSpan(p, sp, new SuperscriptSpan()); + readSpan(p, sp, new SuperscriptSpan(p)); break; case SUBSCRIPT_SPAN: - readSpan(p, sp, new SubscriptSpan()); + readSpan(p, sp, new SubscriptSpan(p)); break; case ABSOLUTE_SIZE_SPAN: - readSpan(p, sp, new AbsoluteSizeSpan(p.readInt())); + readSpan(p, sp, new AbsoluteSizeSpan(p)); break; case TEXT_APPEARANCE_SPAN: - readSpan(p, sp, new TextAppearanceSpan( - p.readInt() != 0 - ? p.readString() - : null, - p.readInt(), // style - p.readInt(), // size - p.readInt() != 0 - ? ColorStateList.CREATOR.createFromParcel(p) - : null, - p.readInt() != 0 - ? ColorStateList.CREATOR.createFromParcel(p) - : null)); + readSpan(p, sp, new TextAppearanceSpan(p)); break; case ANNOTATION: - readSpan(p, sp, - new Annotation(p.readString(), p.readString())); + readSpan(p, sp, new Annotation(p)); break; default: diff --git a/core/java/android/text/TextWatcher.java b/core/java/android/text/TextWatcher.java index 7456b28..bad09f2 100644 --- a/core/java/android/text/TextWatcher.java +++ b/core/java/android/text/TextWatcher.java @@ -20,7 +20,7 @@ package android.text; * When an object of a type is attached to an Editable, its methods will * be called when the text is changed. */ -public interface TextWatcher { +public interface TextWatcher extends NoCopySpan { /** * This method is called to notify you that, within <code>s</code>, * the <code>count</code> characters beginning at <code>start</code> diff --git a/core/java/android/text/format/DateFormat.java b/core/java/android/text/format/DateFormat.java index 73adedf..0dc96c3 100644 --- a/core/java/android/text/format/DateFormat.java +++ b/core/java/android/text/format/DateFormat.java @@ -27,6 +27,7 @@ import com.android.internal.R; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; +import java.util.Locale; import java.util.TimeZone; import java.text.SimpleDateFormat; @@ -188,6 +189,12 @@ public class DateFormat { */ public static final char YEAR = 'y'; + + private static final Object sLocaleLock = new Object(); + private static Locale sIs24HourLocale; + private static boolean sIs24Hour; + + /** * Returns true if user preference is set to 24-hour format. * @param context the context to use for the content resolver @@ -198,20 +205,34 @@ public class DateFormat { Settings.System.TIME_12_24); if (value == null) { + Locale locale = context.getResources().getConfiguration().locale; + + synchronized (sLocaleLock) { + if (sIs24HourLocale != null && sIs24HourLocale.equals(locale)) { + return sIs24Hour; + } + } + java.text.DateFormat natural = java.text.DateFormat.getTimeInstance( - java.text.DateFormat.LONG, - context.getResources().getConfiguration().locale); + java.text.DateFormat.LONG, locale); if (natural instanceof SimpleDateFormat) { SimpleDateFormat sdf = (SimpleDateFormat) natural; String pattern = sdf.toPattern(); if (pattern.indexOf('H') >= 0) { - return true; + value = "24"; } else { - return false; + value = "12"; } + } else { + value = "12"; + } + + synchronized (sLocaleLock) { + sIs24HourLocale = locale; + sIs24Hour = !value.equals("12"); } } diff --git a/core/java/android/text/method/ArrowKeyMovementMethod.java b/core/java/android/text/method/ArrowKeyMovementMethod.java index 7457439..a559b9d 100644 --- a/core/java/android/text/method/ArrowKeyMovementMethod.java +++ b/core/java/android/text/method/ArrowKeyMovementMethod.java @@ -131,6 +131,16 @@ implements MovementMethod } public boolean onKeyDown(TextView widget, Spannable buffer, int keyCode, KeyEvent event) { + if (executeDown(widget, buffer, keyCode)) { + MetaKeyKeyListener.adjustMetaAfterKeypress(buffer); + MetaKeyKeyListener.resetLockedMeta(buffer); + return true; + } + + return false; + } + + private boolean executeDown(TextView widget, Spannable buffer, int keyCode) { boolean handled = false; switch (keyCode) { @@ -170,6 +180,26 @@ implements MovementMethod return false; } + public boolean onKeyOther(TextView view, Spannable text, KeyEvent event) { + int code = event.getKeyCode(); + if (code != KeyEvent.KEYCODE_UNKNOWN + && event.getAction() == KeyEvent.ACTION_MULTIPLE) { + int repeat = event.getRepeatCount(); + boolean first = true; + boolean handled = false; + while ((--repeat) > 0) { + if (first && executeDown(view, text, code)) { + handled = true; + MetaKeyKeyListener.adjustMetaAfterKeypress(text); + MetaKeyKeyListener.resetLockedMeta(text); + } + first = false; + } + return handled; + } + return false; + } + public boolean onTrackballEvent(TextView widget, Spannable text, MotionEvent event) { return false; diff --git a/core/java/android/text/method/BaseKeyListener.java b/core/java/android/text/method/BaseKeyListener.java index a875368..6df6a3a 100644 --- a/core/java/android/text/method/BaseKeyListener.java +++ b/core/java/android/text/method/BaseKeyListener.java @@ -18,7 +18,6 @@ package android.text.method; import android.view.KeyEvent; import android.view.View; -import android.text.InputType; import android.text.*; import android.text.method.TextKeyListener.Capitalize; import android.widget.TextView; @@ -26,7 +25,7 @@ import android.widget.TextView; public abstract class BaseKeyListener extends MetaKeyKeyListener implements KeyListener { - /* package */ static final Object OLD_SEL_START = new Object(); + /* package */ static final Object OLD_SEL_START = new NoCopySpan.Concrete(); /** * Performs the action that happens when you press the DEL key in @@ -127,5 +126,35 @@ implements KeyListener { return super.onKeyDown(view, content, keyCode, event); } + + /** + * Base implementation handles ACTION_MULTIPLE KEYCODE_UNKNOWN by inserting + * the event's text into the content. + */ + public boolean onKeyOther(View view, Editable content, KeyEvent event) { + if (event.getAction() != KeyEvent.ACTION_MULTIPLE + || event.getKeyCode() != KeyEvent.KEYCODE_UNKNOWN) { + // Not something we are interested in. + return false; + } + + int selStart, selEnd; + + { + int a = Selection.getSelectionStart(content); + int b = Selection.getSelectionEnd(content); + + selStart = Math.min(a, b); + selEnd = Math.max(a, b); + } + + CharSequence text = event.getCharacters(); + if (text == null) { + return false; + } + + content.replace(selStart, selEnd, text); + return true; + } } diff --git a/core/java/android/text/method/KeyListener.java b/core/java/android/text/method/KeyListener.java index 4ae6191..8594852 100644 --- a/core/java/android/text/method/KeyListener.java +++ b/core/java/android/text/method/KeyListener.java @@ -66,6 +66,13 @@ public interface KeyListener { int keyCode, KeyEvent event); /** + * If the key listener wants to other kinds of key events, return true, + * otherwise return false and the caller (i.e. the widget host) + * will handle the key. + */ + public boolean onKeyOther(View view, Editable text, KeyEvent event); + + /** * Remove the given shift states from the edited text. */ public void clearMetaKeyState(View view, Editable content, int states); diff --git a/core/java/android/text/method/LinkMovementMethod.java b/core/java/android/text/method/LinkMovementMethod.java index 92ac531..22e9cc6 100644 --- a/core/java/android/text/method/LinkMovementMethod.java +++ b/core/java/android/text/method/LinkMovementMethod.java @@ -252,5 +252,5 @@ extends ScrollingMovementMethod } private static LinkMovementMethod sInstance; - private static Object FROM_BELOW = new Object(); + private static Object FROM_BELOW = new NoCopySpan.Concrete(); } diff --git a/core/java/android/text/method/MetaKeyKeyListener.java b/core/java/android/text/method/MetaKeyKeyListener.java index d5a473b..d89fbec 100644 --- a/core/java/android/text/method/MetaKeyKeyListener.java +++ b/core/java/android/text/method/MetaKeyKeyListener.java @@ -71,10 +71,10 @@ public abstract class MetaKeyKeyListener { | META_SYM_LOCKED | META_SYM_USED | META_SYM_PRESSED | META_SYM_RELEASED; - private static final Object CAP = new Object(); - private static final Object ALT = new Object(); - private static final Object SYM = new Object(); - private static final Object SELECTING = new Object(); + private static final Object CAP = new NoCopySpan.Concrete(); + private static final Object ALT = new NoCopySpan.Concrete(); + private static final Object SYM = new NoCopySpan.Concrete(); + private static final Object SELECTING = new NoCopySpan.Concrete(); /** * Resets all meta state to inactive. @@ -283,6 +283,10 @@ public abstract class MetaKeyKeyListener { } public void clearMetaKeyState(View view, Editable content, int states) { + clearMetaKeyState(content, states); + } + + public static void clearMetaKeyState(Editable content, int states) { if ((states&META_SHIFT_ON) != 0) resetLock(content, CAP); if ((states&META_ALT_ON) != 0) resetLock(content, ALT); if ((states&META_SYM_ON) != 0) resetLock(content, SYM); diff --git a/core/java/android/text/method/MovementMethod.java b/core/java/android/text/method/MovementMethod.java index 9e37e59..29f67a1 100644 --- a/core/java/android/text/method/MovementMethod.java +++ b/core/java/android/text/method/MovementMethod.java @@ -26,6 +26,14 @@ public interface MovementMethod public void initialize(TextView widget, Spannable text); public boolean onKeyDown(TextView widget, Spannable text, int keyCode, KeyEvent event); public boolean onKeyUp(TextView widget, Spannable text, int keyCode, KeyEvent event); + + /** + * If the key listener wants to other kinds of key events, return true, + * otherwise return false and the caller (i.e. the widget host) + * will handle the key. + */ + public boolean onKeyOther(TextView view, Spannable text, KeyEvent event); + public void onTakeFocus(TextView widget, Spannable text, int direction); public boolean onTrackballEvent(TextView widget, Spannable text, MotionEvent event); diff --git a/core/java/android/text/method/NumberKeyListener.java b/core/java/android/text/method/NumberKeyListener.java index 348b658..e500fae 100644 --- a/core/java/android/text/method/NumberKeyListener.java +++ b/core/java/android/text/method/NumberKeyListener.java @@ -24,7 +24,6 @@ import android.text.Selection; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; -import android.util.SparseIntArray; /** * For numeric text entry diff --git a/core/java/android/text/method/PasswordTransformationMethod.java b/core/java/android/text/method/PasswordTransformationMethod.java index edaa836..85adabd 100644 --- a/core/java/android/text/method/PasswordTransformationMethod.java +++ b/core/java/android/text/method/PasswordTransformationMethod.java @@ -22,6 +22,7 @@ import android.graphics.Rect; import android.view.View; import android.text.Editable; import android.text.GetChars; +import android.text.NoCopySpan; import android.text.TextUtils; import android.text.TextWatcher; import android.text.Selection; @@ -249,7 +250,8 @@ implements TransformationMethod, TextWatcher * Used to stash a reference back to the View in the Editable so we * can use it to check the settings. */ - private static class ViewReference extends WeakReference<View> { + private static class ViewReference extends WeakReference<View> + implements NoCopySpan { public ViewReference(View v) { super(v); } diff --git a/core/java/android/text/method/QwertyKeyListener.java b/core/java/android/text/method/QwertyKeyListener.java index 863b2e2..0b39517 100644 --- a/core/java/android/text/method/QwertyKeyListener.java +++ b/core/java/android/text/method/QwertyKeyListener.java @@ -16,18 +16,12 @@ package android.text.method; -import android.os.Message; -import android.os.Handler; import android.text.*; import android.text.method.TextKeyListener.Capitalize; import android.util.SparseArray; -import android.util.SparseIntArray; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; -import android.widget.TextView; - -import java.util.HashMap; /** * This is the standard key listener for alphabetic input on qwerty @@ -442,7 +436,7 @@ public class QwertyKeyListener extends BaseKeyListener { return Character.toUpperCase(src.charAt(0)) + src.substring(1); } - /* package */ static class Replaced + /* package */ static class Replaced implements NoCopySpan { public Replaced(char[] text) { mText = text; diff --git a/core/java/android/text/method/ScrollingMovementMethod.java b/core/java/android/text/method/ScrollingMovementMethod.java index db470be..563ceed 100644 --- a/core/java/android/text/method/ScrollingMovementMethod.java +++ b/core/java/android/text/method/ScrollingMovementMethod.java @@ -144,6 +144,10 @@ implements MovementMethod } public boolean onKeyDown(TextView widget, Spannable buffer, int keyCode, KeyEvent event) { + return executeDown(widget, buffer, keyCode); + } + + private boolean executeDown(TextView widget, Spannable buffer, int keyCode) { boolean handled = false; switch (keyCode) { @@ -171,6 +175,26 @@ implements MovementMethod return false; } + public boolean onKeyOther(TextView view, Spannable text, KeyEvent event) { + int code = event.getKeyCode(); + if (code != KeyEvent.KEYCODE_UNKNOWN + && event.getAction() == KeyEvent.ACTION_MULTIPLE) { + int repeat = event.getRepeatCount(); + boolean first = true; + boolean handled = false; + while ((--repeat) > 0) { + if (first && executeDown(view, text, code)) { + handled = true; + MetaKeyKeyListener.adjustMetaAfterKeypress(text); + MetaKeyKeyListener.resetLockedMeta(text); + } + first = false; + } + return handled; + } + return false; + } + public boolean onTrackballEvent(TextView widget, Spannable text, MotionEvent event) { return false; diff --git a/core/java/android/text/method/SingleLineTransformationMethod.java b/core/java/android/text/method/SingleLineTransformationMethod.java index a4fcf15..6a05fe4 100644 --- a/core/java/android/text/method/SingleLineTransformationMethod.java +++ b/core/java/android/text/method/SingleLineTransformationMethod.java @@ -27,22 +27,24 @@ import android.view.View; /** * This transformation method causes any newline characters (\n) to be - * displayed as spaces instead of causing line breaks. + * displayed as spaces instead of causing line breaks, and causes + * carriage return characters (\r) to have no appearance. */ public class SingleLineTransformationMethod extends ReplacementTransformationMethod { - private static char[] ORIGINAL = new char[] { '\n' }; - private static char[] REPLACEMENT = new char[] { ' ' }; + private static char[] ORIGINAL = new char[] { '\n', '\r' }; + private static char[] REPLACEMENT = new char[] { ' ', '\uFEFF' }; /** - * The character to be replaced is \n. + * The characters to be replaced are \n and \r. */ protected char[] getOriginal() { return ORIGINAL; } /** - * The character \n is replaced with is space. + * The character \n is replaced with is space; + * the character \r is replaced with is FEFF (zero width space). */ protected char[] getReplacement() { return REPLACEMENT; diff --git a/core/java/android/text/method/TextKeyListener.java b/core/java/android/text/method/TextKeyListener.java index b1c380a..5be2a48 100644 --- a/core/java/android/text/method/TextKeyListener.java +++ b/core/java/android/text/method/TextKeyListener.java @@ -38,10 +38,10 @@ public class TextKeyListener extends BaseKeyListener implements SpanWatcher { private static TextKeyListener[] sInstance = new TextKeyListener[Capitalize.values().length * 2]; - /* package */ static final Object ACTIVE = new Object(); - /* package */ static final Object CAPPED = new Object(); - /* package */ static final Object INHIBIT_REPLACEMENT = new Object(); - /* package */ static final Object LAST_TYPED = new Object(); + /* package */ static final Object ACTIVE = new NoCopySpan.Concrete(); + /* package */ static final Object CAPPED = new NoCopySpan.Concrete(); + /* package */ static final Object INHIBIT_REPLACEMENT = new NoCopySpan.Concrete(); + /* package */ static final Object LAST_TYPED = new NoCopySpan.Concrete(); private Capitalize mAutoCap; private boolean mAutoText; @@ -140,6 +140,13 @@ public class TextKeyListener extends BaseKeyListener implements SpanWatcher { return im.onKeyUp(view, content, keyCode, event); } + @Override + public boolean onKeyOther(View view, Editable content, KeyEvent event) { + KeyListener im = getKeyListener(event); + + return im.onKeyOther(view, content, event); + } + /** * Clear all the input state (autotext, autocap, multitap, undo) * from the specified Editable, going beyond Editable.clear(), which @@ -205,6 +212,10 @@ public class TextKeyListener extends BaseKeyListener implements SpanWatcher { return false; } + public boolean onKeyOther(View view, Editable content, KeyEvent event) { + return false; + } + public void clearMetaKeyState(View view, Editable content, int states) { } diff --git a/core/java/android/text/method/Touch.java b/core/java/android/text/method/Touch.java index 8b097c5..65036ad 100644 --- a/core/java/android/text/method/Touch.java +++ b/core/java/android/text/method/Touch.java @@ -17,6 +17,7 @@ package android.text.method; import android.text.Layout; +import android.text.NoCopySpan; import android.text.Layout.Alignment; import android.text.Spannable; import android.view.MotionEvent; @@ -103,7 +104,7 @@ public class Touch { if (ds.length > 0) { if (ds[0].mFarEnough == false) { - int slop = ViewConfiguration.getTouchSlop(); + int slop = ViewConfiguration.get(widget.getContext()).getScaledTouchSlop(); if (Math.abs(event.getX() - ds[0].mX) >= slop || Math.abs(event.getY() - ds[0].mY) >= slop) { @@ -141,7 +142,7 @@ public class Touch { return false; } - private static class DragState { + private static class DragState implements NoCopySpan { public float mX; public float mY; public boolean mFarEnough; diff --git a/core/java/android/text/style/AbsoluteSizeSpan.java b/core/java/android/text/style/AbsoluteSizeSpan.java index 8f6ed5a..484f8ce 100644 --- a/core/java/android/text/style/AbsoluteSizeSpan.java +++ b/core/java/android/text/style/AbsoluteSizeSpan.java @@ -16,17 +16,35 @@ package android.text.style; -import android.graphics.Paint; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class AbsoluteSizeSpan extends MetricAffectingSpan { +public class AbsoluteSizeSpan extends MetricAffectingSpan implements ParcelableSpan { - private int mSize; + private final int mSize; public AbsoluteSizeSpan(int size) { mSize = size; } + public AbsoluteSizeSpan(Parcel src) { + mSize = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.ABSOLUTE_SIZE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mSize); + } + public int getSize() { return mSize; } diff --git a/core/java/android/text/style/AlignmentSpan.java b/core/java/android/text/style/AlignmentSpan.java index d51edcc..b8a37da 100644 --- a/core/java/android/text/style/AlignmentSpan.java +++ b/core/java/android/text/style/AlignmentSpan.java @@ -16,24 +16,40 @@ package android.text.style; +import android.os.Parcel; import android.text.Layout; +import android.text.ParcelableSpan; +import android.text.TextUtils; -public interface AlignmentSpan -extends ParagraphStyle -{ +public interface AlignmentSpan extends ParagraphStyle { public Layout.Alignment getAlignment(); public static class Standard - implements AlignmentSpan - { + implements AlignmentSpan, ParcelableSpan { public Standard(Layout.Alignment align) { mAlignment = align; } + public Standard(Parcel src) { + mAlignment = Layout.Alignment.valueOf(src.readString()); + } + + public int getSpanTypeId() { + return TextUtils.ALIGNMENT_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mAlignment.name()); + } + public Layout.Alignment getAlignment() { return mAlignment; } - private Layout.Alignment mAlignment; + private final Layout.Alignment mAlignment; } } diff --git a/core/java/android/text/style/BackgroundColorSpan.java b/core/java/android/text/style/BackgroundColorSpan.java index 27eda69..580a369 100644 --- a/core/java/android/text/style/BackgroundColorSpan.java +++ b/core/java/android/text/style/BackgroundColorSpan.java @@ -16,16 +16,36 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class BackgroundColorSpan extends CharacterStyle implements UpdateAppearance { +public class BackgroundColorSpan extends CharacterStyle + implements UpdateAppearance, ParcelableSpan { - private int mColor; + private final int mColor; public BackgroundColorSpan(int color) { mColor = color; } + public BackgroundColorSpan(Parcel src) { + mColor = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.BACKGROUND_COLOR_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mColor); + } + public int getBackgroundColor() { return mColor; } diff --git a/core/java/android/text/style/BulletSpan.java b/core/java/android/text/style/BulletSpan.java index 70c4d33..655bd81 100644 --- a/core/java/android/text/style/BulletSpan.java +++ b/core/java/android/text/style/BulletSpan.java @@ -18,17 +18,30 @@ package android.text.style; import android.graphics.Canvas; import android.graphics.Paint; +import android.os.Parcel; import android.text.Layout; +import android.text.ParcelableSpan; import android.text.Spanned; +import android.text.TextUtils; -public class BulletSpan implements LeadingMarginSpan { +public class BulletSpan implements LeadingMarginSpan, ParcelableSpan { + private final int mGapWidth; + private final boolean mWantColor; + private final int mColor; + + private static final int BULLET_RADIUS = 3; + public static final int STANDARD_GAP_WIDTH = 2; public BulletSpan() { mGapWidth = STANDARD_GAP_WIDTH; + mWantColor = false; + mColor = 0; } public BulletSpan(int gapWidth) { mGapWidth = gapWidth; + mWantColor = false; + mColor = 0; } public BulletSpan(int gapWidth, int color) { @@ -37,6 +50,26 @@ public class BulletSpan implements LeadingMarginSpan { mColor = color; } + public BulletSpan(Parcel src) { + mGapWidth = src.readInt(); + mWantColor = src.readInt() != 0; + mColor = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.BULLET_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mGapWidth); + dest.writeInt(mWantColor ? 1 : 0); + dest.writeInt(mColor); + } + public int getLeadingMargin(boolean first) { return 2 * BULLET_RADIUS + mGapWidth; } @@ -66,11 +99,4 @@ public class BulletSpan implements LeadingMarginSpan { p.setStyle(style); } } - - private int mGapWidth; - private boolean mWantColor; - private int mColor; - - private static final int BULLET_RADIUS = 3; - public static final int STANDARD_GAP_WIDTH = 2; } diff --git a/core/java/android/text/style/ForegroundColorSpan.java b/core/java/android/text/style/ForegroundColorSpan.java index 99b3381..476124d 100644 --- a/core/java/android/text/style/ForegroundColorSpan.java +++ b/core/java/android/text/style/ForegroundColorSpan.java @@ -16,16 +16,36 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class ForegroundColorSpan extends CharacterStyle implements UpdateAppearance { +public class ForegroundColorSpan extends CharacterStyle + implements UpdateAppearance, ParcelableSpan { - private int mColor; + private final int mColor; public ForegroundColorSpan(int color) { mColor = color; } + public ForegroundColorSpan(Parcel src) { + mColor = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.FOREGROUND_COLOR_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mColor); + } + public int getForegroundColor() { return mColor; } diff --git a/core/java/android/text/style/LeadingMarginSpan.java b/core/java/android/text/style/LeadingMarginSpan.java index 85a27dc..8e212e3 100644 --- a/core/java/android/text/style/LeadingMarginSpan.java +++ b/core/java/android/text/style/LeadingMarginSpan.java @@ -18,7 +18,10 @@ package android.text.style; import android.graphics.Paint; import android.graphics.Canvas; +import android.os.Parcel; import android.text.Layout; +import android.text.ParcelableSpan; +import android.text.TextUtils; public interface LeadingMarginSpan extends ParagraphStyle @@ -30,9 +33,9 @@ extends ParagraphStyle CharSequence text, int start, int end, boolean first, Layout layout); - public static class Standard - implements LeadingMarginSpan - { + public static class Standard implements LeadingMarginSpan, ParcelableSpan { + private final int mFirst, mRest; + public Standard(int first, int rest) { mFirst = first; mRest = rest; @@ -42,6 +45,24 @@ extends ParagraphStyle this(every, every); } + public Standard(Parcel src) { + mFirst = src.readInt(); + mRest = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.LEADING_MARGIN_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mFirst); + dest.writeInt(mRest); + } + public int getLeadingMargin(boolean first) { return first ? mFirst : mRest; } @@ -53,7 +74,5 @@ extends ParagraphStyle boolean first, Layout layout) { ; } - - private int mFirst, mRest; } } diff --git a/core/java/android/text/style/QuoteSpan.java b/core/java/android/text/style/QuoteSpan.java index 3f4a32f..29dd273 100644 --- a/core/java/android/text/style/QuoteSpan.java +++ b/core/java/android/text/style/QuoteSpan.java @@ -18,26 +18,43 @@ package android.text.style; import android.graphics.Paint; import android.graphics.Canvas; -import android.graphics.RectF; +import android.os.Parcel; import android.text.Layout; +import android.text.ParcelableSpan; +import android.text.TextUtils; -public class QuoteSpan -implements LeadingMarginSpan -{ +public class QuoteSpan implements LeadingMarginSpan, ParcelableSpan { private static final int STRIPE_WIDTH = 2; private static final int GAP_WIDTH = 2; - private int mColor = 0xff0000ff; + private final int mColor; public QuoteSpan() { super(); + mColor = 0xff0000ff; } public QuoteSpan(int color) { - this(); + super(); mColor = color; } + public QuoteSpan(Parcel src) { + mColor = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.QUOTE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mColor); + } + public int getColor() { return mColor; } diff --git a/core/java/android/text/style/RelativeSizeSpan.java b/core/java/android/text/style/RelativeSizeSpan.java index a8ad076..9717362 100644 --- a/core/java/android/text/style/RelativeSizeSpan.java +++ b/core/java/android/text/style/RelativeSizeSpan.java @@ -16,17 +16,35 @@ package android.text.style; -import android.graphics.Paint; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class RelativeSizeSpan extends MetricAffectingSpan { +public class RelativeSizeSpan extends MetricAffectingSpan implements ParcelableSpan { - private float mProportion; + private final float mProportion; public RelativeSizeSpan(float proportion) { mProportion = proportion; } + public RelativeSizeSpan(Parcel src) { + mProportion = src.readFloat(); + } + + public int getSpanTypeId() { + return TextUtils.RELATIVE_SIZE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeFloat(mProportion); + } + public float getSizeChange() { return mProportion; } diff --git a/core/java/android/text/style/ScaleXSpan.java b/core/java/android/text/style/ScaleXSpan.java index ac9e35d..655064b 100644 --- a/core/java/android/text/style/ScaleXSpan.java +++ b/core/java/android/text/style/ScaleXSpan.java @@ -16,17 +16,35 @@ package android.text.style; -import android.graphics.Paint; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class ScaleXSpan extends MetricAffectingSpan { +public class ScaleXSpan extends MetricAffectingSpan implements ParcelableSpan { - private float mProportion; + private final float mProportion; public ScaleXSpan(float proportion) { mProportion = proportion; } + public ScaleXSpan(Parcel src) { + mProportion = src.readFloat(); + } + + public int getSpanTypeId() { + return TextUtils.SCALE_X_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeFloat(mProportion); + } + public float getScaleX() { return mProportion; } diff --git a/core/java/android/text/style/StrikethroughSpan.java b/core/java/android/text/style/StrikethroughSpan.java index dd430e5..b51363a 100644 --- a/core/java/android/text/style/StrikethroughSpan.java +++ b/core/java/android/text/style/StrikethroughSpan.java @@ -16,9 +16,29 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class StrikethroughSpan extends CharacterStyle implements UpdateAppearance { +public class StrikethroughSpan extends CharacterStyle + implements UpdateAppearance, ParcelableSpan { + public StrikethroughSpan() { + } + + public StrikethroughSpan(Parcel src) { + } + + public int getSpanTypeId() { + return TextUtils.STRIKETHROUGH_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + } @Override public void updateDrawState(TextPaint ds) { diff --git a/core/java/android/text/style/StyleSpan.java b/core/java/android/text/style/StyleSpan.java index cc8b06c..8e6147c 100644 --- a/core/java/android/text/style/StyleSpan.java +++ b/core/java/android/text/style/StyleSpan.java @@ -18,7 +18,10 @@ package android.text.style; import android.graphics.Paint; import android.graphics.Typeface; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; /** * @@ -28,9 +31,9 @@ import android.text.TextPaint; * you get bold italic. You can't turn off a style from the base style. * */ -public class StyleSpan extends MetricAffectingSpan { +public class StyleSpan extends MetricAffectingSpan implements ParcelableSpan { - private int mStyle; + private final int mStyle; /** * @@ -42,6 +45,22 @@ public class StyleSpan extends MetricAffectingSpan { mStyle = style; } + public StyleSpan(Parcel src) { + mStyle = src.readInt(); + } + + public int getSpanTypeId() { + return TextUtils.STYLE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(mStyle); + } + /** * Returns the style constant defined in {@link android.graphics.Typeface}. */ diff --git a/core/java/android/text/style/SubscriptSpan.java b/core/java/android/text/style/SubscriptSpan.java index 78d6ba9..de1d8b2 100644 --- a/core/java/android/text/style/SubscriptSpan.java +++ b/core/java/android/text/style/SubscriptSpan.java @@ -16,9 +16,29 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; + +public class SubscriptSpan extends MetricAffectingSpan implements ParcelableSpan { + public SubscriptSpan() { + } + + public SubscriptSpan(Parcel src) { + } + + public int getSpanTypeId() { + return TextUtils.SUBSCRIPT_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + } -public class SubscriptSpan extends MetricAffectingSpan { @Override public void updateDrawState(TextPaint tp) { tp.baselineShift -= (int) (tp.ascent() / 2); diff --git a/core/java/android/text/style/SuperscriptSpan.java b/core/java/android/text/style/SuperscriptSpan.java index 79be4de..285fe84 100644 --- a/core/java/android/text/style/SuperscriptSpan.java +++ b/core/java/android/text/style/SuperscriptSpan.java @@ -16,9 +16,29 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; + +public class SuperscriptSpan extends MetricAffectingSpan implements ParcelableSpan { + public SuperscriptSpan() { + } + + public SuperscriptSpan(Parcel src) { + } + + public int getSpanTypeId() { + return TextUtils.SUPERSCRIPT_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + } -public class SuperscriptSpan extends MetricAffectingSpan { @Override public void updateDrawState(TextPaint tp) { tp.baselineShift += (int) (tp.ascent() / 2); diff --git a/core/java/android/text/style/TextAppearanceSpan.java b/core/java/android/text/style/TextAppearanceSpan.java index c4ec976..de929e3 100644 --- a/core/java/android/text/style/TextAppearanceSpan.java +++ b/core/java/android/text/style/TextAppearanceSpan.java @@ -19,20 +19,22 @@ package android.text.style; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; -import android.graphics.Paint; import android.graphics.Typeface; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; /** * Sets the text color, size, style, and typeface to match a TextAppearance * resource. */ -public class TextAppearanceSpan extends MetricAffectingSpan { - private String mTypeface; - private int mStyle; - private int mTextSize; - private ColorStateList mTextColor; - private ColorStateList mTextColorLink; +public class TextAppearanceSpan extends MetricAffectingSpan implements ParcelableSpan { + private final String mTypeface; + private final int mStyle; + private final int mTextSize; + private final ColorStateList mTextColor; + private final ColorStateList mTextColorLink; /** * Uses the specified TextAppearance resource to determine the @@ -53,11 +55,13 @@ public class TextAppearanceSpan extends MetricAffectingSpan { */ public TextAppearanceSpan(Context context, int appearance, int colorList) { + ColorStateList textColor; + TypedArray a = context.obtainStyledAttributes(appearance, com.android.internal.R.styleable.TextAppearance); - mTextColor = a.getColorStateList(com.android.internal.R.styleable. + textColor = a.getColorStateList(com.android.internal.R.styleable. TextAppearance_textColor); mTextColorLink = a.getColorStateList(com.android.internal.R.styleable. TextAppearance_textColorLink); @@ -79,6 +83,10 @@ public class TextAppearanceSpan extends MetricAffectingSpan { case 3: mTypeface = "monospace"; break; + + default: + mTypeface = null; + break; } a.recycle(); @@ -87,9 +95,11 @@ public class TextAppearanceSpan extends MetricAffectingSpan { a = context.obtainStyledAttributes(com.android.internal.R.style.Theme, com.android.internal.R.styleable.Theme); - mTextColor = a.getColorStateList(colorList); + textColor = a.getColorStateList(colorList); a.recycle(); } + + mTextColor = textColor; } /** @@ -105,6 +115,48 @@ public class TextAppearanceSpan extends MetricAffectingSpan { mTextColorLink = linkColor; } + public TextAppearanceSpan(Parcel src) { + mTypeface = src.readString(); + mStyle = src.readInt(); + mTextSize = src.readInt(); + if (src.readInt() != 0) { + mTextColor = ColorStateList.CREATOR.createFromParcel(src); + } else { + mTextColor = null; + } + if (src.readInt() != 0) { + mTextColorLink = ColorStateList.CREATOR.createFromParcel(src); + } else { + mTextColorLink = null; + } + } + + public int getSpanTypeId() { + return TextUtils.TEXT_APPEARANCE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mTypeface); + dest.writeInt(mStyle); + dest.writeInt(mTextSize); + if (mTextColor != null) { + dest.writeInt(1); + mTextColor.writeToParcel(dest, flags); + } else { + dest.writeInt(0); + } + if (mTextColorLink != null) { + dest.writeInt(1); + mTextColorLink.writeToParcel(dest, flags); + } else { + dest.writeInt(0); + } + } + /** * Returns the typeface family specified by this span, or <code>null</code> * if it does not specify one. diff --git a/core/java/android/text/style/TypefaceSpan.java b/core/java/android/text/style/TypefaceSpan.java index 7519ac2..f194060 100644 --- a/core/java/android/text/style/TypefaceSpan.java +++ b/core/java/android/text/style/TypefaceSpan.java @@ -18,13 +18,16 @@ package android.text.style; import android.graphics.Paint; import android.graphics.Typeface; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; /** * Changes the typeface family of the text to which the span is attached. */ -public class TypefaceSpan extends MetricAffectingSpan { - private String mFamily; +public class TypefaceSpan extends MetricAffectingSpan implements ParcelableSpan { + private final String mFamily; /** * @param family The font family for this typeface. Examples include @@ -34,6 +37,22 @@ public class TypefaceSpan extends MetricAffectingSpan { mFamily = family; } + public TypefaceSpan(Parcel src) { + mFamily = src.readString(); + } + + public int getSpanTypeId() { + return TextUtils.TYPEFACE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mFamily); + } + /** * Returns the font family name. */ diff --git a/core/java/android/text/style/URLSpan.java b/core/java/android/text/style/URLSpan.java index 79809b5..f458611 100644 --- a/core/java/android/text/style/URLSpan.java +++ b/core/java/android/text/style/URLSpan.java @@ -18,17 +18,35 @@ package android.text.style; import android.content.Intent; import android.net.Uri; -import android.text.TextPaint; +import android.os.Parcel; +import android.text.ParcelableSpan; +import android.text.TextUtils; import android.view.View; -public class URLSpan extends ClickableSpan { +public class URLSpan extends ClickableSpan implements ParcelableSpan { - private String mURL; + private final String mURL; public URLSpan(String url) { mURL = url; } + public URLSpan(Parcel src) { + mURL = src.readString(); + } + + public int getSpanTypeId() { + return TextUtils.URL_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mURL); + } + public String getURL() { return mURL; } diff --git a/core/java/android/text/style/UnderlineSpan.java b/core/java/android/text/style/UnderlineSpan.java index ca6f10c..b0cb0e8 100644 --- a/core/java/android/text/style/UnderlineSpan.java +++ b/core/java/android/text/style/UnderlineSpan.java @@ -16,9 +16,29 @@ package android.text.style; +import android.os.Parcel; +import android.text.ParcelableSpan; import android.text.TextPaint; +import android.text.TextUtils; -public class UnderlineSpan extends CharacterStyle implements UpdateAppearance { +public class UnderlineSpan extends CharacterStyle + implements UpdateAppearance, ParcelableSpan { + public UnderlineSpan() { + } + + public UnderlineSpan(Parcel src) { + } + + public int getSpanTypeId() { + return TextUtils.UNDERLINE_SPAN; + } + + public int describeContents() { + return 0; + } + + public void writeToParcel(Parcel dest, int flags) { + } @Override public void updateDrawState(TextPaint ds) { diff --git a/core/java/android/text/util/Rfc822Validator.java b/core/java/android/text/util/Rfc822Validator.java index 9f03bb0..6a6bf69 100644 --- a/core/java/android/text/util/Rfc822Validator.java +++ b/core/java/android/text/util/Rfc822Validator.java @@ -16,6 +16,7 @@ package android.text.util; +import android.text.TextUtils; import android.widget.AutoCompleteTextView; import java.util.regex.Pattern; @@ -67,7 +68,7 @@ public class Rfc822Validator implements AutoCompleteTextView.Validator { /** * @return a string in which all the characters that are illegal for the username - * part of the email address have been removed. + * or the domain name part of the email address have been removed. */ private String removeIllegalCharacters(String s) { StringBuilder result = new StringBuilder(); @@ -101,6 +102,9 @@ public class Rfc822Validator implements AutoCompleteTextView.Validator { * {@inheritDoc} */ public CharSequence fixText(CharSequence cs) { + // Return an empty string if the email address only contains spaces, \n or \t + if (TextUtils.getTrimmedLength(cs) == 0) return ""; + Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(cs); StringBuilder sb = new StringBuilder(); @@ -111,10 +115,10 @@ public class Rfc822Validator implements AutoCompleteTextView.Validator { // If there is no @, just append the domain of the account tokens[i].setAddress(removeIllegalCharacters(text) + "@" + mDomain); } else { - // Otherwise, remove everything right of the '@' and append the domain - // ("a@b" becomes "a@gmail.com"). + // Otherwise, remove the illegal characters on both sides of the '@' String fix = removeIllegalCharacters(text.substring(0, index)); - tokens[i].setAddress(fix + "@" + mDomain); + String domain = removeIllegalCharacters(text.substring(index + 1)); + tokens[i].setAddress(fix + "@" + (domain.length() != 0 ? domain : mDomain)); } sb.append(tokens[i].toString()); diff --git a/core/java/android/util/DisplayMetrics.java b/core/java/android/util/DisplayMetrics.java index 8fc3602..9de4cbe 100644 --- a/core/java/android/util/DisplayMetrics.java +++ b/core/java/android/util/DisplayMetrics.java @@ -16,6 +16,8 @@ package android.util; +import android.os.*; + /** * A structure describing general information about a display, such as its @@ -23,6 +25,16 @@ package android.util; */ public class DisplayMetrics { /** + * The reference density used throughout the system. + * + * @hide Pending API council approval + */ + public static final int DEFAULT_DENSITY = 160; + + private static final int sLcdDensity = SystemProperties.getInt("ro.sf.lcd_density", + DEFAULT_DENSITY); + + /** * The absolute width of the display in pixels. */ public int widthPixels; @@ -43,7 +55,9 @@ public class DisplayMetrics { * example, a 240x320 screen will have a density of 1 even if its width is * 1.8", 1.3", etc. However, if the screen resolution is increased to * 320x480 but the screen size remained 1.5"x2" then the density would be - * increased (probably to 1.5). + * increased (probably to 1.5). + * + * @see #DEFAULT_DENSITY */ public float density; /** @@ -60,7 +74,7 @@ public class DisplayMetrics { * The exact physical pixels per inch of the screen in the Y dimension. */ public float ydpi; - + public DisplayMetrics() { } @@ -76,10 +90,9 @@ public class DisplayMetrics { public void setToDefaults() { widthPixels = 0; heightPixels = 0; - density = 1; - scaledDensity = 1; - xdpi = 160; - ydpi = 160; + density = sLcdDensity / (float) DEFAULT_DENSITY; + scaledDensity = density; + xdpi = sLcdDensity; + ydpi = sLcdDensity; } } - diff --git a/core/java/android/util/TypedValue.java b/core/java/android/util/TypedValue.java index a4ee35a..d4ba9e2 100644 --- a/core/java/android/util/TypedValue.java +++ b/core/java/android/util/TypedValue.java @@ -16,9 +16,6 @@ package android.util; -import android.util.Config; -import android.util.Log; - /** * Container for a dynamically typed data value. Primarily used with * {@link android.content.res.Resources} for holding resource values. @@ -141,6 +138,16 @@ public class TypedValue { /* ------------------------------------------------------------ */ + /** + * If {@link #density} is equal to this value, then the density should be + * treated as the system's default density value: {@link DisplayMetrics#DEFAULT_DENSITY}. + * + * @hide Pending API council approval + */ + public static final int DENSITY_DEFAULT = 0; + + /* ------------------------------------------------------------ */ + /** The type held by this value, as defined by the constants here. * This tells you how to interpret the other fields in the object. */ public int type; @@ -161,7 +168,14 @@ public class TypedValue { /** If Value came from a resource, these are the configurations for which * its contents can change. */ public int changingConfigurations = -1; - + + /** + * If the Value came from a resource, this holds the corresponding pixel density. + * + * @hide Pending API council approval + * */ + public int density; + /* ------------------------------------------------------------ */ /** Return the data for this value as a float. Only use for values @@ -454,6 +468,7 @@ public class TypedValue { data = other.data; assetCookie = other.assetCookie; resourceId = other.resourceId; + density = other.density; } public String toString() diff --git a/core/java/android/view/FocusFinder.java b/core/java/android/view/FocusFinder.java index 4048763..15fb839 100644 --- a/core/java/android/view/FocusFinder.java +++ b/core/java/android/view/FocusFinder.java @@ -397,7 +397,7 @@ public class FocusFinder { int numTouchables = touchables.size(); - int edgeSlop = ViewConfiguration.getEdgeSlop(); + int edgeSlop = ViewConfiguration.get(root.mContext).getScaledEdgeSlop(); Rect closestBounds = new Rect(); Rect touchableBounds = mOtherRect; diff --git a/core/java/android/view/GestureDetector.java b/core/java/android/view/GestureDetector.java index fc9af05..a472689 100644 --- a/core/java/android/view/GestureDetector.java +++ b/core/java/android/view/GestureDetector.java @@ -18,6 +18,7 @@ package android.view; import android.os.Handler; import android.os.Message; +import android.content.Context; /** * Detects various gestures and events using the supplied {@link MotionEvent}s. @@ -34,7 +35,6 @@ import android.os.Message; * </ul> */ public class GestureDetector { - /** * The listener that is used to notify when gestures occur. * If you want to listen for all the different gestures then implement @@ -113,6 +113,14 @@ public class GestureDetector { } /** + * @hide pending API council + */ + public interface OnDoubleTapListener { + boolean onSingleTapConfirmed(MotionEvent e); + boolean onDoubleTapEvent(MotionEvent e); + } + + /** * A convenience class to extend when you only want to listen for a * subset of all the gestures. This implements all methods in the * {@link OnGestureListener} but does nothing and return {@code false} @@ -144,22 +152,40 @@ public class GestureDetector { } } - private static final int TOUCH_SLOP_SQUARE = ViewConfiguration.getTouchSlop() - * ViewConfiguration.getTouchSlop(); - + // TODO: ViewConfiguration + private int mBiggerTouchSlopSquare = 20 * 20; + + private int mTouchSlopSquare; + private int mDoubleTapSlopSquare; + private int mMinimumFlingVelocity; + + private static final int LONGPRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout(); + private static final int TAP_TIMEOUT = ViewConfiguration.getTapTimeout(); + // TODO make new double-tap timeout, and define its events (i.e. either time + // between down-down or time between up-down) + private static final int DOUBLE_TAP_TIMEOUT = ViewConfiguration.getJumpTapTimeout(); + // constants for Message.what used by GestureHandler below private static final int SHOW_PRESS = 1; private static final int LONG_PRESS = 2; + private static final int TAP = 3; private final Handler mHandler; private final OnGestureListener mListener; + private OnDoubleTapListener mDoubleTapListener; private boolean mInLongPress; private boolean mAlwaysInTapRegion; + private boolean mAlwaysInBiggerTapRegion; private MotionEvent mCurrentDownEvent; - private MotionEvent mCurrentUpEvent; - + + /** + * True when the user is still touching for the second tap (down, move, and + * up events). Can only be true if there is a double tap listener attached. + */ + private boolean mIsDoubleTapping; + private float mLastMotionY; private float mLastMotionX; @@ -189,6 +215,12 @@ public class GestureDetector { case LONG_PRESS: dispatchLongPress(); break; + + case TAP: + if (mDoubleTapListener != null) { + mDoubleTapListener.onSingleTapConfirmed(mCurrentDownEvent); + } + break; default: throw new RuntimeException("Unknown message " + msg); //never @@ -203,16 +235,17 @@ public class GestureDetector { * * @param listener the listener invoked for all the callbacks, this must * not be null. - * @param handler the handler to use, this must - * not be null. + * @param handler the handler to use * * @throws NullPointerException if either {@code listener} or * {@code handler} is null. + * + * @deprecated Use {@link #GestureDetector(android.content.Context, + * android.view.GestureDetector.OnGestureListener, android.os.Handler)} instead. */ + @Deprecated public GestureDetector(OnGestureListener listener, Handler handler) { - mHandler = new GestureHandler(handler); - mListener = listener; - init(); + this(null, listener, handler); } /** @@ -222,19 +255,84 @@ public class GestureDetector { * * @param listener the listener invoked for all the callbacks, this must * not be null. + * * @throws NullPointerException if {@code listener} is null. + * + * @deprecated Use {@link #GestureDetector(android.content.Context, + * android.view.GestureDetector.OnGestureListener)} instead. */ + @Deprecated public GestureDetector(OnGestureListener listener) { - mHandler = new GestureHandler(); + this(null, listener, null); + } + + /** + * Creates a GestureDetector with the supplied listener. + * You may only use this constructor from a UI thread (this is the usual situation). + * @see android.os.Handler#Handler() + * + * @param context the application's context + * @param listener the listener invoked for all the callbacks, this must + * not be null. + * + * @throws NullPointerException if {@code listener} is null. + */ + public GestureDetector(Context context, OnGestureListener listener) { + this(context, listener, null); + } + + /** + * Creates a GestureDetector with the supplied listener. + * You may only use this constructor from a UI thread (this is the usual situation). + * @see android.os.Handler#Handler() + * + * @param context the application's context + * @param listener the listener invoked for all the callbacks, this must + * not be null. + * @param handler the handler to use + * + * @throws NullPointerException if {@code listener} is null. + */ + public GestureDetector(Context context, OnGestureListener listener, Handler handler) { + if (handler != null) { + mHandler = new GestureHandler(handler); + } else { + mHandler = new GestureHandler(); + } mListener = listener; - init(); + init(context); } - private void init() { + private void init(Context context) { if (mListener == null) { throw new NullPointerException("OnGestureListener must not be null"); } mIsLongpressEnabled = true; + + // Fallback to support pre-donuts releases + int touchSlop, doubleTapSlop; + if (context == null) { + //noinspection deprecation + touchSlop = ViewConfiguration.getTouchSlop(); + doubleTapSlop = ViewConfiguration.getDoubleTapSlop(); + //noinspection deprecation + mMinimumFlingVelocity = ViewConfiguration.getMinimumFlingVelocity(); + } else { + final ViewConfiguration configuration = ViewConfiguration.get(context); + touchSlop = configuration.getScaledTouchSlop(); + doubleTapSlop = configuration.getScaledDoubleTapSlop(); + mMinimumFlingVelocity = configuration.getScaledMinimumFlingVelocity(); + } + mTouchSlopSquare = touchSlop * touchSlop; + mDoubleTapSlopSquare = doubleTapSlop * doubleTapSlop; + } + + /** + * @hide pending API council + * @param onDoubleTapListener + */ + public void setOnDoubleTapListener(OnDoubleTapListener onDoubleTapListener) { + mDoubleTapListener = onDoubleTapListener; } /** @@ -266,9 +364,6 @@ public class GestureDetector { * else false. */ public boolean onTouchEvent(MotionEvent ev) { - final long tapTime = ViewConfiguration.getTapTimeout(); - final long longpressTime = ViewConfiguration.getLongPressTimeout(); - final int touchSlop = ViewConfiguration.getTouchSlop(); final int action = ev.getAction(); final float y = ev.getY(); final float x = ev.getX(); @@ -282,19 +377,32 @@ public class GestureDetector { switch (action) { case MotionEvent.ACTION_DOWN: + if (mDoubleTapListener != null) { + mHandler.removeMessages(TAP); + if (mCurrentDownEvent != null && isConsideredDoubleTap(mCurrentDownEvent, ev)) { + // This is a second tap + mIsDoubleTapping = true; + handled = mDoubleTapListener.onDoubleTapEvent(ev); + } else { + // This is a first tap + mHandler.sendEmptyMessageDelayed(TAP, DOUBLE_TAP_TIMEOUT); + } + } + mLastMotionX = x; mLastMotionY = y; mCurrentDownEvent = MotionEvent.obtain(ev); mAlwaysInTapRegion = true; + mAlwaysInBiggerTapRegion = true; mInLongPress = false; - + if (mIsLongpressEnabled) { mHandler.removeMessages(LONG_PRESS); mHandler.sendEmptyMessageAtTime(LONG_PRESS, mCurrentDownEvent.getDownTime() - + tapTime + longpressTime); + + TAP_TIMEOUT + LONGPRESS_TIMEOUT); } - mHandler.sendEmptyMessageAtTime(SHOW_PRESS, mCurrentDownEvent.getDownTime() + tapTime); - handled = mListener.onDown(ev); + mHandler.sendEmptyMessageAtTime(SHOW_PRESS, mCurrentDownEvent.getDownTime() + TAP_TIMEOUT); + handled |= mListener.onDown(ev); break; case MotionEvent.ACTION_MOVE: @@ -303,11 +411,13 @@ public class GestureDetector { } final float scrollX = mLastMotionX - x; final float scrollY = mLastMotionY - y; - if (mAlwaysInTapRegion) { + if (mIsDoubleTapping) { + handled = mDoubleTapListener.onDoubleTapEvent(ev); + } else if (mAlwaysInTapRegion) { final int deltaX = (int) (x - mCurrentDownEvent.getX()); final int deltaY = (int) (y - mCurrentDownEvent.getY()); int distance = (deltaX * deltaX) + (deltaY * deltaY); - if (distance > TOUCH_SLOP_SQUARE) { + if (distance > mTouchSlopSquare) { handled = mListener.onScroll(mCurrentDownEvent, ev, scrollX, scrollY); mLastMotionX = x; mLastMotionY = y; @@ -315,6 +425,9 @@ public class GestureDetector { mHandler.removeMessages(SHOW_PRESS); mHandler.removeMessages(LONG_PRESS); } + if (distance > mBiggerTouchSlopSquare) { + mAlwaysInBiggerTapRegion = false; + } } else if ((Math.abs(scrollX) >= 1) || (Math.abs(scrollY) >= 1)) { handled = mListener.onScroll(mCurrentDownEvent, ev, scrollX, scrollY); mLastMotionX = x; @@ -323,8 +436,13 @@ public class GestureDetector { break; case MotionEvent.ACTION_UP: - mCurrentUpEvent = MotionEvent.obtain(ev); - if (mInLongPress) { + MotionEvent currentUpEvent = MotionEvent.obtain(ev); + if (mIsDoubleTapping) { + handled = mDoubleTapListener.onDoubleTapEvent(ev); + mIsDoubleTapping = false; + break; + } else if (mInLongPress) { + mHandler.removeMessages(TAP); mInLongPress = false; break; } @@ -338,9 +456,9 @@ public class GestureDetector { final float velocityY = velocityTracker.getYVelocity(); final float velocityX = velocityTracker.getXVelocity(); - if ((Math.abs(velocityY) > ViewConfiguration.getMinimumFlingVelocity()) - || (Math.abs(velocityX) > ViewConfiguration.getMinimumFlingVelocity())){ - handled = mListener.onFling(mCurrentDownEvent, mCurrentUpEvent, velocityX, velocityY); + if ((Math.abs(velocityY) > mMinimumFlingVelocity) + || (Math.abs(velocityX) > mMinimumFlingVelocity)){ + handled = mListener.onFling(mCurrentDownEvent, currentUpEvent, velocityX, velocityY); } } mVelocityTracker.recycle(); @@ -351,6 +469,7 @@ public class GestureDetector { case MotionEvent.ACTION_CANCEL: mHandler.removeMessages(SHOW_PRESS); mHandler.removeMessages(LONG_PRESS); + mHandler.removeMessages(TAP); mVelocityTracker.recycle(); mVelocityTracker = null; if (mInLongPress) { @@ -361,6 +480,20 @@ public class GestureDetector { return handled; } + private boolean isConsideredDoubleTap(MotionEvent firstDown, MotionEvent secondDown) { + if (!mAlwaysInBiggerTapRegion) { + return false; + } + + if (secondDown.getEventTime() - firstDown.getEventTime() > DOUBLE_TAP_TIMEOUT) { + return false; + } + + int deltaX = (int) firstDown.getX() - (int) secondDown.getX(); + int deltaY = (int) firstDown.getY() - (int) secondDown.getY(); + return (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare); + } + private void dispatchLongPress() { mInLongPress = true; mListener.onLongPress(mCurrentDownEvent); diff --git a/core/java/android/view/IWindowManager.aidl b/core/java/android/view/IWindowManager.aidl index 40251db..a856b24 100644 --- a/core/java/android/view/IWindowManager.aidl +++ b/core/java/android/view/IWindowManager.aidl @@ -104,6 +104,9 @@ interface IWindowManager int getKeycodeState(int sw); int getKeycodeStateForDevice(int devid, int sw); + // Report whether the hardware supports the given keys; returns true if successful + boolean hasKeys(in int[] keycodes, inout boolean[] keyExists); + // For testing void setInTouchMode(boolean showFocus); diff --git a/core/java/android/view/KeyCharacterMap.java b/core/java/android/view/KeyCharacterMap.java index 0347d50..25958aa 100644 --- a/core/java/android/view/KeyCharacterMap.java +++ b/core/java/android/view/KeyCharacterMap.java @@ -18,6 +18,8 @@ package android.view; import android.text.method.MetaKeyKeyListener; import android.util.SparseIntArray; +import android.os.RemoteException; +import android.os.ServiceManager; import android.os.SystemClock; import android.util.SparseArray; @@ -350,6 +352,28 @@ public class KeyCharacterMap return getKeyboardType_native(mPointer); } + /** + * Queries the framework about whether any physical keys exist on the + * device that are capable of producing the given key codes. + */ + public static boolean deviceHasKey(int keyCode) { + int[] codeArray = new int[1]; + codeArray[0] = keyCode; + boolean[] ret = deviceHasKeys(codeArray); + return ret[0]; + } + + public static boolean[] deviceHasKeys(int[] keyCodes) { + boolean[] ret = new boolean[keyCodes.length]; + IWindowManager wm = IWindowManager.Stub.asInterface(ServiceManager.getService("window")); + try { + wm.hasKeys(keyCodes, ret); + } catch (RemoteException e) { + // no fallback; just return the empty array + } + return ret; + } + private int mPointer; private int mKeyboardDevice; diff --git a/core/java/android/view/KeyEvent.java b/core/java/android/view/KeyEvent.java index 1575aad..d5434b6 100644 --- a/core/java/android/view/KeyEvent.java +++ b/core/java/android/view/KeyEvent.java @@ -92,7 +92,7 @@ public class KeyEvent implements Parcelable { public static final int KEYCODE_SYM = 63; public static final int KEYCODE_EXPLORER = 64; public static final int KEYCODE_ENVELOPE = 65; - public static final int KEYCODE_ENTER = 66; + public static final int KEYCODE_ENTER = 66; public static final int KEYCODE_DEL = 67; public static final int KEYCODE_GRAVE = 68; public static final int KEYCODE_MINUS = 69; @@ -144,8 +144,12 @@ public class KeyEvent implements Parcelable { public static final int ACTION_UP = 1; /** * {@link #getAction} value: multiple duplicate key events have - * occurred in a row. The {#link {@link #getRepeatCount()} method returns - * the number of duplicates. + * occurred in a row, or a complex string is being delivered. If the + * key code is not {#link {@link #KEYCODE_UNKNOWN} then the + * {#link {@link #getRepeatCount()} method returns the number of times + * the given key code should be executed. + * Otherwise, if the key code {@link #KEYCODE_UNKNOWN}, then + * this is a sequence of characters as returned by {@link #getCharacters}. */ public static final int ACTION_MULTIPLE = 2; @@ -248,6 +252,7 @@ public class KeyEvent implements Parcelable { private int mFlags; private long mDownTime; private long mEventTime; + private String mCharacters; public interface Callback { /** @@ -406,6 +411,28 @@ public class KeyEvent implements Parcelable { } /** + * Create a new key event for a string of characters. The key code, + * action, and repeat could will automatically be set to + * {@link #KEYCODE_UNKNOWN}, {@link #ACTION_MULTIPLE}, and 0 for you. + * + * @param time The time (in {@link android.os.SystemClock#uptimeMillis}) + * at which this event occured. + * @param characters The string of characters. + * @param device The device ID that generated the key event. + * @param flags The flags for this key event + */ + public KeyEvent(long time, String characters, int device, int flags) { + mDownTime = time; + mEventTime = time; + mCharacters = characters; + mAction = ACTION_MULTIPLE; + mKeyCode = KEYCODE_UNKNOWN; + mRepeatCount = 0; + mDeviceId = device; + mFlags = flags; + } + + /** * Copy an existing key event, modifying its time and repeat count. * * @param origEvent The existing event to be copied. @@ -423,6 +450,7 @@ public class KeyEvent implements Parcelable { mDeviceId = origEvent.mDeviceId; mScancode = origEvent.mScancode; mFlags = origEvent.mFlags; + mCharacters = origEvent.mCharacters; } /** @@ -441,6 +469,8 @@ public class KeyEvent implements Parcelable { mDeviceId = origEvent.mDeviceId; mScancode = origEvent.mScancode; mFlags = origEvent.mFlags; + // Don't copy mCharacters, since one way or the other we'll lose it + // when changing the action. } /** @@ -580,7 +610,7 @@ public class KeyEvent implements Parcelable { /** * Retrieve the key code of the key event. This is the physical key that - * was pressed -- not the Unicode character. + * was pressed, <em>not</em> the Unicode character. * * @return The key code of the event. */ @@ -589,6 +619,18 @@ public class KeyEvent implements Parcelable { } /** + * For the special case of a {@link #ACTION_MULTIPLE} event with key + * code of {@link #KEYCODE_UNKNOWN}, this is a raw string of characters + * associated with the event. In all other cases it is null. + * + * @return Returns a String of 1 or more characters associated with + * the event. + */ + public final String getCharacters() { + return mCharacters; + } + + /** * Retrieve the hardware key id of this key event. These values are not * reliable and vary from device to device. * @@ -772,16 +814,18 @@ public class KeyEvent implements Parcelable { if (receiver.onKeyMultiple(code, count, this)) { return true; } - mAction = ACTION_DOWN; - mRepeatCount = 0; - boolean handled = receiver.onKeyDown(code, this); - if (handled) { - mAction = ACTION_UP; - receiver.onKeyUp(code, this); + if (code != KeyEvent.KEYCODE_UNKNOWN) { + mAction = ACTION_DOWN; + mRepeatCount = 0; + boolean handled = receiver.onKeyDown(code, this); + if (handled) { + mAction = ACTION_UP; + receiver.onKeyUp(code, this); + } + mAction = ACTION_MULTIPLE; + mRepeatCount = count; + return handled; } - mAction = ACTION_MULTIPLE; - mRepeatCount = count; - return handled; } return false; } diff --git a/core/java/android/view/TouchDelegate.java b/core/java/android/view/TouchDelegate.java index 057df92..27b49db 100644 --- a/core/java/android/view/TouchDelegate.java +++ b/core/java/android/view/TouchDelegate.java @@ -77,7 +77,9 @@ public class TouchDelegate { * actual extent. */ public static final int TO_RIGHT = 8; - + + private int mSlop; + /** * Constructor * @@ -87,10 +89,10 @@ public class TouchDelegate { */ public TouchDelegate(Rect bounds, View delegateView) { mBounds = bounds; - - int slop = ViewConfiguration.getTouchSlop(); + + mSlop = ViewConfiguration.get(delegateView.getContext()).getScaledTouchSlop(); mSlopBounds = new Rect(bounds); - mSlopBounds.inset(-slop, -slop); + mSlopBounds.inset(-mSlop, -mSlop); mDelegateView = delegateView; } @@ -141,7 +143,7 @@ public class TouchDelegate { } else { // Offset event coordinates to be outside the target view (in case it does // something like tracking pressed state) - int slop = ViewConfiguration.getTouchSlop(); + int slop = mSlop; event.setLocation(-(slop * 2), -(slop * 2)); } handled = delegateView.dispatchTouchEvent(event); diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java index 85f482c..a51b564 100644 --- a/core/java/android/view/View.java +++ b/core/java/android/view/View.java @@ -60,12 +60,31 @@ import java.util.Arrays; /** * <p> - * The <code>View</code> class represents the basic UI building block. A view + * This class represents the basic building block for user interface components. A View * occupies a rectangular area on the screen and is responsible for drawing and - * event handling. <code>View</code> is the base class for <em>widgets</em>, - * used to create interactive graphical user interfaces. + * event handling. View is the base class for <em>widgets</em>, which are + * used to create interactive UI components (buttons, text fields, etc.). The + * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which + * are invisible containers that hold other Views (or other ViewGroups) and define + * their layout properties. * </p> * + * <div class="special"> + * <p>For an introduction to using this class to develop your + * application's user interface, read the Developer Guide documentation on + * <strong><a href="{@docRoot}guide/topics/ui/index.html">User Interface</a></strong>. Special topics + * include: + * <br/><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a> + * <br/><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a> + * <br/><a href="{@docRoot}guide/topics/ui/layout-objects.html">Common Layout Objects</a> + * <br/><a href="{@docRoot}guide/topics/ui/binding.html">Binding to Data with AdapterView</a> + * <br/><a href="{@docRoot}guide/topics/ui/ui-events.html">Handling UI Events</a> + * <br/><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a> + * <br/><a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a> + * <br/><a href="{@docRoot}guide/topics/ui/how-android-draws.html">How Android Draws Views</a>. + * </p> + * </div> + * * <a name="Using"></a> * <h3>Using Views</h3> * <p> @@ -1308,6 +1327,14 @@ public class View implements Drawable.Callback, KeyEvent.Callback { static final int HAS_BOUNDS = 0x00000010; /** {@hide} */ static final int DRAWN = 0x00000020; + /** + * When this flag is set, this view is running an animation on behalf of its + * children and should therefore not cancel invalidate requests, even if they + * lie outside of this view's bounds. + * + * {@hide} + */ + static final int DRAW_ANIMATION = 0x00000040; /** {@hide} */ static final int SKIP_DRAW = 0x00000080; /** {@hide} */ @@ -1353,8 +1380,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback { */ static final int SCROLL_CONTAINER_ADDED = 0x00100000; - // Note: flag 0x00000040 is available - /** * The parent this view is attached to. * {@hide} @@ -1559,6 +1584,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { private int mNextFocusDownId = View.NO_ID; private CheckForLongPress mPendingCheckForLongPress; + private UnsetPressedState mUnsetPressedState; /** * Whether the long press's action has been invoked. The tap's action is invoked on the @@ -1898,7 +1924,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback { initScrollCache(); mScrollCache.fadingEdgeLength = a.getDimensionPixelSize( - R.styleable.View_fadingEdgeLength, ViewConfiguration.getFadingEdgeLength()); + R.styleable.View_fadingEdgeLength, + ViewConfiguration.get(mContext).getScaledFadingEdgeLength()); } /** @@ -2013,36 +2040,38 @@ public class View implements Drawable.Callback, KeyEvent.Callback { mScrollCache.scrollBar = new ScrollBarDrawable(); } - mScrollCache.scrollBarSize = a.getDimensionPixelSize( + final ScrollabilityCache scrollabilityCache = mScrollCache; + + scrollabilityCache.scrollBarSize = a.getDimensionPixelSize( com.android.internal.R.styleable.View_scrollbarSize, - ViewConfiguration.getScrollBarSize()); + ViewConfiguration.get(mContext).getScaledScrollBarSize()); Drawable track = a.getDrawable(R.styleable.View_scrollbarTrackHorizontal); - mScrollCache.scrollBar.setHorizontalTrackDrawable(track); + scrollabilityCache.scrollBar.setHorizontalTrackDrawable(track); Drawable thumb = a.getDrawable(R.styleable.View_scrollbarThumbHorizontal); if (thumb != null) { - mScrollCache.scrollBar.setHorizontalThumbDrawable(thumb); + scrollabilityCache.scrollBar.setHorizontalThumbDrawable(thumb); } boolean alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawHorizontalTrack, false); if (alwaysDraw) { - mScrollCache.scrollBar.setAlwaysDrawHorizontalTrack(true); + scrollabilityCache.scrollBar.setAlwaysDrawHorizontalTrack(true); } track = a.getDrawable(R.styleable.View_scrollbarTrackVertical); - mScrollCache.scrollBar.setVerticalTrackDrawable(track); + scrollabilityCache.scrollBar.setVerticalTrackDrawable(track); thumb = a.getDrawable(R.styleable.View_scrollbarThumbVertical); if (thumb != null) { - mScrollCache.scrollBar.setVerticalThumbDrawable(thumb); + scrollabilityCache.scrollBar.setVerticalThumbDrawable(thumb); } alwaysDraw = a.getBoolean(R.styleable.View_scrollbarAlwaysDrawVerticalTrack, false); if (alwaysDraw) { - mScrollCache.scrollBar.setAlwaysDrawVerticalTrack(true); + scrollabilityCache.scrollBar.setAlwaysDrawVerticalTrack(true); } // Re-apply user/background padding so that scrollbar(s) get added @@ -2056,7 +2085,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { */ private void initScrollCache() { if (mScrollCache == null) { - mScrollCache = new ScrollabilityCache(); + mScrollCache = new ScrollabilityCache(ViewConfiguration.get(mContext)); } } @@ -2635,6 +2664,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { */ public void setVisibility(int visibility) { setFlags(visibility, VISIBILITY_MASK); + if (mBGDrawable != null) mBGDrawable.setVisible(visibility == VISIBLE, false); } /** @@ -3410,6 +3440,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { } void performCollectViewAttributes(int visibility) { + //noinspection PointlessBitwiseExpression if (((visibility | mViewFlags) & (VISIBILITY_MASK | KEEP_SCREEN_ON)) == (VISIBLE | KEEP_SCREEN_ON)) { mAttachInfo.mKeepScreenOn = true; @@ -3708,10 +3739,13 @@ public class View implements Drawable.Callback, KeyEvent.Callback { } } - final UnsetPressedState unsetPressedState = new UnsetPressedState(); - if (!post(unsetPressedState)) { + if (mUnsetPressedState == null) { + mUnsetPressedState = new UnsetPressedState(); + } + + if (!post(mUnsetPressedState)) { // If the post failed, unpress right now - unsetPressedState.run(); + mUnsetPressedState.run(); } } break; @@ -3734,7 +3768,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { final int y = (int) event.getY(); // Be lenient about moving outside of buttons - int slop = ViewConfiguration.getTouchSlop(); + int slop = ViewConfiguration.get(mContext).getScaledTouchSlop(); if ((x < 0 - slop) || (x >= getWidth() + slop) || (y < 0 - slop) || (y >= getHeight() + slop)) { // Outside button @@ -4413,14 +4447,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * @see #invalidate() */ public void postInvalidate() { - // We try only with the AttachInfo because there's no point in invalidating - // if we are not attached to our window - if (mAttachInfo != null) { - Message msg = Message.obtain(); - msg.what = AttachInfo.INVALIDATE_MSG; - msg.obj = this; - mAttachInfo.mHandler.sendMessage(msg); - } + postInvalidateDelayed(0); } /** @@ -4436,16 +4463,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * @see #invalidate(Rect) */ public void postInvalidate(int left, int top, int right, int bottom) { - // We try only with the AttachInfo because there's no point in invalidating - // if we are not attached to our window - if (mAttachInfo != null) { - Message msg = Message.obtain(); - msg.what = AttachInfo.INVALIDATE_RECT_MSG; - msg.obj = this; - msg.arg1 = (left << 16) | (top & 0xFFFF); - msg.arg2 = (right << 16) | (bottom & 0xFFFF); - mAttachInfo.mHandler.sendMessage(msg); - } + postInvalidateDelayed(0, left, top, right, bottom); } /** @@ -4477,16 +4495,22 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * @param right The right coordinate of the rectangle to invalidate. * @param bottom The bottom coordinate of the rectangle to invalidate. */ - public void postInvalidateDelayed(long delayMilliseconds, int left, int top - , int right, int bottom) { + public void postInvalidateDelayed(long delayMilliseconds, int left, int top, + int right, int bottom) { + // We try only with the AttachInfo because there's no point in invalidating // if we are not attached to our window if (mAttachInfo != null) { - Message msg = Message.obtain(); + final AttachInfo.InvalidateInfo info = AttachInfo.InvalidateInfo.acquire(); + info.target = this; + info.left = left; + info.top = top; + info.right = right; + info.bottom = bottom; + + final Message msg = Message.obtain(); msg.what = AttachInfo.INVALIDATE_RECT_MSG; - msg.obj = this; - msg.arg1 = (left << 16) | (top & 0xFFFF); - msg.arg2 = (right << 16) | (bottom & 0xFFFF); + msg.obj = info; mAttachInfo.mHandler.sendMessageDelayed(msg, delayMilliseconds); } } @@ -4865,7 +4889,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback { final boolean drawHorizontalScrollBar = (viewFlags & SCROLLBARS_HORIZONTAL) == SCROLLBARS_HORIZONTAL; final boolean drawVerticalScrollBar = - (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL; + (viewFlags & SCROLLBARS_VERTICAL) == SCROLLBARS_VERTICAL + && !isVerticalScrollBarHidden(); if (drawVerticalScrollBar || drawHorizontalScrollBar) { final int width = mRight - mLeft; @@ -4887,6 +4912,16 @@ public class View implements Drawable.Callback, KeyEvent.Callback { } } } + + /** + * Override this if the vertical scrollbar needs to be hidden in a subclass, like when + * FastScroller is visible. + * @return whether to temporarily hide the vertical scrollbar + * @hide + */ + protected boolean isVerticalScrollBarHidden() { + return false; + } /** * <p>Draw the horizontal scrollbar if @@ -5022,6 +5057,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { if (mPendingCheckForLongPress != null) { removeCallbacks(mPendingCheckForLongPress); } + destroyDrawingCache(); } /** @@ -5408,7 +5444,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback { if (width <= 0 || height <= 0 || (width * height * (opaque ? 2 : 4) >= // Projected bitmap size in bytes - ViewConfiguration.getMaximumDrawingCacheSize())) { + ViewConfiguration.get(mContext).getScaledMaximumDrawingCacheSize())) { if (mDrawingCache != null) { mDrawingCache.recycle(); } @@ -5485,9 +5521,10 @@ public class View implements Drawable.Callback, KeyEvent.Callback { final int restoreCount = canvas.save(); canvas.translate(-mScrollX, -mScrollY); + mPrivateFlags |= DRAWN; + // Fast path for layouts with no backgrounds if ((mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { - mPrivateFlags |= DRAWN; if (ViewDebug.TRACE_HIERARCHY) { ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); } @@ -5616,6 +5653,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback { ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); } + mPrivateFlags |= DRAWN; + /* * Draw traversal performs several drawing steps which must be executed * in the appropriate order: @@ -5656,7 +5695,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback { boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0; if (!verticalEdges && !horizontalEdges) { // Step 3, draw the content - mPrivateFlags |= DRAWN; onDraw(canvas); // Step 4, draw the children @@ -5760,7 +5798,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback { } // Step 3, draw the content - mPrivateFlags |= DRAWN; onDraw(canvas); // Step 4, draw the children @@ -7671,6 +7708,67 @@ public class View implements Drawable.Callback, KeyEvent.Callback { void playSoundEffect(int effectId); } + /** + * InvalidateInfo is used to post invalidate(int, int, int, int) messages + * to a Handler. This class contains the target (View) to invalidate and + * the coordinates of the dirty rectangle. + * + * For performance purposes, this class also implements a pool of up to + * POOL_LIMIT objects that get reused. This reduces memory allocations + * whenever possible. + * + * The pool is implemented as a linked list of InvalidateInfo object with + * the root pointing to the next available InvalidateInfo. If the root + * is null (i.e. when all instances from the pool have been acquired), + * then a new InvalidateInfo is created and returned to the caller. + * + * An InvalidateInfo is sent back to the pool by calling its release() + * method. If the pool is full the object is simply discarded. + * + * This implementation follows the object pool pattern used in the + * MotionEvent class. + */ + static class InvalidateInfo { + private static final int POOL_LIMIT = 10; + private static final Object sLock = new Object(); + + private static int sAcquiredCount = 0; + private static InvalidateInfo sRoot; + + private InvalidateInfo next; + + View target; + + int left; + int top; + int right; + int bottom; + + static InvalidateInfo acquire() { + synchronized (sLock) { + if (sRoot == null) { + return new InvalidateInfo(); + } + + InvalidateInfo info = sRoot; + sRoot = info.next; + sAcquiredCount--; + + return info; + } + } + + void release() { + synchronized (sLock) { + if (sAcquiredCount < POOL_LIMIT) { + sAcquiredCount++; + next = sRoot; + sRoot = this; + } + } + } + } + final IWindowSession mSession; final IWindow mWindow; @@ -7839,18 +7937,21 @@ public class View implements Drawable.Callback, KeyEvent.Callback { * instances of View.</p> */ private static class ScrollabilityCache { - public int fadingEdgeLength = ViewConfiguration.getFadingEdgeLength(); + public int fadingEdgeLength; - public int scrollBarSize = ViewConfiguration.getScrollBarSize(); + public int scrollBarSize; public ScrollBarDrawable scrollBar; public final Paint paint; public final Matrix matrix; public Shader shader; - private int mLastColor = 0; + private int mLastColor; + + public ScrollabilityCache(ViewConfiguration configuration) { + fadingEdgeLength = configuration.getScaledFadingEdgeLength(); + scrollBarSize = configuration.getScaledScrollBarSize(); - public ScrollabilityCache() { paint = new Paint(); matrix = new Matrix(); // use use a height of 1, and then wack the matrix each time we diff --git a/core/java/android/view/ViewConfiguration.java b/core/java/android/view/ViewConfiguration.java index b7110ce..7153ea1 100644 --- a/core/java/android/view/ViewConfiguration.java +++ b/core/java/android/view/ViewConfiguration.java @@ -16,17 +16,19 @@ package android.view; +import android.content.Context; +import android.util.DisplayMetrics; +import android.util.SparseArray; + /** * Contains methods to standard constants used in the UI for timeouts, sizes, and distances. - * */ public class ViewConfiguration { - /** * Defines the width of the horizontal scrollbar and the height of the vertical scrollbar in * pixels */ - private static final int SCROLL_BAR_SIZE = 6; + private static final int SCROLL_BAR_SIZE = 10; /** * Defines the length of the fading edges in pixels @@ -83,6 +85,11 @@ public class ViewConfiguration { private static final int TOUCH_SLOP = 12; /** + * Distance between the first touch and second touch to still be considered a double tap + */ + private static final int DOUBLE_TAP_SLOP = 100; + + /** * Distance a touch needs to be outside of a window's bounds for it to * count as outside for purposes of dismissing the window. */ @@ -97,28 +104,124 @@ public class ViewConfiguration { * The maximum size of View's drawing cache, expressed in bytes. This size * should be at least equal to the size of the screen in ARGB888 format. */ - private static final int MAXIMUM_DRAWING_CACHE_SIZE = 320 * 480 * 4; // One HVGA screen, ARGB8888 + @Deprecated + private static final int MAXIMUM_DRAWING_CACHE_SIZE = 320 * 480 * 4; // HVGA screen, ARGB8888 /** * The coefficient of friction applied to flings/scrolls. */ private static float SCROLL_FRICTION = 0.015f; + private final int mEdgeSlop; + private final int mFadingEdgeLength; + private final int mMinimumFlingVelocity; + private final int mScrollbarSize; + private final int mTouchSlop; + private final int mDoubleTapSlop; + private final int mWindowTouchSlop; + private final int mMaximumDrawingCacheSize; + + private static final SparseArray<ViewConfiguration> sConfigurations = + new SparseArray<ViewConfiguration>(2); + + /** + * @deprecated Use {@link android.view.ViewConfiguration#get(android.content.Context)} instead. + */ + @Deprecated + public ViewConfiguration() { + mEdgeSlop = EDGE_SLOP; + mFadingEdgeLength = FADING_EDGE_LENGTH; + mMinimumFlingVelocity = MINIMUM_FLING_VELOCITY; + mScrollbarSize = SCROLL_BAR_SIZE; + mTouchSlop = TOUCH_SLOP; + mDoubleTapSlop = DOUBLE_TAP_SLOP; + mWindowTouchSlop = WINDOW_TOUCH_SLOP; + //noinspection deprecation + mMaximumDrawingCacheSize = MAXIMUM_DRAWING_CACHE_SIZE; + } + + /** + * Creates a new configuration for the specified context. The configuration depends on + * various parameters of the context, like the dimension of the display or the density + * of the display. + * + * @param context The application context used to initialize this view configuration. + * + * @see #get(android.content.Context) + * @see android.util.DisplayMetrics + */ + private ViewConfiguration(Context context) { + final DisplayMetrics metrics = context.getResources().getDisplayMetrics(); + final float density = metrics.density; + + mEdgeSlop = (int) (density * EDGE_SLOP + 0.5f); + mFadingEdgeLength = (int) (density * FADING_EDGE_LENGTH + 0.5f); + mMinimumFlingVelocity = (int) (density * MINIMUM_FLING_VELOCITY + 0.5f); + mScrollbarSize = (int) (density * SCROLL_BAR_SIZE + 0.5f); + mTouchSlop = (int) (density * TOUCH_SLOP + 0.5f); + mDoubleTapSlop = (int) (density * DOUBLE_TAP_SLOP + 0.5f); + mWindowTouchSlop = (int) (density * WINDOW_TOUCH_SLOP + 0.5f); + + // Size of the screen in bytes, in ARGB_8888 format + mMaximumDrawingCacheSize = 4 * metrics.widthPixels * metrics.heightPixels; + } + + /** + * Returns a configuration for the specified context. The configuration depends on + * various parameters of the context, like the dimension of the display or the + * density of the display. + * + * @param context The application context used to initialize the view configuration. + */ + public static ViewConfiguration get(Context context) { + final DisplayMetrics metrics = context.getResources().getDisplayMetrics(); + final int density = (int) (100.0f * metrics.density); + + ViewConfiguration configuration = sConfigurations.get(density); + if (configuration == null) { + configuration = new ViewConfiguration(context); + sConfigurations.put(density, configuration); + } + + return configuration; + } + /** * @return The width of the horizontal scrollbar and the height of the vertical * scrollbar in pixels + * + * @deprecated Use {@link #getScaledScrollBarSize()} instead. */ + @Deprecated public static int getScrollBarSize() { return SCROLL_BAR_SIZE; } /** + * @return The width of the horizontal scrollbar and the height of the vertical + * scrollbar in pixels + */ + public int getScaledScrollBarSize() { + return mScrollbarSize; + } + + /** * @return Defines the length of the fading edges in pixels + * + * @deprecated Use {@link #getScaledFadingEdgeLength()} instead. */ + @Deprecated public static int getFadingEdgeLength() { return FADING_EDGE_LENGTH; } - + + /** + * @return Defines the length of the fading edges in pixels + */ + public int getScaledFadingEdgeLength() { + return mFadingEdgeLength; + } + /** * @return Defines the duration in milliseconds of the pressed state in child * components. @@ -156,44 +259,121 @@ public class ViewConfiguration { /** * @return Inset in pixels to look for touchable content when the user touches the edge of the * screen + * + * @deprecated Use {@link #getScaledEdgeSlop()} instead. */ + @Deprecated public static int getEdgeSlop() { return EDGE_SLOP; } - + + /** + * @return Inset in pixels to look for touchable content when the user touches the edge of the + * screen + */ + public int getScaledEdgeSlop() { + return mEdgeSlop; + } + /** * @return Distance a touch can wander before we think the user is scrolling in pixels + * + * @deprecated Use {@link #getScaledTouchSlop()} instead. */ + @Deprecated public static int getTouchSlop() { return TOUCH_SLOP; } + + /** + * @return Distance a touch can wander before we think the user is scrolling in pixels + */ + public int getScaledTouchSlop() { + return mTouchSlop; + } + + /** + * @return Distance between the first touch and second touch to still be + * considered a double tap + * @deprecated Use {@link #getScaledDoubleTapSlop()} instead. + * @hide The only client of this should be GestureDetector, which needs this + * for clients that still use its deprecated constructor. + */ + @Deprecated + public static int getDoubleTapSlop() { + return DOUBLE_TAP_SLOP; + } /** + * @return Distance between the first touch and second touch to still be + * considered a double tap + * @hide pending API council + */ + public int getScaledDoubleTapSlop() { + return mDoubleTapSlop; + } + + /** * @return Distance a touch must be outside the bounds of a window for it * to be counted as outside the window for purposes of dismissing that * window. + * + * @deprecated Use {@link #getScaledWindowTouchSlop()} instead. */ + @Deprecated public static int getWindowTouchSlop() { return WINDOW_TOUCH_SLOP; } + + /** + * @return Distance a touch must be outside the bounds of a window for it + * to be counted as outside the window for purposes of dismissing that + * window. + */ + public int getScaledWindowTouchSlop() { + return mWindowTouchSlop; + } /** - * Minimum velocity to initiate a fling, as measured in pixels per second + * @return Minimum velocity to initiate a fling, as measured in pixels per second. + * + * @deprecated Use {@link #getScaledMinimumFlingVelocity()} instead. */ - public static int getMinimumFlingVelocity() { - return MINIMUM_FLING_VELOCITY; + @Deprecated + public static int getMinimumFlingVelocity() { + return MINIMUM_FLING_VELOCITY; + } + + /** + * @return Minimum velocity to initiate a fling, as measured in pixels per second. + */ + public int getScaledMinimumFlingVelocity() { + return mMinimumFlingVelocity; } /** * The maximum drawing cache size expressed in bytes. * * @return the maximum size of View's drawing cache expressed in bytes + * + * @deprecated Use {@link #getScaledMaximumDrawingCacheSize()} instead. */ + @Deprecated public static int getMaximumDrawingCacheSize() { + //noinspection deprecation return MAXIMUM_DRAWING_CACHE_SIZE; } /** + * The maximum drawing cache size expressed in bytes. + * + * @return the maximum size of View's drawing cache expressed in bytes + */ + public int getScaledMaximumDrawingCacheSize() { + return mMaximumDrawingCacheSize; + } + + /** * The amount of time that the zoom controls should be * displayed on the screen expressed in milliseconds. * diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java index e26a19e..c758662 100644 --- a/core/java/android/view/ViewGroup.java +++ b/core/java/android/view/ViewGroup.java @@ -25,6 +25,7 @@ import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Region; +import android.graphics.RectF; import android.os.Parcelable; import android.util.AttributeSet; import android.util.EventLog; @@ -74,6 +75,7 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager // The current transformation to apply on the child being drawn private Transformation mChildTransformation; + private RectF mInvalidateRegion; // Target of Motion events private View mMotionTarget; @@ -1199,6 +1201,8 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager } + // We will draw our child's animation, let's reset the flag + mPrivateFlags &= ~DRAW_ANIMATION; mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED; boolean more = false; @@ -1328,8 +1332,15 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager boolean concatMatrix = false; if (a != null) { - if (!a.isInitialized()) { + if (mInvalidateRegion == null) { + mInvalidateRegion = new RectF(); + } + final RectF region = mInvalidateRegion; + + final boolean initialized = a.isInitialized(); + if (!initialized) { a.initialize(cr - cl, cb - ct, getWidth(), getHeight()); + a.initializeInvalidateRegion(cl, ct, cr, cb); child.onAnimationStart(); } @@ -1347,10 +1358,22 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager FLAG_OPTIMIZE_INVALIDATE) { mGroupFlags |= FLAG_INVALIDATE_REQUIRED; } else if ((flags & FLAG_INVALIDATE_REQUIRED) == 0) { + // The child need to draw an animation, potentially offscreen, so + // make sure we do not cancel invalidate requests + mPrivateFlags |= DRAW_ANIMATION; invalidate(cl, ct, cr, cb); } } else { - mGroupFlags |= FLAG_INVALIDATE_REQUIRED; + a.getInvalidateRegion(cl, ct, cr, cb, region, transformToApply); + + // The child need to draw an animation, potentially offscreen, so + // make sure we do not cancel invalidate requests + mPrivateFlags |= DRAW_ANIMATION; + // Enlarge the invalidate region to account for rounding errors + // in Animation#getInvalidateRegion(); Using 0.5f is unfortunately + // not enough for some types of animations (e.g. scale down.) + invalidate((int) (region.left - 1.0f), (int) (region.top - 1.0f), + (int) (region.right + 1.0f), (int) (region.bottom + 1.0f)); } } } else if ((flags & FLAG_SUPPORT_STATIC_TRANSFORMATIONS) == @@ -1367,7 +1390,8 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager } } - if (!concatMatrix && canvas.quickReject(cl, ct, cr, cb, Canvas.EdgeType.BW)) { + if (!concatMatrix && canvas.quickReject(cl, ct, cr, cb, Canvas.EdgeType.BW) && + (child.mPrivateFlags & DRAW_ANIMATION) == 0) { return more; } @@ -1435,10 +1459,13 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager } } + // Clear the flag as early as possible to allow draw() implementations + // to call invalidate() successfully when doing animations + child.mPrivateFlags |= DRAWN; + if (hasNoCache) { // Fast path for layouts with no backgrounds if ((child.mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { - child.mPrivateFlags |= DRAWN; if (ViewDebug.TRACE_HIERARCHY) { ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); } @@ -1455,7 +1482,6 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager cachePaint.setAlpha(255); mGroupFlags &= ~FLAG_ALPHA_LOWER_THAN_ONE; } - child.mPrivateFlags |= DRAWN; if (ViewRoot.PROFILE_DRAWING) { EventLog.writeEvent(60003, hashCode()); } @@ -1922,8 +1948,7 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager LayoutAnimationController.AnimationParameters animationParams = params.layoutAnimationParameters; if (animationParams == null) { - animationParams = - new LayoutAnimationController.AnimationParameters(); + animationParams = new LayoutAnimationController.AnimationParameters(); params.layoutAnimationParameters = animationParams; } @@ -2278,8 +2303,16 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager final int[] location = attachInfo.mInvalidateChildLocation; location[CHILD_LEFT_INDEX] = child.mLeft; location[CHILD_TOP_INDEX] = child.mTop; + + // If the child is drawing an animation, we want to copy this flag onto + // ourselves and the parent to make sure the invalidate request goes + // through + final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION; do { + if (drawAnimation && parent instanceof View) { + ((View) parent).mPrivateFlags |= DRAW_ANIMATION; + } parent = parent.invalidateChildInParent(location, dirty); } while (parent != null); } @@ -2307,7 +2340,8 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager final int left = mLeft; final int top = mTop; - if (dirty.intersect(0, 0, mRight - left, mBottom - top)) { + if (dirty.intersect(0, 0, mRight - left, mBottom - top) || + (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) { mPrivateFlags &= ~DRAWING_CACHE_VALID; location[CHILD_LEFT_INDEX] = left; diff --git a/core/java/android/view/ViewRoot.java b/core/java/android/view/ViewRoot.java index 9e0289a..4e46397 100644 --- a/core/java/android/view/ViewRoot.java +++ b/core/java/android/view/ViewRoot.java @@ -177,13 +177,14 @@ public final class ViewRoot extends Handler implements ViewParent, boolean mUseGL; boolean mGlWanted; + final ViewConfiguration mViewConfiguration; + /** * see {@link #playSoundEffect(int)} */ AudioManager mAudioManager; - public ViewRoot(Context context) { super(); @@ -224,6 +225,7 @@ public final class ViewRoot extends Handler implements ViewParent, mSurface = new Surface(); mAdded = false; mAttachInfo = new View.AttachInfo(sWindowSession, mWindow, this, this); + mViewConfiguration = ViewConfiguration.get(context); } @Override @@ -1101,6 +1103,7 @@ public final class ViewRoot extends Handler implements ViewParent, mAttachInfo.mDrawingTime = SystemClock.uptimeMillis(); canvas.translate(0, -yoff); + mView.mPrivateFlags |= View.DRAWN; mView.draw(canvas); canvas.translate(0, yoff); @@ -1139,6 +1142,8 @@ public final class ViewRoot extends Handler implements ViewParent, Canvas canvas; try { canvas = surface.lockCanvas(dirty); + // TODO: Do this in native + canvas.setDensityScale(mView.getResources().getDisplayMetrics().density); } catch (Surface.OutOfResourcesException e) { Log.e("ViewRoot", "OutOfResourcesException locking surface", e); // TODO: we should ask the window manager to do something! @@ -1175,6 +1180,7 @@ public final class ViewRoot extends Handler implements ViewParent, dirty.setEmpty(); mAttachInfo.mDrawingTime = SystemClock.uptimeMillis(); canvas.translate(0, -yoff); + mView.mPrivateFlags |= View.DRAWN; mView.draw(canvas); canvas.translate(0, yoff); @@ -1197,6 +1203,23 @@ public final class ViewRoot extends Handler implements ViewParent, if (LOCAL_LOGV) { Log.v("ViewRoot", "Surface " + surface + " unlockCanvasAndPost"); } + + } else if (mWidth == 0 || mHeight == 0) { + // This is a special case where a window dimension is 0 -- we + // normally wouldn't draw anything because we have an empty + // dirty rect, but the surface flinger may be waiting for us to + // draw the window before it stops freezing the screen, so we + // need to diddle it like this to keep it from getting stuck. + Canvas canvas; + try { + canvas = surface.lockCanvas(dirty); + } catch (Surface.OutOfResourcesException e) { + Log.e("ViewRoot", "OutOfResourcesException locking surface", e); + // TODO: we should ask the window manager to do something! + // for now we just do nothing + return; + } + surface.unlockCanvasAndPost(canvas); } if (scrolling) { @@ -1414,6 +1437,7 @@ public final class ViewRoot extends Handler implements ViewParent, public final static int FINISHED_EVENT = 1010; public final static int DISPATCH_KEY_FROM_IME = 1011; public final static int FINISH_INPUT_CONNECTION = 1012; + public final static int CHECK_FOCUS = 1013; @Override public void handleMessage(Message msg) { @@ -1422,11 +1446,9 @@ public final class ViewRoot extends Handler implements ViewParent, ((View) msg.obj).invalidate(); break; case View.AttachInfo.INVALIDATE_RECT_MSG: - int left = msg.arg1 >>> 16; - int top = msg.arg1 & 0xFFFF; - int right = msg.arg2 >>> 16; - int bottom = msg.arg2 & 0xFFFF; - ((View) msg.obj).invalidate(left, top, right, bottom); + final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; + info.target.invalidate(info.left, info.top, info.right, info.bottom); + info.release(); break; case DO_TRAVERSAL: if (mProfile) { @@ -1478,7 +1500,7 @@ public final class ViewRoot extends Handler implements ViewParent, event.offsetLocation(0, mCurScrollY); handled = mView.dispatchTouchEvent(event); if (!handled && isDown) { - int edgeSlop = ViewConfiguration.getEdgeSlop(); + int edgeSlop = mViewConfiguration.getScaledEdgeSlop(); final int edgeFlags = event.getEdgeFlags(); int direction = View.FOCUS_UP; @@ -1615,7 +1637,7 @@ public final class ViewRoot extends Handler implements ViewParent, dispatchDetachedFromWindow(); break; case DISPATCH_KEY_FROM_IME: - if (LOCAL_LOGV) Log.v( + if (true) Log.v( "ViewRoot", "Dispatching key " + msg.obj + " from IME to " + mView); deliverKeyEventToViewHierarchy((KeyEvent)msg.obj, false); @@ -1626,6 +1648,12 @@ public final class ViewRoot extends Handler implements ViewParent, imm.reportFinishInputConnection((InputConnection)msg.obj); } } break; + case CHECK_FOCUS: { + InputMethodManager imm = InputMethodManager.peekInstance(); + if (imm != null) { + imm.checkFocus((View)msg.obj); + } + } break; } } @@ -2042,8 +2070,10 @@ public final class ViewRoot extends Handler implements ViewParent, } private void deliverKeyEvent(KeyEvent event, boolean sendDone) { - boolean handled = false; - handled = mView.dispatchKeyEventPreIme(event); + // If mView is null, we just consume the key event because it doesn't + // make sense to do anything else with it. + boolean handled = mView != null + ? mView.dispatchKeyEventPreIme(event) : true; if (handled) { if (sendDone) { if (LOCAL_LOGV) Log.v( @@ -2061,7 +2091,7 @@ public final class ViewRoot extends Handler implements ViewParent, if (WindowManager.LayoutParams.mayUseInputMethod( mWindowAttributes.flags)) { InputMethodManager imm = InputMethodManager.peekInstance(); - if (imm != null && mView != null && imm.isActive()) { + if (imm != null && mView != null) { int seq = enqueuePendingEvent(event, sendDone); if (DEBUG_IMF) Log.v(TAG, "Sending key event to IME: seq=" + seq + " event=" + event); @@ -2748,7 +2778,6 @@ public final class ViewRoot extends Handler implements ViewParent, synchronized (mActions) { final ArrayList<HandlerAction> actions = mActions; - final int count = actions.size(); while (actions.remove(handlerAction)) { // Keep going @@ -2776,7 +2805,20 @@ public final class ViewRoot extends Handler implements ViewParent, @Override public boolean equals(Object o) { - return action.equals(o); + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + HandlerAction that = (HandlerAction) o; + + return !(action != null ? !action.equals(that.action) : that.action != null); + + } + + @Override + public int hashCode() { + int result = action != null ? action.hashCode() : 0; + result = 31 * result + (int) (delay ^ (delay >>> 32)); + return result; } } } diff --git a/core/java/android/view/VolumePanel.java b/core/java/android/view/VolumePanel.java index f4d0fde..a573983 100644 --- a/core/java/android/view/VolumePanel.java +++ b/core/java/android/view/VolumePanel.java @@ -16,18 +16,17 @@ package android.view; -import android.media.ToneGenerator; -import android.media.AudioManager; -import android.media.AudioService; -import android.media.AudioSystem; +import android.bluetooth.HeadsetBase; import android.content.Context; import android.content.Intent; -import android.content.IntentFilter; import android.content.res.Resources; +import android.media.AudioManager; +import android.media.AudioService; +import android.media.AudioSystem; +import android.media.ToneGenerator; import android.os.Handler; import android.os.Message; import android.os.Vibrator; -import android.text.TextUtils; import android.util.Config; import android.util.Log; import android.widget.ImageView; @@ -39,7 +38,7 @@ import android.widget.Toast; * Handle the volume up and down keys. * * This code really should be moved elsewhere. - * + * * @hide */ public class VolumePanel extends Handler @@ -54,7 +53,7 @@ public class VolumePanel extends Handler * PhoneWindow will implement this part. */ public static final int PLAY_SOUND_DELAY = 300; - + /** * The delay before vibrating. This small period exists so if the user is * moving to silent mode, it will not emit a short vibrate (it normally @@ -64,28 +63,30 @@ public class VolumePanel extends Handler public static final int VIBRATE_DELAY = 300; private static final int VIBRATE_DURATION = 300; - private static final int BEEP_DURATION = 150; + private static final int BEEP_DURATION = 150; private static final int MAX_VOLUME = 100; private static final int FREE_DELAY = 10000; - + private static final int MSG_VOLUME_CHANGED = 0; private static final int MSG_FREE_RESOURCES = 1; private static final int MSG_PLAY_SOUND = 2; private static final int MSG_STOP_SOUNDS = 3; private static final int MSG_VIBRATE = 4; - + private static final int RINGTONE_VOLUME_TEXT = com.android.internal.R.string.volume_ringtone; private static final int MUSIC_VOLUME_TEXT = com.android.internal.R.string.volume_music; private static final int INCALL_VOLUME_TEXT = com.android.internal.R.string.volume_call; private static final int ALARM_VOLUME_TEXT = com.android.internal.R.string.volume_alarm; private static final int UNKNOWN_VOLUME_TEXT = com.android.internal.R.string.volume_unknown; private static final int NOTIFICATION_VOLUME_TEXT = - com.android.internal.R.string.volume_notification; - + com.android.internal.R.string.volume_notification; + private static final int BLUETOOTH_INCALL_VOLUME_TEXT = + com.android.internal.R.string.volume_bluetooth_call; + protected Context mContext; private AudioManager mAudioManager; protected AudioService mAudioService; - + private final Toast mToast; private final View mView; private final TextView mMessage; @@ -117,13 +118,13 @@ public class VolumePanel extends Handler mToneGenerators = new ToneGenerator[AudioSystem.getNumStreamTypes()]; mVibrator = new Vibrator(); } - + public void postVolumeChanged(int streamType, int flags) { if (hasMessages(MSG_VOLUME_CHANGED)) return; removeMessages(MSG_FREE_RESOURCES); obtainMessage(MSG_VOLUME_CHANGED, streamType, flags).sendToTarget(); } - + /** * Override this if you have other work to do when the volume changes (for * example, vibrating, playing a sound, etc.). Make sure to call through to @@ -132,31 +133,31 @@ public class VolumePanel extends Handler protected void onVolumeChanged(int streamType, int flags) { if (LOGD) Log.d(TAG, "onVolumeChanged(streamType: " + streamType + ", flags: " + flags + ")"); - + if ((flags & AudioManager.FLAG_SHOW_UI) != 0) { onShowVolumeChanged(streamType, flags); } - + if ((flags & AudioManager.FLAG_PLAY_SOUND) != 0) { removeMessages(MSG_PLAY_SOUND); sendMessageDelayed(obtainMessage(MSG_PLAY_SOUND, streamType, flags), PLAY_SOUND_DELAY); } - + if ((flags & AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE) != 0) { removeMessages(MSG_PLAY_SOUND); removeMessages(MSG_VIBRATE); onStopSounds(); } - + removeMessages(MSG_FREE_RESOURCES); - sendMessageDelayed(obtainMessage(MSG_FREE_RESOURCES), FREE_DELAY); + sendMessageDelayed(obtainMessage(MSG_FREE_RESOURCES), FREE_DELAY); } protected void onShowVolumeChanged(int streamType, int flags) { int index = mAudioService.getStreamVolume(streamType); int message = UNKNOWN_VOLUME_TEXT; int additionalMessage = 0; - + if (LOGD) { Log.d(TAG, "onShowVolumeChanged(streamType: " + streamType + ", flags: " + flags + "), index: " + index); @@ -166,13 +167,13 @@ public class VolumePanel extends Handler int max = mAudioService.getStreamMaxVolume(streamType); switch (streamType) { - + case AudioManager.STREAM_RING: { message = RINGTONE_VOLUME_TEXT; setRingerIcon(index); break; } - + case AudioManager.STREAM_MUSIC: { message = MUSIC_VOLUME_TEXT; if (mAudioManager.isBluetoothA2dpOn()) { @@ -184,7 +185,7 @@ public class VolumePanel extends Handler } break; } - + case AudioManager.STREAM_VOICE_CALL: { /* * For in-call voice call volume, there is no inaudible volume. @@ -194,13 +195,7 @@ public class VolumePanel extends Handler index++; max++; message = INCALL_VOLUME_TEXT; - if (mAudioManager.isBluetoothScoOn()) { - additionalMessage = - com.android.internal.R.string.volume_call_hint_playing_through_bluetooth; - setLargeIcon(com.android.internal.R.drawable.ic_volume_bluetooth_in_call); - } else { - setSmallIcon(index); - } + setSmallIcon(index); break; } @@ -209,12 +204,25 @@ public class VolumePanel extends Handler setSmallIcon(index); break; } - + case AudioManager.STREAM_NOTIFICATION: { message = NOTIFICATION_VOLUME_TEXT; setSmallIcon(index); break; } + + case AudioManager.STREAM_BLUETOOTH_SCO: { + /* + * For in-call voice call volume, there is no inaudible volume. + * Rescale the UI control so the progress bar doesn't go all + * the way to zero and don't show the mute icon. + */ + index++; + max++; + message = BLUETOOTH_INCALL_VOLUME_TEXT; + setLargeIcon(com.android.internal.R.drawable.ic_volume_bluetooth_in_call); + break; + } } String messageString = Resources.getSystem().getString(message); @@ -228,25 +236,25 @@ public class VolumePanel extends Handler mAdditionalMessage.setVisibility(View.VISIBLE); mAdditionalMessage.setText(Resources.getSystem().getString(additionalMessage)); } - + if (max != mLevel.getMax()) { mLevel.setMax(max); } mLevel.setProgress(index); - + mToast.setView(mView); mToast.setDuration(Toast.LENGTH_SHORT); mToast.setGravity(Gravity.TOP, 0, 0); mToast.show(); - + // Do a little vibrate if applicable (only when going into vibrate mode) - if ((flags & AudioManager.FLAG_VIBRATE) != 0 && + if ((flags & AudioManager.FLAG_VIBRATE) != 0 && mAudioService.isStreamAffectedByRingerMode(streamType) && mAudioService.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE && mAudioService.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER)) { sendMessageDelayed(obtainMessage(MSG_VIBRATE), VIBRATE_DELAY); } - + } protected void onPlaySound(int streamType, int flags) { @@ -256,7 +264,7 @@ public class VolumePanel extends Handler // Force stop right now onStopSounds(); } - + synchronized (this) { ToneGenerator toneGen = getOrCreateToneGenerator(streamType); toneGen.startTone(ToneGenerator.TONE_PROP_BEEP); @@ -266,7 +274,7 @@ public class VolumePanel extends Handler } protected void onStopSounds() { - + synchronized (this) { int numStreamTypes = AudioSystem.getNumStreamTypes(); for (int i = numStreamTypes - 1; i >= 0; i--) { @@ -277,17 +285,17 @@ public class VolumePanel extends Handler } } } - + protected void onVibrate() { - + // Make sure we ended up in vibrate ringer mode if (mAudioService.getRingerMode() != AudioManager.RINGER_MODE_VIBRATE) { return; } - + mVibrator.vibrate(VIBRATE_DURATION); } - + /** * Lock on this VolumePanel instance as long as you use the returned ToneGenerator. */ @@ -303,13 +311,13 @@ public class VolumePanel extends Handler /** * Makes the small icon visible, and hides the large icon. - * + * * @param index The volume index, where 0 means muted. */ private void setSmallIcon(int index) { mLargeStreamIcon.setVisibility(View.GONE); mSmallStreamIcon.setVisibility(View.VISIBLE); - + mSmallStreamIcon.setImageResource(index == 0 ? com.android.internal.R.drawable.ic_volume_off_small : com.android.internal.R.drawable.ic_volume_small); @@ -317,7 +325,7 @@ public class VolumePanel extends Handler /** * Makes the large image view visible with the given icon. - * + * * @param resId The icon to display. */ private void setLargeIcon(int resId) { @@ -329,7 +337,7 @@ public class VolumePanel extends Handler /** * Makes the ringer icon visible with an icon that is chosen * based on the current ringer mode. - * + * * @param index */ private void setRingerIcon(int index) { @@ -350,13 +358,13 @@ public class VolumePanel extends Handler } mLargeStreamIcon.setImageResource(icon); } - + protected void onFreeResources() { // We'll keep the views, just ditch the cached drawable and hence // bitmaps mSmallStreamIcon.setImageDrawable(null); mLargeStreamIcon.setImageDrawable(null); - + synchronized (this) { for (int i = mToneGenerators.length - 1; i >= 0; i--) { if (mToneGenerators[i] != null) { @@ -366,26 +374,26 @@ public class VolumePanel extends Handler } } } - + @Override public void handleMessage(Message msg) { switch (msg.what) { - + case MSG_VOLUME_CHANGED: { onVolumeChanged(msg.arg1, msg.arg2); break; } - + case MSG_FREE_RESOURCES: { onFreeResources(); break; } - + case MSG_STOP_SOUNDS: { onStopSounds(); break; } - + case MSG_PLAY_SOUND: { onPlaySound(msg.arg1, msg.arg2); break; @@ -395,8 +403,8 @@ public class VolumePanel extends Handler onVibrate(); break; } - + } } - + } diff --git a/core/java/android/view/Window.java b/core/java/android/view/Window.java index a68436b..428de67 100644 --- a/core/java/android/view/Window.java +++ b/core/java/android/view/Window.java @@ -525,6 +525,21 @@ public abstract class Window { } /** + * Specify custom animations to use for the window, as per + * {@link WindowManager.LayoutParams#windowAnimations + * WindowManager.LayoutParams.windowAnimations}. Providing anything besides + * 0 here will override the animations the window would + * normally retrieve from its theme. + */ + public void setWindowAnimations(int resId) { + final WindowManager.LayoutParams attrs = getAttributes(); + attrs.windowAnimations = resId; + if (mCallback != null) { + mCallback.onWindowAttributesChanged(attrs); + } + } + + /** * Specify an explicit soft input mode to use for the window, as per * {@link WindowManager.LayoutParams#softInputMode * WindowManager.LayoutParams.softInputMode}. Providing anything besides diff --git a/core/java/android/view/WindowManager.java b/core/java/android/view/WindowManager.java index 7e47ad1..d08a6fa 100644 --- a/core/java/android/view/WindowManager.java +++ b/core/java/android/view/WindowManager.java @@ -16,6 +16,7 @@ package android.view; +import android.content.pm.ActivityInfo; import android.graphics.PixelFormat; import android.os.IBinder; import android.os.Parcel; @@ -126,8 +127,6 @@ public interface WindowManager extends ViewManager { * @see #TYPE_APPLICATION_MEDIA * @see #TYPE_APPLICATION_SUB_PANEL * @see #TYPE_APPLICATION_ATTACHED_DIALOG - * @see #TYPE_INPUT_METHOD - * @see #TYPE_INPUT_METHOD_DIALOG * @see #TYPE_STATUS_BAR * @see #TYPE_SEARCH_BAR * @see #TYPE_PHONE @@ -645,6 +644,17 @@ public interface WindowManager extends ViewManager { */ public String packageName = null; + /** + * Specific orientation value for a window. + * May be any of the same values allowed + * for {@link android.content.pm.ActivityInfo#screenOrientation}. + * If not set, a default value of + * {@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_UNSPECIFIED} + * will be used. + */ + public int screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; + + public LayoutParams() { super(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); type = TYPE_APPLICATION; @@ -722,6 +732,7 @@ public interface WindowManager extends ViewManager { out.writeStrongBinder(token); out.writeString(packageName); TextUtils.writeToParcel(mTitle, out, parcelableFlags); + out.writeInt(screenOrientation); } public static final Parcelable.Creator<LayoutParams> CREATOR @@ -755,6 +766,7 @@ public interface WindowManager extends ViewManager { token = in.readStrongBinder(); packageName = in.readString(); mTitle = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); + screenOrientation = in.readInt(); } public static final int LAYOUT_CHANGED = 1<<0; @@ -767,6 +779,7 @@ public interface WindowManager extends ViewManager { public static final int ALPHA_CHANGED = 1<<7; public static final int MEMORY_TYPE_CHANGED = 1<<8; public static final int SOFT_INPUT_MODE_CHANGED = 1<<9; + public static final int SCREEN_ORIENTATION_CHANGED = 1<<10; public final int copyFrom(LayoutParams o) { int changes = 0; @@ -862,6 +875,10 @@ public interface WindowManager extends ViewManager { changes |= DIM_AMOUNT_CHANGED; } + if (screenOrientation != o.screenOrientation) { + screenOrientation = o.screenOrientation; + changes |= SCREEN_ORIENTATION_CHANGED; + } return changes; } @@ -907,6 +924,10 @@ public interface WindowManager extends ViewManager { sb.append(" wanim=0x"); sb.append(Integer.toHexString(windowAnimations)); } + if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) { + sb.append("or="); + sb.append(screenOrientation); + } sb.append('}'); return sb.toString(); } diff --git a/core/java/android/view/WindowManagerPolicy.java b/core/java/android/view/WindowManagerPolicy.java index 6af4915..542b35f 100644 --- a/core/java/android/view/WindowManagerPolicy.java +++ b/core/java/android/view/WindowManagerPolicy.java @@ -289,16 +289,18 @@ public interface WindowManagerPolicy { * Can be called by the policy to force a window to be hidden, * regardless of whether the client or window manager would like * it shown. Must be called with the window manager lock held. + * Returns true if {@link #showLw} was last called for the window. */ - public void hideLw(boolean doAnimation); + public boolean hideLw(boolean doAnimation); /** * Can be called to undo the effect of {@link #hideLw}, allowing a * window to be shown as long as the window manager and client would * also like it to be shown. Must be called with the window manager * lock held. + * Returns true if {@link #hideLw} was last called for the window. */ - public void showLw(boolean doAnimation); + public boolean showLw(boolean doAnimation); } /** No transition happening. */ @@ -735,10 +737,17 @@ public interface WindowManagerPolicy { * ActivityInfo.SCREEN_ORIENTATION_PORTRAIT}), return a surface * rotation. */ - public int rotationForOrientation(int orientation); + public int rotationForOrientation(int orientation, int lastRotation, + boolean displayEnabled); /** - * Called when the system is mostly done booting + * Called when the system is mostly done booting to dentermine whether + * the system should go into safe mode. + */ + public boolean detectSafeMode(); + + /** + * Called when the system is mostly done booting. */ public void systemReady(); diff --git a/core/java/android/view/animation/Animation.java b/core/java/android/view/animation/Animation.java index 9264398..c96b3e5 100644 --- a/core/java/android/view/animation/Animation.java +++ b/core/java/android/view/animation/Animation.java @@ -20,13 +20,14 @@ import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.TypedValue; +import android.graphics.RectF; /** * Abstraction for an Animation that can be applied to Views, Surfaces, or * other objects. See the {@link android.view.animation animation package * description file}. */ -public abstract class Animation { +public abstract class Animation implements Cloneable { /** * Repeat the animation indefinitely. */ @@ -174,8 +175,12 @@ public abstract class Animation { */ private int mZAdjustment; - // Indicates what was the last value returned by getTransformation() private boolean mMore = true; + private boolean mOneMoreTime = true; + + RectF mPreviousRegion = new RectF(); + Transformation mTransformation = new Transformation(); + Transformation mPreviousTransformation = new Transformation(); /** * Creates a new animation with a duration of 0ms, the default interpolator, with @@ -217,16 +222,28 @@ public abstract class Animation { a.recycle(); } + @Override + protected Animation clone() throws CloneNotSupportedException { + final Animation animation = (Animation) super.clone(); + animation.mPreviousRegion = new RectF(); + animation.mTransformation = new Transformation(); + animation.mPreviousTransformation = new Transformation(); + return animation; + } + /** * Reset the initialization state of this animation. * * @see #initialize(int, int, int, int) */ public void reset() { + mPreviousRegion.setEmpty(); + mPreviousTransformation.clear(); mInitialized = false; mCycleFlip = false; mRepeated = 0; mMore = true; + mOneMoreTime = true; } /** @@ -255,10 +272,8 @@ public abstract class Animation { * @param parentHeight Height of the animated object's parent */ public void initialize(int width, int height, int parentWidth, int parentHeight) { + reset(); mInitialized = true; - mCycleFlip = false; - mRepeated = 0; - mMore = true; } /** @@ -707,6 +722,11 @@ public abstract class Animation { } } + if (!mMore && mOneMoreTime) { + mOneMoreTime = false; + return true; + } + return mMore; } @@ -765,7 +785,54 @@ public abstract class Animation { return value; } } - + + /** + * @param left + * @param top + * @param right + * @param bottom + * @param invalidate + * @param transformation + * + * @hide + */ + public void getInvalidateRegion(int left, int top, int right, int bottom, + RectF invalidate, Transformation transformation) { + + final RectF previousRegion = mPreviousRegion; + + invalidate.set(left, top, right, bottom); + transformation.getMatrix().mapRect(invalidate); + invalidate.union(previousRegion); + + previousRegion.set(left, top, right, bottom); + transformation.getMatrix().mapRect(previousRegion); + + final Transformation tempTransformation = mTransformation; + final Transformation previousTransformation = mPreviousTransformation; + + tempTransformation.set(transformation); + transformation.set(previousTransformation); + previousTransformation.set(tempTransformation); + } + + /** + * @param left + * @param top + * @param right + * @param bottom + * + * @hide + */ + public void initializeInvalidateRegion(int left, int top, int right, int bottom) { + final RectF region = mPreviousRegion; + region.set(left, top, right, bottom); + if (mFillBefore) { + final Transformation previousTransformation = mPreviousTransformation; + applyTransformation(0.0f, previousTransformation); + } + } + /** * Utility class to parse a string description of a size. */ diff --git a/core/java/android/view/animation/AnimationSet.java b/core/java/android/view/animation/AnimationSet.java index 688da70..7b56f00 100644 --- a/core/java/android/view/animation/AnimationSet.java +++ b/core/java/android/view/animation/AnimationSet.java @@ -19,6 +19,7 @@ package android.view.animation; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; +import android.graphics.RectF; import java.util.ArrayList; import java.util.List; @@ -39,6 +40,7 @@ public class AnimationSet extends Animation { private static final int PROPERTY_SHARE_INTERPOLATOR_MASK = 0x10; private static final int PROPERTY_DURATION_MASK = 0x20; private static final int PROPERTY_MORPH_MATRIX_MASK = 0x40; + private static final int PROPERTY_CHANGE_BOUNDS_MASK = 0x80; private int mFlags = 0; @@ -82,6 +84,22 @@ public class AnimationSet extends Animation { init(); } + @Override + protected AnimationSet clone() throws CloneNotSupportedException { + final AnimationSet animation = (AnimationSet) super.clone(); + animation.mTempTransformation = new Transformation(); + animation.mAnimations = new ArrayList<Animation>(); + + final int count = mAnimations.size(); + final ArrayList<Animation> animations = mAnimations; + + for (int i = 0; i < count; i++) { + animation.mAnimations.add(animations.get(i).clone()); + } + + return animation; + } + private void setFlag(int mask, boolean value) { if (value) { mFlags |= mask; @@ -145,6 +163,11 @@ public class AnimationSet extends Animation { mFlags |= PROPERTY_MORPH_MATRIX_MASK; } + boolean changeBounds = (mFlags & PROPERTY_CHANGE_BOUNDS_MASK) == 0; + if (changeBounds && a.willChangeTransformationMatrix()) { + mFlags |= PROPERTY_CHANGE_BOUNDS_MASK; + } + if (mAnimations.size() == 1) { mDuration = a.getStartOffset() + a.getDuration(); mLastEnd = mStartOffset + mDuration; @@ -239,7 +262,54 @@ public class AnimationSet extends Animation { } return duration; } - + + /** + * @hide + */ + public void getInvalidateRegion(int left, int top, int right, int bottom, + RectF invalidate, Transformation transformation) { + + final RectF previousRegion = mPreviousRegion; + + invalidate.set(left, top, right, bottom); + transformation.getMatrix().mapRect(invalidate); + invalidate.union(previousRegion); + + previousRegion.set(left, top, right, bottom); + transformation.getMatrix().mapRect(previousRegion); + + final Transformation tempTransformation = mTransformation; + final Transformation previousTransformation = mPreviousTransformation; + + tempTransformation.set(transformation); + transformation.set(previousTransformation); + previousTransformation.set(tempTransformation); + } + + /** + * @hide + */ + public void initializeInvalidateRegion(int left, int top, int right, int bottom) { + final RectF region = mPreviousRegion; + region.set(left, top, right, bottom); + + if (mFillBefore) { + final int count = mAnimations.size(); + final ArrayList<Animation> animations = mAnimations; + final Transformation temp = mTempTransformation; + + final Transformation previousTransformation = mPreviousTransformation; + + for (int i = count - 1; i >= 0; --i) { + final Animation a = animations.get(i); + + temp.clear(); + a.applyTransformation(0.0f, temp); + previousTransformation.compose(temp); + } + } + } + /** * The transformation of an animation set is the concatenation of all of its * component animations. @@ -313,7 +383,7 @@ public class AnimationSet extends Animation { == PROPERTY_SHARE_INTERPOLATOR_MASK; boolean startOffsetSet = (mFlags & PROPERTY_START_OFFSET_MASK) == PROPERTY_START_OFFSET_MASK; - + if (shareInterpolator) { ensureInterpolator(); } @@ -327,7 +397,13 @@ public class AnimationSet extends Animation { final int repeatMode = mRepeatMode; final Interpolator interpolator = mInterpolator; final long startOffset = mStartOffset; - + + + long[] storedOffsets = mStoredOffsets; + if (storedOffsets == null || storedOffsets.length != count) { + storedOffsets = mStoredOffsets = new long[count]; + } + for (int i = 0; i < count; i++) { Animation a = children.get(i); if (durationSet) { @@ -346,42 +422,36 @@ public class AnimationSet extends Animation { a.setInterpolator(interpolator); } if (startOffsetSet) { - a.setStartOffset(startOffset); + long offset = a.getStartOffset(); + a.setStartOffset(offset + startOffset); + storedOffsets[i] = offset; } a.initialize(width, height, parentWidth, parentHeight); } } - /** - * @hide - * @param startOffset the startOffset to add to the children's startOffset - */ - void saveChildrenStartOffset(long startOffset) { - final ArrayList<Animation> children = mAnimations; - final int count = children.size(); - long[] storedOffsets = mStoredOffsets = new long[count]; - - for (int i = 0; i < count; i++) { - Animation animation = children.get(i); - long offset = animation.getStartOffset(); - animation.setStartOffset(offset + startOffset); - storedOffsets[i] = offset; - } + @Override + public void reset() { + super.reset(); + restoreChildrenStartOffset(); } /** * @hide */ void restoreChildrenStartOffset() { + final long[] offsets = mStoredOffsets; + if (offsets == null) return; + final ArrayList<Animation> children = mAnimations; final int count = children.size(); - final long[] offsets = mStoredOffsets; + for (int i = 0; i < count; i++) { children.get(i).setStartOffset(offsets[i]); } } - + /** * @return All the child animations in this AnimationSet. Note that * this may include other AnimationSets, which are not expanded. @@ -394,4 +464,9 @@ public class AnimationSet extends Animation { public boolean willChangeTransformationMatrix() { return (mFlags & PROPERTY_MORPH_MATRIX_MASK) == PROPERTY_MORPH_MATRIX_MASK; } + + @Override + public boolean willChangeBounds() { + return (mFlags & PROPERTY_CHANGE_BOUNDS_MASK) == PROPERTY_CHANGE_BOUNDS_MASK; + } } diff --git a/core/java/android/view/animation/LayoutAnimationController.java b/core/java/android/view/animation/LayoutAnimationController.java index 9cfa8d7..882e738 100644 --- a/core/java/android/view/animation/LayoutAnimationController.java +++ b/core/java/android/view/animation/LayoutAnimationController.java @@ -318,9 +318,16 @@ public class LayoutAnimationController { * @see #getDelayForView(android.view.View) */ public final Animation getAnimationForView(View view) { - final long delay = getDelayForView(view); + final long delay = getDelayForView(view) + mAnimation.getStartOffset(); mMaxDelay = Math.max(mMaxDelay, delay); - return new DelayedAnimation(delay, mAnimation); + + try { + final Animation animation = mAnimation.clone(); + animation.setStartOffset(delay); + return animation; + } catch (CloneNotSupportedException e) { + return null; + } } /** @@ -425,149 +432,4 @@ public class LayoutAnimationController { */ public int index; } - - /** - * Encapsulates an animation and delays its start offset by a specified - * amount. This allows to reuse the same base animation for various views - * and get the effect of running multiple instances of the animation at - * different times. - */ - private static class DelayedAnimation extends Animation { - private final long mDelay; - private final Animation mAnimation; - - /** - * Creates a new delayed animation that will delay the controller's - * animation by the specified delay in milliseconds. - * - * @param delay the delay in milliseconds by which to offset the - * @param animation the animation to delay - */ - private DelayedAnimation(long delay, Animation animation) { - mDelay = delay; - mAnimation = animation; - } - - @Override - public boolean isInitialized() { - return mAnimation.isInitialized(); - } - - @Override - public void initialize(int width, int height, int parentWidth, int parentHeight) { - mAnimation.initialize(width, height, parentWidth, parentHeight); - } - - @Override - public void reset() { - mAnimation.reset(); - } - - @Override - public boolean getTransformation(long currentTime, Transformation outTransformation) { - final long oldOffset = mAnimation.getStartOffset(); - final boolean isSet = mAnimation instanceof AnimationSet; - if (isSet) { - AnimationSet set = ((AnimationSet) mAnimation); - set.saveChildrenStartOffset(mDelay); - } - mAnimation.setStartOffset(oldOffset + mDelay); - - boolean result = mAnimation.getTransformation(currentTime, - outTransformation); - - if (isSet) { - AnimationSet set = ((AnimationSet) mAnimation); - set.restoreChildrenStartOffset(); - } - mAnimation.setStartOffset(oldOffset); - - return result; - } - - @Override - public void setStartTime(long startTimeMillis) { - mAnimation.setStartTime(startTimeMillis); - } - - @Override - public long getStartTime() { - return mAnimation.getStartTime(); - } - - @Override - public void setInterpolator(Interpolator i) { - mAnimation.setInterpolator(i); - } - - @Override - public void setStartOffset(long startOffset) { - mAnimation.setStartOffset(startOffset); - } - - @Override - public void setDuration(long durationMillis) { - mAnimation.setDuration(durationMillis); - } - - @Override - public void scaleCurrentDuration(float scale) { - mAnimation.scaleCurrentDuration(scale); - } - - @Override - public void setRepeatMode(int repeatMode) { - mAnimation.setRepeatMode(repeatMode); - } - - @Override - public void setFillBefore(boolean fillBefore) { - mAnimation.setFillBefore(fillBefore); - } - - @Override - public void setFillAfter(boolean fillAfter) { - mAnimation.setFillAfter(fillAfter); - } - - @Override - public Interpolator getInterpolator() { - return mAnimation.getInterpolator(); - } - - @Override - public long getDuration() { - return mAnimation.getDuration(); - } - - @Override - public long getStartOffset() { - return mAnimation.getStartOffset() + mDelay; - } - - @Override - public int getRepeatMode() { - return mAnimation.getRepeatMode(); - } - - @Override - public boolean getFillBefore() { - return mAnimation.getFillBefore(); - } - - @Override - public boolean getFillAfter() { - return mAnimation.getFillAfter(); - } - - @Override - public boolean willChangeTransformationMatrix() { - return mAnimation.willChangeTransformationMatrix(); - } - - @Override - public boolean willChangeBounds() { - return mAnimation.willChangeBounds(); - } - } } diff --git a/core/java/android/view/inputmethod/BaseInputConnection.java b/core/java/android/view/inputmethod/BaseInputConnection.java index a6ce293..56c6c92 100644 --- a/core/java/android/view/inputmethod/BaseInputConnection.java +++ b/core/java/android/view/inputmethod/BaseInputConnection.java @@ -17,35 +17,365 @@ package android.view.inputmethod; import android.content.Context; +import android.content.res.TypedArray; +import android.os.Bundle; import android.os.Handler; -import android.os.Message; +import android.os.SystemClock; +import android.text.Editable; +import android.text.NoCopySpan; +import android.text.Selection; +import android.text.Spannable; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.TextUtils; +import android.text.method.MetaKeyKeyListener; +import android.util.Log; +import android.util.LogPrinter; +import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.View; import android.view.ViewRoot; +class ComposingText implements NoCopySpan { +} + /** * Base class for implementors of the InputConnection interface, taking care - * of implementing common system-oriented parts of the functionality. + * of most of the common behavior for providing a connection to an Editable. + * Implementors of this class will want to be sure to implement + * {@link #getEditable} to provide access to their own editable object. */ -public abstract class BaseInputConnection implements InputConnection { +public class BaseInputConnection implements InputConnection { + private static final boolean DEBUG = false; + private static final String TAG = "BaseInputConnection"; + static final Object COMPOSING = new ComposingText(); + final InputMethodManager mIMM; final Handler mH; final View mTargetView; + final boolean mDummyMode; + + private Object[] mDefaultComposingSpans; + + Editable mEditable; + KeyCharacterMap mKeyCharacterMap; - BaseInputConnection(InputMethodManager mgr) { + BaseInputConnection(InputMethodManager mgr, boolean dummyMode) { mIMM = mgr; mTargetView = null; mH = null; + mDummyMode = dummyMode; } - public BaseInputConnection(View targetView) { + public BaseInputConnection(View targetView, boolean dummyMode) { mIMM = (InputMethodManager)targetView.getContext().getSystemService( Context.INPUT_METHOD_SERVICE); mH = targetView.getHandler(); mTargetView = targetView; + mDummyMode = dummyMode; + } + + public static final void removeComposingSpans(Spannable text) { + text.removeSpan(COMPOSING); + Object[] sps = text.getSpans(0, text.length(), Object.class); + if (sps != null) { + for (int i=sps.length-1; i>=0; i--) { + Object o = sps[i]; + if ((text.getSpanFlags(o)&Spanned.SPAN_COMPOSING) != 0) { + text.removeSpan(o); + } + } + } + } + + public static void setComposingSpans(Spannable text) { + final Object[] sps = text.getSpans(0, text.length(), Object.class); + if (sps != null) { + for (int i=sps.length-1; i>=0; i--) { + final Object o = sps[i]; + if (o == COMPOSING) { + text.removeSpan(o); + continue; + } + final int fl = text.getSpanFlags(o); + if ((fl&(Spanned.SPAN_COMPOSING|Spanned.SPAN_POINT_MARK_MASK)) + != (Spanned.SPAN_COMPOSING|Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)) { + text.setSpan(o, text.getSpanStart(o), text.getSpanEnd(o), + (fl&Spanned.SPAN_POINT_MARK_MASK) + | Spanned.SPAN_COMPOSING + | Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } + } + + text.setSpan(COMPOSING, 0, text.length(), + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING); + } + + public static int getComposingSpanStart(Spannable text) { + return text.getSpanStart(COMPOSING); + } + + public static int getComposingSpanEnd(Spannable text) { + return text.getSpanEnd(COMPOSING); + } + + /** + * Return the target of edit operations. The default implementation + * returns its own fake editable that is just used for composing text; + * subclasses that are real text editors should override this and + * supply their own. + */ + public Editable getEditable() { + if (mEditable == null) { + mEditable = Editable.Factory.getInstance().newEditable(""); + Selection.setSelection(mEditable, 0); + } + return mEditable; } /** + * Default implementation does nothing. + */ + public boolean beginBatchEdit() { + return false; + } + + /** + * Default implementation does nothing. + */ + public boolean endBatchEdit() { + return false; + } + + /** + * Default implementation uses + * {@link MetaKeyKeyListener#clearMetaKeyState(long, int) + * MetaKeyKeyListener.clearMetaKeyState(long, int)} to clear the state. + */ + public boolean clearMetaKeyStates(int states) { + final Editable content = getEditable(); + if (content == null) return false; + MetaKeyKeyListener.clearMetaKeyState(content, states); + return true; + } + + /** + * Default implementation does nothing. + */ + public boolean commitCompletion(CompletionInfo text) { + return false; + } + + /** + * Default implementation replaces any existing composing text with + * the given text. In addition, only if dummy mode, a key event is + * sent for the new text and the current editable buffer cleared. + */ + public boolean commitText(CharSequence text, int newCursorPosition) { + if (DEBUG) Log.v(TAG, "commitText " + text); + replaceText(text, newCursorPosition, false); + sendCurrentText(); + return true; + } + + /** + * The default implementation performs the deletion around the current + * selection position of the editable text. + */ + public boolean deleteSurroundingText(int leftLength, int rightLength) { + if (DEBUG) Log.v(TAG, "deleteSurroundingText " + leftLength + + " / " + rightLength); + final Editable content = getEditable(); + if (content == null) return false; + + beginBatchEdit(); + + int a = Selection.getSelectionStart(content); + int b = Selection.getSelectionEnd(content); + + if (a > b) { + int tmp = a; + a = b; + b = tmp; + } + + // ignore the composing text. + int ca = getComposingSpanStart(content); + int cb = getComposingSpanEnd(content); + if (cb < ca) { + int tmp = ca; + ca = cb; + cb = tmp; + } + if (ca != -1 && cb != -1) { + if (ca < a) a = ca; + if (cb > b) b = cb; + } + + int deleted = 0; + + if (leftLength > 0) { + int start = a - leftLength; + if (start < 0) start = 0; + content.delete(start, a); + deleted = a - start; + } + + if (rightLength > 0) { + b = b - deleted; + + int end = b + rightLength; + if (end > content.length()) end = content.length(); + + content.delete(b, end); + } + + endBatchEdit(); + + return true; + } + + /** + * The default implementation removes the composing state from the + * current editable text. In addition, only if dummy mode, a key event is + * sent for the new text and the current editable buffer cleared. + */ + public boolean finishComposingText() { + if (DEBUG) Log.v(TAG, "finishComposingText"); + final Editable content = getEditable(); + if (content != null) { + beginBatchEdit(); + removeComposingSpans(content); + endBatchEdit(); + sendCurrentText(); + } + return true; + } + + /** + * The default implementation uses TextUtils.getCapsMode to get the + * cursor caps mode for the current selection position in the editable + * text, unless in dummy mode in which case 0 is always returned. + */ + public int getCursorCapsMode(int reqModes) { + if (mDummyMode) return 0; + + final Editable content = getEditable(); + if (content == null) return 0; + + int a = Selection.getSelectionStart(content); + int b = Selection.getSelectionEnd(content); + + if (a > b) { + int tmp = a; + a = b; + b = tmp; + } + + return TextUtils.getCapsMode(content, a, reqModes); + } + + /** + * The default implementation always returns null. + */ + public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { + return null; + } + + /** + * The default implementation returns the given amount of text from the + * current cursor position in the buffer. + */ + public CharSequence getTextBeforeCursor(int length, int flags) { + final Editable content = getEditable(); + if (content == null) return null; + + int a = Selection.getSelectionStart(content); + int b = Selection.getSelectionEnd(content); + + if (a > b) { + int tmp = a; + a = b; + b = tmp; + } + + if (length > a) { + length = a; + } + + if ((flags&GET_TEXT_WITH_STYLES) != 0) { + return content.subSequence(a - length, a); + } + return TextUtils.substring(content, a - length, a); + } + + /** + * The default implementation returns the given amount of text from the + * current cursor position in the buffer. + */ + public CharSequence getTextAfterCursor(int length, int flags) { + final Editable content = getEditable(); + if (content == null) return null; + + int a = Selection.getSelectionStart(content); + int b = Selection.getSelectionEnd(content); + + if (a > b) { + int tmp = a; + a = b; + b = tmp; + } + + if (b + length > content.length()) { + length = content.length() - b; + } + + + if ((flags&GET_TEXT_WITH_STYLES) != 0) { + return content.subSequence(b, b + length); + } + return TextUtils.substring(content, b, b + length); + } + + /** + * The default implementation does nothing. + */ + public boolean performContextMenuAction(int id) { + return false; + } + + /** + * The default implementation does nothing. + */ + public boolean performPrivateCommand(String action, Bundle data) { + return false; + } + + /** + * The default implementation places the given text into the editable, + * replacing any existing composing text. The new text is marked as + * in a composing state with the composing style. + */ + public boolean setComposingText(CharSequence text, int newCursorPosition) { + if (DEBUG) Log.v(TAG, "setComposingText " + text); + replaceText(text, newCursorPosition, true); + return true; + } + + /** + * The default implementation changes the selection position in the + * current editable text. + */ + public boolean setSelection(int start, int end) { + if (DEBUG) Log.v(TAG, "setSelection " + start + ", " + end); + final Editable content = getEditable(); + if (content == null) return false; + Selection.setSelection(content, start, end); + return true; + } + + /** * Provides standard implementation for sending a key event to the window * attached to the input connection's view. */ @@ -82,4 +412,144 @@ public abstract class BaseInputConnection implements InputConnection { mIMM.updateStatusIcon(resId, packageName); return true; } + + private void sendCurrentText() { + if (!mDummyMode) { + return; + } + + Editable content = getEditable(); + if (content != null) { + if (content.length() == 1) { + // If it's 1 character, we have a chance of being + // able to generate normal key events... + if (mKeyCharacterMap == null) { + mKeyCharacterMap = KeyCharacterMap.load( + KeyCharacterMap.BUILT_IN_KEYBOARD); + } + char[] chars = new char[1]; + content.getChars(0, 1, chars, 0); + KeyEvent[] events = mKeyCharacterMap.getEvents(chars); + if (events != null) { + for (int i=0; i<events.length; i++) { + if (DEBUG) Log.v(TAG, "Sending: " + events[i]); + sendKeyEvent(events[i]); + } + content.clear(); + return; + } + } + + // Otherwise, revert to the special key event containing + // the actual characters. + KeyEvent event = new KeyEvent(SystemClock.uptimeMillis(), + content.toString(), KeyCharacterMap.BUILT_IN_KEYBOARD, 0); + sendKeyEvent(event); + content.clear(); + } + } + + private void replaceText(CharSequence text, int newCursorPosition, + boolean composing) { + final Editable content = getEditable(); + if (content == null) { + return; + } + + beginBatchEdit(); + + // delete composing text set previously. + int a = getComposingSpanStart(content); + int b = getComposingSpanEnd(content); + + if (DEBUG) Log.v(TAG, "Composing span: " + a + " to " + b); + + if (b < a) { + int tmp = a; + a = b; + b = tmp; + } + + if (a != -1 && b != -1) { + removeComposingSpans(content); + } else { + a = Selection.getSelectionStart(content); + b = Selection.getSelectionEnd(content); + if (a >=0 && b>= 0 && a != b) { + if (b < a) { + int tmp = a; + a = b; + b = tmp; + } + } + } + + if (composing) { + Spannable sp = null; + if (!(text instanceof Spannable)) { + sp = new SpannableStringBuilder(text); + text = sp; + if (mDefaultComposingSpans == null) { + Context context; + if (mTargetView != null) { + context = mTargetView.getContext(); + } else if (mIMM.mServedView != null) { + context = mIMM.mServedView.getContext(); + } else { + context = null; + } + if (context != null) { + TypedArray ta = context.getTheme() + .obtainStyledAttributes(new int[] { + com.android.internal.R.attr.candidatesTextStyleSpans + }); + CharSequence style = ta.getText(0); + ta.recycle(); + if (style != null && style instanceof Spanned) { + mDefaultComposingSpans = ((Spanned)style).getSpans( + 0, style.length(), Object.class); + } + } + } + if (mDefaultComposingSpans != null) { + for (int i = 0; i < mDefaultComposingSpans.length; ++i) { + sp.setSpan(mDefaultComposingSpans[i], 0, sp.length(), + Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + } + } + } else { + sp = (Spannable)text; + } + setComposingSpans(sp); + } + + // Adjust newCursorPosition to be relative the start of the text. + newCursorPosition += a; + + if (DEBUG) Log.v(TAG, "Replacing from " + a + " to " + b + " with \"" + + text + "\", composing=" + composing + + ", type=" + text.getClass().getCanonicalName()); + + if (DEBUG) { + LogPrinter lp = new LogPrinter(Log.VERBOSE, TAG); + lp.println("Current text:"); + TextUtils.dumpSpans(content, lp, " "); + lp.println("Composing text:"); + TextUtils.dumpSpans(text, lp, " "); + } + + content.replace(a, b, text); + if (newCursorPosition < 0) newCursorPosition = 0; + if (newCursorPosition > content.length()) + newCursorPosition = content.length(); + Selection.setSelection(content, newCursorPosition); + + if (DEBUG) { + LogPrinter lp = new LogPrinter(Log.VERBOSE, TAG); + lp.println("Final text:"); + TextUtils.dumpSpans(content, lp, " "); + } + + endBatchEdit(); + } } diff --git a/core/java/android/view/inputmethod/DefaultInputMethod.java b/core/java/android/view/inputmethod/DefaultInputMethod.java deleted file mode 100644 index 073b01c..0000000 --- a/core/java/android/view/inputmethod/DefaultInputMethod.java +++ /dev/null @@ -1,239 +0,0 @@ -package android.view.inputmethod; - -import android.graphics.Rect; -import android.os.Bundle; -import android.os.IBinder; -import android.os.RemoteException; -import android.util.Log; -import android.view.KeyEvent; -import android.view.MotionEvent; - -import com.android.internal.view.IInputContext; -import com.android.internal.view.IInputMethod; -import com.android.internal.view.IInputMethodCallback; -import com.android.internal.view.IInputMethodSession; -import com.android.internal.view.InputConnectionWrapper; - -/** - * This is the default input method that runs in the same context of the - * application that requests text input. It does nothing but returns false for - * any key events, so that all key events will be processed by the key listener - * of the focused text box. - * {@hide} - */ -public class DefaultInputMethod implements InputMethod, InputMethodSession { - private static IInputMethod sInstance = new SimpleInputMethod( - new DefaultInputMethod()); - - private static InputMethodInfo sProperty = new InputMethodInfo( - "android.text.inputmethod", DefaultInputMethod.class.getName(), - "Default", "android.text.inputmethod.defaultImeSettings"); - - private InputConnection mInputConnection; - - public static IInputMethod getInstance() { - return sInstance; - } - - public static InputMethodInfo getMetaInfo() { - return sProperty; - } - - public void bindInput(InputBinding binding) { - mInputConnection = binding.getConnection(); - } - - public void unbindInput() { - } - - public void createSession(SessionCallback callback) { - callback.sessionCreated(this); - } - - public void setSessionEnabled(InputMethodSession session, boolean enabled) { - } - - public void revokeSession(InputMethodSession session) { - } - - public void finishInput() { - mInputConnection.hideStatusIcon(); - } - - public void displayCompletions(CompletionInfo[] completions) { - } - - public void updateExtractedText(int token, ExtractedText text) { - } - - public void updateSelection(int oldSelStart, int oldSelEnd, - int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { - } - - public void updateCursor(Rect newCursor) { - } - - public void dispatchKeyEvent(int seq, KeyEvent event, EventCallback callback) { - callback.finishedEvent(seq, false); - } - - public void dispatchTrackballEvent(int seq, MotionEvent event, EventCallback callback) { - callback.finishedEvent(seq, false); - } - - public void restartInput(EditorInfo attribute) { - } - - public void attachToken(IBinder token) { - } - - public void startInput(EditorInfo attribute) { - mInputConnection - .showStatusIcon("android", com.android.internal.R.drawable.ime_qwerty); - } - - public void appPrivateCommand(String action, Bundle data) { - } - - public void hideSoftInput() { - } - - public void showSoftInput(int flags) { - } -} - -// ---------------------------------------------------------------------- - -class SimpleInputMethod extends IInputMethod.Stub { - final InputMethod mInputMethod; - - static class Session extends IInputMethodSession.Stub { - final InputMethodSession mSession; - - Session(InputMethodSession session) { - mSession = session; - } - - public void finishInput() { - mSession.finishInput(); - } - - public void updateSelection(int oldSelStart, int oldSelEnd, - int newSelStart, int newSelEnd, int candidatesStart, int candidatesEnd) { - mSession.updateSelection(oldSelStart, oldSelEnd, - newSelStart, newSelEnd, candidatesStart, candidatesEnd); - } - - public void updateCursor(Rect newCursor) { - mSession.updateCursor(newCursor); - } - - static class InputMethodEventCallbackWrapper implements InputMethodSession.EventCallback { - final IInputMethodCallback mCb; - InputMethodEventCallbackWrapper(IInputMethodCallback cb) { - mCb = cb; - } - public void finishedEvent(int seq, boolean handled) { - try { - mCb.finishedEvent(seq, handled); - } catch (RemoteException e) { - } - } - } - - public void dispatchKeyEvent(int seq, KeyEvent event, IInputMethodCallback callback) { - mSession.dispatchKeyEvent(seq, event, - new InputMethodEventCallbackWrapper(callback)); - } - - public void dispatchTrackballEvent(int seq, MotionEvent event, IInputMethodCallback callback) { - mSession.dispatchTrackballEvent(seq, event, - new InputMethodEventCallbackWrapper(callback)); - } - - public void displayCompletions(CompletionInfo[] completions) { - mSession.displayCompletions(completions); - } - - public void updateExtractedText(int token, ExtractedText text) { - mSession.updateExtractedText(token, text); - } - - public void appPrivateCommand(String action, Bundle data) { - mSession.appPrivateCommand(action, data); - } - } - - public SimpleInputMethod(InputMethod inputMethod) { - mInputMethod = inputMethod; - } - - public InputMethod getInternalInputMethod() { - return mInputMethod; - } - - public void attachToken(IBinder token) { - mInputMethod.attachToken(token); - } - - public void bindInput(InputBinding binding) { - InputConnectionWrapper ic = new InputConnectionWrapper( - IInputContext.Stub.asInterface(binding.getConnectionToken())); - InputBinding nu = new InputBinding(ic, binding); - mInputMethod.bindInput(nu); - } - - public void unbindInput() { - mInputMethod.unbindInput(); - } - - public void restartInput(EditorInfo attribute) { - mInputMethod.restartInput(attribute); - } - - public void startInput(EditorInfo attribute) { - mInputMethod.startInput(attribute); - } - - static class InputMethodSessionCallbackWrapper implements InputMethod.SessionCallback { - final IInputMethodCallback mCb; - InputMethodSessionCallbackWrapper(IInputMethodCallback cb) { - mCb = cb; - } - - public void sessionCreated(InputMethodSession session) { - try { - mCb.sessionCreated(new Session(session)); - } catch (RemoteException e) { - } - } - } - - public void createSession(IInputMethodCallback callback) throws RemoteException { - mInputMethod.createSession(new InputMethodSessionCallbackWrapper(callback)); - } - - public void setSessionEnabled(IInputMethodSession session, boolean enabled) throws RemoteException { - try { - InputMethodSession ls = ((Session)session).mSession; - mInputMethod.setSessionEnabled(ls, enabled); - } catch (ClassCastException e) { - Log.w("SimpleInputMethod", "Incoming session not of correct type: " + session, e); - } - } - - public void revokeSession(IInputMethodSession session) throws RemoteException { - try { - InputMethodSession ls = ((Session)session).mSession; - mInputMethod.revokeSession(ls); - } catch (ClassCastException e) { - Log.w("SimpleInputMethod", "Incoming session not of correct type: " + session, e); - } - } - - public void showSoftInput(boolean blah) { - } - - public void hideSoftInput() { - } -} diff --git a/core/java/android/view/inputmethod/EditorInfo.java b/core/java/android/view/inputmethod/EditorInfo.java index c050691..b2f26d7 100644 --- a/core/java/android/view/inputmethod/EditorInfo.java +++ b/core/java/android/view/inputmethod/EditorInfo.java @@ -5,6 +5,7 @@ import android.os.Parcel; import android.os.Parcelable; import android.text.InputType; import android.text.TextUtils; +import android.util.Printer; /** * An EditorInfo describes several attributes of a text editing object @@ -21,7 +22,7 @@ public class EditorInfo implements InputType, Parcelable { * @see #TYPE_MASK_VARIATION * @see #TYPE_MASK_FLAGS */ - public int inputType = TYPE_CLASS_TEXT; + public int inputType = TYPE_NULL; /** * A string supplying additional information about the content type that @@ -71,6 +72,26 @@ public class EditorInfo implements InputType, Parcelable { public CharSequence label; /** + * Name of the package that owns this editor. + */ + public String packageName; + + /** + * Identifier for the editor's field. This is optional, and may be + * 0. By default it is filled in with the result of + * {@link android.view.View#getId() View.getId()} on the View that + * is being edited. + */ + public int fieldId; + + /** + * Additional name for the editor's field. This can supply additional + * name information for the field. By default it is null. The actual + * contents have no meaning. + */ + public String fieldName; + + /** * Any extra data to supply to the input method. This is for extended * communication with specific input methods; the name fields in the * bundle should be scoped (such as "com.mydomain.im.SOME_FIELD") so @@ -81,6 +102,24 @@ public class EditorInfo implements InputType, Parcelable { public Bundle extras; /** + * Write debug output of this object. + */ + public void dump(Printer pw, String prefix) { + pw.println(prefix + "inputType=0x" + Integer.toHexString(inputType) + + " privateContentType=" + privateContentType); + pw.println(prefix + "initialSelStart=" + initialSelStart + + " initialSelEnd=" + initialSelEnd + + " initialCapsMode=0x" + + Integer.toHexString(initialCapsMode)); + pw.println(prefix + "hintText=" + hintText + + " label=" + label); + pw.println(prefix + "packageName=" + packageName + + " fieldId=" + fieldId + + " fieldName=" + fieldName); + pw.println(prefix + "extras=" + extras); + } + + /** * Used to package this object into a {@link Parcel}. * * @param dest The {@link Parcel} to be written. @@ -94,6 +133,9 @@ public class EditorInfo implements InputType, Parcelable { dest.writeInt(initialCapsMode); TextUtils.writeToParcel(hintText, dest, flags); TextUtils.writeToParcel(label, dest, flags); + dest.writeString(packageName); + dest.writeInt(fieldId); + dest.writeString(fieldName); dest.writeBundle(extras); } @@ -110,6 +152,9 @@ public class EditorInfo implements InputType, Parcelable { res.initialCapsMode = source.readInt(); res.hintText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); res.label = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); + res.packageName = source.readString(); + res.fieldId = source.readInt(); + res.fieldName = source.readString(); res.extras = source.readBundle(); return res; } diff --git a/core/java/android/view/inputmethod/ExtractedText.java b/core/java/android/view/inputmethod/ExtractedText.java index 0ca3c79..e5d3cae 100644 --- a/core/java/android/view/inputmethod/ExtractedText.java +++ b/core/java/android/view/inputmethod/ExtractedText.java @@ -19,6 +19,22 @@ public class ExtractedText implements Parcelable { public int startOffset; /** + * If the content is a report of a partial text change, this is the + * offset where the change starts and it runs until + * {@link #partialEndOffset}. If the content is the full text, this + * field is -1. + */ + public int partialStartOffset; + + /** + * If the content is a report of a partial text change, this is the offset + * where the change ends. Note that the actual text may be larger or + * smaller than the difference between this and {@link #partialEndOffset}, + * meaning a reduction or increase, respectively, in the total text. + */ + public int partialEndOffset; + + /** * The offset where the selection currently starts within the extracted * text. The real selection start position is at * <var>startOffset</var>+<var>selectionStart</var>. @@ -52,6 +68,8 @@ public class ExtractedText implements Parcelable { public void writeToParcel(Parcel dest, int flags) { TextUtils.writeToParcel(text, dest, flags); dest.writeInt(startOffset); + dest.writeInt(partialStartOffset); + dest.writeInt(partialEndOffset); dest.writeInt(selectionStart); dest.writeInt(selectionEnd); dest.writeInt(flags); @@ -65,6 +83,8 @@ public class ExtractedText implements Parcelable { ExtractedText res = new ExtractedText(); res.text = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); res.startOffset = source.readInt(); + res.partialStartOffset = source.readInt(); + res.partialEndOffset = source.readInt(); res.selectionStart = source.readInt(); res.selectionEnd = source.readInt(); res.flags = source.readInt(); diff --git a/core/java/android/view/inputmethod/ExtractedTextRequest.java b/core/java/android/view/inputmethod/ExtractedTextRequest.java index d962329..e84b094 100644 --- a/core/java/android/view/inputmethod/ExtractedTextRequest.java +++ b/core/java/android/view/inputmethod/ExtractedTextRequest.java @@ -16,6 +16,13 @@ public class ExtractedTextRequest implements Parcelable { public int token; /** + * Additional request flags, having the same possible values as the + * flags parameter of {@link InputConnection#getTextBeforeCursor + * InputConnection.getTextBeforeCursor()}. + */ + public int flags; + + /** * Hint for the maximum number of lines to return. */ public int hintMaxLines; @@ -33,6 +40,7 @@ public class ExtractedTextRequest implements Parcelable { */ public void writeToParcel(Parcel dest, int flags) { dest.writeInt(token); + dest.writeInt(this.flags); dest.writeInt(hintMaxLines); dest.writeInt(hintMaxChars); } @@ -45,6 +53,7 @@ public class ExtractedTextRequest implements Parcelable { public ExtractedTextRequest createFromParcel(Parcel source) { ExtractedTextRequest res = new ExtractedTextRequest(); res.token = source.readInt(); + res.flags = source.readInt(); res.hintMaxLines = source.readInt(); res.hintMaxChars = source.readInt(); return res; diff --git a/core/java/android/view/inputmethod/InputConnection.java b/core/java/android/view/inputmethod/InputConnection.java index bd7b050..8c30d3f 100644 --- a/core/java/android/view/inputmethod/InputConnection.java +++ b/core/java/android/view/inputmethod/InputConnection.java @@ -32,6 +32,21 @@ import android.view.KeyEvent; */ public interface InputConnection { /** + * Flag for use with {@link #getTextAfterCursor} and + * {@link #getTextBeforeCursor} to have style information returned along + * with the text. If not set, you will receive only the raw text. If + * set, you may receive a complex CharSequence of both text and style + * spans. + */ + static final int GET_TEXT_WITH_STYLES = 0x0001; + + /** + * Flag for use with {@link #getExtractedText} to indicate you would + * like to receive updates when the extracted text changes. + */ + public static final int GET_EXTRACTED_TEXT_MONITOR = 0x0001; + + /** * Get <var>n</var> characters of text before the current cursor position. * * <p>This method may fail either if the input connection has become invalid @@ -40,11 +55,13 @@ public interface InputConnection { * In either case, a null is returned. * * @param n The expected length of the text. + * @param flags Supplies additional options controlling how the text is + * returned. May be either 0 or {@link #GET_TEXT_WITH_STYLES}. * * @return Returns the text before the cursor position; the length of the * returned text might be less than <var>n</var>. */ - public CharSequence getTextBeforeCursor(int n); + public CharSequence getTextBeforeCursor(int n, int flags); /** * Get <var>n</var> characters of text after the current cursor position. @@ -55,11 +72,13 @@ public interface InputConnection { * In either case, a null is returned. * * @param n The expected length of the text. + * @param flags Supplies additional options controlling how the text is + * returned. May be either 0 or {@link #GET_TEXT_WITH_STYLES}. * * @return Returns the text after the cursor position; the length of the * returned text might be less than <var>n</var>. */ - public CharSequence getTextAfterCursor(int n); + public CharSequence getTextAfterCursor(int n, int flags); /** * Retrieve the current capitalization mode in effect at the current @@ -82,8 +101,6 @@ public interface InputConnection { */ public int getCursorCapsMode(int reqModes); - public static final int EXTRACTED_TEXT_MONITOR = 0x0001; - /** * Retrieve the current text in the input connection's editor, and monitor * for any changes to it. This function returns with the current text, @@ -97,7 +114,7 @@ public interface InputConnection { * * @param request Description of how the text should be returned. * @param flags Additional options to control the client, either 0 or - * {@link #EXTRACTED_TEXT_MONITOR}. + * {@link #GET_EXTRACTED_TEXT_MONITOR}. * * @return Returns an ExtractedText object describing the state of the * text view and containing the extracted text itself. @@ -141,7 +158,7 @@ public interface InputConnection { /** * Have the text editor finish whatever composing text is currently - * active. This simple leaves the text as-is, removing any special + * active. This simply leaves the text as-is, removing any special * composing styling or other state that was around it. The cursor * position remains unchanged. */ @@ -177,6 +194,22 @@ public interface InputConnection { public boolean commitCompletion(CompletionInfo text); /** + * Set the selection of the text editor. To set the cursor position, + * start and end should have the same value. + */ + public boolean setSelection(int start, int end); + + /** + * Perform a context menu action on the field. The given id may be one of: + * {@link android.R.id#selectAll}, + * {@link android.R.id#startSelectingText}, {@link android.R.id#stopSelectingText}, + * {@link android.R.id#cut}, {@link android.R.id#copy}, + * {@link android.R.id#paste}, {@link android.R.id#copyUrl}, + * or {@link android.R.id#switchInputMethod} + */ + public boolean performContextMenuAction(int id); + + /** * Tell the editor that you are starting a batch of editor operations. * The editor will try to avoid sending you updates about its state * until {@link #endBatchEdit} is called. diff --git a/core/java/android/view/inputmethod/InputConnectionWrapper.java b/core/java/android/view/inputmethod/InputConnectionWrapper.java deleted file mode 100644 index f65b2a1..0000000 --- a/core/java/android/view/inputmethod/InputConnectionWrapper.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2007-2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ - -package android.view.inputmethod; - -import android.os.Bundle; -import android.view.KeyEvent; - -/** - * Wrapper around InputConnection interface, calling through to another - * implementation of it. - */ -public class InputConnectionWrapper implements InputConnection { - InputConnection mBase; - - /** - * Create a new wrapper around an existing InputConnection implementation. - */ - public InputConnectionWrapper(InputConnection base) { - mBase = base; - } - - /** - * Return the base InputConnection that this class is wrapping. - */ - InputConnection getBase() { - return mBase; - } - - public CharSequence getTextBeforeCursor(int n) { - return mBase.getTextBeforeCursor(n); - } - - public CharSequence getTextAfterCursor(int n) { - return mBase.getTextAfterCursor(n); - } - - public int getCursorCapsMode(int reqModes) { - return mBase.getCursorCapsMode(reqModes); - } - - public ExtractedText getExtractedText(ExtractedTextRequest request, - int flags) { - return mBase.getExtractedText(request, flags); - } - - public boolean deleteSurroundingText(int leftLength, int rightLength) { - return mBase.deleteSurroundingText(leftLength, rightLength); - } - - public boolean setComposingText(CharSequence text, int newCursorPosition) { - return mBase.setComposingText(text, newCursorPosition); - } - - public boolean finishComposingText() { - return mBase.finishComposingText(); - } - - public boolean commitText(CharSequence text, int newCursorPosition) { - return mBase.commitText(text, newCursorPosition); - } - - public boolean commitCompletion(CompletionInfo text) { - return mBase.commitCompletion(text); - } - - public boolean beginBatchEdit() { - return mBase.beginBatchEdit(); - } - - public boolean endBatchEdit() { - return mBase.endBatchEdit(); - } - - public boolean sendKeyEvent(KeyEvent event) { - return mBase.sendKeyEvent(event); - } - - public boolean clearMetaKeyStates(int states) { - return mBase.clearMetaKeyStates(states); - } - - public boolean performPrivateCommand(String action, Bundle data) { - return mBase.performPrivateCommand(action, data); - } - - public boolean showStatusIcon(String packageName, int resId) { - return mBase.showStatusIcon(packageName, resId); - } - - public boolean hideStatusIcon() { - return mBase.hideStatusIcon(); - } -} diff --git a/core/java/android/view/inputmethod/InputMethod.java b/core/java/android/view/inputmethod/InputMethod.java index c0e6590..740dca8 100644 --- a/core/java/android/view/inputmethod/InputMethod.java +++ b/core/java/android/view/inputmethod/InputMethod.java @@ -113,12 +113,15 @@ public interface InputMethod { * is ready for this input method to process received events and send result * text back to the application. * - * @param attribute The attribute of the text box (typically, a EditText) + * @param inputConnection Optional specific input connection for + * communicating with the text box; if null, you should use the generic + * bound input connection. + * @param info Information about the text box (typically, an EditText) * that requests input. * * @see EditorInfo */ - public void startInput(EditorInfo attribute); + public void startInput(InputConnection inputConnection, EditorInfo info); /** * This method is called when the state of this input method needs to be @@ -128,12 +131,15 @@ public interface InputMethod { * Typically, this method is called when the input focus is moved from one * text box to another. * + * @param inputConnection Optional specific input connection for + * communicating with the text box; if null, you should use the generic + * bound input connection. * @param attribute The attribute of the text box (typically, a EditText) * that requests input. * * @see EditorInfo */ - public void restartInput(EditorInfo attribute); + public void restartInput(InputConnection inputConnection, EditorInfo attribute); /** * Create a new {@link InputMethodSession} that can be handed to client @@ -173,6 +179,13 @@ public interface InputMethod { public static final int SHOW_EXPLICIT = 0x00001; /** + * Flag for {@link #showSoftInput(int)}: this show has been forced to + * happen by the user. If set, the input method should remain visible + * until deliberated dismissed by the user in its UI. + */ + public static final int SHOW_FORCED = 0x00002; + + /** * Request that any soft input part of the input method be shown to the user. * * @param flags Provide additional information about the show request. diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java index a9a9594..99d5aa5 100644 --- a/core/java/android/view/inputmethod/InputMethodManager.java +++ b/core/java/android/view/inputmethod/InputMethodManager.java @@ -26,11 +26,14 @@ import android.os.Message; import android.os.RemoteException; import android.os.ServiceManager; import android.util.Log; +import android.util.PrintWriterPrinter; +import android.util.Printer; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewRoot; +import com.android.internal.os.HandlerCaller; import com.android.internal.view.IInputConnectionWrapper; import com.android.internal.view.IInputContext; import com.android.internal.view.IInputMethodCallback; @@ -39,7 +42,11 @@ import com.android.internal.view.IInputMethodManager; import com.android.internal.view.IInputMethodSession; import com.android.internal.view.InputBindResult; +import java.io.FileDescriptor; +import java.io.PrintWriter; import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; /** * Central system API to the overall input method framework (IMF) architecture, @@ -199,8 +206,7 @@ public final class InputMethodManager { // global lock. final H mH; - // The currently active input connection. - final MutableInputConnectionWrapper mInputConnectionWrapper; + // Our generic input connection if the current target does not have its own. final IInputContext mIInputContext; /** @@ -208,11 +214,6 @@ public final class InputMethodManager { */ boolean mActive = false; - /** - * The current base input connection, used when mActive is true. - */ - InputConnection mCurrentInputConnection; - // ----------------------------------------------------------- /** @@ -270,7 +271,7 @@ public final class InputMethodManager { // ----------------------------------------------------------- - static final int MSG_CHECK_FOCUS = 1; + static final int MSG_DUMP = 1; class H extends Handler { H(Looper looper) { @@ -280,85 +281,55 @@ public final class InputMethodManager { @Override public void handleMessage(Message msg) { switch (msg.what) { - case MSG_CHECK_FOCUS: - checkFocus(); + case MSG_DUMP: { + HandlerCaller.SomeArgs args = (HandlerCaller.SomeArgs)msg.obj; + try { + doDump((FileDescriptor)args.arg1, + (PrintWriter)args.arg2, (String[])args.arg3); + } catch (RuntimeException e) { + ((PrintWriter)args.arg2).println("Exception: " + e); + } + synchronized (args.arg4) { + ((CountDownLatch)args.arg4).countDown(); + } return; + } } } } - static class NoOpInputConnection implements InputConnection { - - public boolean clearMetaKeyStates(int states) { - return false; - } - - public boolean beginBatchEdit() { - return false; - } - - public boolean endBatchEdit() { - return false; - } - - public boolean commitCompletion(CompletionInfo text) { - return false; - } - - public boolean commitText(CharSequence text, int newCursorPosition) { - return false; - } - - public boolean deleteSurroundingText(int leftLength, int rightLength) { - return false; - } - - public int getCursorCapsMode(int reqModes) { - return 0; - } - - public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { - return null; - } - - public CharSequence getTextAfterCursor(int n) { - return null; + class ControlledInputConnectionWrapper extends IInputConnectionWrapper { + public ControlledInputConnectionWrapper(Looper mainLooper, InputConnection conn) { + super(mainLooper, conn); } - public CharSequence getTextBeforeCursor(int n) { - return null; - } - - public boolean hideStatusIcon() { - return false; - } - - public boolean performPrivateCommand(String action, Bundle data) { - return false; - } - - public boolean sendKeyEvent(KeyEvent event) { - return false; - } - - public boolean setComposingText(CharSequence text, int newCursorPosition) { - return false; - } - - public boolean finishComposingText() { - return false; - } - - public boolean showStatusIcon(String packageName, int resId) { - return false; + public boolean isActive() { + return mActive; } } - final NoOpInputConnection mNoOpInputConnection = new NoOpInputConnection(); - final IInputMethodClient.Stub mClient = new IInputMethodClient.Stub() { - public void setUsingInputMethod(boolean state) { + @Override protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { + // No need to check for dump permission, since we only give this + // interface to the system. + CountDownLatch latch = new CountDownLatch(1); + HandlerCaller.SomeArgs sargs = new HandlerCaller.SomeArgs(); + sargs.arg1 = fd; + sargs.arg2 = fout; + sargs.arg3 = args; + sargs.arg4 = latch; + mH.sendMessage(mH.obtainMessage(MSG_DUMP, sargs)); + try { + if (!latch.await(5, TimeUnit.SECONDS)) { + fout.println("Timeout waiting for dump"); + } + } catch (InterruptedException e) { + fout.println("Interrupted waiting for dump"); + } + } + + public void setUsingInputMethod(boolean state) { } public void onBindMethod(InputBindResult res) { @@ -403,62 +374,17 @@ public final class InputMethodManager { public void setActive(boolean active) { mActive = active; - mInputConnectionWrapper.setBaseInputConnection(active - ? mCurrentInputConnection : mNoOpInputConnection); } }; - final InputConnection mDummyInputConnection = new BaseInputConnection(this) { - public boolean beginBatchEdit() { - return false; - } - public boolean endBatchEdit() { - return false; - } - public boolean commitText(CharSequence text, int newCursorPosition) { - return false; - } - public boolean commitCompletion(CompletionInfo text) { - return false; - } - public boolean deleteSurroundingText(int leftLength, int rightLength) { - return false; - } - public ExtractedText getExtractedText(ExtractedTextRequest request, - int flags) { - return null; - } - public CharSequence getTextAfterCursor(int n) { - return null; - } - public CharSequence getTextBeforeCursor(int n) { - return null; - } - public int getCursorCapsMode(int reqModes) { - return 0; - } - public boolean clearMetaKeyStates(int states) { - return false; - } - public boolean performPrivateCommand(String action, Bundle data) { - return false; - } - public boolean setComposingText(CharSequence text, int newCursorPosition) { - return false; - } - public boolean finishComposingText() { - return false; - } - }; + final InputConnection mDummyInputConnection = new BaseInputConnection(this, true); InputMethodManager(IInputMethodManager service, Looper looper) { mService = service; mMainLooper = looper; mH = new H(looper); - mInputConnectionWrapper = new MutableInputConnectionWrapper(mNoOpInputConnection); - mIInputContext = new IInputConnectionWrapper(looper, - mInputConnectionWrapper); - setCurrentInputConnection(mDummyInputConnection); + mIInputContext = new ControlledInputConnectionWrapper(looper, + mDummyInputConnection); if (mInstance == null) { mInstance = this; @@ -563,22 +489,12 @@ public final class InputMethodManager { } /** - * Record the desired input connection, but only set it if mActive is true. - */ - void setCurrentInputConnection(InputConnection connection) { - mCurrentInputConnection = connection; - mInputConnectionWrapper.setBaseInputConnection(mActive - ? connection : mNoOpInputConnection); - } - - /** * Reset all of the state associated with a served view being connected * to an input method */ void clearConnectionLocked() { mCurrentTextBoxAttribute = null; mServedInputConnection = null; - setCurrentInputConnection(mDummyInputConnection); } /** @@ -659,13 +575,20 @@ public final class InputMethodManager { } /** - * Flag for {@link #showSoftInput} to indicate that the this is an implicit + * Flag for {@link #showSoftInput} to indicate that this is an implicit * request to show the input window, not as the result of a direct request * by the user. The window may not be shown in this case. */ public static final int SHOW_IMPLICIT = 0x0001; /** + * Flag for {@link #showSoftInput} to indicate that the user has forced + * the input method open (such as by long-pressing menu) so it should + * not be closed until they explicitly do so. + */ + public static final int SHOW_FORCED = 0x0002; + + /** * Explicitly request that the current input method's soft input area be * shown to the user, if needed. Call this if the user interacts with * your view in such a way that they have expressed they would like to @@ -689,6 +612,14 @@ public final class InputMethodManager { } } + /** @hide */ + public void showSoftInputUnchecked(int flags) { + try { + mService.showSoftInput(mClient, flags); + } catch (RemoteException e) { + } + } + /** * Flag for {@link #hideSoftInputFromWindow} to indicate that the soft * input window should only be hidden if it was not explicitly shown @@ -697,6 +628,13 @@ public final class InputMethodManager { public static final int HIDE_IMPLICIT_ONLY = 0x0001; /** + * Flag for {@link #hideSoftInputFromWindow} to indicate that the soft + * input window should normally be hidden, unless it was originally + * shown with {@link #SHOW_FORCED}. + */ + public static final int HIDE_NOT_ALWAYS = 0x0002; + + /** * Request to hide the soft input window from the context of the window * that is currently accepting input. This should be called as a result * of the user doing some actually than fairly explicitly requests to @@ -779,6 +717,8 @@ public final class InputMethodManager { // do its stuff. // Life is good: let's hook everything up! EditorInfo tba = new EditorInfo(); + tba.packageName = view.getContext().getPackageName(); + tba.fieldId = view.getId(); InputConnection ic = view.onCreateInputConnection(tba); if (DEBUG) Log.v(TAG, "Starting input: tba=" + tba + " ic=" + ic); @@ -801,22 +741,23 @@ public final class InputMethodManager { mCurrentTextBoxAttribute = tba; mServedConnecting = false; mServedInputConnection = ic; + IInputContext servedContext; if (ic != null) { mCursorSelStart = tba.initialSelStart; mCursorSelEnd = tba.initialSelEnd; mCursorCandStart = -1; mCursorCandEnd = -1; mCursorRect.setEmpty(); - setCurrentInputConnection(ic); + servedContext = new ControlledInputConnectionWrapper(vh.getLooper(), ic); } else { - setCurrentInputConnection(mDummyInputConnection); + servedContext = null; } try { if (DEBUG) Log.v(TAG, "START INPUT: " + view + " ic=" + ic + " tba=" + tba + " initial=" + initial); - InputBindResult res = mService.startInput(mClient, tba, initial, - mCurMethod == null); + InputBindResult res = mService.startInput(mClient, + servedContext, tba, initial, mCurMethod == null); if (DEBUG) Log.v(TAG, "Starting input: Bind result=" + res); if (res != null) { if (res.id != null) { @@ -885,10 +826,20 @@ public final class InputMethodManager { + " winFocus=" + view.hasWindowFocus()); if (mServedView == view) { ic = mServedInputConnection; - if (view.hasWindowFocus()) { + // The following code would auto-hide the IME if we end up + // with no more views with focus. This can happen, however, + // whenever we go into touch mode, so it ends up hiding + // at times when we don't really want it to. For now it + // seems better to just turn it all off. + if (false && view.hasWindowFocus()) { mLastServedView = view; - mH.removeMessages(MSG_CHECK_FOCUS); - mH.sendEmptyMessage(MSG_CHECK_FOCUS); + Handler vh = view.getHandler(); + if (vh != null) { + // This will result in a call to checkFocus() below. + vh.removeMessages(ViewRoot.CHECK_FOCUS); + vh.sendMessage(vh.obtainMessage(ViewRoot.CHECK_FOCUS, + view)); + } } } } @@ -898,8 +849,14 @@ public final class InputMethodManager { } } - void checkFocus() { + /** + * @hide + */ + public void checkFocus(View view) { synchronized (mH) { + if (view != mLastServedView) { + return; + } if (DEBUG) Log.v(TAG, "checkFocus: view=" + mServedView + " last=" + mLastServedView); if (mServedView == mLastServedView) { @@ -915,7 +872,7 @@ public final class InputMethodManager { void closeCurrentInput() { try { - mService.hideSoftInput(mClient, 0); + mService.hideSoftInput(mClient, HIDE_NOT_ALWAYS); } catch (RemoteException e) { } } @@ -1006,6 +963,32 @@ public final class InputMethodManager { } /** + * Call {@link InputMethodSession#appPrivateCommand(String, Bundle) + * InputMethodSession.appPrivateCommand()} on the current Input Method. + * @param view Optional View that is sending the command, or null if + * you want to send the command regardless of the view that is attached + * to the input method. + * @param action Name of the command to be performed. This <em>must</em> + * be a scoped name, i.e. prefixed with a package name you own, so that + * different developers will not create conflicting commands. + * @param data Any data to include with the command. + */ + public void sendAppPrivateCommand(View view, String action, Bundle data) { + synchronized (mH) { + if ((view != null && mServedView != view) + || mCurrentTextBoxAttribute == null || mCurMethod == null) { + return; + } + try { + if (DEBUG) Log.v(TAG, "APP PRIVATE COMMAND " + action + ": " + data); + mCurMethod.appPrivateCommand(action, data); + } catch (RemoteException e) { + Log.w(TAG, "IME died: " + mCurId, e); + } + } + } + + /** * Force switch to a new input method component. This can only be called * from the currently active input method, as validated by the given token. * @param token Supplies the identifying token given to an input method @@ -1048,7 +1031,7 @@ public final class InputMethodManager { synchronized (mH) { if (DEBUG) Log.d(TAG, "dispatchKeyEvent"); - if (mCurMethod == null || mCurrentTextBoxAttribute == null) { + if (mCurMethod == null) { try { callback.finishedEvent(seq, false); } catch (RemoteException e) { @@ -1116,4 +1099,33 @@ public final class InputMethodManager { } } } + + void doDump(FileDescriptor fd, PrintWriter fout, String[] args) { + final Printer p = new PrintWriterPrinter(fout); + p.println("Input method client state for " + this + ":"); + + p.println(" mService=" + mService); + p.println(" mMainLooper=" + mMainLooper); + p.println(" mIInputContext=" + mIInputContext); + p.println(" mActive=" + mActive + + " mBindSequence=" + mBindSequence + + " mCurId=" + mCurId); + p.println(" mCurMethod=" + mCurMethod); + p.println(" mServedView=" + mServedView); + p.println(" mLastServedView=" + mLastServedView); + p.println(" mServedConnecting=" + mServedConnecting); + if (mCurrentTextBoxAttribute != null) { + p.println(" mCurrentTextBoxAttribute:"); + mCurrentTextBoxAttribute.dump(p, " "); + } else { + p.println(" mCurrentTextBoxAttribute: null"); + } + p.println(" mServedInputConnection=" + mServedInputConnection); + p.println(" mCompletions=" + mCompletions); + p.println(" mCursorRect=" + mCursorRect); + p.println(" mCursorSelStart=" + mCursorSelStart + + " mCursorSelEnd=" + mCursorSelEnd + + " mCursorCandStart=" + mCursorCandStart + + " mCursorCandEnd=" + mCursorCandEnd); + } } diff --git a/core/java/android/view/inputmethod/MutableInputConnectionWrapper.java b/core/java/android/view/inputmethod/MutableInputConnectionWrapper.java deleted file mode 100644 index 025a059..0000000 --- a/core/java/android/view/inputmethod/MutableInputConnectionWrapper.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2007-2008 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ - -package android.view.inputmethod; - - -/** - * Special version of {@link InputConnectionWrapper} that allows the base - * input connection to be modified after it is initially set. - */ -public class MutableInputConnectionWrapper extends InputConnectionWrapper { - public MutableInputConnectionWrapper(InputConnection base) { - super(base); - } - - /** - * Change the base InputConnection for this wrapper. All calls will then be - * delegated to the base input connection. - * - * @param base The new base InputConnection for this wrapper. - */ - public void setBaseInputConnection(InputConnection base) { - mBase = base; - } -} diff --git a/core/java/android/webkit/ByteArrayBuilder.java b/core/java/android/webkit/ByteArrayBuilder.java index 16d663c..806b458 100644 --- a/core/java/android/webkit/ByteArrayBuilder.java +++ b/core/java/android/webkit/ByteArrayBuilder.java @@ -94,6 +94,14 @@ class ByteArrayBuilder { return mChunks.isEmpty(); } + public synchronized void clear() { + Chunk c = getFirstChunk(); + while (c != null) { + releaseChunk(c); + c = getFirstChunk(); + } + } + private Chunk appendChunk(int length) { if (length < mMinCapacity) { length = mMinCapacity; diff --git a/core/java/android/webkit/FileLoader.java b/core/java/android/webkit/FileLoader.java index 10343b2..54a4c1d 100644 --- a/core/java/android/webkit/FileLoader.java +++ b/core/java/android/webkit/FileLoader.java @@ -76,8 +76,12 @@ class FileLoader extends StreamLoader { protected boolean setupStreamAndSendStatus() { try { if (mIsAsset) { - mDataStream = mContext.getAssets().open(mPath, - AssetManager.ACCESS_STREAMING); + try { + mDataStream = mContext.getAssets().open(mPath); + } catch (java.io.FileNotFoundException ex) { + // try the rest files included in the package + mDataStream = mContext.getAssets().openNonAsset(mPath); + } } else { if (!mAllowFileAccess) { mHandler.error(EventHandler.FILE_ERROR, diff --git a/core/java/android/webkit/FrameLoader.java b/core/java/android/webkit/FrameLoader.java index 7a3bbe6..5e323eb 100644 --- a/core/java/android/webkit/FrameLoader.java +++ b/core/java/android/webkit/FrameLoader.java @@ -220,6 +220,7 @@ class FrameLoader { // Tell the Listener respond with the cache file CacheLoader cacheLoader = new CacheLoader(mListener, result); + mListener.setCacheLoader(cacheLoader); cacheLoader.load(); } diff --git a/core/java/android/webkit/LoadListener.java b/core/java/android/webkit/LoadListener.java index 3f2bbe5..3694969 100644 --- a/core/java/android/webkit/LoadListener.java +++ b/core/java/android/webkit/LoadListener.java @@ -33,6 +33,8 @@ import android.util.Config; import android.util.Log; import android.webkit.CacheManager.CacheResult; +import com.android.internal.R; + import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -56,6 +58,9 @@ class LoadListener extends Handler implements EventHandler { private static final int MSG_CONTENT_ERROR = 130; private static final int MSG_LOCATION_CHANGED = 140; private static final int MSG_LOCATION_CHANGED_REQUEST = 150; + private static final int MSG_STATUS = 160; + private static final int MSG_SSL_CERTIFICATE = 170; + private static final int MSG_SSL_ERROR = 180; // Standard HTTP status codes in a more representative format private static final int HTTP_OK = 200; @@ -166,9 +171,7 @@ class LoadListener extends Handler implements EventHandler { * available. The headers are sent onto WebCore to see what we * should do with them. */ - if (mNativeLoader != 0) { - commitHeadersCheckRedirect(); - } + handleHeaders((Headers) msg.obj); break; case MSG_CONTENT_DATA: @@ -177,7 +180,7 @@ class LoadListener extends Handler implements EventHandler { * in it's data buffer. This data buffer could be filled from a * file (this thread) or from http (Network thread). */ - if (mNativeLoader != 0) { + if (mNativeLoader != 0 && !ignoreCallbacks()) { commitLoad(); } break; @@ -189,7 +192,7 @@ class LoadListener extends Handler implements EventHandler { * error. * */ - tearDown(); + handleEndData(); break; case MSG_CONTENT_ERROR: @@ -197,8 +200,7 @@ class LoadListener extends Handler implements EventHandler { * This message is sent when a load error has occured. The * LoadListener will clean itself up. */ - notifyError(); - tearDown(); + handleError(msg.arg1, (String) msg.obj); break; case MSG_LOCATION_CHANGED: @@ -224,6 +226,33 @@ class LoadListener extends Handler implements EventHandler { stopMsg, contMsg); break; + case MSG_STATUS: + /* + * This message is sent from the network thread when the http + * stack has received the status response from the server. + */ + HashMap status = (HashMap) msg.obj; + handleStatus(((Integer) status.get("major")).intValue(), + ((Integer) status.get("minor")).intValue(), + ((Integer) status.get("code")).intValue(), + (String) status.get("reason")); + break; + + case MSG_SSL_CERTIFICATE: + /* + * This message is sent when the network thread receives a ssl + * certificate. + */ + handleCertificate((SslCertificate) msg.obj); + break; + + case MSG_SSL_ERROR: + /* + * This message is sent when the network thread encounters a + * ssl error. + */ + handleSslError((SslError) msg.obj); + break; } } @@ -257,6 +286,11 @@ class LoadListener extends Handler implements EventHandler { */ public void headers(Headers headers) { if (Config.LOGV) Log.v(LOGTAG, "LoadListener.headers"); + sendMessageInternal(obtainMessage(MSG_CONTENT_HEADERS, headers)); + } + + // Does the header parsing work on the WebCore thread. + private void handleHeaders(Headers headers) { if (mCancelled) return; mHeaders = headers; mMimeType = ""; @@ -375,7 +409,7 @@ class LoadListener extends Handler implements EventHandler { mCacheResult.encoding = mEncoding; } } - sendMessageInternal(obtainMessage(MSG_CONTENT_HEADERS)); + commitHeadersCheckRedirect(); } /** @@ -404,11 +438,20 @@ class LoadListener extends Handler implements EventHandler { + " code: " + code + " reason: " + reasonPhrase); } + HashMap status = new HashMap(); + status.put("major", majorVersion); + status.put("minor", minorVersion); + status.put("code", code); + status.put("reason", reasonPhrase); + sendMessageInternal(obtainMessage(MSG_STATUS, status)); + } + // Handle the status callback on the WebCore thread. + private void handleStatus(int major, int minor, int code, String reason) { if (mCancelled) return; mStatusCode = code; - mStatusText = reasonPhrase; + mStatusText = reason; mPermanent = false; } @@ -418,8 +461,15 @@ class LoadListener extends Handler implements EventHandler { * connection. In this context, can be called multiple * times if we have redirects * @param certificate The SSL certifcate + * IMPORTANT: as this is called from network thread, can't call native + * directly */ public void certificate(SslCertificate certificate) { + sendMessageInternal(obtainMessage(MSG_SSL_CERTIFICATE, certificate)); + } + + // Handle the certificate on the WebCore thread. + private void handleCertificate(SslCertificate certificate) { // if this is the top-most main-frame page loader if (mIsMainPageLoader) { // update the browser frame (ie, the main frame) @@ -436,14 +486,20 @@ class LoadListener extends Handler implements EventHandler { * directly */ public void error(int id, String description) { - mErrorID = id; - mErrorDescription = description; - sendMessageInternal(obtainMessage(MSG_CONTENT_ERROR)); if (Config.LOGV) { Log.v(LOGTAG, "LoadListener.error url:" + url() + " id:" + id + " description:" + description); } + sendMessageInternal(obtainMessage(MSG_CONTENT_ERROR, id, 0, description)); + } + + // Handle the error on the WebCore thread. + private void handleError(int id, String description) { + mErrorID = id; + mErrorDescription = description; detachRequestHandle(); + notifyError(); + tearDown(); } /** @@ -453,11 +509,15 @@ class LoadListener extends Handler implements EventHandler { * @param length The length of data. * IMPORTANT: as this is called from network thread, can't call native * directly + * XXX: Unlike the other network thread methods, this method can do the + * work of decoding the data and appending it to the data builder because + * mDataBuilder is a thread-safe structure. */ public void data(byte[] data, int length) { if (Config.LOGV) { Log.v(LOGTAG, "LoadListener.data(): url: " + url()); } + // Decode base64 data // Note: It's fine that we only decode base64 here and not in the other // data call because the only caller of the stream version is not @@ -479,7 +539,7 @@ class LoadListener extends Handler implements EventHandler { sendMessage = mDataBuilder.isEmpty(); mDataBuilder.append(data, 0, length); } - if (sendMessage && !ignoreCallbacks()) { + if (sendMessage) { // Send a message whenever data comes in after a write to WebCore sendMessageInternal(obtainMessage(MSG_CONTENT_DATA)); } @@ -495,7 +555,11 @@ class LoadListener extends Handler implements EventHandler { if (Config.LOGV) { Log.v(LOGTAG, "LoadListener.endData(): url: " + url()); } + sendMessageInternal(obtainMessage(MSG_CONTENT_FINISHED)); + } + // Handle the end of data. + private void handleEndData() { if (mCancelled) return; switch (mStatusCode) { @@ -505,17 +569,13 @@ class LoadListener extends Handler implements EventHandler { case HTTP_FOUND: case HTTP_SEE_OTHER: case HTTP_TEMPORARY_REDIRECT: - if (mMethod == null && mRequestHandle == null) { - Log.e(LOGTAG, "LoadListener.endData(): method is null!"); - Log.e(LOGTAG, "LoadListener.endData(): url = " + url()); - } // 301, 302, 303, and 307 - redirect if (mStatusCode == HTTP_TEMPORARY_REDIRECT) { if (mRequestHandle != null && mRequestHandle.getMethod().equals("POST")) { sendMessageInternal(obtainMessage( MSG_LOCATION_CHANGED_REQUEST)); - } else if (mMethod != null && mMethod.equals("POST")) { + } else if (mMethod.equals("POST")) { sendMessageInternal(obtainMessage( MSG_LOCATION_CHANGED_REQUEST)); } else { @@ -558,9 +618,14 @@ class LoadListener extends Handler implements EventHandler { default: break; } - - sendMessageInternal(obtainMessage(MSG_CONTENT_FINISHED)); detachRequestHandle(); + tearDown(); + } + + /* This method is called from CacheLoader when the initial request is + * serviced by the Cache. */ + /* package */ void setCacheLoader(CacheLoader c) { + mCacheLoader = c; } /** @@ -574,9 +639,16 @@ class LoadListener extends Handler implements EventHandler { CacheResult result = CacheManager.getCacheFile(url(), headers); + // Go ahead and set the cache loader to null in case the result is + // null. + mCacheLoader = null; + if (result != null) { - CacheLoader cacheLoader = - new CacheLoader(this, result); + // The contents of the cache may need to be revalidated so just + // remember the cache loader in the case that the server responds + // positively to the cached content. This is also used to detect if + // a redirect came from the cache. + mCacheLoader = new CacheLoader(this, result); // If I got a cachedUrl and the revalidation header was not // added, then the cached content valid, we should use it. @@ -589,14 +661,8 @@ class LoadListener extends Handler implements EventHandler { "and usable: " + url()); } // Load the cached file - cacheLoader.load(); + mCacheLoader.load(); return true; - } else { - // The contents of the cache need to be revalidated - // so just provide the listener with the cache loader - // in the case that the server response positively to - // the cached content. - setCacheLoader(cacheLoader); } } return false; @@ -615,7 +681,11 @@ class LoadListener extends Handler implements EventHandler { " primary error: " + error.getPrimaryError() + " certificate: " + error.getCertificate()); } + sendMessageInternal(obtainMessage(MSG_SSL_ERROR, error)); + } + // Handle the ssl error on the WebCore thread. + private void handleSslError(SslError error) { if (!mCancelled) { mSslError = error; Network.getInstance(mContext).handleSslErrorRequest(this); @@ -705,14 +775,6 @@ class LoadListener extends Handler implements EventHandler { } /** - * Set the CacheLoader for the case where we might want to load from cache - * @param result - */ - void setCacheLoader(CacheLoader result) { - mCacheLoader = result; - } - - /** * This is called when a request can be satisfied by the cache, however, * the cache result could be a redirect. In this case we need to issue * the network request. @@ -1002,6 +1064,11 @@ class LoadListener extends Handler implements EventHandler { clearNativeLoader(); } + // This count is transferred from RequestHandle to LoadListener when + // loading from the cache so that we can detect redirect loops that switch + // between the network and the cache. + private int mCacheRedirectCount; + /* * Perform the actual redirection. This involves setting up the new URL, * informing WebCore and then telling the Network to start loading again. @@ -1014,6 +1081,14 @@ class LoadListener extends Handler implements EventHandler { return; } + // Do the same check for a redirect loop that + // RequestHandle.setupRedirect does. + if (mCacheRedirectCount >= RequestHandle.MAX_REDIRECT_COUNT) { + handleError(EventHandler.ERROR_REDIRECT_LOOP, mContext.getString( + R.string.httpErrorRedirectLoop)); + return; + } + String redirectTo = mHeaders.getLocation(); if (redirectTo != null) { int nativeResponse = createNativeResponse(); @@ -1031,7 +1106,7 @@ class LoadListener extends Handler implements EventHandler { return; } else if (!URLUtil.isNetworkUrl(redirectTo)) { final String text = mContext - .getString(com.android.internal.R.string.open_permission_deny) + .getString(R.string.open_permission_deny) + "\n" + redirectTo; nativeAddData(text.getBytes(), text.length()); nativeFinished(); @@ -1057,6 +1132,13 @@ class LoadListener extends Handler implements EventHandler { if (mRequestHeaders == null) { mRequestHeaders = new HashMap<String, String>(); } + boolean fromCache = false; + if (mCacheLoader != null) { + // This is a redirect from the cache loader. Increment the + // redirect count to avoid redirect loops. + mCacheRedirectCount++; + fromCache = true; + } if (!checkCache(mRequestHeaders)) { // mRequestHandle can be null when the request was satisfied // by the cache, and the cache returned a redirect @@ -1064,23 +1146,37 @@ class LoadListener extends Handler implements EventHandler { mRequestHandle.setupRedirect(redirectTo, mStatusCode, mRequestHeaders); } else { - String method = mMethod; - - if (method == null) { + // If the original request came from the cache, there is no + // RequestHandle, we have to create a new one through + // Network.requestURL. + Network network = Network.getInstance(getContext()); + if (!network.requestURL(mMethod, mRequestHeaders, + mPostData, this, mIsHighPriority)) { + // Signal a bad url error if we could not load the + // redirection. + handleError(EventHandler.ERROR_BAD_URL, + mContext.getString(R.string.httpErrorBadUrl)); return; } - - Network network = Network.getInstance(getContext()); - network.requestURL(method, mRequestHeaders, - mPostData, this, mIsHighPriority); } + if (fromCache) { + // If we are coming from a cache load, we need to transfer + // the redirect count to the new (or old) RequestHandle to + // keep the redirect count in sync. + mRequestHandle.setRedirectCount(mCacheRedirectCount); + } + } else if (!fromCache) { + // Switching from network to cache means we need to grab the + // redirect count from the RequestHandle to keep the count in + // sync. Add 1 to account for the current redirect. + mCacheRedirectCount = mRequestHandle.getRedirectCount() + 1; } + // Clear the buffered data since the redirect is valid. + mDataBuilder.clear(); } else { - // With a null redirect, commit the original headers, the buffered - // data, and then finish the load. commitHeaders(); commitLoad(); - nativeFinished(); + tearDown(); } if (Config.LOGV) { @@ -1167,14 +1263,16 @@ class LoadListener extends Handler implements EventHandler { quoted = !quoted; } else { if (!quoted) { - if (header.startsWith( - HttpAuthHeader.BASIC_TOKEN, i)) { + if (header.regionMatches(true, i, + HttpAuthHeader.BASIC_TOKEN, 0, + HttpAuthHeader.BASIC_TOKEN.length())) { pos[posLen++] = i; continue; } - if (header.startsWith( - HttpAuthHeader.DIGEST_TOKEN, i)) { + if (header.regionMatches(true, i, + HttpAuthHeader.DIGEST_TOKEN, 0, + HttpAuthHeader.DIGEST_TOKEN.length())) { pos[posLen++] = i; continue; } @@ -1186,8 +1284,9 @@ class LoadListener extends Handler implements EventHandler { if (posLen > 0) { // consider all digest schemes first (if any) for (int i = 0; i < posLen; i++) { - if (header.startsWith(HttpAuthHeader.DIGEST_TOKEN, - pos[i])) { + if (header.regionMatches(true, pos[i], + HttpAuthHeader.DIGEST_TOKEN, 0, + HttpAuthHeader.DIGEST_TOKEN.length())) { String sub = header.substring(pos[i], (i + 1 < posLen ? pos[i + 1] : headerLen)); @@ -1201,7 +1300,9 @@ class LoadListener extends Handler implements EventHandler { // ...then consider all basic schemes (if any) for (int i = 0; i < posLen; i++) { - if (header.startsWith(HttpAuthHeader.BASIC_TOKEN, pos[i])) { + if (header.regionMatches(true, pos[i], + HttpAuthHeader.BASIC_TOKEN, 0, + HttpAuthHeader.BASIC_TOKEN.length())) { String sub = header.substring(pos[i], (i + 1 < posLen ? pos[i + 1] : headerLen)); @@ -1262,9 +1363,8 @@ class LoadListener extends Handler implements EventHandler { // type (implying text/plain). if (URLUtil.isDataUrl(mUrl) && mMimeType.length() != 0) { cancel(); - final String text = mContext.getString( - com.android.internal.R.string.httpErrorBadUrl); - error(EventHandler.ERROR_BAD_URL, text); + final String text = mContext.getString(R.string.httpErrorBadUrl); + handleError(EventHandler.ERROR_BAD_URL, text); } else { // Note: This is ok because this is used only for the main content // of frames. If no content-type was specified, it is fine to diff --git a/core/java/android/webkit/MimeTypeMap.java b/core/java/android/webkit/MimeTypeMap.java index 685e352..c9cc208 100644 --- a/core/java/android/webkit/MimeTypeMap.java +++ b/core/java/android/webkit/MimeTypeMap.java @@ -480,6 +480,7 @@ public /* package */ class MimeTypeMap { sMimeTypeMap.loadEntry("video/mpeg", "mpg", false); sMimeTypeMap.loadEntry("video/mpeg", "mpe", false); sMimeTypeMap.loadEntry("video/mp4", "mp4", false); + sMimeTypeMap.loadEntry("video/mpeg", "VOB", false); sMimeTypeMap.loadEntry("video/quicktime", "qt", false); sMimeTypeMap.loadEntry("video/quicktime", "mov", false); sMimeTypeMap.loadEntry("video/vnd.mpegurl", "mxu", false); diff --git a/core/java/android/webkit/TextDialog.java b/core/java/android/webkit/TextDialog.java index b7b40b1..9af30c5 100644 --- a/core/java/android/webkit/TextDialog.java +++ b/core/java/android/webkit/TextDialog.java @@ -33,7 +33,6 @@ import android.text.Selection; import android.text.Spannable; import android.text.TextPaint; import android.text.TextUtils; -import android.text.method.MetaKeyKeyListener; import android.text.method.MovementMethod; import android.text.method.PasswordTransformationMethod; import android.text.method.TextKeyListener; @@ -44,7 +43,6 @@ import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; -import android.view.View.MeasureSpec; import android.view.ViewConfiguration; import android.widget.AbsoluteLayout.LayoutParams; import android.widget.ArrayAdapter; @@ -69,10 +67,8 @@ import java.util.ArrayList; // on the enter key. The method for blocking unmatched key ups prevents // the shift key from working properly. private boolean mGotEnterDown; - // Determines whether we allow calls to requestRectangleOnScreen to - // propagate. We only want to scroll if the user is typing. If the - // user is simply navigating through a textfield, we do not want to - // scroll. + // mScrollToAccommodateCursor being set to false prevents us from scrolling + // the cursor on screen when using the trackball to select a textfield. private boolean mScrollToAccommodateCursor; private int mMaxLength; // Keep track of the text before the change so we know whether we actually @@ -183,6 +179,11 @@ import java.util.ArrayList; mWebView.shortPressOnTextField(); return true; } + // If we reached here, then this is a single line textfield, and + // the user pressed ENTER. In this case, we want to hide the + // soft input method. + InputMethodManager.getInstance(mContext) + .hideSoftInputFromWindow(getWindowToken(), 0); sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); sendDomEvent(event); } @@ -405,6 +406,12 @@ import java.util.ArrayList; //mWebView.setSelection(start, end); return true; } + // If the user is in a textfield, and the movement method is not + // handling the trackball events, it means they are at the end of the + // field and continuing to move the trackball. In this case, we should + // not scroll the cursor on screen bc the user may be attempting to + // scroll the page, possibly in the opposite direction of the cursor. + mScrollToAccommodateCursor = false; return false; } @@ -419,6 +426,17 @@ import java.util.ArrayList; mHandler.removeMessages(LONGPRESS); mWebView.removeView(this); mWebView.requestFocus(); + mScrollToAccommodateCursor = false; + } + + /* package */ void enableScrollOnScreen(boolean enable) { + mScrollToAccommodateCursor = enable; + } + + /* package */ void bringIntoView() { + if (getLayout() != null) { + bringPointIntoView(Selection.getSelectionEnd(getText())); + } } @Override @@ -437,8 +455,16 @@ import java.util.ArrayList; mWebView.passToJavaScript(getText().toString(), event); } + /** + * Always use this instead of setAdapter, as this has features specific to + * the TextDialog. + */ public void setAdapterCustom(AutoCompleteAdapter adapter) { - adapter.setTextView(this); + if (adapter != null) { + adapter.setTextView(this); + } else { + setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE); + } super.setAdapter(adapter); } @@ -483,12 +509,12 @@ import java.util.ArrayList; PasswordTransformationMethod method; if (inPassword) { method = PasswordTransformationMethod.getInstance(); + setInputType(EditorInfo.TYPE_CLASS_TEXT|EditorInfo. + TYPE_TEXT_VARIATION_PASSWORD); } else { method = null; } setTransformationMethod(method); - setInputType(inPassword ? EditorInfo.TYPE_TEXT_VARIATION_PASSWORD : - EditorInfo.TYPE_CLASS_TEXT); } /* package */ void setMaxLength(int maxLength) { @@ -539,7 +565,6 @@ import java.util.ArrayList; // Set up a measure spec so a layout can always be recreated. mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); - mScrollToAccommodateCursor = false; requestFocus(); } @@ -547,18 +572,23 @@ import java.util.ArrayList; * Set whether this is a single-line textfield or a multi-line textarea. * Textfields scroll horizontally, and do not handle the enter key. * Textareas behave oppositely. + * Do NOT call this after calling setInPassword(true). This will result in + * removing the password input type. */ public void setSingleLine(boolean single) { if (mSingle != single) { TextKeyListener.Capitalize cap; + int inputType = EditorInfo.TYPE_CLASS_TEXT; if (single) { cap = TextKeyListener.Capitalize.NONE; } else { cap = TextKeyListener.Capitalize.SENTENCES; + inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; } setKeyListener(TextKeyListener.getInstance(!single, cap)); mSingle = single; setHorizontallyScrolling(single); + setInputType(inputType); } } diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java index 1a7c4ff..5c470cf 100644 --- a/core/java/android/webkit/WebSettings.java +++ b/core/java/android/webkit/WebSettings.java @@ -316,10 +316,15 @@ public class WebSettings { buffer.append("en"); } - final String device = Build.DEVICE; - if (device.length() > 0) { + final String model = Build.MODEL; + if (model.length() > 0) { buffer.append("; "); - buffer.append(device); + buffer.append(model); + } + final String id = Build.ID; + if (id.length() > 0) { + buffer.append(" Build/"); + buffer.append(id); } final String base = mContext.getResources().getText( com.android.internal.R.string.web_user_agent).toString(); diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java index cab278be..3306700 100644 --- a/core/java/android/webkit/WebView.java +++ b/core/java/android/webkit/WebView.java @@ -68,6 +68,8 @@ import android.widget.RelativeLayout; import android.widget.Scroller; import android.widget.Toast; import android.widget.ZoomControls; +import android.widget.ZoomRingController; +import android.widget.FrameLayout; import android.widget.AdapterView.OnItemClickListener; import java.io.File; @@ -107,17 +109,14 @@ public class WebView extends AbsoluteLayout static final boolean DEBUG = false; static final boolean LOGV_ENABLED = DEBUG ? Config.LOGD : Config.LOGV; - private class ExtendedZoomControls extends RelativeLayout { + private class ExtendedZoomControls extends FrameLayout { public ExtendedZoomControls(Context context, AttributeSet attrs) { super(context, attrs); - LayoutInflater inflater = (LayoutInflater) context - .getSystemService(Context.LAYOUT_INFLATER_SERVICE); - inflater.inflate(com.android.internal.R.layout.zoom_magnify, this - , true); - mZoomControls = (ZoomControls) findViewById - (com.android.internal.R.id.zoomControls); - mZoomMagnify = (ImageView) findViewById - (com.android.internal.R.id.zoomMagnify); + LayoutInflater inflater = (LayoutInflater) + context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true); + mZoomControls = (ZoomControls) findViewById(com.android.internal.R.id.zoomControls); + mZoomMagnify = (ImageView) findViewById(com.android.internal.R.id.zoomMagnify); } public void show(boolean showZoom, boolean canZoomOut) { @@ -258,6 +257,27 @@ public class WebView extends AbsoluteLayout // Whether to forward the touch events to WebCore private boolean mForwardTouchEvents = false; + // Whether we are in the drag tap mode, which exists starting at the second + // tap's down, through its move, and includes its up. These events should be + // given to the method on the zoom controller. + private boolean mInZoomTapDragMode; + + // The event time of the previous touch up. + private long mPreviousUpTime; + + private Runnable mRemoveReleaseSingleTap = new Runnable() { + public void run() { + mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); + mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); + mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); + } + }; + + // Whether to prevent drag during touch. The initial value depends on + // mForwardTouchEvents. If WebCore wants touch events, we assume it will + // take control of touch events unless it says no for touch down event. + private boolean mPreventDrag; + // If updateTextEntry gets called while we are out of focus, use this // variable to remember to do it next time we gain focus. private boolean mNeedsUpdateTextEntry = false; @@ -269,8 +289,7 @@ public class WebView extends AbsoluteLayout * Customizable constant */ // pre-computed square of ViewConfiguration.getTouchSlop() - private static final int TOUCH_SLOP_SQUARE = - ViewConfiguration.getTouchSlop() * ViewConfiguration.getTouchSlop(); + private int mTouchSlopSquare; // This should be ViewConfiguration.getTapTimeout() // But system time out is 100ms, which is too short for the browser. // In the browser, if it switches out of tap too soon, jump tap won't work. @@ -360,6 +379,8 @@ public class WebView extends AbsoluteLayout static final int LONG_PRESS_ENTER = 23; static final int PREVENT_TOUCH_ID = 24; static final int WEBCORE_NEED_TOUCH_EVENTS = 25; + // obj=Rect in doc coordinates + static final int INVAL_RECT_MSG_ID = 26; // width which view is considered to be fully zoomed out static final int ZOOM_OUT_WIDTH = 1024; @@ -373,6 +394,9 @@ public class WebView extends AbsoluteLayout // initial scale in percent. 0 means using default. private int mInitialScale = 0; + // set to true temporarily while the zoom control is being dragged + private boolean mPreviewZoomOnly = false; + // computed scale and inverse, from mZoomWidth. private float mActualScale = 1; private float mInvActualScale = 1; @@ -490,7 +514,73 @@ public class WebView extends AbsoluteLayout return mExtra; } } + + private ZoomRingController mZoomRingController; + + private ZoomRingController.OnZoomListener mZoomListener = + new ZoomRingController.OnZoomListener() { + + public void onCenter(int x, int y) { + // Don't translate when the control is invoked, hence we do nothing + // in this callback + } + + public boolean onPan(int deltaX, int deltaY) { + return pinScrollBy(deltaX, deltaY, false, 0); + } + + public void onVisibilityChanged(boolean visible) { + if (visible) { + mZoomControls.show(false, canZoomScrollOut()); + } else { + mZoomControls.hide(); + } + } + + public void onBeginDrag(float startAngle) { + mPreviewZoomOnly = true; + } + + public void onEndDrag(float endAngle) { + mPreviewZoomOnly = false; + setNewZoomScale(mActualScale, true); + } + + public boolean onDragZoom(int deltaZoomLevel, int centerX, + int centerY, float startAngle, float curAngle) { + + if (mZoomScale == mMinZoomScale && deltaZoomLevel < 0 || + mZoomScale == mMaxZoomScale && deltaZoomLevel > 0 || + deltaZoomLevel == 0) { + return false; + } + + int deltaX = centerX - getViewWidth() / 2; + int deltaY = centerY - getViewHeight() / 2; + pinScrollBy(deltaX, deltaY, false, 0); + + while (deltaZoomLevel != 0) { + if (deltaZoomLevel > 0) { + if (!zoomIn()) return false; + deltaZoomLevel--; + } else { + if (!zoomOut()) return false; + deltaZoomLevel++; + } + } + + pinScrollBy(-deltaX, -deltaY, false, 0); + + return true; + } + + public void onSimpleZoom(boolean zoomIn) { + if (zoomIn) zoomIn(); + else zoomOut(); + } + }; + /** * Construct a new WebView with a Context object. * @param context A Context object used to access application assets. @@ -518,11 +608,6 @@ public class WebView extends AbsoluteLayout super(context, attrs, defStyle); init(); - TypedArray a = context.obtainStyledAttributes( - com.android.internal.R.styleable.View); - initializeScrollbars(a); - a.recycle(); - mCallbackProxy = new CallbackProxy(context, this); mWebViewCore = new WebViewCore(context, this, mCallbackProxy); mDatabase = WebViewDatabase.getInstance(context); @@ -532,6 +617,8 @@ public class WebView extends AbsoluteLayout mFocusData.mX = 0; mFocusData.mY = 0; mScroller = new Scroller(context); + mZoomRingController = new ZoomRingController(context, this); + mZoomRingController.setCallback(mZoomListener); } private void init() { @@ -541,9 +628,9 @@ public class WebView extends AbsoluteLayout setClickable(true); setLongClickable(true); - // should be conditional on if we're in the browser activity? - setHorizontalScrollBarEnabled(true); - setVerticalScrollBarEnabled(true); + final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); + mTouchSlopSquare = slop * slop; + mMinLockSnapReverseDistance = slop; } /* package */ boolean onSavePassword(String schemePlusHost, String username, @@ -648,7 +735,7 @@ public class WebView extends AbsoluteLayout * to. */ private int getViewWidth() { - if (mOverlayVerticalScrollbar) { + if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) { return getWidth(); } else { return getWidth() - getVerticalScrollbarWidth(); @@ -660,7 +747,7 @@ public class WebView extends AbsoluteLayout * to. */ private int getViewHeight() { - if (mOverlayHorizontalScrollbar) { + if (!isHorizontalScrollBarEnabled() || mOverlayHorizontalScrollbar) { return getHeight(); } else { return getHeight() - getHorizontalScrollbarHeight(); @@ -732,7 +819,6 @@ public class WebView extends AbsoluteLayout */ public void destroy() { clearTextEntry(); - getViewTreeObserver().removeOnGlobalFocusChangeListener(this); if (mWebViewCore != null) { // Set the handlers to null before destroying WebViewCore so no // more messages will be posted. @@ -1165,7 +1251,7 @@ public class WebView extends AbsoluteLayout nativeClearFocus(-1, -1); if (top) { // go to the top of the document - return pinScrollTo(mScrollX, 0, true); + return pinScrollTo(mScrollX, 0, true, 0); } // Page up int h = getHeight(); @@ -1176,7 +1262,7 @@ public class WebView extends AbsoluteLayout y = -h / 2; } mUserScroll = true; - return mScroller.isFinished() ? pinScrollBy(0, y, true) + return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) : extendScroll(y); } @@ -1191,7 +1277,7 @@ public class WebView extends AbsoluteLayout } nativeClearFocus(-1, -1); if (bottom) { - return pinScrollTo(mScrollX, mContentHeight, true); + return pinScrollTo(mScrollX, mContentHeight, true, 0); } // Page down. int h = getHeight(); @@ -1202,7 +1288,7 @@ public class WebView extends AbsoluteLayout y = h / 2; } mUserScroll = true; - return mScroller.isFinished() ? pinScrollBy(0, y, true) + return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) : extendScroll(y); } @@ -1485,12 +1571,14 @@ public class WebView extends AbsoluteLayout if (mDrawHistory) { // If history Picture is drawn, don't update scroll. They will // be updated when we get out of that mode. - if (scale != mActualScale) { + if (scale != mActualScale && !mPreviewZoomOnly) { mCallbackProxy.onScaleChanged(mActualScale, scale); } mActualScale = scale; mInvActualScale = 1 / scale; - sendViewSizeZoom(); + if (!mPreviewZoomOnly) { + sendViewSizeZoom(); + } } else { // update our scroll so we don't appear to jump // i.e. keep the center of the doc in the center of the view @@ -1502,7 +1590,7 @@ public class WebView extends AbsoluteLayout float sy = ratio * oldY + (ratio - 1) * getViewHeight() * 0.5f; // now update our new scale and inverse - if (scale != mActualScale) { + if (scale != mActualScale && !mPreviewZoomOnly) { mCallbackProxy.onScaleChanged(mActualScale, scale); } mActualScale = scale; @@ -1514,8 +1602,10 @@ public class WebView extends AbsoluteLayout mScrollX = pinLocX(Math.round(sx)); mScrollY = pinLocY(Math.round(sy)); - sendViewSizeZoom(); - sendOurVisibleRect(); + if (!mPreviewZoomOnly) { + sendViewSizeZoom(); + sendOurVisibleRect(); + } } } } @@ -1716,8 +1806,8 @@ public class WebView extends AbsoluteLayout */ public void clearFormData() { if (inEditingMode()) { - ArrayAdapter<String> adapter = null; - mTextEntry.setAdapter(adapter); + AutoCompleteAdapter adapter = null; + mTextEntry.setAdapterCustom(adapter); } } @@ -1812,7 +1902,7 @@ public class WebView extends AbsoluteLayout nativeSetFindIsDown(); // Now that the dialog has been removed, ensure that we scroll to a // location that is not beyond the end of the page. - pinScrollTo(mScrollX, mScrollY, false); + pinScrollTo(mScrollX, mScrollY, false, 0); invalidate(); } @@ -1855,13 +1945,13 @@ public class WebView extends AbsoluteLayout // helper to pin the scrollBy parameters (already in view coordinates) // returns true if the scroll was changed - private boolean pinScrollBy(int dx, int dy, boolean animate) { - return pinScrollTo(mScrollX + dx, mScrollY + dy, animate); + private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) { + return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration); } // helper to pin the scrollTo parameters (already in view coordinates) // returns true if the scroll was changed - private boolean pinScrollTo(int x, int y, boolean animate) { + private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) { x = pinLocX(x); y = pinLocY(y); int dx = x - mScrollX; @@ -1875,7 +1965,7 @@ public class WebView extends AbsoluteLayout // Log.d(LOGTAG, "startScroll: " + dx + " " + dy); mScroller.startScroll(mScrollX, mScrollY, dx, dy, - computeDuration(dx, dy)); + animationDuration > 0 ? animationDuration : computeDuration(dx, dy)); invalidate(); } else { mScroller.abortAnimation(); // just in case @@ -1910,10 +2000,10 @@ public class WebView extends AbsoluteLayout // vertical scroll? // Log.d(LOGTAG, "setContentScrollBy cy=" + cy); if (cy == 0 && cx != 0) { - pinScrollBy(cx, 0, true); + pinScrollBy(cx, 0, true, 0); } } else { - pinScrollBy(cx, cy, true); + pinScrollBy(cx, cy, true, 0); } } @@ -1933,7 +2023,7 @@ public class WebView extends AbsoluteLayout int vy = contentToView(cy); // Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" + // vx + " " + vy + "]"); - pinScrollTo(vx, vy, false); + pinScrollTo(vx, vy, false, 0); if (mScrollX != vx || mScrollY != vy) { return true; } else { @@ -1950,7 +2040,7 @@ public class WebView extends AbsoluteLayout } int vx = contentToView(cx); int vy = contentToView(cy); - pinScrollTo(vx, vy, true); + pinScrollTo(vx, vy, true, 0); } /** @@ -2692,12 +2782,9 @@ public class WebView extends AbsoluteLayout InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(mTextEntry, 0); + mTextEntry.enableScrollOnScreen(true); } - // Used to register the global focus change listener one time to avoid - // multiple references to WebView - private boolean mGlobalFocusChangeListenerAdded; - private void updateTextEntry() { if (mTextEntry == null) { mTextEntry = new TextDialog(mContext, WebView.this); @@ -2730,9 +2817,6 @@ public class WebView extends AbsoluteLayout // Note that sendOurVisibleRect calls viewToContent, so the coordinates // should be in content coordinates. if (!Rect.intersects(node.mBounds, visibleRect)) { - if (alreadyThere) { - mTextEntry.remove(); - } // Node is not on screen, so do not bother. return; } @@ -2785,21 +2869,32 @@ public class WebView extends AbsoluteLayout } } mTextEntry.setMaxLength(maxLength); - ArrayAdapter<String> adapter = null; - mTextEntry.setAdapter(adapter); - mTextEntry.setInPassword(node.mIsPassword); + AutoCompleteAdapter adapter = null; + mTextEntry.setAdapterCustom(adapter); mTextEntry.setSingleLine(node.mIsTextField); + mTextEntry.setInPassword(node.mIsPassword); if (null == text) { mTextEntry.setText("", 0, 0); } else { - mTextEntry.setText(text, 0, text.length()); + // Change to true to enable the old style behavior, where + // entering a textfield/textarea always set the selection to the + // whole field. This was desirable for the case where the user + // intends to scroll past the field using the trackball. + // However, it causes a problem when replying to emails - the + // user expects the cursor to be at the beginning of the + // textarea. Testing out a new behavior, where textfields set + // selection at the end, and textareas at the beginning. + if (false) { + mTextEntry.setText(text, 0, text.length()); + } else if (node.mIsTextField) { + int length = text.length(); + mTextEntry.setText(text, length, length); + } else { + mTextEntry.setText(text, 0, 0); + } } mTextEntry.requestFocus(); } - if (!mGlobalFocusChangeListenerAdded) { - getViewTreeObserver().addOnGlobalFocusChangeListener(this); - mGlobalFocusChangeListenerAdded = true; - } } private class UpdateTextEntryAdapter implements Runnable { @@ -3114,24 +3209,17 @@ public class WebView extends AbsoluteLayout // Implementation for OnHierarchyChangeListener public void onChildViewAdded(View parent, View child) {} - // When we are removed, remove this as a global focus change listener. public void onChildViewRemoved(View p, View child) { if (child == this) { - p.getViewTreeObserver().removeOnGlobalFocusChangeListener(this); - mGlobalFocusChangeListenerAdded = false; + if (inEditingMode()) { + clearTextEntry(); + mNeedsUpdateTextEntry = true; + } } } - - // Use this to know when the textview has lost focus, and something other - // than the webview has gained focus. Stop drawing the focus ring, remove - // the TextView, and set a flag to put it back when we regain focus. + + @Deprecated public void onGlobalFocusChanged(View oldFocus, View newFocus) { - if (oldFocus == mTextEntry && newFocus != this) { - mDrawFocusRing = false; - mTextEntry.updateCachedTextfield(); - removeView(mTextEntry); - mNeedsUpdateTextEntry = true; - } } // To avoid drawing the focus ring, and remove the TextView when our window @@ -3153,16 +3241,10 @@ public class WebView extends AbsoluteLayout mDrawFocusRing = false; } } else { - // If our window has lost focus, stop drawing the focus ring, and - // remove the TextView if displayed, and flag it to be added when - // we regain focus. + // If our window has lost focus, stop drawing the focus ring mDrawFocusRing = false; mGotKeyDown = false; mShiftIsPressed = false; - if (inEditingMode()) { - clearTextEntry(); - mNeedsUpdateTextEntry = true; - } } invalidate(); super.onWindowFocusChanged(hasWindowFocus); @@ -3245,9 +3327,8 @@ public class WebView extends AbsoluteLayout // 3. If there is a same direction back and forth, lock it. // adjustable parameters + private int mMinLockSnapReverseDistance; private static final float MAX_SLOPE_FOR_DIAG = 1.5f; - private static final int MIN_LOCK_SNAP_REVERSE_DISTANCE = - ViewConfiguration.getTouchSlop(); private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; @Override @@ -3261,6 +3342,27 @@ public class WebView extends AbsoluteLayout + mTouchMode); } + if (mZoomRingController.isVisible()) { + if (mInZoomTapDragMode) { + mZoomRingController.handleDoubleTapEvent(ev); + if (ev.getAction() == MotionEvent.ACTION_UP) { + // Just released the second tap, no longer in tap-drag mode + mInZoomTapDragMode = false; + } + return true; + } else { + // TODO: properly do this. + /* + * When the zoom widget is showing, the user can tap outside of + * it to dismiss it. Furthermore, he can drag outside of it to + * pan the browser. However, we do not want a tap on a link to + * open the link. + */ + post(mRemoveReleaseSingleTap); + // Continue through to normal processing + } + } + int action = ev.getAction(); float x = ev.getX(); float y = ev.getY(); @@ -3315,8 +3417,20 @@ public class WebView extends AbsoluteLayout nativeMoveSelection(viewToContent(mSelectX) , viewToContent(mSelectY), false); mTouchSelection = mExtendSelection = true; + } else if (!ZoomRingController.useOldZoom(mContext) && + eventTime - mPreviousUpTime < DOUBLE_TAP_TIMEOUT && + getSettings().supportZoom() && + mMinZoomScale < mMaxZoomScale) { + // Found doubletap, invoke the zoom controller + mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); + mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); + mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); + mZoomRingController.setVisible(true); + mInZoomTapDragMode = true; + mZoomRingController.handleDoubleTapEvent(ev); } else { mTouchMode = TOUCH_INIT_MODE; + mPreventDrag = mForwardTouchEvents; } if (mTouchMode == TOUCH_INIT_MODE) { mPrivateHandler.sendMessageDelayed(mPrivateHandler @@ -3359,8 +3473,8 @@ public class WebView extends AbsoluteLayout invalidate(); break; } - if ((deltaX * deltaX + deltaY * deltaY) - < TOUCH_SLOP_SQUARE) { + if (mPreventDrag || (deltaX * deltaX + deltaY * deltaY) + < mTouchSlopSquare) { break; } @@ -3371,6 +3485,9 @@ public class WebView extends AbsoluteLayout mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); } + // Prevent double-tap from being invoked + mPreviousUpTime = 0; + // if it starts nearly horizontal or vertical, enforce it int ax = Math.abs(deltaX); int ay = Math.abs(deltaY); @@ -3418,9 +3535,9 @@ public class WebView extends AbsoluteLayout // reverse direction means lock in the snap mode if ((ax > MAX_SLOPE_FOR_DIAG * ay) && ((mSnapPositive && - deltaX < -MIN_LOCK_SNAP_REVERSE_DISTANCE) + deltaX < -mMinLockSnapReverseDistance) || (!mSnapPositive && - deltaX > MIN_LOCK_SNAP_REVERSE_DISTANCE))) { + deltaX > mMinLockSnapReverseDistance))) { mSnapScrollMode = SNAP_X_LOCK; } } else { @@ -3432,9 +3549,9 @@ public class WebView extends AbsoluteLayout // reverse direction means lock in the snap mode if ((ay > MAX_SLOPE_FOR_DIAG * ax) && ((mSnapPositive && - deltaY < -MIN_LOCK_SNAP_REVERSE_DISTANCE) + deltaY < -mMinLockSnapReverseDistance) || (!mSnapPositive && - deltaY > MIN_LOCK_SNAP_REVERSE_DISTANCE))) { + deltaY > mMinLockSnapReverseDistance))) { mSnapScrollMode = SNAP_Y_LOCK; } } @@ -3457,16 +3574,18 @@ public class WebView extends AbsoluteLayout mUserScroll = true; } - boolean showPlusMinus = mMinZoomScale < mMaxZoomScale; - boolean showMagnify = canZoomScrollOut(); - if (mZoomControls != null && (showPlusMinus || showMagnify)) { - if (mZoomControls.getVisibility() == View.VISIBLE) { - mPrivateHandler.removeCallbacks(mZoomControlRunnable); - } else { - mZoomControls.show(showPlusMinus, showMagnify); + if (ZoomRingController.useOldZoom(mContext)) { + boolean showPlusMinus = mMinZoomScale < mMaxZoomScale; + boolean showMagnify = canZoomScrollOut(); + if (mZoomControls != null && (showPlusMinus || showMagnify)) { + if (mZoomControls.getVisibility() == View.VISIBLE) { + mPrivateHandler.removeCallbacks(mZoomControlRunnable); + } else { + mZoomControls.show(showPlusMinus, showMagnify); + } + mPrivateHandler.postDelayed(mZoomControlRunnable, + ZOOM_CONTROLS_TIMEOUT); } - mPrivateHandler.postDelayed(mZoomControlRunnable, - ZOOM_CONTROLS_TIMEOUT); } if (done) { // return false to indicate that we can't pan out of the @@ -3479,7 +3598,8 @@ public class WebView extends AbsoluteLayout switch (mTouchMode) { case TOUCH_INIT_MODE: // tap mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); - if (getSettings().supportZoom()) { + if (getSettings().supportZoom() + && (mMinZoomScale < mMaxZoomScale)) { mPrivateHandler.sendMessageDelayed(mPrivateHandler .obtainMessage(RELEASE_SINGLE_TAP), DOUBLE_TAP_TIMEOUT); @@ -3559,6 +3679,7 @@ public class WebView extends AbsoluteLayout mVelocityTracker.recycle(); mVelocityTracker = null; } + mPreviousUpTime = eventTime; break; } case MotionEvent.ACTION_CANCEL: { @@ -3604,6 +3725,7 @@ public class WebView extends AbsoluteLayout private static final int TRACKBALL_WAIT = 100; private static final int TRACKBALL_SCALE = 400; private static final int TRACKBALL_SCROLL_COUNT = 5; + private static final int TRACKBALL_MOVE_COUNT = 10; private static final int TRACKBALL_MULTIPLIER = 3; private static final int SELECT_CURSOR_OFFSET = 16; private int mSelectX = 0; @@ -3658,7 +3780,11 @@ public class WebView extends AbsoluteLayout mTrackballDown = false; mTrackballUpTime = time; if (mShiftIsPressed) { - mExtendSelection = true; + if (mExtendSelection) { + commitCopy(); + } else { + mExtendSelection = true; + } } if (LOGV_ENABLED) { Log.v(LOGTAG, "onTrackballEvent up ev=" + ev @@ -3735,7 +3861,7 @@ public class WebView extends AbsoluteLayout int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET : 0; - pinScrollBy(scrollX, scrollY, true); + pinScrollBy(scrollX, scrollY, true, 0); Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); requestRectangleOnScreen(select); invalidate(); @@ -3841,6 +3967,7 @@ public class WebView extends AbsoluteLayout KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : KeyEvent.KEYCODE_DPAD_RIGHT; + count = Math.min(count, TRACKBALL_MOVE_COUNT); if (LOGV_ENABLED) { Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode + " count=" + count @@ -3870,7 +3997,7 @@ public class WebView extends AbsoluteLayout yMove = 0; } if (xMove != 0 || yMove != 0) { - pinScrollBy(xMove, yMove, true); + pinScrollBy(xMove, yMove, true, 0); } mUserScroll = true; } @@ -4056,7 +4183,7 @@ public class WebView extends AbsoluteLayout View v = mTextEntry; int x = viewToContent((v.getLeft() + v.getRight()) >> 1); int y = viewToContent((v.getTop() + v.getBottom()) >> 1); - int contentSize = ViewConfiguration.getTouchSlop(); + int contentSize = ViewConfiguration.get(getContext()).getScaledTouchSlop(); nativeMotionUp(x, y, contentSize, true); } } @@ -4066,21 +4193,15 @@ public class WebView extends AbsoluteLayout return; } switchOutDrawHistory(); - // call uiOverride to check whether it is a special node, - // phone/email/address, which are not handled by WebKit + // FIXME: we don't know if the current (x,y) is on a focus node or + // not -- so playing the sound effect here is premature if (nativeUpdateFocusNode()) { - FocusNode node = mFocusNode; - if (!node.mIsTextField && !node.mIsTextArea) { - if (mCallbackProxy.uiOverrideUrlLoading(node.mText)) { - return; - } - } playSoundEffect(SoundEffectConstants.CLICK); } // mLastTouchX and mLastTouchY are the point in the current viewport int contentX = viewToContent((int) mLastTouchX + mScrollX); int contentY = viewToContent((int) mLastTouchY + mScrollY); - int contentSize = ViewConfiguration.getTouchSlop(); + int contentSize = ViewConfiguration.get(getContext()).getScaledTouchSlop(); nativeMotionUp(contentX, contentY, contentSize, true); } @@ -4208,7 +4329,7 @@ public class WebView extends AbsoluteLayout } if ((scrollYDelta | scrollXDelta) != 0) { - return pinScrollBy(scrollXDelta, scrollYDelta, !immediate); + return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); } return false; @@ -4443,6 +4564,15 @@ public class WebView extends AbsoluteLayout } break; case UPDATE_TEXT_ENTRY_MSG_ID: + // this is sent after finishing resize in WebViewCore. Make + // sure the text edit box is still on the screen. + boolean alreadyThere = inEditingMode(); + if (alreadyThere && nativeUpdateFocusNode()) { + FocusNode node = mFocusNode; + if (node.mIsTextField || node.mIsTextArea) { + mTextEntry.bringIntoView(); + } + } updateTextEntry(); break; case RECOMPUTE_FOCUS_MSG_ID: @@ -4450,6 +4580,17 @@ public class WebView extends AbsoluteLayout nativeRecomputeFocus(); } break; + case INVAL_RECT_MSG_ID: { + Rect r = (Rect)msg.obj; + if (r == null) { + invalidate(); + } else { + // we need to scale r from content into view coords, + // which viewInvalidate() does for us + viewInvalidate(r.left, r.top, r.right, r.bottom); + } + break; + } case UPDATE_TEXT_ENTRY_ADAPTER: HashMap data = (HashMap) msg.obj; if (mTextEntry.isSameTextField(msg.arg1)) { @@ -4494,12 +4635,12 @@ public class WebView extends AbsoluteLayout break; case PREVENT_TOUCH_ID: - // update may have already been paused by touch; restore since - // this effectively aborts touch and skips logic in touch up - if (mTouchMode == TOUCH_DRAG_MODE) { - WebViewCore.resumeUpdate(mWebViewCore); + if (msg.arg1 == MotionEvent.ACTION_DOWN) { + mPreventDrag = msg.arg2 == 1; + if (mPreventDrag) { + mTouchMode = TOUCH_DONE_MODE; + } } - mTouchMode = TOUCH_DONE_MODE; break; default: @@ -4665,6 +4806,12 @@ public class WebView extends AbsoluteLayout listView.setSelection(mSelection); } } + dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { + public void onCancel(DialogInterface dialog) { + mWebViewCore.sendMessage( + EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); + } + }); dialog.show(); } } @@ -4809,11 +4956,11 @@ public class WebView extends AbsoluteLayout // FIXME: Necessary because ScrollView/ListView do not scroll left/right int maxH = Math.min(viewFocus.right - visRect.right, maxXScroll); if (maxH > 0) { - pinScrollBy(maxH, 0, true); + pinScrollBy(maxH, 0, true, 0); } else { maxH = Math.max(viewFocus.left - visRect.left, -maxXScroll); if (maxH < 0) { - pinScrollBy(maxH, 0, true); + pinScrollBy(maxH, 0, true, 0); } } if (mLastFocusBounds.isEmpty()) return keyHandled; diff --git a/core/java/android/webkit/WebViewCore.java b/core/java/android/webkit/WebViewCore.java index 323b44d..8f78887 100644 --- a/core/java/android/webkit/WebViewCore.java +++ b/core/java/android/webkit/WebViewCore.java @@ -799,12 +799,11 @@ final class WebViewCore { case TOUCH_EVENT: { TouchEventData ted = (TouchEventData) msg.obj; - if (nativeHandleTouchEvent(ted.mAction, ted.mX, - ted.mY)) { - Message.obtain(mWebView.mPrivateHandler, - WebView.PREVENT_TOUCH_ID) - .sendToTarget(); - } + Message.obtain( + mWebView.mPrivateHandler, + WebView.PREVENT_TOUCH_ID, ted.mAction, + nativeHandleTouchEvent(ted.mAction, ted.mX, + ted.mY) ? 1 : 0).sendToTarget(); break; } @@ -1434,10 +1433,15 @@ final class WebViewCore { } } - // called by JNI + /* Called by JNI. The coordinates are in doc coordinates, so they need to + be scaled before they can be used by the view system, which happens + in WebView since it (and its thread) know the current scale factor. + */ private void sendViewInvalidate(int left, int top, int right, int bottom) { if (mWebView != null) { - mWebView.postInvalidate(left, top, right, bottom); + Message.obtain(mWebView.mPrivateHandler, + WebView.INVAL_RECT_MSG_ID, + new Rect(left, top, right, bottom)).sendToTarget(); } } diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java index 19ec77d..378d218 100644 --- a/core/java/android/widget/AbsListView.java +++ b/core/java/android/widget/AbsListView.java @@ -369,7 +369,6 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te private int mLastTouchMode = TOUCH_MODE_UNKNOWN; - // TODO: REMOVE WHEN WE'RE DONE WITH PROFILING private static final boolean PROFILE_SCROLLING = false; private boolean mScrollProfilingStarted = false; @@ -423,6 +422,8 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te */ private FastScroller mFastScroller; + private int mTouchSlop; + /** * Interface definition for a callback to be invoked when the list or grid * has been scrolled. @@ -558,6 +559,15 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te public boolean isFastScrollEnabled() { return mFastScrollEnabled; } + + /** + * If fast scroll is visible, then don't draw the vertical scrollbar. + * @hide + */ + @Override + protected boolean isVerticalScrollBarHidden() { + return mFastScroller != null ? mFastScroller.isVisible() : false; + } /** * When smooth scrollbar is enabled, the position and size of the scrollbar thumb @@ -696,6 +706,8 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te setWillNotDraw(false); setAlwaysDrawnWithCacheEnabled(false); setScrollingCacheEnabled(true); + + mTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop(); } private void useDefaultSelector() { @@ -1758,8 +1770,7 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te // Check if we have moved far enough that it looks more like a // scroll than a tap final int distance = Math.abs(deltaY); - int touchSlop = ViewConfiguration.getTouchSlop(); - if (distance > touchSlop) { + if (distance > mTouchSlop) { createScrollingCache(); mTouchMode = TOUCH_MODE_SCROLL; mMotionCorrection = deltaY; @@ -1979,8 +1990,9 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te velocityTracker.computeCurrentVelocity(1000); int initialVelocity = (int)velocityTracker.getYVelocity(); - if ((Math.abs(initialVelocity) > ViewConfiguration.getMinimumFlingVelocity()) && - (getChildCount() > 0)){ + if ((Math.abs(initialVelocity) > + ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) && + (getChildCount() > 0)) { if (mFlingRunnable == null) { mFlingRunnable = new FlingRunnable(); } @@ -2714,7 +2726,9 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te int screenHeight = WindowManagerImpl.getDefault().getDefaultDisplay().getHeight(); final int[] xy = new int[2]; getLocationOnScreen(xy); - int bottomGap = screenHeight - xy[1] - getHeight() + 20; + // TODO: The 20 below should come from the theme and be expressed in dip + final float scale = getContext().getResources().getDisplayMetrics().density; + int bottomGap = screenHeight - xy[1] - getHeight() + (int) (scale * 20); mPopup.showAtLocation(this, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, xy[0], bottomGap); // Make sure we get focus if we are showing the popup diff --git a/core/java/android/widget/AnalogClock.java b/core/java/android/widget/AnalogClock.java index fbb0105..cf9c588 100644 --- a/core/java/android/widget/AnalogClock.java +++ b/core/java/android/widget/AnalogClock.java @@ -28,6 +28,7 @@ import android.os.Handler; import android.text.format.Time; import android.util.AttributeSet; import android.view.View; +import android.widget.RemoteViews.RemoteView; import java.util.TimeZone; @@ -35,6 +36,7 @@ import java.util.TimeZone; * This widget display an analogic clock with two hands for hours and * minutes. */ +@RemoteView public class AnalogClock extends View { private Time mCalendar; diff --git a/core/java/android/widget/AutoCompleteTextView.java b/core/java/android/widget/AutoCompleteTextView.java index 7d52901..7a51676 100644 --- a/core/java/android/widget/AutoCompleteTextView.java +++ b/core/java/android/widget/AutoCompleteTextView.java @@ -110,8 +110,14 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe private Validator mValidator = null; + private boolean mBlockCompletion; + private AutoCompleteTextView.ListSelectorHider mHideSelector; + // Indicates whether this AutoCompleteTextView is attached to a window or not + // The widget is attached to a window when mAttachCount > 0 + private int mAttachCount; + public AutoCompleteTextView(Context context) { this(context, null); } @@ -145,19 +151,13 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe mHintResource = a.getResourceId(R.styleable.AutoCompleteTextView_completionHintView, R.layout.simple_dropdown_hint); - // A little trickiness for backwards compatibility: if the app - // didn't specify an explicit content type, then we will fill in the - // auto complete flag for them. - int contentType = a.getInt( - R.styleable.AutoCompleteTextView_inputType, - EditorInfo.TYPE_NULL); - if (contentType == EditorInfo.TYPE_NULL) { - contentType = getInputType(); - if ((contentType&EditorInfo.TYPE_MASK_CLASS) - == EditorInfo.TYPE_CLASS_TEXT) { - contentType |= EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE; - setRawInputType(contentType); - } + // Always turn on the auto complete input type flag, since it + // makes no sense to use this widget without it. + int inputType = getInputType(); + if ((inputType&EditorInfo.TYPE_MASK_CLASS) + == EditorInfo.TYPE_CLASS_TEXT) { + inputType |= EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE; + setRawInputType(inputType); } a.recycle(); @@ -300,6 +300,15 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe /** * <p>Changes the list of data used for auto completion. The provided list * must be a filterable list adapter.</p> + * + * <p>The caller is still responsible for managing any resources used by the adapter. + * Notably, when the AutoCompleteTextView is closed or released, the adapter is not notified. + * A common case is the use of {@link android.widget.CursorAdapter}, which + * contains a {@link android.database.Cursor} that must be closed. This can be done + * automatically (see + * {@link android.app.Activity#startManagingCursor(android.database.Cursor) + * startManagingCursor()}), + * or by manually closing the cursor when the AutoCompleteTextView is dismissed.</p> * * @param adapter the adapter holding the auto completion data * @@ -368,7 +377,10 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe && keyCode != KeyEvent.KEYCODE_DPAD_CENTER))) { int curIndex = mDropDownList.getSelectedItemPosition(); boolean consumed; - if (keyCode == KeyEvent.KEYCODE_DPAD_UP && curIndex <= 0) { + final boolean below = !mPopup.isAboveAnchor(); + if ((below && keyCode == KeyEvent.KEYCODE_DPAD_UP && curIndex <= 0) || + (!below && keyCode == KeyEvent.KEYCODE_DPAD_DOWN && curIndex >= + mDropDownList.getAdapter().getCount() - 1)) { // When the selection is at the top, we block the key // event to prevent focus from moving. mDropDownList.hideSelector(); @@ -409,13 +421,15 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe return true; } } else { - if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { + if (below && keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { // when the selection is at the bottom, we block the // event to avoid going to the next focusable widget Adapter adapter = mDropDownList.getAdapter(); if (adapter != null && curIndex == adapter.getCount() - 1) { return true; } + } else if (!below && keyCode == KeyEvent.KEYCODE_DPAD_UP && curIndex == 0) { + return true; } } } @@ -462,6 +476,8 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe } void doBeforeTextChanged() { + if (mBlockCompletion) return; + // when text is changed, inserted or deleted, we attempt to show // the drop down mOpenBefore = isPopupShowing(); @@ -469,6 +485,8 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe } void doAfterTextChanged() { + if (mBlockCompletion) return; + // if the list was open before the keystroke, but closed afterwards, // then something in the keystroke processing (an input filter perhaps) // called performCompletion() and we shouldn't do any more processing. @@ -579,9 +597,13 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe performCompletion(null, -1, -1); } - @Override public void onCommitCompletion(CompletionInfo completion) { + @Override + public void onCommitCompletion(CompletionInfo completion) { if (isPopupShowing()) { + mBlockCompletion = true; replaceText(completion.getText()); + mBlockCompletion = false; + if (mItemClickListener != null) { final DropDownListView list = mDropDownList; // Note that we don't have a View here, so we will need to @@ -604,7 +626,10 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe Log.w(TAG, "performCompletion: no selected item"); return; } + + mBlockCompletion = true; replaceText(convertSelectionToString(selectedItem)); + mBlockCompletion = false; if (mItemClickListener != null) { final DropDownListView list = mDropDownList; @@ -620,6 +645,14 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe dismissDropDown(); } + + /** + * Identifies whether the view is currently performing a text completion, so subclasses + * can decide whether to respond to text changed events. + */ + public boolean isPerformingCompletion() { + return mBlockCompletion; + } /** * <p>Performs the text completion by replacing the current text by the @@ -636,6 +669,8 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe } public void onFilterComplete(int count) { + if (mAttachCount <= 0) return; + /* * This checks enoughToFilter() again because filtering requests * are asynchronous, so the result may come back after enough text @@ -671,8 +706,15 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe } @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + mAttachCount++; + } + + @Override protected void onDetachedFromWindow() { dismissDropDown(); + mAttachCount--; super.onDetachedFromWindow(); } @@ -694,7 +736,7 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe boolean result = super.setFrame(l, t, r, b); if (mPopup.isShowing()) { - mPopup.update(this, getMeasuredWidth() - mPaddingLeft - mPaddingRight, -1); + mPopup.update(this, r - l, -1); } return result; @@ -707,10 +749,10 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe int height = buildDropDown(); if (mPopup.isShowing()) { mPopup.update(this, mDropDownHorizontalOffset, mDropDownVerticalOffset, - getMeasuredWidth() - mPaddingLeft - mPaddingRight, height); + getWidth(), height); } else { mPopup.setWindowLayoutMode(0, ViewGroup.LayoutParams.WRAP_CONTENT); - mPopup.setWidth(getMeasuredWidth() - mPaddingLeft - mPaddingRight); + mPopup.setWidth(getWidth()); mPopup.setHeight(height); mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED); mPopup.setOutsideTouchable(true); @@ -739,7 +781,7 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe int N = mAdapter.getCount(); if (N > 20) N = 20; CompletionInfo[] completions = new CompletionInfo[N]; - for (int i=0; i<N; i++) { + for (int i = 0; i < N; i++) { Object item = mAdapter.getItem(i); long id = mAdapter.getItemId(i); completions[i] = new CompletionInfo(id, i, @@ -783,7 +825,7 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe // measure the hint's height to find how much more vertical space // we need to add to the drop down's height - int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); + int widthSpec = MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST); int heightSpec = MeasureSpec.UNSPECIFIED; hintView.measure(widthSpec, heightSpec); @@ -807,8 +849,8 @@ public class AutoCompleteTextView extends EditText implements Filter.FilterListe } // Max height available on the screen for a popup anchored to us - final int maxHeight = mPopup.getMaxAvailableHeight(this); - otherHeights += dropDownView.getPaddingTop() + dropDownView.getPaddingBottom(); + final int maxHeight = mPopup.getMaxAvailableHeight(this, mDropDownVerticalOffset); + //otherHeights += dropDownView.getPaddingTop() + dropDownView.getPaddingBottom(); return mDropDownList.measureHeightOfChildren(MeasureSpec.UNSPECIFIED, 0, ListView.NO_POSITION, maxHeight - otherHeights, 2) + otherHeights; diff --git a/core/java/android/widget/CompoundButton.java b/core/java/android/widget/CompoundButton.java index e56a741..d4482dc 100644 --- a/core/java/android/widget/CompoundButton.java +++ b/core/java/android/widget/CompoundButton.java @@ -251,7 +251,12 @@ public abstract class CompoundButton extends Button implements Checkable { invalidate(); } } - + + @Override + protected boolean verifyDrawable(Drawable who) { + return super.verifyDrawable(who) || who == mButtonDrawable; + } + static class SavedState extends BaseSavedState { boolean checked; diff --git a/core/java/android/widget/ExpandableListView.java b/core/java/android/widget/ExpandableListView.java index 3de561a..0fc8f49 100644 --- a/core/java/android/widget/ExpandableListView.java +++ b/core/java/android/widget/ExpandableListView.java @@ -187,6 +187,9 @@ public class ExpandableListView extends ListView { private Drawable mChildDivider; private boolean mClipChildDivider; + // Bounds of the indicator to be drawn + private final Rect mIndicatorRect = new Rect(); + public ExpandableListView(Context context) { this(context, null); } @@ -247,17 +250,16 @@ public class ExpandableListView extends ListView { final int myB = mBottom; - PositionMetadata pos = null; + PositionMetadata pos; View item; Drawable indicator; int t, b; // Start at a value that is neither child nor group int lastItemType = ~(ExpandableListPosition.CHILD | ExpandableListPosition.GROUP); - - // Bounds of the indicator to be drawn - Rect indicatorRect = new Rect(); - + + final Rect indicatorRect = mIndicatorRect; + // The "child" mentioned in the following two lines is this // View's child, not referring to an expandable list's // notion of a child (as opposed to a group) @@ -303,11 +305,11 @@ public class ExpandableListView extends ListView { // Use item's full height + the divider height if (mStackFromBottom) { // See ListView#dispatchDraw - indicatorRect.top = t - mDividerHeight; + indicatorRect.top = t;// - mDividerHeight; indicatorRect.bottom = b; } else { indicatorRect.top = t; - indicatorRect.bottom = b + mDividerHeight; + indicatorRect.bottom = b;// + mDividerHeight; } // Get the indicator (with its state set to the item's state) diff --git a/core/java/android/widget/FastScroller.java b/core/java/android/widget/FastScroller.java index bdcfeef..57e21e4 100644 --- a/core/java/android/widget/FastScroller.java +++ b/core/java/android/widget/FastScroller.java @@ -34,7 +34,8 @@ import android.view.MotionEvent; */ class FastScroller { - + // Minimum number of pages to justify showing a fast scroll thumb + private static int MIN_PAGES = 4; // Scroll thumb not showing private static final int STATE_NONE = 0; // Not implemented yet - fade-in transition @@ -154,6 +155,10 @@ class FastScroller { setState(STATE_NONE); } + boolean isVisible() { + return !(mState == STATE_NONE); + } + public void draw(Canvas canvas) { if (mState == STATE_NONE) { @@ -214,7 +219,13 @@ class FastScroller { void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - + // Are there enough pages to require fast scroll? + if (visibleItemCount > 0 && totalItemCount / visibleItemCount < MIN_PAGES) { + if (mState != STATE_NONE) { + setState(STATE_NONE); + } + return; + } if (totalItemCount - visibleItemCount > 0 && mState != STATE_DRAGGING ) { mThumbY = ((mList.getHeight() - mThumbH) * firstVisibleItem) / (totalItemCount - visibleItemCount); diff --git a/core/java/android/widget/Gallery.java b/core/java/android/widget/Gallery.java index 7b9735c..ffabb02 100644 --- a/core/java/android/widget/Gallery.java +++ b/core/java/android/widget/Gallery.java @@ -180,7 +180,7 @@ public class Gallery extends AbsSpinner implements GestureDetector.OnGestureList public Gallery(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - mGestureDetector = new GestureDetector(this); + mGestureDetector = new GestureDetector(context, this); mGestureDetector.setIsLongpressEnabled(true); TypedArray a = context.obtainStyledAttributes( diff --git a/core/java/android/widget/HorizontalScrollView.java b/core/java/android/widget/HorizontalScrollView.java new file mode 100644 index 0000000..96fe595 --- /dev/null +++ b/core/java/android/widget/HorizontalScrollView.java @@ -0,0 +1,1197 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.widget; + +import android.util.AttributeSet; +import android.graphics.Rect; +import android.view.View; +import android.view.VelocityTracker; +import android.view.ViewConfiguration; +import android.view.ViewGroup; +import android.view.KeyEvent; +import android.view.FocusFinder; +import android.view.MotionEvent; +import android.view.ViewParent; +import android.view.animation.AnimationUtils; +import android.content.Context; +import android.content.res.TypedArray; + +import java.util.List; + +/** + * Layout container for a view hierarchy that can be scrolled by the user, + * allowing it to be larger than the physical display. A HorizontalScrollView + * is a {@link FrameLayout}, meaning you should place one child in it + * containing the entire contents to scroll; this child may itself be a layout + * manager with a complex hierarchy of objects. A child that is often used + * is a {@link LinearLayout} in a horizontal orientation, presenting a horizontal + * array of top-level items that the user can scroll through. + * + * <p>You should never use a HorizontalScrollView with a {@link ListView}, since + * ListView takes care of its own scrolling. Most importantly, doing this + * defeats all of the important optimizations in ListView for dealing with + * large lists, since it effectively forces the ListView to display its entire + * list of items to fill up the infinite container supplied by HorizontalScrollView. + * + * <p>The {@link TextView} class also + * takes care of its own scrolling, so does not require a ScrollView, but + * using the two together is possible to achieve the effect of a text view + * within a larger container. + * + * <p>HorizontalScrollView only supports horizontal scrolling. + */ +public class HorizontalScrollView extends FrameLayout { + private static final int ANIMATED_SCROLL_GAP = ScrollView.ANIMATED_SCROLL_GAP; + + private static final float MAX_SCROLL_FACTOR = ScrollView.MAX_SCROLL_FACTOR; + + + private long mLastScroll; + + private final Rect mTempRect = new Rect(); + private Scroller mScroller; + + /** + * Flag to indicate that we are moving focus ourselves. This is so the + * code that watches for focus changes initiated outside this ScrollView + * knows that it does not have to do anything. + */ + private boolean mScrollViewMovedFocus; + + /** + * Position of the last motion event. + */ + private float mLastMotionX; + + /** + * True when the layout has changed but the traversal has not come through yet. + * Ideally the view hierarchy would keep track of this for us. + */ + private boolean mIsLayoutDirty = true; + + /** + * The child to give focus to in the event that a child has requested focus while the + * layout is dirty. This prevents the scroll from being wrong if the child has not been + * laid out before requesting focus. + */ + private View mChildToScrollTo = null; + + /** + * True if the user is currently dragging this ScrollView around. This is + * not the same as 'is being flinged', which can be checked by + * mScroller.isFinished() (flinging begins when the user lifts his finger). + */ + private boolean mIsBeingDragged = false; + + /** + * Determines speed during touch scrolling + */ + private VelocityTracker mVelocityTracker; + + /** + * When set to true, the scroll view measure its child to make it fill the currently + * visible area. + */ + private boolean mFillViewport; + + /** + * Whether arrow scrolling is animated. + */ + private boolean mSmoothScrollingEnabled = true; + + private int mTouchSlop; + + public HorizontalScrollView(Context context) { + this(context, null); + } + + public HorizontalScrollView(Context context, AttributeSet attrs) { + this(context, attrs, com.android.internal.R.attr.horizontalScrollViewStyle); + } + + public HorizontalScrollView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + initScrollView(); + + TypedArray a = context.obtainStyledAttributes(attrs, + android.R.styleable.HorizontalScrollView, defStyle, 0); + + setFillViewport(a.getBoolean(android.R.styleable.HorizontalScrollView_fillViewport, false)); + + a.recycle(); + } + + @Override + protected float getLeftFadingEdgeStrength() { + if (getChildCount() == 0) { + return 0.0f; + } + + final int length = getHorizontalFadingEdgeLength(); + if (mScrollX < length) { + return mScrollX / (float) length; + } + + return 1.0f; + } + + @Override + protected float getRightFadingEdgeStrength() { + if (getChildCount() == 0) { + return 0.0f; + } + + final int length = getHorizontalFadingEdgeLength(); + final int rightEdge = getWidth() - mPaddingRight; + final int span = getChildAt(0).getRight() - mScrollX - rightEdge; + if (span < length) { + return span / (float) length; + } + + return 1.0f; + } + + /** + * @return The maximum amount this scroll view will scroll in response to + * an arrow event. + */ + public int getMaxScrollAmount() { + return (int) (MAX_SCROLL_FACTOR * (mRight - mLeft)); + } + + + private void initScrollView() { + mScroller = new Scroller(getContext()); + setFocusable(true); + setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); + setWillNotDraw(false); + mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); + } + + @Override + public void addView(View child) { + if (getChildCount() > 0) { + throw new IllegalStateException("HorizontalScrollView can host only one direct child"); + } + + super.addView(child); + } + + @Override + public void addView(View child, int index) { + if (getChildCount() > 0) { + throw new IllegalStateException("HorizontalScrollView can host only one direct child"); + } + + super.addView(child, index); + } + + @Override + public void addView(View child, ViewGroup.LayoutParams params) { + if (getChildCount() > 0) { + throw new IllegalStateException("HorizontalScrollView can host only one direct child"); + } + + super.addView(child, params); + } + + @Override + public void addView(View child, int index, ViewGroup.LayoutParams params) { + if (getChildCount() > 0) { + throw new IllegalStateException("HorizontalScrollView can host only one direct child"); + } + + super.addView(child, index, params); + } + + /** + * @return Returns true this HorizontalScrollView can be scrolled + */ + private boolean canScroll() { + View child = getChildAt(0); + if (child != null) { + int childWidth = child.getWidth(); + return getWidth() < childWidth + mPaddingLeft + mPaddingRight ; + } + return false; + } + + /** + * Indicates whether this ScrollView's content is stretched to fill the viewport. + * + * @return True if the content fills the viewport, false otherwise. + */ + public boolean isFillViewport() { + return mFillViewport; + } + + /** + * Indicates this ScrollView whether it should stretch its content width to fill + * the viewport or not. + * + * @param fillViewport True to stretch the content's width to the viewport's + * boundaries, false otherwise. + */ + public void setFillViewport(boolean fillViewport) { + if (fillViewport != mFillViewport) { + mFillViewport = fillViewport; + requestLayout(); + } + } + + /** + * @return Whether arrow scrolling will animate its transition. + */ + public boolean isSmoothScrollingEnabled() { + return mSmoothScrollingEnabled; + } + + /** + * Set whether arrow scrolling will animate its transition. + * @param smoothScrollingEnabled whether arrow scrolling will animate its transition + */ + public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) { + mSmoothScrollingEnabled = smoothScrollingEnabled; + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + + if (!mFillViewport) { + return; + } + + final int widthMode = MeasureSpec.getMode(widthMeasureSpec); + if (widthMode == MeasureSpec.UNSPECIFIED) { + return; + } + + final View child = getChildAt(0); + int width = getMeasuredWidth(); + if (child.getMeasuredHeight() < width) { + final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); + + int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec, mPaddingTop + + mPaddingBottom, lp.height); + width -= mPaddingLeft; + width -= mPaddingRight; + int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); + + child.measure(childWidthMeasureSpec, childHeightMeasureSpec); + } + } + + @Override + public boolean dispatchKeyEvent(KeyEvent event) { + // Let the focused view and/or our descendants get the key first + boolean handled = super.dispatchKeyEvent(event); + if (handled) { + return true; + } + return executeKeyEvent(event); + } + + /** + * You can call this function yourself to have the scroll view perform + * scrolling from a key event, just as if the event had been dispatched to + * it by the view hierarchy. + * + * @param event The key event to execute. + * @return Return true if the event was handled, else false. + */ + public boolean executeKeyEvent(KeyEvent event) { + mTempRect.setEmpty(); + + if (!canScroll()) { + if (isFocused()) { + View currentFocused = findFocus(); + if (currentFocused == this) currentFocused = null; + View nextFocused = FocusFinder.getInstance().findNextFocus(this, + currentFocused, View.FOCUS_RIGHT); + return nextFocused != null && nextFocused != this && + nextFocused.requestFocus(View.FOCUS_RIGHT); + } + return false; + } + + boolean handled = false; + if (event.getAction() == KeyEvent.ACTION_DOWN) { + switch (event.getKeyCode()) { + case KeyEvent.KEYCODE_DPAD_LEFT: + if (!event.isAltPressed()) { + handled = arrowScroll(View.FOCUS_LEFT); + } else { + handled = fullScroll(View.FOCUS_LEFT); + } + break; + case KeyEvent.KEYCODE_DPAD_RIGHT: + if (!event.isAltPressed()) { + handled = arrowScroll(View.FOCUS_RIGHT); + } else { + handled = fullScroll(View.FOCUS_RIGHT); + } + break; + case KeyEvent.KEYCODE_SPACE: + pageScroll(event.isShiftPressed() ? View.FOCUS_LEFT : View.FOCUS_RIGHT); + break; + } + } + + return handled; + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent ev) { + /* + * This method JUST determines whether we want to intercept the motion. + * If we return true, onMotionEvent will be called and we do the actual + * scrolling there. + */ + + /* + * Shortcut the most recurring case: the user is in the dragging + * state and he is moving his finger. We want to intercept this + * motion. + */ + final int action = ev.getAction(); + if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) { + return true; + } + + if (!canScroll()) { + mIsBeingDragged = false; + return false; + } + + final float x = ev.getX(); + + switch (action) { + case MotionEvent.ACTION_MOVE: + /* + * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check + * whether the user has moved far enough from his original down touch. + */ + + /* + * Locally do absolute value. mLastMotionX is set to the x value + * of the down event. + */ + final int xDiff = (int) Math.abs(x - mLastMotionX); + if (xDiff > mTouchSlop) { + mIsBeingDragged = true; + if (mParent != null) mParent.requestDisallowInterceptTouchEvent(true); + } + break; + + case MotionEvent.ACTION_DOWN: + /* Remember location of down touch */ + mLastMotionX = x; + + /* + * If being flinged and user touches the screen, initiate drag; + * otherwise don't. mScroller.isFinished should be false when + * being flinged. + */ + mIsBeingDragged = !mScroller.isFinished(); + break; + + case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_UP: + /* Release the drag */ + mIsBeingDragged = false; + break; + } + + /* + * The only time we want to intercept motion events is if we are in the + * drag mode. + */ + return mIsBeingDragged; + } + + @Override + public boolean onTouchEvent(MotionEvent ev) { + + if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) { + // Don't handle edge touches immediately -- they may actually belong to one of our + // descendants. + return false; + } + + if (!canScroll()) { + return false; + } + + if (mVelocityTracker == null) { + mVelocityTracker = VelocityTracker.obtain(); + } + mVelocityTracker.addMovement(ev); + + final int action = ev.getAction(); + final float x = ev.getX(); + + switch (action) { + case MotionEvent.ACTION_DOWN: + /* + * If being flinged and user touches, stop the fling. isFinished + * will be false if being flinged. + */ + if (!mScroller.isFinished()) { + mScroller.abortAnimation(); + } + + // Remember where the motion event started + mLastMotionX = x; + break; + case MotionEvent.ACTION_MOVE: + // Scroll to follow the motion event + final int deltaX = (int) (mLastMotionX - x); + mLastMotionX = x; + + if (deltaX < 0) { + if (mScrollX > 0) { + scrollBy(deltaX, 0); + } + } else if (deltaX > 0) { + final int rightEdge = getWidth() - mPaddingRight; + final int availableToScroll = getChildAt(0).getRight() - mScrollX - rightEdge; + if (availableToScroll > 0) { + scrollBy(Math.min(availableToScroll, deltaX), 0); + } + } + break; + case MotionEvent.ACTION_UP: + final VelocityTracker velocityTracker = mVelocityTracker; + velocityTracker.computeCurrentVelocity(1000); + int initialVelocity = (int) velocityTracker.getXVelocity(); + + if ((Math.abs(initialVelocity) > + ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) && + getChildCount() > 0) { + fling(-initialVelocity); + } + + if (mVelocityTracker != null) { + mVelocityTracker.recycle(); + mVelocityTracker = null; + } + } + return true; + } + + /** + * <p> + * Finds the next focusable component that fits in this View's bounds + * (excluding fading edges) pretending that this View's left is located at + * the parameter left. + * </p> + * + * @param leftFocus look for a candidate is the one at the left of the bounds + * if leftFocus is true, or at the right of the bounds if leftFocus + * is false + * @param left the left offset of the bounds in which a focusable must be + * found (the fading edge is assumed to start at this position) + * @param preferredFocusable the View that has highest priority and will be + * returned if it is within my bounds (null is valid) + * @return the next focusable component in the bounds or null if none can be found + */ + private View findFocusableViewInMyBounds(final boolean leftFocus, + final int left, View preferredFocusable) { + /* + * The fading edge's transparent side should be considered for focus + * since it's mostly visible, so we divide the actual fading edge length + * by 2. + */ + final int fadingEdgeLength = getHorizontalFadingEdgeLength() / 2; + final int leftWithoutFadingEdge = left + fadingEdgeLength; + final int rightWithoutFadingEdge = left + getWidth() - fadingEdgeLength; + + if ((preferredFocusable != null) + && (preferredFocusable.getLeft() < rightWithoutFadingEdge) + && (preferredFocusable.getRight() > leftWithoutFadingEdge)) { + return preferredFocusable; + } + + return findFocusableViewInBounds(leftFocus, leftWithoutFadingEdge, + rightWithoutFadingEdge); + } + + /** + * <p> + * Finds the next focusable component that fits in the specified bounds. + * </p> + * + * @param leftFocus look for a candidate is the one at the left of the bounds + * if leftFocus is true, or at the right of the bounds if + * leftFocus is false + * @param left the left offset of the bounds in which a focusable must be + * found + * @param right the right offset of the bounds in which a focusable must + * be found + * @return the next focusable component in the bounds or null if none can + * be found + */ + private View findFocusableViewInBounds(boolean leftFocus, int left, int right) { + + List<View> focusables = getFocusables(View.FOCUS_FORWARD); + View focusCandidate = null; + + /* + * A fully contained focusable is one where its left is below the bound's + * left, and its right is above the bound's right. A partially + * contained focusable is one where some part of it is within the + * bounds, but it also has some part that is not within bounds. A fully contained + * focusable is preferred to a partially contained focusable. + */ + boolean foundFullyContainedFocusable = false; + + int count = focusables.size(); + for (int i = 0; i < count; i++) { + View view = focusables.get(i); + int viewLeft = view.getLeft(); + int viewRight = view.getRight(); + + if (left < viewRight && viewLeft < right) { + /* + * the focusable is in the target area, it is a candidate for + * focusing + */ + + final boolean viewIsFullyContained = (left < viewLeft) && + (viewRight < right); + + if (focusCandidate == null) { + /* No candidate, take this one */ + focusCandidate = view; + foundFullyContainedFocusable = viewIsFullyContained; + } else { + final boolean viewIsCloserToBoundary = + (leftFocus && viewLeft < focusCandidate.getLeft()) || + (!leftFocus && viewRight > focusCandidate.getRight()); + + if (foundFullyContainedFocusable) { + if (viewIsFullyContained && viewIsCloserToBoundary) { + /* + * We're dealing with only fully contained views, so + * it has to be closer to the boundary to beat our + * candidate + */ + focusCandidate = view; + } + } else { + if (viewIsFullyContained) { + /* Any fully contained view beats a partially contained view */ + focusCandidate = view; + foundFullyContainedFocusable = true; + } else if (viewIsCloserToBoundary) { + /* + * Partially contained view beats another partially + * contained view if it's closer + */ + focusCandidate = view; + } + } + } + } + } + + return focusCandidate; + } + + /** + * <p>Handles scrolling in response to a "page up/down" shortcut press. This + * method will scroll the view by one page left or right and give the focus + * to the leftmost/rightmost component in the new visible area. If no + * component is a good candidate for focus, this scrollview reclaims the + * focus.</p> + * + * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} + * to go one page left or {@link android.view.View#FOCUS_RIGHT} + * to go one page right + * @return true if the key event is consumed by this method, false otherwise + */ + public boolean pageScroll(int direction) { + boolean right = direction == View.FOCUS_RIGHT; + int width = getWidth(); + + if (right) { + mTempRect.left = getScrollX() + width; + int count = getChildCount(); + if (count > 0) { + View view = getChildAt(count - 1); + if (mTempRect.left + width > view.getRight()) { + mTempRect.left = view.getRight() - width; + } + } + } else { + mTempRect.left = getScrollX() - width; + if (mTempRect.left < 0) { + mTempRect.left = 0; + } + } + mTempRect.right = mTempRect.left + width; + + return scrollAndFocus(direction, mTempRect.left, mTempRect.right); + } + + /** + * <p>Handles scrolling in response to a "home/end" shortcut press. This + * method will scroll the view to the left or right and give the focus + * to the leftmost/rightmost component in the new visible area. If no + * component is a good candidate for focus, this scrollview reclaims the + * focus.</p> + * + * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} + * to go the left of the view or {@link android.view.View#FOCUS_RIGHT} + * to go the right + * @return true if the key event is consumed by this method, false otherwise + */ + public boolean fullScroll(int direction) { + boolean right = direction == View.FOCUS_RIGHT; + int width = getWidth(); + + mTempRect.left = 0; + mTempRect.right = width; + + if (right) { + int count = getChildCount(); + if (count > 0) { + View view = getChildAt(count - 1); + mTempRect.right = view.getRight(); + mTempRect.left = mTempRect.right - width; + } + } + + return scrollAndFocus(direction, mTempRect.left, mTempRect.right); + } + + /** + * <p>Scrolls the view to make the area defined by <code>left</code> and + * <code>right</code> visible. This method attempts to give the focus + * to a component visible in this area. If no component can be focused in + * the new visible area, the focus is reclaimed by this scrollview.</p> + * + * @param direction the scroll direction: {@link android.view.View#FOCUS_LEFT} + * to go left {@link android.view.View#FOCUS_RIGHT} to right + * @param left the left offset of the new area to be made visible + * @param right the right offset of the new area to be made visible + * @return true if the key event is consumed by this method, false otherwise + */ + private boolean scrollAndFocus(int direction, int left, int right) { + boolean handled = true; + + int width = getWidth(); + int containerLeft = getScrollX(); + int containerRight = containerLeft + width; + boolean goLeft = direction == View.FOCUS_LEFT; + + View newFocused = findFocusableViewInBounds(goLeft, left, right); + if (newFocused == null) { + newFocused = this; + } + + if (left >= containerLeft && right <= containerRight) { + handled = false; + } else { + int delta = goLeft ? (left - containerLeft) : (right - containerRight); + doScrollX(delta); + } + + if (newFocused != findFocus() && newFocused.requestFocus(direction)) { + mScrollViewMovedFocus = true; + mScrollViewMovedFocus = false; + } + + return handled; + } + + /** + * Handle scrolling in response to a left or right arrow click. + * + * @param direction The direction corresponding to the arrow key that was + * pressed + * @return True if we consumed the event, false otherwise + */ + public boolean arrowScroll(int direction) { + + View currentFocused = findFocus(); + if (currentFocused == this) currentFocused = null; + + View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); + + final int maxJump = getMaxScrollAmount(); + + if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump)) { + nextFocused.getDrawingRect(mTempRect); + offsetDescendantRectToMyCoords(nextFocused, mTempRect); + int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); + doScrollX(scrollDelta); + nextFocused.requestFocus(direction); + } else { + // no new focus + int scrollDelta = maxJump; + + if (direction == View.FOCUS_LEFT && getScrollX() < scrollDelta) { + scrollDelta = getScrollX(); + } else if (direction == View.FOCUS_RIGHT) { + + int daRight = getChildAt(getChildCount() - 1).getRight(); + + int screenRight = getScrollX() + getWidth(); + + if (daRight - screenRight < maxJump) { + scrollDelta = daRight - screenRight; + } + } + if (scrollDelta == 0) { + return false; + } + doScrollX(direction == View.FOCUS_RIGHT ? scrollDelta : -scrollDelta); + } + + if (currentFocused != null && currentFocused.isFocused() + && isOffScreen(currentFocused)) { + // previously focused item still has focus and is off screen, give + // it up (take it back to ourselves) + // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are + // sure to + // get it) + final int descendantFocusability = getDescendantFocusability(); // save + setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS); + requestFocus(); + setDescendantFocusability(descendantFocusability); // restore + } + return true; + } + + /** + * @return whether the descendant of this scroll view is scrolled off + * screen. + */ + private boolean isOffScreen(View descendant) { + return !isWithinDeltaOfScreen(descendant, 0); + } + + /** + * @return whether the descendant of this scroll view is within delta + * pixels of being on the screen. + */ + private boolean isWithinDeltaOfScreen(View descendant, int delta) { + descendant.getDrawingRect(mTempRect); + offsetDescendantRectToMyCoords(descendant, mTempRect); + + return (mTempRect.right + delta) >= getScrollX() + && (mTempRect.left - delta) <= (getScrollX() + getWidth()); + } + + /** + * Smooth scroll by a X delta + * + * @param delta the number of pixels to scroll by on the X axis + */ + private void doScrollX(int delta) { + if (delta != 0) { + if (mSmoothScrollingEnabled) { + smoothScrollBy(delta, 0); + } else { + scrollBy(delta, 0); + } + } + } + + /** + * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. + * + * @param dx the number of pixels to scroll by on the X axis + * @param dy the number of pixels to scroll by on the Y axis + */ + public final void smoothScrollBy(int dx, int dy) { + long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll; + if (duration > ANIMATED_SCROLL_GAP) { + mScroller.startScroll(mScrollX, mScrollY, dx, dy); + invalidate(); + } else { + if (!mScroller.isFinished()) { + mScroller.abortAnimation(); + } + scrollBy(dx, dy); + } + mLastScroll = AnimationUtils.currentAnimationTimeMillis(); + } + + /** + * Like {@link #scrollTo}, but scroll smoothly instead of immediately. + * + * @param x the position where to scroll on the X axis + * @param y the position where to scroll on the Y axis + */ + public final void smoothScrollTo(int x, int y) { + smoothScrollBy(x - mScrollX, y - mScrollY); + } + + /** + * <p>The scroll range of a scroll view is the overall width of all of its + * children.</p> + */ + @Override + protected int computeHorizontalScrollRange() { + int count = getChildCount(); + return count == 0 ? getWidth() : getChildAt(0).getRight(); + } + + + @Override + protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { + ViewGroup.LayoutParams lp = child.getLayoutParams(); + + int childWidthMeasureSpec; + int childHeightMeasureSpec; + + childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop + + mPaddingBottom, lp.height); + + childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); + + child.measure(childWidthMeasureSpec, childHeightMeasureSpec); + } + + @Override + protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, + int parentHeightMeasureSpec, int heightUsed) { + final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); + + final int childHeightMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, + mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin + + heightUsed, lp.height); + final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( + lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED); + + child.measure(childWidthMeasureSpec, childHeightMeasureSpec); + } + + @Override + public void computeScroll() { + if (mScroller.computeScrollOffset()) { + // This is called at drawing time by ViewGroup. We don't want to + // re-show the scrollbars at this point, which scrollTo will do, + // so we replicate most of scrollTo here. + // + // It's a little odd to call onScrollChanged from inside the drawing. + // + // It is, except when you remember that computeScroll() is used to + // animate scrolling. So unless we want to defer the onScrollChanged() + // until the end of the animated scrolling, we don't really have a + // choice here. + // + // I agree. The alternative, which I think would be worse, is to post + // something and tell the subclasses later. This is bad because there + // will be a window where mScrollX/Y is different from what the app + // thinks it is. + // + int oldX = mScrollX; + int oldY = mScrollY; + int x = mScroller.getCurrX(); + int y = mScroller.getCurrY(); + if (getChildCount() > 0) { + View child = getChildAt(0); + mScrollX = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); + mScrollY = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); + } else { + mScrollX = x; + mScrollY = y; + } + if (oldX != mScrollX || oldY != mScrollY) { + onScrollChanged(mScrollX, mScrollY, oldX, oldY); + } + + // Keep on drawing until the animation has finished. + postInvalidate(); + } + } + + /** + * Scrolls the view to the given child. + * + * @param child the View to scroll to + */ + private void scrollToChild(View child) { + child.getDrawingRect(mTempRect); + + /* Offset from child's local coordinates to ScrollView coordinates */ + offsetDescendantRectToMyCoords(child, mTempRect); + + int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); + + if (scrollDelta != 0) { + scrollBy(scrollDelta, 0); + } + } + + /** + * If rect is off screen, scroll just enough to get it (or at least the + * first screen size chunk of it) on screen. + * + * @param rect The rectangle. + * @param immediate True to scroll immediately without animation + * @return true if scrolling was performed + */ + private boolean scrollToChildRect(Rect rect, boolean immediate) { + final int delta = computeScrollDeltaToGetChildRectOnScreen(rect); + final boolean scroll = delta != 0; + if (scroll) { + if (immediate) { + scrollBy(delta, 0); + } else { + smoothScrollBy(delta, 0); + } + } + return scroll; + } + + /** + * Compute the amount to scroll in the X direction in order to get + * a rectangle completely on the screen (or, if taller than the screen, + * at least the first screen size chunk of it). + * + * @param rect The rect. + * @return The scroll delta. + */ + protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) { + + int width = getWidth(); + int screenLeft = getScrollX(); + int screenRight = screenLeft + width; + + int fadingEdge = getHorizontalFadingEdgeLength(); + + // leave room for left fading edge as long as rect isn't at very left + if (rect.left > 0) { + screenLeft += fadingEdge; + } + + // leave room for right fading edge as long as rect isn't at very right + if (rect.right < getChildAt(0).getWidth()) { + screenRight -= fadingEdge; + } + + int scrollXDelta = 0; + + if (rect.right > screenRight && rect.left > screenLeft) { + // need to move right to get it in view: move right just enough so + // that the entire rectangle is in view (or at least the first + // screen size chunk). + + if (rect.width() > width) { + // just enough to get screen size chunk on + scrollXDelta += (rect.left - screenLeft); + } else { + // get entire rect at right of screen + scrollXDelta += (rect.right - screenRight); + } + + // make sure we aren't scrolling beyond the end of our content + int right = getChildAt(getChildCount() - 1).getRight(); + int distanceToRight = right - screenRight; + scrollXDelta = Math.min(scrollXDelta, distanceToRight); + + } else if (rect.left < screenLeft && rect.right < screenRight) { + // need to move right to get it in view: move right just enough so that + // entire rectangle is in view (or at least the first screen + // size chunk of it). + + if (rect.width() > width) { + // screen size chunk + scrollXDelta -= (screenRight - rect.right); + } else { + // entire rect at left + scrollXDelta -= (screenLeft - rect.left); + } + + // make sure we aren't scrolling any further than the left our content + scrollXDelta = Math.max(scrollXDelta, -getScrollX()); + } + return scrollXDelta; + } + + @Override + public void requestChildFocus(View child, View focused) { + if (!mScrollViewMovedFocus) { + if (!mIsLayoutDirty) { + scrollToChild(focused); + } else { + // The child may not be laid out yet, we can't compute the scroll yet + mChildToScrollTo = focused; + } + } + super.requestChildFocus(child, focused); + } + + + /** + * When looking for focus in children of a scroll view, need to be a little + * more careful not to give focus to something that is scrolled off screen. + * + * This is more expensive than the default {@link android.view.ViewGroup} + * implementation, otherwise this behavior might have been made the default. + */ + @Override + protected boolean onRequestFocusInDescendants(int direction, + Rect previouslyFocusedRect) { + + // convert from forward / backward notation to up / down / left / right + // (ugh). + if (direction == View.FOCUS_FORWARD) { + direction = View.FOCUS_RIGHT; + } else if (direction == View.FOCUS_BACKWARD) { + direction = View.FOCUS_LEFT; + } + + final View nextFocus = previouslyFocusedRect == null ? + FocusFinder.getInstance().findNextFocus(this, null, direction) : + FocusFinder.getInstance().findNextFocusFromRect(this, + previouslyFocusedRect, direction); + + if (nextFocus == null) { + return false; + } + + if (isOffScreen(nextFocus)) { + return false; + } + + return nextFocus.requestFocus(direction, previouslyFocusedRect); + } + + @Override + public boolean requestChildRectangleOnScreen(View child, Rect rectangle, + boolean immediate) { + // offset into coordinate space of this scroll view + rectangle.offset(child.getLeft() - child.getScrollX(), + child.getTop() - child.getScrollY()); + + return scrollToChildRect(rectangle, immediate); + } + + @Override + public void requestLayout() { + mIsLayoutDirty = true; + super.requestLayout(); + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + super.onLayout(changed, l, t, r, b); + mIsLayoutDirty = false; + // Give a child focus if it needs it + if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) { + scrollToChild(mChildToScrollTo); + } + mChildToScrollTo = null; + + // Calling this with the present values causes it to re-clam them + scrollTo(mScrollX, mScrollY); + } + + @Override + protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + + View currentFocused = findFocus(); + if (null == currentFocused || this == currentFocused) + return; + + final int maxJump = mRight - mLeft; + + if (isWithinDeltaOfScreen(currentFocused, maxJump)) { + currentFocused.getDrawingRect(mTempRect); + offsetDescendantRectToMyCoords(currentFocused, mTempRect); + int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect); + doScrollX(scrollDelta); + } + } + + /** + * Return true if child is an descendant of parent, (or equal to the parent). + */ + private boolean isViewDescendantOf(View child, View parent) { + if (child == parent) { + return true; + } + + final ViewParent theParent = child.getParent(); + return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent); + } + + /** + * Fling the scroll view + * + * @param velocityX The initial velocity in the X direction. Positive + * numbers mean that the finger/curor is moving down the screen, + * which means we want to scroll towards the left. + */ + public void fling(int velocityX) { + int width = getWidth() - mPaddingRight - mPaddingLeft; + int right = getChildAt(0).getWidth(); + + mScroller.fling(mScrollX, mScrollY, velocityX, 0, 0, right - width, 0, 0); + + final boolean movingRight = velocityX > 0; + + View newFocused = findFocusableViewInMyBounds(movingRight, + mScroller.getFinalX(), findFocus()); + + if (newFocused == null) { + newFocused = this; + } + + if (newFocused != findFocus() + && newFocused.requestFocus(movingRight ? View.FOCUS_RIGHT : View.FOCUS_LEFT)) { + mScrollViewMovedFocus = true; + mScrollViewMovedFocus = false; + } + + invalidate(); + } + + /** + * {@inheritDoc} + * + * <p>This version also clamps the scrolling to the bounds of our child. + */ + public void scrollTo(int x, int y) { + // we rely on the fact the View.scrollBy calls scrollTo. + if (getChildCount() > 0) { + View child = getChildAt(0); + x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); + y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); + if (x != mScrollX || y != mScrollY) { + super.scrollTo(x, y); + } + } + } + + private int clamp(int n, int my, int child) { + if (my >= child || n < 0) { + return 0; + } + if ((my + n) > child) { + return child - my; + } + return n; + } +} diff --git a/core/java/android/widget/LinearLayout.java b/core/java/android/widget/LinearLayout.java index 36ed8bd..85a7339 100644 --- a/core/java/android/widget/LinearLayout.java +++ b/core/java/android/widget/LinearLayout.java @@ -336,7 +336,7 @@ public class LinearLayout extends ViewGroup { // heightMode is either UNSPECIFIED OR AT_MOST, and this child // wanted to stretch to fill available space. Translate that to // WRAP_CONTENT so that it does not end up with a height of 0 - oldHeight = lp.height; + oldHeight = 0; lp.height = LayoutParams.WRAP_CONTENT; } @@ -475,8 +475,6 @@ public class LinearLayout extends ViewGroup { matchWidthLocally ? margin : measuredWidth); allFillParent = allFillParent && lp.width == LayoutParams.FILL_PARENT; - alternativeMaxWidth = Math.max(alternativeMaxWidth, - matchWidthLocally ? margin : measuredWidth); mTotalLength += child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin + getNextLocationOffset(child); @@ -607,7 +605,7 @@ public class LinearLayout extends ViewGroup { // widthMode is either UNSPECIFIED OR AT_MOST, and this child // wanted to stretch to fill available space. Translate that to // WRAP_CONTENT so that it does not end up with a width of 0 - oldWidth = lp.width; + oldWidth = 0; lp.width = LayoutParams.WRAP_CONTENT; } @@ -766,8 +764,6 @@ public class LinearLayout extends ViewGroup { matchHeightLocally ? margin : childHeight); allFillParent = allFillParent && lp.height == LayoutParams.FILL_PARENT; - alternativeMaxHeight = Math.max(alternativeMaxHeight, - matchHeightLocally ? margin : childHeight); if (baselineAligned) { final int childBaseline = child.getBaseline(); @@ -803,8 +799,7 @@ public class LinearLayout extends ViewGroup { maxHeight = Math.max(maxHeight, ascent + descent); } } else { - alternativeMaxHeight = Math.max(alternativeMaxHeight, - weightedMaxHeight); + alternativeMaxHeight = Math.max(alternativeMaxHeight, weightedMaxHeight); } if (!allFillParent && heightMode != MeasureSpec.EXACTLY) { diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java index dfc7bc3..9c7f600 100644 --- a/core/java/android/widget/ListView.java +++ b/core/java/android/widget/ListView.java @@ -1718,12 +1718,11 @@ public class ListView extends AbsListView { } /** - * Sets the currently selected item + * Sets the currently selected item. If in touch mode, the item will not be selected + * but it will still be positioned appropriately. If the specified selection position + * is less than 0, then the item at position 0 will be selected. * * @param position Index (starting at 0) of the data item to be selected. - * - * If in touch mode, the item will not be selected but it will still be positioned - * appropriately. */ @Override public void setSelection(int position) { diff --git a/core/java/android/widget/PopupWindow.java b/core/java/android/widget/PopupWindow.java index 50248c1..dada105 100644 --- a/core/java/android/widget/PopupWindow.java +++ b/core/java/android/widget/PopupWindow.java @@ -632,17 +632,36 @@ public class PopupWindow { WindowManager.LayoutParams p = createPopupLayout(anchor.getWindowToken()); preparePopup(p); + mAboveAnchor = findDropDownPosition(anchor, p, xoff, yoff); + if (mBackground != null) { mPopupView.refreshDrawableState(); } - mAboveAnchor = findDropDownPosition(anchor, p, xoff, yoff); + if (mHeightMode < 0) p.height = mLastHeight = mHeightMode; if (mWidthMode < 0) p.width = mLastWidth = mWidthMode; + p.windowAnimations = computeAnimationResource(); + invokePopup(p); } /** + * Indicates whether the popup is showing above (the y coordinate of the popup's bottom + * is less than the y coordinate of the anchor) or below the anchor view (the y coordinate + * of the popup is greater than y coordinate of the anchor's bottom). + * + * The value returned + * by this method is meaningful only after {@link #showAsDropDown(android.view.View)} + * or {@link #showAsDropDown(android.view.View, int, int)} was invoked. + * + * @return True if this popup is showing above the anchor view, false otherwise. + */ + public boolean isAboveAnchor() { + return mAboveAnchor; + } + + /** * <p>Prepare the popup by embedding in into a new ViewGroup if the * background drawable is not null. If embedding is required, the layout * parameters' height is mnodified to take into account the background's @@ -662,18 +681,6 @@ public class PopupWindow { popupViewContainer.setBackgroundDrawable(mBackground); popupViewContainer.addView(mContentView, listParams); - if (p.height >= 0) { - // accomodate the popup's height to take into account the - // background's padding - p.height += popupViewContainer.getPaddingTop() + - popupViewContainer.getPaddingBottom(); - } - if (p.width >= 0) { - // accomodate the popup's width to take into account the - // background's padding - p.width += popupViewContainer.getPaddingLeft() + - popupViewContainer.getPaddingRight(); - } mPopupView = popupViewContainer; } else { mPopupView = mContentView; @@ -720,7 +727,8 @@ public class PopupWindow { p.flags = computeFlags(p.flags); p.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL; p.token = token; - + p.setTitle("PopupWindow:" + Integer.toHexString(hashCode())); + return p; } @@ -781,7 +789,9 @@ public class PopupWindow { * * @return true if the popup is translated upwards to fit on screen */ - private boolean findDropDownPosition(View anchor, WindowManager.LayoutParams p, int xoff, int yoff) { + private boolean findDropDownPosition(View anchor, WindowManager.LayoutParams p, + int xoff, int yoff) { + anchor.getLocationInWindow(mDrawingLocation); p.x = mDrawingLocation[0] + xoff; p.y = mDrawingLocation[1] + anchor.getMeasuredHeight() + yoff; @@ -795,8 +805,7 @@ public class PopupWindow { anchor.getWindowVisibleDisplayFrame(displayFrame); final View root = anchor.getRootView(); - if (mScreenLocation[1] + anchor.getMeasuredHeight() + yoff + mPopupHeight > displayFrame.bottom - || p.x + mPopupWidth - root.getWidth() > 0) { + if (p.y + mPopupHeight > displayFrame.bottom || p.x + mPopupWidth - root.getWidth() > 0) { // if the drop down disappears at the bottom of the screen. we try to // scroll a parent scrollview or move the drop down back up on top of // the edit box @@ -815,11 +824,11 @@ public class PopupWindow { // determine whether there is more space above or below the anchor anchor.getLocationOnScreen(mScreenLocation); - onTop = (displayFrame.bottom - mScreenLocation[1] - anchor.getMeasuredHeight() - yoff) - < (mScreenLocation[1] - yoff - displayFrame.top); + onTop = (displayFrame.bottom - mScreenLocation[1] - anchor.getMeasuredHeight() - yoff) < + (mScreenLocation[1] - yoff - displayFrame.top); if (onTop) { p.gravity = Gravity.LEFT | Gravity.BOTTOM; - p.y = root.getHeight() - mDrawingLocation[1] - yoff; + p.y = root.getHeight() - mDrawingLocation[1] + yoff; } else { p.y = mDrawingLocation[1] + anchor.getMeasuredHeight() + yoff; } @@ -841,15 +850,30 @@ public class PopupWindow { * shown. */ public int getMaxAvailableHeight(View anchor) { + return getMaxAvailableHeight(anchor, 0); + } + + /** + * Returns the maximum height that is available for the popup to be + * completely shown. It is recommended that this height be the maximum for + * the popup's height, otherwise it is possible that the popup will be + * clipped. + * + * @param anchor The view on which the popup window must be anchored. + * @param yOffset y offset from the view's bottom edge + * @return The maximum available height for the popup to be completely + * shown. + */ + public int getMaxAvailableHeight(View anchor, int yOffset) { final Rect displayFrame = new Rect(); anchor.getWindowVisibleDisplayFrame(displayFrame); final int[] anchorPos = mDrawingLocation; anchor.getLocationOnScreen(anchorPos); - final int distanceToBottom = displayFrame.bottom - - (anchorPos[1] + anchor.getHeight()); - final int distanceToTop = anchorPos[1] - displayFrame.top; + final int distanceToBottom = displayFrame.bottom - + (anchorPos[1] + anchor.getHeight()) - yOffset; + final int distanceToTop = anchorPos[1] - displayFrame.top + yOffset; // anchorPos[1] is distance from anchor to top of screen int returnedHeight = Math.max(distanceToBottom, distanceToTop); @@ -939,10 +963,12 @@ public class PopupWindow { */ public void update(int x, int y, int width, int height) { if (width != -1) { + mLastWidth = width; setWidth(width); } if (height != -1) { + mLastHeight = height; setHeight(height); } @@ -990,22 +1016,6 @@ public class PopupWindow { } if (update) { - if (mPopupView != mContentView) { - final View popupViewContainer = mPopupView; - if (p.height >= 0) { - // accomodate the popup's height to take into account the - // background's padding - p.height += popupViewContainer.getPaddingTop() + - popupViewContainer.getPaddingBottom(); - } - if (p.width >= 0) { - // accomodate the popup's width to take into account the - // background's padding - p.width += popupViewContainer.getPaddingLeft() + - popupViewContainer.getPaddingRight(); - } - } - mWindowManager.updateViewLayout(mPopupView, p); } } diff --git a/core/java/android/widget/ProgressBar.java b/core/java/android/widget/ProgressBar.java index 2e04b5d..434e9f3 100644 --- a/core/java/android/widget/ProgressBar.java +++ b/core/java/android/widget/ProgressBar.java @@ -761,7 +761,7 @@ public class ProgressBar extends View { if (dr == mProgressDrawable || dr == mIndeterminateDrawable) { final Rect dirty = dr.getBounds(); final int scrollX = mScrollX + mPaddingLeft; - final int scrollY = mScrollY + mPaddingRight; + final int scrollY = mScrollY + mPaddingTop; invalidate(dirty.left + scrollX, dirty.top + scrollY, dirty.right + scrollX, dirty.bottom + scrollY); diff --git a/core/java/android/widget/RadioGroup.java b/core/java/android/widget/RadioGroup.java index ed8df22..393346a 100644 --- a/core/java/android/widget/RadioGroup.java +++ b/core/java/android/widget/RadioGroup.java @@ -122,6 +122,23 @@ public class RadioGroup extends LinearLayout { } } + @Override + public void addView(View child, int index, ViewGroup.LayoutParams params) { + if (child instanceof RadioButton) { + final RadioButton button = (RadioButton) child; + if (button.isChecked()) { + mProtectFromCheckedChange = true; + if (mCheckedId != -1) { + setCheckedStateForView(mCheckedId, false); + } + mProtectFromCheckedChange = false; + setCheckedId(button.getId()); + } + } + + super.addView(child, index, params); + } + /** * <p>Sets the selection to the radio button whose identifier is passed in * parameter. Using -1 as the selection identifier clears the selection; diff --git a/core/java/android/widget/RelativeLayout.java b/core/java/android/widget/RelativeLayout.java index 91d5805..9ded52b 100644 --- a/core/java/android/widget/RelativeLayout.java +++ b/core/java/android/widget/RelativeLayout.java @@ -152,7 +152,7 @@ public class RelativeLayout extends ViewGroup { private void initFromAttributes(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RelativeLayout); - mIgnoreGravity = a.getResourceId(R.styleable.RelativeLayout_ignoreGravity, 0); + mIgnoreGravity = a.getResourceId(R.styleable.RelativeLayout_ignoreGravity, View.NO_ID); mGravity = a.getInt(R.styleable.RelativeLayout_gravity, mGravity); a.recycle(); } @@ -263,7 +263,7 @@ public class RelativeLayout extends ViewGroup { int right = Integer.MIN_VALUE; int bottom = Integer.MIN_VALUE; - if ((horizontalGravity || verticalGravity) && mIgnoreGravity != 0) { + if ((horizontalGravity || verticalGravity) && mIgnoreGravity != View.NO_ID) { ignore = findViewById(mIgnoreGravity); } diff --git a/core/java/android/widget/RemoteViews.aidl b/core/java/android/widget/RemoteViews.aidl new file mode 100644 index 0000000..ec86410 --- /dev/null +++ b/core/java/android/widget/RemoteViews.aidl @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2007, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.widget; + +parcelable RemoteViews; diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java index 5721095..a1023bd 100644 --- a/core/java/android/widget/RemoteViews.java +++ b/core/java/android/widget/RemoteViews.java @@ -22,6 +22,7 @@ import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.graphics.Bitmap; +import android.graphics.PorterDuff; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; @@ -422,6 +423,131 @@ public class RemoteViews implements Parcelable, Filter { } /** + * Equivalent to calling a combination of {@link Drawable#setAlpha(int)}, + * {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)}, + * and/or {@link Drawable#setLevel(int)} on the {@link Drawable} of a given view. + * <p> + * These operations will be performed on the {@link Drawable} returned by the + * target {@link View#getBackground()} by default. If targetBackground is false, + * we assume the target is an {@link ImageView} and try applying the operations + * to {@link ImageView#getDrawable()}. + * <p> + * You can omit specific calls by marking their values with null or -1. + */ + private class SetDrawableParameters extends Action { + public SetDrawableParameters(int id, boolean targetBackground, int alpha, + int colorFilter, PorterDuff.Mode mode, int level) { + this.viewId = id; + this.targetBackground = targetBackground; + this.alpha = alpha; + this.colorFilter = colorFilter; + this.filterMode = mode; + this.level = level; + } + + public SetDrawableParameters(Parcel parcel) { + viewId = parcel.readInt(); + targetBackground = parcel.readInt() != 0; + alpha = parcel.readInt(); + colorFilter = parcel.readInt(); + boolean hasMode = parcel.readInt() != 0; + if (hasMode) { + filterMode = PorterDuff.Mode.valueOf(parcel.readString()); + } else { + filterMode = null; + } + level = parcel.readInt(); + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(TAG); + dest.writeInt(viewId); + dest.writeInt(targetBackground ? 1 : 0); + dest.writeInt(alpha); + dest.writeInt(colorFilter); + if (filterMode != null) { + dest.writeInt(1); + dest.writeString(filterMode.toString()); + } else { + dest.writeInt(0); + } + dest.writeInt(level); + } + + @Override + public void apply(View root) { + final View target = root.findViewById(viewId); + if (target == null) { + return; + } + + // Pick the correct drawable to modify for this view + Drawable targetDrawable = null; + if (targetBackground) { + targetDrawable = target.getBackground(); + } else if (target instanceof ImageView) { + ImageView imageView = (ImageView) target; + targetDrawable = imageView.getDrawable(); + } + + // Perform modifications only if values are set correctly + if (alpha != -1) { + targetDrawable.setAlpha(alpha); + } + if (colorFilter != -1 && filterMode != null) { + targetDrawable.setColorFilter(colorFilter, filterMode); + } + if (level != -1) { + targetDrawable.setLevel(level); + } + } + + int viewId; + boolean targetBackground; + int alpha; + int colorFilter; + PorterDuff.Mode filterMode; + int level; + + public final static int TAG = 8; + } + + /** + * Equivalent to calling {@link android.widget.TextView#setTextColor(int)}. + */ + private class SetTextColor extends Action { + public SetTextColor(int id, int color) { + this.viewId = id; + this.color = color; + } + + public SetTextColor(Parcel parcel) { + viewId = parcel.readInt(); + color = parcel.readInt(); + } + + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(TAG); + dest.writeInt(viewId); + dest.writeInt(color); + } + + @Override + public void apply(View root) { + final View target = root.findViewById(viewId); + if (target instanceof TextView) { + final TextView textView = (TextView) target; + textView.setTextColor(color); + } + } + + int viewId; + int color; + + public final static int TAG = 9; + } + + /** * Create a new RemoteViews object that will display the views contained * in the specified layout file. * @@ -471,6 +597,12 @@ public class RemoteViews implements Parcelable, Filter { case SetOnClickPendingIntent.TAG: mActions.add(new SetOnClickPendingIntent(parcel)); break; + case SetDrawableParameters.TAG: + mActions.add(new SetDrawableParameters(parcel)); + break; + case SetTextColor.TAG: + mActions.add(new SetTextColor(parcel)); + break; default: throw new ActionException("Tag " + tag + "not found"); } @@ -595,6 +727,48 @@ public class RemoteViews implements Parcelable, Filter { } /** + * Equivalent to calling a combination of {@link Drawable#setAlpha(int)}, + * {@link Drawable#setColorFilter(int, android.graphics.PorterDuff.Mode)}, + * and/or {@link Drawable#setLevel(int)} on the {@link Drawable} of a given + * view. + * <p> + * You can omit specific calls by marking their values with null or -1. + * + * @param viewId The id of the view that contains the target + * {@link Drawable} + * @param targetBackground If true, apply these parameters to the + * {@link Drawable} returned by + * {@link android.view.View#getBackground()}. Otherwise, assume + * the target view is an {@link ImageView} and apply them to + * {@link ImageView#getDrawable()}. + * @param alpha Specify an alpha value for the drawable, or -1 to leave + * unchanged. + * @param colorFilter Specify a color for a + * {@link android.graphics.ColorFilter} for this drawable, or -1 + * to leave unchanged. + * @param mode Specify a PorterDuff mode for this drawable, or null to leave + * unchanged. + * @param level Specify the level for the drawable, or -1 to leave + * unchanged. + */ + public void setDrawableParameters(int viewId, boolean targetBackground, int alpha, + int colorFilter, PorterDuff.Mode mode, int level) { + addAction(new SetDrawableParameters(viewId, targetBackground, alpha, + colorFilter, mode, level)); + } + + /** + * Equivalent to calling {@link android.widget.TextView#setTextColor(int)}. + * + * @param viewId The id of the view whose text should change + * @param color Sets the text color for all the states (normal, selected, + * focused) to be this color. + */ + public void setTextColor(int viewId, int color) { + addAction(new SetTextColor(viewId, color)); + } + + /** * Inflates the view hierarchy represented by this object and applies * all of the actions. * diff --git a/core/java/android/widget/ScrollBarDrawable.java b/core/java/android/widget/ScrollBarDrawable.java index 17f9128..3b113ae 100644 --- a/core/java/android/widget/ScrollBarDrawable.java +++ b/core/java/android/widget/ScrollBarDrawable.java @@ -152,10 +152,12 @@ public class ScrollBarDrawable extends Drawable { } else { track = mHorizontalTrack; } - if (mChanged) { - track.setBounds(bounds); + if (track != null) { + if (mChanged) { + track.setBounds(bounds); + } + track.draw(canvas); } - track.draw(canvas); } protected void drawThumb(Canvas canvas, Rect bounds, int offset, int length, boolean vertical) { diff --git a/core/java/android/widget/ScrollView.java b/core/java/android/widget/ScrollView.java index 20166cf..c9b3751 100644 --- a/core/java/android/widget/ScrollView.java +++ b/core/java/android/widget/ScrollView.java @@ -44,13 +44,7 @@ import java.util.List; * manager with a complex hierarchy of objects. A child that is often used * is a {@link LinearLayout} in a vertical orientation, presenting a vertical * array of top-level items that the user can scroll through. - * - * <p>You should never use a ScrollView with a {@link ListView}, since - * ListView takes care of its own scrolling. Most importantly, doing this - * defeats all of the important optimizations in ListView for dealing with - * large lists, since it effectively forces the ListView to display its entire - * list of items to fill up the infinite container supplied by ScrollView. - * + * * <p>The {@link TextView} class also * takes care of its own scrolling, so does not require a ScrollView, but * using the two together is possible to achieve the effect of a text view @@ -62,13 +56,9 @@ public class ScrollView extends FrameLayout { static final String TAG = "ScrollView"; static final boolean localLOGV = false || Config.LOGV; - private static final int ANIMATED_SCROLL_GAP = 250; + static final int ANIMATED_SCROLL_GAP = 250; - /** - * When arrow scrolling, ListView will never scroll more than this factor - * times the height of the list. - */ - private static final float MAX_SCROLL_FACTOR = 0.5f; + static final float MAX_SCROLL_FACTOR = 0.5f; private long mLastScroll; @@ -124,6 +114,8 @@ public class ScrollView extends FrameLayout { */ private boolean mSmoothScrollingEnabled = true; + private int mTouchSlop; + public ScrollView(Context context) { this(context, null); } @@ -165,8 +157,8 @@ public class ScrollView extends FrameLayout { } final int length = getVerticalFadingEdgeLength(); - final int bottom = getChildAt(0).getBottom(); - final int span = bottom - mScrollY - getHeight(); + final int bottomEdge = getHeight() - mPaddingBottom; + final int span = getChildAt(0).getBottom() - mScrollY - bottomEdge; if (span < length) { return span / (float) length; } @@ -188,6 +180,7 @@ public class ScrollView extends FrameLayout { setFocusable(true); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setWillNotDraw(false); + mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop(); } @Override @@ -401,7 +394,7 @@ public class ScrollView extends FrameLayout { * of the down event. */ final int yDiff = (int) Math.abs(y - mLastMotionY); - if (yDiff > ViewConfiguration.getTouchSlop()) { + if (yDiff > mTouchSlop) { mIsBeingDragged = true; } break; @@ -488,8 +481,9 @@ public class ScrollView extends FrameLayout { velocityTracker.computeCurrentVelocity(1000); int initialVelocity = (int) velocityTracker.getYVelocity(); - if ((Math.abs(initialVelocity) > ViewConfiguration.getMinimumFlingVelocity()) && - (getChildCount() > 0)) { + if ((Math.abs(initialVelocity) > + ViewConfiguration.get(mContext).getScaledMinimumFlingVelocity()) && + getChildCount() > 0) { fling(-initialVelocity); } @@ -812,7 +806,7 @@ public class ScrollView extends FrameLayout { /** * Smooth scroll by a Y delta * - * @param delta the number of pixels to scroll by on the X axis + * @param delta the number of pixels to scroll by on the Y axis */ private void doScrollY(int delta) { if (delta != 0) { @@ -923,8 +917,8 @@ public class ScrollView extends FrameLayout { int y = mScroller.getCurrY(); if (getChildCount() > 0) { View child = getChildAt(0); - mScrollX = clamp(x, this.getWidth(), child.getWidth()); - mScrollY = clamp(y, this.getHeight(), child.getHeight()); + mScrollX = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); + mScrollY = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); if (localLOGV) Log.v(TAG, "mScrollY=" + mScrollY + " y=" + y + " height=" + this.getHeight() + " child height=" + child.getHeight()); @@ -1167,8 +1161,8 @@ public class ScrollView extends FrameLayout { * which means we want to scroll towards the top. */ public void fling(int velocityY) { - int height = getHeight(); - int bottom = getChildAt(getChildCount() - 1).getBottom(); + int height = getHeight() - mPaddingBottom - mPaddingTop; + int bottom = getChildAt(0).getHeight(); mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0, bottom - height); @@ -1198,8 +1192,8 @@ public class ScrollView extends FrameLayout { // we rely on the fact the View.scrollBy calls scrollTo. if (getChildCount() > 0) { View child = getChildAt(0); - x = clamp(x, this.getWidth(), child.getWidth()); - y = clamp(y, this.getHeight(), child.getHeight()); + x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth()); + y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight()); if (x != mScrollX || y != mScrollY) { super.scrollTo(x, y); } diff --git a/core/java/android/widget/Scroller.java b/core/java/android/widget/Scroller.java index fbe5e57..febc956 100644 --- a/core/java/android/widget/Scroller.java +++ b/core/java/android/widget/Scroller.java @@ -132,6 +132,26 @@ public class Scroller { } /** + * Returns the start X offset in the scroll. + * + * @return The start X offset as an absolute distance from the origin. + * @hide pending API council + */ + public final int getStartX() { + return mStartX; + } + + /** + * Returns the start Y offset in the scroll. + * + * @return The start Y offset as an absolute distance from the origin. + * @hide pending API council + */ + public final int getStartY() { + return mStartY; + } + + /** * Returns where the scroll will end. Valid only for "fling" scrolls. * * @return The final X offset as an absolute distance from the origin. diff --git a/core/java/android/widget/SimpleAdapter.java b/core/java/android/widget/SimpleAdapter.java index 261da9f..093c24e 100644 --- a/core/java/android/widget/SimpleAdapter.java +++ b/core/java/android/widget/SimpleAdapter.java @@ -36,12 +36,16 @@ import java.util.Map; * Binding data to views occurs in two phases. First, if a * {@link android.widget.SimpleAdapter.ViewBinder} is available, * {@link ViewBinder#setViewValue(android.view.View, Object, String)} - * is invoked. If the returned value is true, binding has occured. If the - * returned value is false and the view to bind is a TextView, - * {@link #setViewText(TextView, String)} is invoked. If the returned value - * is false and the view to bind is an ImageView, - * {@link #setViewImage(ImageView, int)} or {@link #setViewImage(ImageView, String)} is - * invoked. If no appropriate binding can be found, an {@link IllegalStateException} is thrown. + * is invoked. If the returned value is true, binding has occurred. + * If the returned value is false, the following views are then tried in order: + * <ul> + * <li> A view that implements Checkable (e.g. CheckBox). The expected bind value is a boolean. + * <li> TextView. The expected bind value is a string and {@link #setViewText(TextView, String)} + * is invoked. + * <li> ImageView. The expected bind value is a resource id or a string and + * {@link #setViewImage(ImageView, int)} or {@link #setViewImage(ImageView, String)} is invoked. + * </ul> + * If no appropriate binding can be found, an {@link IllegalStateException} is thrown. */ public class SimpleAdapter extends BaseAdapter implements Filterable { private int[] mTo; @@ -176,7 +180,16 @@ public class SimpleAdapter extends BaseAdapter implements Filterable { } if (!bound) { - if (v instanceof TextView) { + if (v instanceof Checkable) { + if (data instanceof Boolean) { + ((Checkable) v).setChecked((Boolean) data); + } else { + throw new IllegalStateException(v.getClass().getName() + + " should be bound to a Boolean, not a " + data.getClass()); + } + } else if (v instanceof TextView) { + // Note: keep the instanceof TextView check at the bottom of these + // ifs since a lot of views are TextViews (e.g. CheckBoxes). setViewText((TextView) v, text); } else if (v instanceof ImageView) { if (data instanceof Integer) { diff --git a/core/java/android/widget/SlidingDrawer.java b/core/java/android/widget/SlidingDrawer.java new file mode 100644 index 0000000..e77c4ca --- /dev/null +++ b/core/java/android/widget/SlidingDrawer.java @@ -0,0 +1,938 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.widget; + +import android.view.ViewGroup; +import android.view.View; +import android.view.MotionEvent; +import android.view.VelocityTracker; +import android.view.SoundEffectConstants; +import android.content.Context; +import android.content.res.TypedArray; +import android.util.AttributeSet; +import android.graphics.Canvas; +import android.graphics.Rect; +import android.graphics.Bitmap; +import android.os.SystemClock; +import android.os.Handler; +import android.os.Message; +import android.R; + +/** + * SlidingDrawer hides content out of the screen and allows the user to drag a handle + * to bring the content on screen. SlidingDrawer can be used vertically or horizontally. + * + * A special widget composed of two children views: the handle, that the users drags, + * and the content, attached to the handle and dragged with it. + * + * SlidingDrawer should be used as an overlay inside layouts. This means SlidingDrawer + * should only be used inside of a FrameLayout or a RelativeLayout for instance. The + * size of the SlidingDrawer defines how much space the content will occupy once slid + * out so SlidingDrawer should usually use fill_parent for both its dimensions. + * + * Inside an XML layout, SlidingDrawer must define the id of the handle and of the + * content: + * + * <pre class="prettyprint"> + * <SlidingDrawer + * android:id="@+id/drawer" + * android:layout_width="fill_parent" + * android:layout_height="fill_parent" + * + * android:handle="@+id/handle" + * android:content="@+id/content"> + * + * <ImageView + * android:id="@id/handle" + * android:layout_width="88dip" + * android:layout_height="44dip" /> + * + * <GridView + * android:id="@id/content" + * android:layout_width="fill_parent" + * android:layout_height="fill_parent" /> + * + * </SlidingDrawer> + * </pre> + * + * @attr ref android.R.styleable#SlidingDrawer_content + * @attr ref android.R.styleable#SlidingDrawer_handle + * @attr ref android.R.styleable#SlidingDrawer_topOffset + * @attr ref android.R.styleable#SlidingDrawer_bottomOffset + * @attr ref android.R.styleable#SlidingDrawer_orientation + * @attr ref android.R.styleable#SlidingDrawer_allowSingleTap + * @attr ref android.R.styleable#SlidingDrawer_animateOnClick + */ +public class SlidingDrawer extends ViewGroup { + public static final int ORIENTATION_HORIZONTAL = 0; + public static final int ORIENTATION_VERTICAL = 1; + + private static final int TAP_THRESHOLD = 6; + private static final float MAXIMUM_TAP_VELOCITY = 100.0f; + private static final float MAXIMUM_MINOR_VELOCITY = 150.0f; + private static final float MAXIMUM_MAJOR_VELOCITY = 200.0f; + private static final float MAXIMUM_ACCELERATION = 2000.0f; + private static final int VELOCITY_UNITS = 1000; + private static final int MSG_ANIMATE = 1000; + private static final int ANIMATION_FRAME_DURATION = 1000 / 60; + + private static final int EXPANDED_FULL_OPEN = -10001; + private static final int COLLAPSED_FULL_CLOSED = -10002; + + private final int mHandleId; + private final int mContentId; + + private View mHandle; + private View mContent; + + private final Rect mFrame = new Rect(); + private final Rect mInvalidate = new Rect(); + private boolean mTracking; + private boolean mLocked; + + private VelocityTracker mVelocityTracker; + + private boolean mVertical; + private boolean mExpanded; + private int mBottomOffset; + private int mTopOffset; + private int mHandleHeight; + private int mHandleWidth; + + private OnDrawerOpenListener mOnDrawerOpenListener; + private OnDrawerCloseListener mOnDrawerCloseListener; + private OnDrawerScrollListener mOnDrawerScrollListener; + + private final Handler mHandler = new SlidingHandler(); + private float mAnimatedAcceleration; + private float mAnimatedVelocity; + private float mAnimationPosition; + private long mAnimationLastTime; + private long mCurrentAnimationTime; + private int mTouchDelta; + private boolean mAnimating; + private boolean mAllowSingleTap; + private boolean mAnimateOnClick; + + private final int mTapThreshold; + private final int mMaximumTapVelocity; + private final int mMaximumMinorVelocity; + private final int mMaximumMajorVelocity; + private final int mMaximumAcceleration; + private final int mVelocityUnits; + + /** + * Callback invoked when the drawer is opened. + */ + public static interface OnDrawerOpenListener { + /** + * Invoked when the drawer becomes fully open. + */ + public void onDrawerOpened(); + } + + /** + * Callback invoked when the drawer is closed. + */ + public static interface OnDrawerCloseListener { + /** + * Invoked when the drawer becomes fully closed. + */ + public void onDrawerClosed(); + } + + /** + * Callback invoked when the drawer is scrolled. + */ + public static interface OnDrawerScrollListener { + /** + * Invoked when the user starts dragging/flinging the drawer's handle. + */ + public void onScrollStarted(); + + /** + * Invoked when the user stops dragging/flinging the drawer's handle. + */ + public void onScrollEnded(); + } + + /** + * Creates a new SlidingDrawer from a specified set of attributes defined in XML. + * + * @param context The application's environment. + * @param attrs The attributes defined in XML. + */ + public SlidingDrawer(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + /** + * Creates a new SlidingDrawer from a specified set of attributes defined in XML. + * + * @param context The application's environment. + * @param attrs The attributes defined in XML. + * @param defStyle The style to apply to this widget. + */ + public SlidingDrawer(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SlidingDrawer, defStyle, 0); + + int orientation = a.getInt(R.styleable.SlidingDrawer_orientation, ORIENTATION_VERTICAL); + mVertical = orientation == ORIENTATION_VERTICAL; + mBottomOffset = (int) a.getDimension(R.styleable.SlidingDrawer_bottomOffset, 0.0f); + mTopOffset = (int) a.getDimension(R.styleable.SlidingDrawer_topOffset, 0.0f); + mAllowSingleTap = a.getBoolean(R.styleable.SlidingDrawer_allowSingleTap, true); + mAnimateOnClick = a.getBoolean(R.styleable.SlidingDrawer_animateOnClick, true); + + int handleId = a.getResourceId(R.styleable.SlidingDrawer_handle, 0); + if (handleId == 0) { + throw new IllegalArgumentException("The handle attribute is required and must refer " + + "to a valid child."); + } + + int contentId = a.getResourceId(R.styleable.SlidingDrawer_content, 0); + if (contentId == 0) { + throw new IllegalArgumentException("The handle attribute is required and must refer " + + "to a valid child."); + } + + mHandleId = handleId; + mContentId = contentId; + + final float density = getResources().getDisplayMetrics().density; + mTapThreshold = (int) (TAP_THRESHOLD * density + 0.5f); + mMaximumTapVelocity = (int) (MAXIMUM_TAP_VELOCITY * density + 0.5f); + mMaximumMinorVelocity = (int) (MAXIMUM_MINOR_VELOCITY * density + 0.5f); + mMaximumMajorVelocity = (int) (MAXIMUM_MAJOR_VELOCITY * density + 0.5f); + mMaximumAcceleration = (int) (MAXIMUM_ACCELERATION * density + 0.5f); + mVelocityUnits = (int) (VELOCITY_UNITS * density + 0.5f); + + a.recycle(); + + setAlwaysDrawnWithCacheEnabled(false); + } + + @Override + protected void onFinishInflate() { + mHandle = findViewById(mHandleId); + if (mHandle == null) { + throw new IllegalArgumentException("The handle attribute is must refer to an" + + " existing child."); + } + mHandle.setOnClickListener(new DrawerToggler()); + + mContent = findViewById(mContentId); + if (mContent == null) { + throw new IllegalArgumentException("The content attribute is must refer to an" + + " existing child."); + } + mContent.setVisibility(View.GONE); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); + int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); + + int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); + int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); + + if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) { + throw new RuntimeException("SlidingDrawer cannot have UNSPECIFIED dimensions"); + } + + final View handle = mHandle; + measureChild(handle, widthMeasureSpec, heightMeasureSpec); + + if (mVertical) { + int height = heightSpecSize - handle.getMeasuredHeight() - mTopOffset; + mContent.measure(MeasureSpec.makeMeasureSpec(widthSpecSize, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); + } else { + int width = widthSpecSize - handle.getMeasuredWidth() - mTopOffset; + mContent.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(heightSpecSize, MeasureSpec.EXACTLY)); + } + + setMeasuredDimension(widthSpecSize, heightSpecSize); + } + + @Override + protected void dispatchDraw(Canvas canvas) { + final long drawingTime = getDrawingTime(); + final View handle = mHandle; + final boolean isVertical = mVertical; + + drawChild(canvas, handle, drawingTime); + + if (mTracking || mAnimating) { + final Bitmap cache = mContent.getDrawingCache(); + if (cache != null) { + if (isVertical) { + canvas.drawBitmap(cache, 0, handle.getBottom(), null); + } else { + canvas.drawBitmap(cache, handle.getRight(), 0, null); + } + } else { + canvas.save(); + canvas.translate(isVertical ? 0 : handle.getLeft() - mTopOffset, + isVertical ? handle.getTop() - mTopOffset : 0); + drawChild(canvas, mContent, drawingTime); + canvas.restore(); + } + } else if (mExpanded) { + drawChild(canvas, mContent, drawingTime); + } + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + if (mTracking) { + return; + } + + final int width = r - l; + final int height = b - t; + + final View handle = mHandle; + + int childWidth = handle.getMeasuredWidth(); + int childHeight = handle.getMeasuredHeight(); + + int childLeft; + int childTop; + + final View content = mContent; + + if (mVertical) { + childLeft = (width - childWidth) / 2; + childTop = mExpanded ? mTopOffset : height - childHeight + mBottomOffset; + + content.layout(0, mTopOffset + childHeight, content.getMeasuredWidth(), + mTopOffset + childHeight + content.getMeasuredHeight()); + } else { + childLeft = mExpanded ? mTopOffset : width - childWidth + mBottomOffset; + childTop = (height - childHeight) / 2; + + content.layout(mTopOffset + childWidth, 0, + mTopOffset + childWidth + content.getMeasuredWidth(), + content.getMeasuredHeight()); + } + + handle.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight); + mHandleHeight = handle.getHeight(); + mHandleWidth = handle.getWidth(); + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent event) { + if (mLocked) { + return false; + } + + final int action = event.getAction(); + + float x = event.getX(); + float y = event.getY(); + + final Rect frame = mFrame; + final View handle = mHandle; + + handle.getHitRect(frame); + if (!mTracking && !frame.contains((int) x, (int) y)) { + return false; + } + + if (action == MotionEvent.ACTION_DOWN) { + if (mOnDrawerScrollListener != null) { + mOnDrawerScrollListener.onScrollStarted(); + } + mTracking = true; + + handle.setPressed(true); + // Must be called before prepareTracking() + prepareContent(); + + if (mVertical) { + final int top = mHandle.getTop(); + mTouchDelta = (int) y - top; + prepareTracking(top); + } else { + final int left = mHandle.getLeft(); + mTouchDelta = (int) x - left; + prepareTracking(left); + } + mVelocityTracker.addMovement(event); + } + + return true; + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + if (mLocked) { + return true; + } + + if (mTracking) { + mVelocityTracker.addMovement(event); + final int action = event.getAction(); + switch (action) { + case MotionEvent.ACTION_MOVE: + moveHandle((int) (mVertical ? event.getY() : event.getX()) - mTouchDelta); + break; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: { + final VelocityTracker velocityTracker = mVelocityTracker; + velocityTracker.computeCurrentVelocity(mVelocityUnits); + + float yVelocity = velocityTracker.getYVelocity(); + float xVelocity = velocityTracker.getXVelocity(); + boolean negative; + + final boolean vertical = mVertical; + if (vertical) { + negative = yVelocity < 0; + if (xVelocity < 0) { + xVelocity = -xVelocity; + } + if (xVelocity > mMaximumMinorVelocity) { + xVelocity = mMaximumMinorVelocity; + } + } else { + negative = xVelocity < 0; + if (yVelocity < 0) { + yVelocity = -yVelocity; + } + if (yVelocity > mMaximumMinorVelocity) { + yVelocity = mMaximumMinorVelocity; + } + } + + float velocity = (float) Math.hypot(xVelocity, yVelocity); + if (negative) { + velocity = -velocity; + } + + final int top = mHandle.getTop(); + final int left = mHandle.getLeft(); + + if (Math.abs(velocity) < mMaximumTapVelocity) { + if (vertical ? (mExpanded && top < mTapThreshold + mTopOffset) || + (!mExpanded && top > mBottomOffset + mBottom - mTop - + mHandleHeight - mTapThreshold) : + (mExpanded && left < mTapThreshold + mTopOffset) || + (!mExpanded && left > mBottomOffset + mRight - mLeft - + mHandleWidth - mTapThreshold)) { + + if (mAllowSingleTap) { + playSoundEffect(SoundEffectConstants.CLICK); + + if (mExpanded) { + animateClose(vertical ? top : left); + } else { + animateOpen(vertical ? top : left); + } + } + + } else { + performFling(vertical ? top : left, velocity, false); + } + } else { + performFling(vertical ? top : left, velocity, false); + } + } + break; + } + } + + return mTracking || mAnimating || super.onTouchEvent(event); + } + + private void animateClose(int position) { + prepareTracking(position); + performFling(position, mMaximumAcceleration, true); + } + + private void animateOpen(int position) { + prepareTracking(position); + performFling(position, -mMaximumAcceleration, true); + } + + private void performFling(int position, float velocity, boolean always) { + mAnimationPosition = position; + mAnimatedVelocity = velocity; + + if (mExpanded) { + if (always || (velocity > mMaximumMajorVelocity || + (position > mTopOffset + (mVertical ? mHandleHeight : mHandleWidth) && + velocity > -mMaximumMajorVelocity))) { + // We are expanded, but they didn't move sufficiently to cause + // us to retract. Animate back to the expanded position. + mAnimatedAcceleration = mMaximumAcceleration; + if (velocity < 0) { + mAnimatedVelocity = 0; + } + } else { + // We are expanded and are now going to animate away. + mAnimatedAcceleration = -mMaximumAcceleration; + if (velocity > 0) { + mAnimatedVelocity = 0; + } + } + } else { + if (!always && (velocity > mMaximumMajorVelocity || + (position > (mVertical ? getHeight() : getWidth()) / 2 && + velocity > -mMaximumMajorVelocity))) { + // We are collapsed, and they moved enough to allow us to expand. + mAnimatedAcceleration = mMaximumAcceleration; + if (velocity < 0) { + mAnimatedVelocity = 0; + } + } else { + // We are collapsed, but they didn't move sufficiently to cause + // us to retract. Animate back to the collapsed position. + mAnimatedAcceleration = -mMaximumAcceleration; + if (velocity > 0) { + mAnimatedVelocity = 0; + } + } + } + + long now = SystemClock.uptimeMillis(); + mAnimationLastTime = now; + mCurrentAnimationTime = now + ANIMATION_FRAME_DURATION; + mAnimating = true; + mHandler.removeMessages(MSG_ANIMATE); + mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurrentAnimationTime); + stopTracking(); + } + + private void prepareTracking(int position) { + mTracking = true; + mVelocityTracker = VelocityTracker.obtain(); + boolean opening = !mExpanded; + if (opening) { + mAnimatedAcceleration = mMaximumAcceleration; + mAnimatedVelocity = mMaximumMajorVelocity; + mAnimationPosition = mBottomOffset + + (mVertical ? getHeight() - mHandleHeight : getWidth() - mHandleWidth); + moveHandle((int) mAnimationPosition); + mAnimating = true; + mHandler.removeMessages(MSG_ANIMATE); + long now = SystemClock.uptimeMillis(); + mAnimationLastTime = now; + mCurrentAnimationTime = now + ANIMATION_FRAME_DURATION; + mAnimating = true; + } else { + if (mAnimating) { + mAnimating = false; + mHandler.removeMessages(MSG_ANIMATE); + } + moveHandle(position); + } + } + + private void moveHandle(int position) { + final View handle = mHandle; + + if (mVertical) { + if (position == EXPANDED_FULL_OPEN) { + handle.offsetTopAndBottom(mTopOffset - handle.getTop()); + invalidate(); + } else if (position == COLLAPSED_FULL_CLOSED) { + handle.offsetTopAndBottom(mBottomOffset + mBottom - mTop - + mHandleHeight - handle.getTop()); + invalidate(); + } else { + final int top = handle.getTop(); + int deltaY = position - top; + if (position < mTopOffset) { + deltaY = mTopOffset - top; + } else if (deltaY > mBottomOffset + mBottom - mTop - mHandleHeight - top) { + deltaY = mBottomOffset + mBottom - mTop - mHandleHeight - top; + } + handle.offsetTopAndBottom(deltaY); + + final Rect frame = mFrame; + final Rect region = mInvalidate; + + handle.getHitRect(frame); + region.set(frame); + + region.union(frame.left, frame.top - deltaY, frame.right, frame.bottom - deltaY); + region.union(0, frame.bottom - deltaY, getWidth(), + frame.bottom - deltaY + mContent.getHeight()); + + invalidate(region); + } + } else { + if (position == EXPANDED_FULL_OPEN) { + handle.offsetLeftAndRight(mTopOffset - handle.getLeft()); + invalidate(); + } else if (position == COLLAPSED_FULL_CLOSED) { + handle.offsetLeftAndRight(mBottomOffset + mRight - mLeft - + mHandleWidth - handle.getLeft()); + invalidate(); + } else { + final int left = handle.getLeft(); + int deltaX = position - left; + if (position < mTopOffset) { + deltaX = mTopOffset - left; + } else if (deltaX > mBottomOffset + mRight - mLeft - mHandleWidth - left) { + deltaX = mBottomOffset + mRight - mLeft - mHandleWidth - left; + } + handle.offsetLeftAndRight(deltaX); + + final Rect frame = mFrame; + final Rect region = mInvalidate; + + handle.getHitRect(frame); + region.set(frame); + + region.union(frame.left - deltaX, frame.top, frame.right - deltaX, frame.bottom); + region.union(frame.right - deltaX, 0, + frame.right - deltaX + mContent.getWidth(), getHeight()); + + invalidate(region); + } + } + } + + private void prepareContent() { + if (mAnimating) { + return; + } + + // Something changed in the content, we need to honor the layout request + // before creating the cached bitmap + final View content = mContent; + if (content.isLayoutRequested()) { + if (mVertical) { + final int childHeight = mHandleHeight; + int height = mBottom - mTop - childHeight - mTopOffset; + content.measure(MeasureSpec.makeMeasureSpec(mRight - mLeft, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); + content.layout(0, mTopOffset + childHeight, content.getMeasuredWidth(), + mTopOffset + childHeight + content.getMeasuredHeight()); + } else { + final int childWidth = mHandle.getWidth(); + int width = mRight - mLeft - childWidth - mTopOffset; + content.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), + MeasureSpec.makeMeasureSpec(mBottom - mTop, MeasureSpec.EXACTLY)); + content.layout(childWidth + mTopOffset, 0, + mTopOffset + childWidth + content.getMeasuredWidth(), + content.getMeasuredHeight()); + } + } + // Try only once... we should really loop but it's not a big deal + // if the draw was cancelled, it will only be temporary anyway + content.getViewTreeObserver().dispatchOnPreDraw(); + content.buildDrawingCache(); + + content.setVisibility(View.GONE); + } + + private void stopTracking() { + mHandle.setPressed(false); + mTracking = false; + + if (mOnDrawerScrollListener != null) { + mOnDrawerScrollListener.onScrollEnded(); + } + + if (mVelocityTracker != null) { + mVelocityTracker.recycle(); + mVelocityTracker = null; + } + } + + private void doAnimation() { + if (mAnimating) { + incrementAnimation(); + if (mAnimationPosition >= mBottomOffset + (mVertical ? getHeight() : getWidth()) - 1) { + mAnimating = false; + closeDrawer(); + } else if (mAnimationPosition < mTopOffset) { + mAnimating = false; + openDrawer(); + } else { + moveHandle((int) mAnimationPosition); + mCurrentAnimationTime += ANIMATION_FRAME_DURATION; + mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), + mCurrentAnimationTime); + } + } + } + + private void incrementAnimation() { + long now = SystemClock.uptimeMillis(); + float t = (now - mAnimationLastTime) / 1000.0f; // ms -> s + final float position = mAnimationPosition; + final float v = mAnimatedVelocity; // px/s + final float a = mAnimatedAcceleration; // px/s/s + mAnimationPosition = position + (v * t) + (0.5f * a * t * t); // px + mAnimatedVelocity = v + (a * t); // px/s + mAnimationLastTime = now; // ms + } + + /** + * Toggles the drawer open and close. Takes effect immediately. + * + * @see #open() + * @see #close() + * @see #animateClose() + * @see #animateOpen() + * @see #animateToggle() + */ + public void toggle() { + if (!mExpanded) { + openDrawer(); + } else { + closeDrawer(); + } + invalidate(); + requestLayout(); + } + + /** + * Toggles the drawer open and close with an animation. + * + * @see #open() + * @see #close() + * @see #animateClose() + * @see #animateOpen() + * @see #toggle() + */ + public void animateToggle() { + if (!mExpanded) { + animateOpen(); + } else { + animateClose(); + } + } + + /** + * Opens the drawer immediately. + * + * @see #toggle() + * @see #close() + * @see #animateOpen() + */ + public void open() { + openDrawer(); + invalidate(); + requestLayout(); + } + + /** + * Closes the drawer immediately. + * + * @see #toggle() + * @see #open() + * @see #animateClose() + */ + public void close() { + closeDrawer(); + invalidate(); + requestLayout(); + } + + /** + * Closes the drawer with an animation. + * + * @see #close() + * @see #open() + * @see #animateOpen() + * @see #animateToggle() + * @see #toggle() + */ + public void animateClose() { + final OnDrawerScrollListener scrollListener = mOnDrawerScrollListener; + if (scrollListener != null) { + scrollListener.onScrollStarted(); + } + prepareContent(); + animateClose(mVertical ? mHandle.getTop() : mHandle.getLeft()); + if (scrollListener != null) { + scrollListener.onScrollEnded(); + } + } + + /** + * Opens the drawer with an animation. + * + * @see #close() + * @see #open() + * @see #animateClose() + * @see #animateToggle() + * @see #toggle() + */ + public void animateOpen() { + final OnDrawerScrollListener scrollListener = mOnDrawerScrollListener; + if (scrollListener != null) { + scrollListener.onScrollStarted(); + } + prepareContent(); + animateOpen(mVertical ? mHandle.getTop() : mHandle.getLeft()); + if (scrollListener != null) { + scrollListener.onScrollEnded(); + } + } + + private void closeDrawer() { + moveHandle(COLLAPSED_FULL_CLOSED); + mContent.setVisibility(View.GONE); + mContent.destroyDrawingCache(); + + if (!mExpanded) { + return; + } + + mExpanded = false; + if (mOnDrawerCloseListener != null) { + mOnDrawerCloseListener.onDrawerClosed(); + } + } + + private void openDrawer() { + moveHandle(EXPANDED_FULL_OPEN); + mContent.setVisibility(View.VISIBLE); + + if (mExpanded) { + return; + } + + mExpanded = true; + if (mOnDrawerOpenListener != null) { + mOnDrawerOpenListener.onDrawerOpened(); + } + } + + /** + * Sets the listener that receives a notification when the drawer becomes open. + * + * @param onDrawerOpenListener The listener to be notified when the drawer is opened. + */ + public void setOnDrawerOpenListener(OnDrawerOpenListener onDrawerOpenListener) { + mOnDrawerOpenListener = onDrawerOpenListener; + } + + /** + * Sets the listener that receives a notification when the drawer becomes close. + * + * @param onDrawerCloseListener The listener to be notified when the drawer is closed. + */ + public void setOnDrawerCloseListener(OnDrawerCloseListener onDrawerCloseListener) { + mOnDrawerCloseListener = onDrawerCloseListener; + } + + /** + * Sets the listener that receives a notification when the drawer starts or ends + * a scroll. A fling is considered as a scroll. A fling will also trigger a + * drawer opened or drawer closed event. + * + * @param onDrawerScrollListener The listener to be notified when scrolling + * starts or stops. + */ + public void setOnDrawerScrollListener(OnDrawerScrollListener onDrawerScrollListener) { + mOnDrawerScrollListener = onDrawerScrollListener; + } + + /** + * Returns the handle of the drawer. + * + * @return The View reprenseting the handle of the drawer, identified by + * the "handle" id in XML. + */ + public View getHandle() { + return mHandle; + } + + /** + * Returns the content of the drawer. + * + * @return The View reprenseting the content of the drawer, identified by + * the "content" id in XML. + */ + public View getContent() { + return mContent; + } + + /** + * Unlocks the SlidingDrawer so that touch events are processed. + * + * @see #lock() + */ + public void unlock() { + mLocked = false; + } + + /** + * Locks the SlidingDrawer so that touch events are ignores. + * + * @see #unlock() + */ + public void lock() { + mLocked = true; + } + + /** + * Indicates whether the drawer is currently fully opened. + * + * @return True if the drawer is opened, false otherwise. + */ + public boolean isOpened() { + return mExpanded; + } + + /** + * Indicates whether the drawer is scrolling or flinging. + * + * @return True if the drawer is scroller or flinging, false otherwise. + */ + public boolean isMoving() { + return mTracking || mAnimating; + } + + private class DrawerToggler implements OnClickListener { + public void onClick(View v) { + if (mLocked) { + return; + } + // mAllowSingleTap isn't relevant here; you're *always* + // allowed to open/close the drawer by clicking with the + // trackball. + + if (mAnimateOnClick) { + animateToggle(); + } else { + toggle(); + } + } + } + + private class SlidingHandler extends Handler { + public void handleMessage(Message m) { + switch (m.what) { + case MSG_ANIMATE: + doAnimation(); + break; + } + } + } +} diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java index aa70663..d21c017 100644 --- a/core/java/android/widget/TextView.java +++ b/core/java/android/widget/TextView.java @@ -17,6 +17,7 @@ package android.widget; import android.content.Context; +import android.content.Intent; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; @@ -42,6 +43,7 @@ import android.text.GraphicsOperations; import android.text.ClipboardManager; import android.text.InputFilter; import android.text.Layout; +import android.text.ParcelableSpan; import android.text.Selection; import android.text.SpanWatcher; import android.text.Spannable; @@ -69,7 +71,6 @@ import android.text.method.TransformationMethod; import android.text.style.ParagraphStyle; import android.text.style.URLSpan; import android.text.style.UpdateAppearance; -import android.text.style.UpdateLayout; import android.text.util.Linkify; import android.util.AttributeSet; import android.util.Log; @@ -168,6 +169,9 @@ import org.xmlpull.v1.XmlPullParserException; */ @RemoteView public class TextView extends View implements ViewTreeObserver.OnPreDrawListener { + static final String TAG = "TextView"; + static final boolean DEBUG_EXTRACT = false; + private static int PRIORITY = 100; private ColorStateList mTextColor; @@ -178,6 +182,9 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener private boolean mFreezesText; private boolean mFrozenWithFocus; + private boolean mEatTouchRelease = false; + private boolean mScrolled = false; + private Editable.Factory mEditableFactory = Editable.Factory.getInstance(); private Spannable.Factory mSpannableFactory = Spannable.Factory.getInstance(); @@ -213,6 +220,13 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener private CharSequence mError; private boolean mErrorWasChanged; private PopupWindow mPopup; + /** + * This flag is set if the TextView tries to display an error before it + * is attached to the window (so its position is still unknown). + * It causes the error to be shown later, when onAttachedToWindow() + * is called. + */ + private boolean mShowErrorAfterAttach; private CharWrapper mCharWrapper = null; @@ -235,7 +249,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener float[] mTmpOffset = new float[2]; ExtractedTextRequest mExtracting; final ExtractedText mTmpExtracted = new ExtractedText(); - boolean mBatchEditing; + int mBatchEditNesting; + boolean mCursorChanged; + boolean mContentChanged; + int mChangedStart, mChangedEnd, mChangedDelta; } InputMethodState mInputMethodState; @@ -2342,9 +2359,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * Sets the string value of the TextView. TextView <em>does not</em> accept * HTML-like formatting, which you can do with text strings in XML resource files. * To style your strings, attach android.text.style.* objects to a - * {@link android.text.SpannableString SpannableString}, or see - * <a href="{@docRoot}reference/available-resources.html#stringresources"> - * String Resources</a> for an example of setting formatted text in the XML resource file. + * {@link android.text.SpannableString SpannableString}, or see the + * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources"> + * Available Resource Types</a> documentation for an example of setting + * formatted text in the XML resource file. * * @attr ref android.R.styleable#TextView_text */ @@ -2698,20 +2716,33 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener */ public void setInputType(int type) { setInputType(type, false); - if ((type&(EditorInfo.TYPE_MASK_CLASS + final boolean isPassword = (type&(EditorInfo.TYPE_MASK_CLASS |EditorInfo.TYPE_MASK_VARIATION)) == (EditorInfo.TYPE_CLASS_TEXT - |EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) { + |EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); + boolean forceUpdate = false; + if (isPassword) { setTransformationMethod(PasswordTransformationMethod.getInstance()); setTypefaceByIndex(MONOSPACE, 0); + } else if (mTransformation == PasswordTransformationMethod.getInstance()) { + // We need to clean up if we were previously in password mode. + setTypefaceByIndex(-1, -1); + forceUpdate = true; } + boolean multiLine = (type&(EditorInfo.TYPE_MASK_CLASS | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE)) == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE); - if (mSingleLine == multiLine) { - setSingleLine(!multiLine); - } + + // We need to update the single line mode if it has changed or we + // were previously in password mode. + if (mSingleLine == multiLine || forceUpdate) { + // Change single line mode, but only change the transformation if + // we are not in password mode. + applySingleLine(!multiLine, !isPassword); + } + InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null) imm.restartInput(this); } @@ -2814,7 +2845,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * given integer is the resource ID of an XML resource holding an * {@link android.R.styleable#InputExtras <input-extras>} XML tree. * - * @see #getInputExtras() + * @see #getInputExtras(boolean) * @see EditorInfo#extras * @attr ref android.R.styleable#TextView_editorExtras */ @@ -2832,7 +2863,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * * @param create If true, the extras will be created if they don't already * exist. Otherwise, null will be returned if none have been created. - * @see #setInputExtras(int) + * @see #setInputExtras(int)View * @see EditorInfo#extras * @attr ref android.R.styleable#TextView_editorExtras */ @@ -2916,6 +2947,11 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } private void showError() { + if (getWindowToken() == null) { + mShowErrorAfterAttach = true; + return; + } + if (mPopup == null) { LayoutInflater inflater = LayoutInflater.from(getContext()); TextView err = (TextView) inflater.inflate(com.android.internal.R.layout.textview_hint, @@ -2979,6 +3015,8 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener mPopup.dismiss(); } } + + mShowErrorAfterAttach = false; } private void chooseSize(PopupWindow pop, CharSequence text, TextView tv) { @@ -3269,6 +3307,16 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + + if (mShowErrorAfterAttach) { + showError(); + mShowErrorAfterAttach = false; + } + } + + @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); @@ -3311,6 +3359,16 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } @Override + protected boolean verifyDrawable(Drawable who) { + final boolean verified = super.verifyDrawable(who); + if (!verified && mDrawables != null) { + return who == mDrawables.mDrawableLeft || who == mDrawables.mDrawableTop || + who == mDrawables.mDrawableRight || who == mDrawables.mDrawableBottom; + } + return verified; + } + + @Override protected void onDraw(Canvas canvas) { // Draw the background for this view super.onDraw(canvas); @@ -3505,38 +3563,48 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } */ - InputMethodManager imm = InputMethodManager.peekInstance(); - if (highlight != null && mInputMethodState != null - && !mInputMethodState.mBatchEditing && imm != null) { - if (imm.isActive(this)) { - int candStart = -1; - int candEnd = -1; - if (mText instanceof Spannable) { - Spannable sp = (Spannable)mText; - candStart = EditableInputConnection.getComposingSpanStart(sp); - candEnd = EditableInputConnection.getComposingSpanEnd(sp); + final InputMethodState ims = mInputMethodState; + if (ims != null && ims.mBatchEditNesting == 0) { + InputMethodManager imm = InputMethodManager.peekInstance(); + if (imm != null) { + if (imm.isActive(this)) { + boolean reported = false; + if (ims.mContentChanged) { + // We are in extract mode and the content has changed + // in some way... just report complete new text to the + // input method. + reported = reportExtractedText(); + } + if (!reported && highlight != null) { + int candStart = -1; + int candEnd = -1; + if (mText instanceof Spannable) { + Spannable sp = (Spannable)mText; + candStart = EditableInputConnection.getComposingSpanStart(sp); + candEnd = EditableInputConnection.getComposingSpanEnd(sp); + } + imm.updateSelection(this, selStart, selEnd, candStart, candEnd); + } + } + + if (imm.isWatchingCursor(this) && highlight != null) { + highlight.computeBounds(ims.mTmpRectF, true); + ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; + + canvas.getMatrix().mapPoints(ims.mTmpOffset); + ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); + + ims.mTmpRectF.offset(0, voffsetCursor - voffsetText); + + ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), + (int)(ims.mTmpRectF.top + 0.5), + (int)(ims.mTmpRectF.right + 0.5), + (int)(ims.mTmpRectF.bottom + 0.5)); + + imm.updateCursor(this, + ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, + ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); } - imm.updateSelection(this, selStart, selEnd, candStart, candEnd); - } - - if (imm.isWatchingCursor(this)) { - final InputMethodState ims = mInputMethodState; - highlight.computeBounds(ims.mTmpRectF, true); - ims.mTmpOffset[0] = ims.mTmpOffset[1] = 0; - - canvas.getMatrix().mapPoints(ims.mTmpOffset); - ims.mTmpRectF.offset(ims.mTmpOffset[0], ims.mTmpOffset[1]); - - ims.mTmpRectF.offset(0, voffsetCursor - voffsetText); - - ims.mCursorRectInWindow.set((int)(ims.mTmpRectF.left + 0.5), - (int)(ims.mTmpRectF.top + 0.5), - (int)(ims.mTmpRectF.right + 0.5), - (int)(ims.mTmpRectF.bottom + 0.5)); - - imm.updateCursor(this, - ims.mCursorRectInWindow.left, ims.mCursorRectInWindow.top, - ims.mCursorRectInWindow.right, ims.mCursorRectInWindow.bottom); } } @@ -3634,7 +3702,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener @Override public boolean onKeyDown(int keyCode, KeyEvent event) { - int which = doKeyDown(keyCode, event); + int which = doKeyDown(keyCode, event, null); if (which == 0) { // Go through default dispatching. return super.onKeyDown(keyCode, event); @@ -3647,12 +3715,18 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { KeyEvent down = new KeyEvent(event, KeyEvent.ACTION_DOWN); - int which = doKeyDown(keyCode, down); + int which = doKeyDown(keyCode, down, event); if (which == 0) { // Go through default dispatching. return super.onKeyMultiple(keyCode, repeatCount, event); } + if (which == -1) { + // Consumed the whole thing. + return true; + } + repeatCount--; + // We are going to dispatch the remaining events to either the input // or movement method. To do this, we will just send a repeated stream // of down and up events until we have done the complete repeatCount. @@ -3680,7 +3754,34 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return true; } - private int doKeyDown(int keyCode, KeyEvent event) { + /** + * Returns true if pressing ENTER in this field advances focus instead + * of inserting the character. This is true mostly in single-line fields, + * but also in mail addresses and subjects which will display on multiple + * lines but where it doesn't make sense to insert newlines. + */ + private boolean advanceFocusOnEnter() { + if (mInput == null) { + return false; + } + + if (mSingleLine) { + return true; + } + + if ((mInputType & EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { + int variation = mInputType & EditorInfo.TYPE_MASK_VARIATION; + + if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS || + variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_SUBJECT) { + return true; + } + } + + return false; + } + + private int doKeyDown(int keyCode, KeyEvent event, KeyEvent otherEvent) { if (!isEnabled()) { return 0; } @@ -3688,7 +3789,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: - if (mSingleLine && mInput != null) { + if (advanceFocusOnEnter()) { return 0; } } @@ -3702,20 +3803,63 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener */ mErrorWasChanged = false; - if (mInput.onKeyDown(this, (Editable) mText, keyCode, event)) { - if (mError != null && !mErrorWasChanged) { - setError(null, null); + boolean doDown = true; + if (otherEvent != null) { + try { + beginBatchEdit(); + boolean handled = mInput.onKeyOther(this, (Editable) mText, + otherEvent); + if (mError != null && !mErrorWasChanged) { + setError(null, null); + } + doDown = false; + if (handled) { + return -1; + } + } catch (AbstractMethodError e) { + // onKeyOther was added after 1.0, so if it isn't + // implemented we need to try to dispatch as a regular down. + } finally { + endBatchEdit(); + } + } + + if (doDown) { + beginBatchEdit(); + if (mInput.onKeyDown(this, (Editable) mText, keyCode, event)) { + endBatchEdit(); + if (mError != null && !mErrorWasChanged) { + setError(null, null); + } + return 1; } - return 1; + endBatchEdit(); } } // bug 650865: sometimes we get a key event before a layout. // don't try to move around if we don't know the layout. - if (mMovement != null && mLayout != null) - if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) - return 2; + if (mMovement != null && mLayout != null) { + boolean doDown = true; + if (otherEvent != null) { + try { + boolean handled = mMovement.onKeyOther(this, (Editable) mText, + otherEvent); + doDown = false; + if (handled) { + return -1; + } + } catch (AbstractMethodError e) { + // onKeyOther was added after 1.0, so if it isn't + // implemented we need to try to dispatch as a regular down. + } + } + if (doDown) { + if (mMovement.onKeyDown(this, (Spannable)mText, keyCode, event)) + return 2; + } + } return 0; } @@ -3728,8 +3872,27 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: + /* + * If there is a click listener, just call through to + * super, which will invoke it. + * + * If there isn't a click listener, try to show the soft + * input method. (It will also + * call performClick(), but that won't do anything in + * this case.) + */ + if (mOnClickListener == null) { + if (mMovement != null && mText instanceof Editable + && mLayout != null && onCheckIsTextEditor()) { + InputMethodManager imm = (InputMethodManager) + getContext().getSystemService(Context.INPUT_METHOD_SERVICE); + imm.showSoftInput(this, 0); + } + } + return super.onKeyUp(keyCode, event); + case KeyEvent.KEYCODE_ENTER: - if (mSingleLine && mInput != null) { + if (advanceFocusOnEnter()) { /* * If there is a click listener, just call through to * super, which will invoke it. @@ -3803,14 +3966,56 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener /** * If this TextView contains editable content, extract a portion of it * based on the information in <var>request</var> in to <var>outText</var>. - * @return Returns true if the text is editable and was successfully - * extracted, else false. + * @return Returns true if the text was successfully extracted, else false. */ public boolean extractText(ExtractedTextRequest request, ExtractedText outText) { - Editable content = getEditableText(); + return extractTextInternal(request, -1, -1, -1, outText); + } + + boolean extractTextInternal(ExtractedTextRequest request, + int partialStartOffset, int partialEndOffset, int delta, + ExtractedText outText) { + final CharSequence content = mText; if (content != null) { - outText.text = content.subSequence(0, content.length()); + final int N = content.length(); + if (partialStartOffset < 0) { + outText.partialStartOffset = outText.partialEndOffset = -1; + partialStartOffset = 0; + partialEndOffset = N; + } else { + // Adjust offsets to ensure we contain full spans. + if (content instanceof Spanned) { + Spanned spanned = (Spanned)content; + Object[] spans = spanned.getSpans(partialStartOffset, + partialEndOffset, ParcelableSpan.class); + int i = spans.length; + while (i > 0) { + i--; + int j = spanned.getSpanStart(spans[i]); + if (j < partialStartOffset) partialStartOffset = j; + j = spanned.getSpanEnd(spans[i]); + if (j > partialEndOffset) partialEndOffset = j; + } + } + outText.partialStartOffset = partialStartOffset; + outText.partialEndOffset = partialEndOffset; + // Now use the delta to determine the actual amount of text + // we need. + partialEndOffset += delta; + if (partialEndOffset > N) { + partialEndOffset = N; + } else if (partialEndOffset < 0) { + partialEndOffset = 0; + } + } + if ((request.flags&InputConnection.GET_TEXT_WITH_STYLES) != 0) { + outText.text = content.subSequence(partialStartOffset, + partialEndOffset); + } else { + outText.text = TextUtils.substring(content, partialStartOffset, + partialEndOffset); + } outText.startOffset = 0; outText.selectionStart = Selection.getSelectionStart(content); outText.selectionEnd = Selection.getSelectionEnd(content); @@ -3819,19 +4024,45 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return false; } - void reportExtractedText() { - if (mInputMethodState != null) { + boolean reportExtractedText() { + final InputMethodState ims = mInputMethodState; + if (ims != null && ims.mContentChanged) { + ims.mContentChanged = false; final ExtractedTextRequest req = mInputMethodState.mExtracting; if (req != null) { InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null) { - if (extractText(req, mInputMethodState.mTmpExtracted)) { + if (DEBUG_EXTRACT) Log.v(TAG, "Retrieving extracted start=" + + ims.mChangedStart + " end=" + ims.mChangedEnd + + " delta=" + ims.mChangedDelta); + if (extractTextInternal(req, ims.mChangedStart, ims.mChangedEnd, + ims.mChangedDelta, ims.mTmpExtracted)) { + if (DEBUG_EXTRACT) Log.v(TAG, "Reporting extracted start=" + + ims.mTmpExtracted.partialStartOffset + + " end=" + ims.mTmpExtracted.partialEndOffset + + ": " + ims.mTmpExtracted.text); imm.updateExtractedText(this, req.token, mInputMethodState.mTmpExtracted); + return true; } } } } + return false; + } + + /** + * This is used to remove all style-impacting spans from text before new + * extracted text is being replaced into it, so that we don't have any + * lingering spans applied during the replace. + */ + static void removeParcelableSpans(Spannable spannable, int start, int end) { + Object[] spans = spannable.getSpans(start, end, ParcelableSpan.class); + int i = spans.length; + while (i > 0) { + i--; + spannable.removeSpan(spans[i]); + } } /** @@ -3839,7 +4070,21 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * returned by {@link #extractText(ExtractedTextRequest, ExtractedText)}. */ public void setExtractedText(ExtractedText text) { - setText(text.text, TextView.BufferType.EDITABLE); + Editable content = getEditableText(); + if (content == null) { + setText(text.text, TextView.BufferType.EDITABLE); + } else if (text.partialStartOffset < 0) { + removeParcelableSpans(content, 0, content.length()); + content.replace(0, content.length(), text.text); + } else { + final int N = content.length(); + int start = text.partialStartOffset; + if (start > N) start = N; + int end = text.partialEndOffset; + if (end > N) end = N; + removeParcelableSpans(content, start, end); + content.replace(start, end, text.text); + } Selection.setSelection((Spannable)getText(), text.selectionStart, text.selectionEnd); } @@ -3866,36 +4111,91 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener public void onCommitCompletion(CompletionInfo text) { } + public void beginBatchEdit() { + final InputMethodState ims = mInputMethodState; + if (ims != null) { + int nesting = ++ims.mBatchEditNesting; + if (nesting == 1) { + ims.mCursorChanged = false; + ims.mChangedDelta = 0; + if (ims.mContentChanged) { + // We already have a pending change from somewhere else, + // so turn this into a full update. + ims.mChangedStart = 0; + ims.mChangedEnd = mText.length(); + } else { + ims.mChangedStart = -1; + ims.mChangedEnd = -1; + ims.mContentChanged = false; + } + onBeginBatchEdit(); + } + } + } + + public void endBatchEdit() { + final InputMethodState ims = mInputMethodState; + if (ims != null) { + int nesting = --ims.mBatchEditNesting; + if (nesting == 0) { + finishBatchEdit(ims); + } + } + } + + void ensureEndedBatchEdit() { + final InputMethodState ims = mInputMethodState; + if (ims != null && ims.mBatchEditNesting != 0) { + ims.mBatchEditNesting = 0; + finishBatchEdit(ims); + } + } + + void finishBatchEdit(final InputMethodState ims) { + onEndBatchEdit(); + + if (ims.mContentChanged) { + updateAfterEdit(); + reportExtractedText(); + } else if (ims.mCursorChanged) { + // Cheezy way to get us to report the current cursor location. + invalidateCursor(); + } + } + + void updateAfterEdit() { + invalidate(); + int curs = Selection.getSelectionStart(mText); + + if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == + Gravity.BOTTOM) { + registerForPreDraw(); + } + + if (curs >= 0) { + mHighlightPathBogus = true; + + if (isFocused()) { + mShowCursor = SystemClock.uptimeMillis(); + makeBlink(); + } + } + + checkForResize(); + } + /** * Called by the framework in response to a request to begin a batch - * of edit operations from the current input method, as a result of - * it calling {@link InputConnection#beginBatchEdit - * InputConnection.beginBatchEdit()}. The default implementation sets - * up the TextView's internal state to take care of this; if overriding - * you should call through to the super class. + * of edit operations through a call to link {@link #beginBatchEdit()}. */ public void onBeginBatchEdit() { - if (mInputMethodState != null) { - // XXX we should be smarter here, such as not doing invalidates - // until all edits are done. - mInputMethodState.mBatchEditing = true; - } } /** * Called by the framework in response to a request to end a batch - * of edit operations from the current input method, as a result of - * it calling {@link InputConnection#endBatchEdit - * InputConnection.endBatchEdit()}. The default implementation sets - * up the TextView's internal state to take care of this; if overriding - * you should call through to the super class. + * of edit operations through a call to link {@link #endBatchEdit}. */ public void onEndBatchEdit() { - if (mInputMethodState != null) { - mInputMethodState.mBatchEditing = false; - // Cheezy way to get us to report the current cursor location. - invalidateCursor(); - } } /** @@ -4542,9 +4842,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } /** - * Returns true if anything changed. + * Move the point, specified by the offset, into the view if it is needed. + * This has to be called after layout. Returns true if anything changed. */ - private boolean bringPointIntoView(int offset) { + public boolean bringPointIntoView(int offset) { boolean changed = false; int line = mLayout.getLineForOffset(offset); @@ -4794,7 +5095,6 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * @attr ref android.R.styleable#TextView_singleLine */ public void setSingleLine(boolean singleLine) { - mSingleLine = singleLine; if ((mInputType&EditorInfo.TYPE_MASK_CLASS) == EditorInfo.TYPE_CLASS_TEXT) { if (singleLine) { @@ -4803,19 +5103,27 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener mInputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE; } } + applySingleLine(singleLine, true); + } + private void applySingleLine(boolean singleLine, boolean applyTransformation) { + mSingleLine = singleLine; if (singleLine) { setLines(1); setHorizontallyScrolling(true); - setTransformationMethod(SingleLineTransformationMethod. - getInstance()); + if (applyTransformation) { + setTransformationMethod(SingleLineTransformationMethod. + getInstance()); + } } else { setMaxLines(Integer.MAX_VALUE); setHorizontallyScrolling(false); - setTransformationMethod(null); + if (applyTransformation) { + setTransformationMethod(null); + } } } - + /** * Causes words in the text that are longer than the view is wide * to be ellipsized instead of broken in the middle. You may also @@ -4938,6 +5246,8 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener float mScroll; Marquee(TextView v) { + final float density = v.getContext().getResources().getDisplayMetrics().density; + mScrollUnit = (MARQUEE_PIXELS_PER_SECOND * density) / (float) MARQUEE_RESOLUTION; mView = new WeakReference<TextView>(v); } @@ -5006,7 +5316,6 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener if (textView != null && textView.mLayout != null) { mStatus = MARQUEE_STARTING; mScroll = 0.0f; - mScrollUnit = MARQUEE_PIXELS_PER_SECOND / (float) MARQUEE_RESOLUTION; mMaxScroll = textView.mLayout.getLineWidth(0) - (textView.getWidth() - textView.getCompoundPaddingLeft() - textView.getCompoundPaddingRight()); textView.invalidate(); @@ -5046,6 +5355,16 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } /** + * This method is called when the selection has changed, in case any + * subclasses would like to know. + * + * @param selStart The new selection start location. + * @param selEnd The new selection end location. + */ + protected void onSelectionChanged(int selStart, int selEnd) { + } + + /** * Adds a TextWatcher to the list of those whose methods are called * whenever this TextView's text changes. * <p> @@ -5123,26 +5442,22 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener */ void handleTextChanged(CharSequence buffer, int start, int before, int after) { - invalidate(); - - int curs = Selection.getSelectionStart(buffer); - - if (curs >= 0 || (mGravity & Gravity.VERTICAL_GRAVITY_MASK) == - Gravity.BOTTOM) { - registerForPreDraw(); - } - - if (curs >= 0) { - mHighlightPathBogus = true; - - if (isFocused()) { - mShowCursor = SystemClock.uptimeMillis(); - makeBlink(); + final InputMethodState ims = mInputMethodState; + if (ims == null || ims.mBatchEditNesting == 0) { + updateAfterEdit(); + } + if (ims != null) { + ims.mContentChanged = true; + if (ims.mChangedStart < 0) { + ims.mChangedStart = start; + ims.mChangedEnd = start+before; + } else { + if (ims.mChangedStart > start) ims.mChangedStart = start; + if (ims.mChangedEnd < (start+before)) ims.mChangedEnd = start+before; } + ims.mChangedDelta += after-before; } - - checkForResize(); - + sendOnTextChanged(buffer, start, before, after); onTextChanged(buffer, start, before, after); } @@ -5151,19 +5466,27 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener * Not private so it can be called from an inner class without going * through a thunk. */ - void spanChange(Spanned buf, Object what, int o, int n) { + void spanChange(Spanned buf, Object what, int oldStart, int newStart, + int oldEnd, int newEnd) { // XXX Make the start and end move together if this ends up // spending too much time invalidating. + boolean selChanged = false; + int newSelStart=-1, newSelEnd=-1; + + final InputMethodState ims = mInputMethodState; + if (what == Selection.SELECTION_END) { mHighlightPathBogus = true; + selChanged = true; + newSelEnd = newStart; if (!isFocused()) { mSelectionMoved = true; } - if (o >= 0 || n >= 0) { - invalidateCursor(Selection.getSelectionStart(buf), o, n); + if (oldStart >= 0 || newStart >= 0) { + invalidateCursor(Selection.getSelectionStart(buf), oldStart, newStart); registerForPreDraw(); if (isFocused()) { @@ -5175,28 +5498,81 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener if (what == Selection.SELECTION_START) { mHighlightPathBogus = true; + selChanged = true; + newSelStart = newStart; if (!isFocused()) { mSelectionMoved = true; } - if (o >= 0 || n >= 0) { - invalidateCursor(Selection.getSelectionEnd(buf), o, n); + if (oldStart >= 0 || newStart >= 0) { + int end = Selection.getSelectionEnd(buf); + invalidateCursor(end, oldStart, newStart); } } + if (selChanged) { + if ((buf.getSpanFlags(what)&Spanned.SPAN_INTERMEDIATE) == 0) { + if (newSelStart < 0) { + newSelStart = Selection.getSelectionStart(buf); + } + if (newSelEnd < 0) { + newSelEnd = Selection.getSelectionEnd(buf); + } + onSelectionChanged(newSelStart, newSelEnd); + } + } + if (what instanceof UpdateAppearance || what instanceof ParagraphStyle) { - invalidate(); - mHighlightPathBogus = true; - checkForResize(); + if (ims == null || ims.mBatchEditNesting == 0) { + invalidate(); + mHighlightPathBogus = true; + checkForResize(); + } else { + ims.mContentChanged = true; + } } if (MetaKeyKeyListener.isMetaTracker(buf, what)) { mHighlightPathBogus = true; if (Selection.getSelectionStart(buf) >= 0) { - invalidateCursor(); + if (ims == null || ims.mBatchEditNesting == 0) { + invalidateCursor(); + } else { + ims.mCursorChanged = true; + } + } + } + + if (what instanceof ParcelableSpan) { + // If this is a span that can be sent to a remote process, + // the current extract editor would be interested in it. + if (ims != null && ims.mExtracting != null) { + if (ims.mBatchEditNesting != 0) { + if (oldStart >= 0) { + if (ims.mChangedStart > oldStart) { + ims.mChangedStart = oldStart; + } + if (ims.mChangedStart > oldEnd) { + ims.mChangedStart = oldEnd; + } + } + if (newStart >= 0) { + if (ims.mChangedStart > newStart) { + ims.mChangedStart = newStart; + } + if (ims.mChangedStart > newEnd) { + ims.mChangedStart = newEnd; + } + } + } else { + if (DEBUG_EXTRACT) Log.v(TAG, "Span change outside of batch: " + + oldStart + "-" + oldEnd + "," + + newStart + "-" + newEnd + what); + ims.mContentChanged = true; + } } } } @@ -5205,36 +5581,45 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener implements TextWatcher, SpanWatcher { public void beforeTextChanged(CharSequence buffer, int start, int before, int after) { + if (DEBUG_EXTRACT) Log.v(TAG, "beforeTextChanged start=" + start + + " before=" + before + " after=" + after + ": " + buffer); TextView.this.sendBeforeTextChanged(buffer, start, before, after); } public void onTextChanged(CharSequence buffer, int start, int before, int after) { + if (DEBUG_EXTRACT) Log.v(TAG, "onTextChanged start=" + start + + " before=" + before + " after=" + after + ": " + buffer); TextView.this.handleTextChanged(buffer, start, before, after); } public void afterTextChanged(Editable buffer) { + if (DEBUG_EXTRACT) Log.v(TAG, "afterTextChanged: " + buffer); TextView.this.sendAfterTextChanged(buffer); if (MetaKeyKeyListener.getMetaState(buffer, MetaKeyKeyListener.META_SELECTING) != 0) { MetaKeyKeyListener.stopSelecting(TextView.this, buffer); } - - TextView.this.reportExtractedText(); } public void onSpanChanged(Spannable buf, Object what, int s, int e, int st, int en) { - TextView.this.spanChange(buf, what, s, st); + if (DEBUG_EXTRACT) Log.v(TAG, "onSpanChanged s=" + s + " e=" + e + + " st=" + st + " en=" + en + " what=" + what + ": " + buf); + TextView.this.spanChange(buf, what, s, st, e, en); } public void onSpanAdded(Spannable buf, Object what, int s, int e) { - TextView.this.spanChange(buf, what, -1, s); + if (DEBUG_EXTRACT) Log.v(TAG, "onSpanAdded s=" + s + " e=" + e + + " what=" + what + ": " + buf); + TextView.this.spanChange(buf, what, -1, s, -1, e); } public void onSpanRemoved(Spannable buf, Object what, int s, int e) { - TextView.this.spanChange(buf, what, s, -1); + if (DEBUG_EXTRACT) Log.v(TAG, "onSpanRemoved s=" + s + " e=" + e + + " what=" + what + ": " + buf); + TextView.this.spanChange(buf, what, s, -1, e, -1); } } @@ -5258,6 +5643,8 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { mShowCursor = SystemClock.uptimeMillis(); + ensureEndedBatchEdit(); + if (focused) { int selStart = getSelectionStart(); int selEnd = getSelectionEnd(); @@ -5362,22 +5749,28 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener public boolean onTouchEvent(MotionEvent event) { final boolean superResult = super.onTouchEvent(event); + final int action = event.getAction(); + /* * Don't handle the release after a long press, because it will * move the selection away from whatever the menu action was * trying to affect. */ - if (mEatTouchRelease && event.getAction() == MotionEvent.ACTION_UP) { + if (mEatTouchRelease && action == MotionEvent.ACTION_UP) { mEatTouchRelease = false; return superResult; } - if (mMovement != null && mText instanceof Spannable && - mLayout != null) { + if (mMovement != null && mText instanceof Spannable && mLayout != null) { + + if (action == MotionEvent.ACTION_DOWN) { + mScrolled = false; + } + boolean moved = mMovement.onTouchEvent(this, (Spannable) mText, event); if (mText instanceof Editable && onCheckIsTextEditor()) { - if (event.getAction() == MotionEvent.ACTION_UP && isFocused()) { + if (action == MotionEvent.ACTION_UP && isFocused() && !mScrolled) { InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(this, 0); @@ -5393,6 +5786,12 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } @Override + public void cancelLongPress() { + super.cancelLongPress(); + mScrolled = true; + } + + @Override public boolean onTrackballEvent(MotionEvent event) { if (mMovement != null && mText instanceof Spannable && mLayout != null) { @@ -5568,28 +5967,28 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener switch (keyCode) { case KeyEvent.KEYCODE_A: if (canSelectAll()) { - return onMenu(ID_SELECT_ALL); + return onTextContextMenuItem(ID_SELECT_ALL); } break; case KeyEvent.KEYCODE_X: if (canCut()) { - return onMenu(ID_CUT); + return onTextContextMenuItem(ID_CUT); } break; case KeyEvent.KEYCODE_C: if (canCopy()) { - return onMenu(ID_COPY); + return onTextContextMenuItem(ID_COPY); } break; case KeyEvent.KEYCODE_V: if (canPaste()) { - return onMenu(ID_PASTE); + return onTextContextMenuItem(ID_PASTE); } break; @@ -5655,6 +6054,38 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return false; } + /** + * Returns a word to add to the dictionary from the context menu, + * or null if there is no cursor or no word at the cursor. + */ + private String getWordForDictionary() { + int end = getSelectionEnd(); + + if (end < 0) { + return null; + } + + int start = end; + char c; + int len = mText.length(); + + while (start > 0 && (((c = mTransformed.charAt(start - 1)) == '\'') || + (Character.isLetterOrDigit(c)))) { + start--; + } + + while (end < len && (((c = mTransformed.charAt(end)) == '\'') || + (Character.isLetterOrDigit(c)))) { + end++; + } + + if (start == end) { + return null; + } + + return TextUtils.substring(mTransformed, start, end); + } + @Override protected void onCreateContextMenu(ContextMenu menu) { super.onCreateContextMenu(menu); @@ -5696,7 +6127,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener setOnMenuItemClickListener(handler); added = true; } else { - menu.add(0, ID_SELECT_TEXT, 0, + menu.add(0, ID_START_SELECTING_TEXT, 0, com.android.internal.R.string.selectText). setOnMenuItemClickListener(handler); added = true; @@ -5755,34 +6186,60 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } } - InputMethodManager imm = InputMethodManager.peekInstance(); - if (imm != null && imm.isActive(this)) { - menu.add(1, ID_SWITCH_IME, 0, com.android.internal.R.string.inputMethod). + if (isInputMethodTarget()) { + menu.add(1, ID_SWITCH_INPUT_METHOD, 0, com.android.internal.R.string.inputMethod). setOnMenuItemClickListener(handler); added = true; } + String word = getWordForDictionary(); + if (word != null) { + menu.add(1, ID_ADD_TO_DICTIONARY, 0, + getContext().getString(com.android.internal.R.string.addToDictionary, word)). + setOnMenuItemClickListener(handler); + added = true; + + } + if (added) { menu.setHeaderTitle(com.android.internal.R.string.editTextMenuTitle); } } - private static final int ID_SELECT_ALL = com.android.internal.R.id.selectAll; - private static final int ID_SELECT_TEXT = com.android.internal.R.id.selectText; - private static final int ID_STOP_SELECTING_TEXT = com.android.internal.R.id.stopSelectingText; - private static final int ID_CUT = com.android.internal.R.id.cut; - private static final int ID_COPY = com.android.internal.R.id.copy; - private static final int ID_PASTE = com.android.internal.R.id.paste; - private static final int ID_COPY_URL = com.android.internal.R.id.copyUrl; - private static final int ID_SWITCH_IME = com.android.internal.R.id.inputMethod; + /** + * Returns whether this text view is a current input method target. The + * default implementation just checks with {@link InputMethodManager}. + */ + public boolean isInputMethodTarget() { + InputMethodManager imm = InputMethodManager.peekInstance(); + return imm != null && imm.isActive(this); + } + + private static final int ID_SELECT_ALL = android.R.id.selectAll; + private static final int ID_START_SELECTING_TEXT = android.R.id.startSelectingText; + private static final int ID_STOP_SELECTING_TEXT = android.R.id.stopSelectingText; + private static final int ID_CUT = android.R.id.cut; + private static final int ID_COPY = android.R.id.copy; + private static final int ID_PASTE = android.R.id.paste; + private static final int ID_COPY_URL = android.R.id.copyUrl; + private static final int ID_SWITCH_INPUT_METHOD = android.R.id.switchInputMethod; + private static final int ID_ADD_TO_DICTIONARY = android.R.id.addToDictionary; private class MenuHandler implements MenuItem.OnMenuItemClickListener { public boolean onMenuItemClick(MenuItem item) { - return onMenu(item.getItemId()); + return onTextContextMenuItem(item.getItemId()); } } - private boolean onMenu(int id) { + /** + * Called when a context menu option for the text view is selected. Currently + * this will be one of: {@link android.R.id#selectAll}, + * {@link android.R.id#startSelectingText}, {@link android.R.id#stopSelectingText}, + * {@link android.R.id#cut}, {@link android.R.id#copy}, + * {@link android.R.id#paste}, {@link android.R.id#copyUrl}, + * or {@link android.R.id#switchInputMethod}. + */ + public boolean onTextContextMenuItem(int id) { int selStart = getSelectionStart(); int selEnd = getSelectionEnd(); @@ -5807,10 +6264,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener switch (id) { case ID_SELECT_ALL: Selection.setSelection((Spannable) mText, 0, - mText.length()); + mText.length()); return true; - case ID_SELECT_TEXT: + case ID_START_SELECTING_TEXT: MetaKeyKeyListener.startSelecting(this, (Spannable) mText); return true; @@ -5865,12 +6322,23 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return true; - case ID_SWITCH_IME: + case ID_SWITCH_INPUT_METHOD: InputMethodManager imm = InputMethodManager.peekInstance(); if (imm != null) { imm.showInputMethodPicker(); } return true; + + case ID_ADD_TO_DICTIONARY: + String word = getWordForDictionary(); + + if (word != null) { + Intent i = new Intent("com.android.settings.USER_DICTIONARY_INSERT"); + i.putExtra("word", word); + getContext().startActivity(i); + } + + return true; } return false; @@ -5885,8 +6353,6 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener return false; } - private boolean mEatTouchRelease = false; - @ViewDebug.ExportedProperty private CharSequence mText; private CharSequence mTransformed; diff --git a/core/java/android/widget/ViewAnimator.java b/core/java/android/widget/ViewAnimator.java index acc9c46..8c652e5 100644 --- a/core/java/android/widget/ViewAnimator.java +++ b/core/java/android/widget/ViewAnimator.java @@ -144,6 +144,56 @@ public class ViewAnimator extends FrameLayout { } } + @Override + public void removeAllViews() { + super.removeAllViews(); + mWhichChild = 0; + mFirstTime = true; + } + + @Override + public void removeView(View view) { + final int index = indexOfChild(view); + if (index >= 0) { + removeViewAt(index); + } + } + + @Override + public void removeViewAt(int index) { + super.removeViewAt(index); + final int childCount = getChildCount(); + if (childCount == 0) { + mWhichChild = 0; + mFirstTime = true; + } else if (mWhichChild >= childCount) { + // Displayed is above child count, so float down to top of stack + setDisplayedChild(childCount - 1); + } else if (mWhichChild == index) { + // Displayed was removed, so show the new child living in its place + setDisplayedChild(mWhichChild); + } + } + + public void removeViewInLayout(View view) { + removeView(view); + } + + public void removeViews(int start, int count) { + super.removeViews(start, count); + if (getChildCount() == 0) { + mWhichChild = 0; + mFirstTime = true; + } else if (mWhichChild >= start && mWhichChild < start + count) { + // Try showing new displayed child, wrapping if needed + setDisplayedChild(mWhichChild); + } + } + + public void removeViewsInLayout(int start, int count) { + removeViews(start, count); + } + /** * Returns the View corresponding to the currently displayed child. * diff --git a/core/java/android/widget/ZoomButton.java b/core/java/android/widget/ZoomButton.java index 5df8c8a..df3f307 100644 --- a/core/java/android/widget/ZoomButton.java +++ b/core/java/android/widget/ZoomButton.java @@ -54,7 +54,7 @@ public class ZoomButton extends ImageButton implements OnLongClickListener { public ZoomButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mHandler = new Handler(); - mGestureDetector = new GestureDetector(new SimpleOnGestureListener() { + mGestureDetector = new GestureDetector(context, new SimpleOnGestureListener() { @Override public void onLongPress(MotionEvent e) { onLongClick(ZoomButton.this); diff --git a/core/java/android/widget/ZoomControls.java b/core/java/android/widget/ZoomControls.java index 1fd662c..fdc05b6 100644 --- a/core/java/android/widget/ZoomControls.java +++ b/core/java/android/widget/ZoomControls.java @@ -81,7 +81,9 @@ public class ZoomControls extends LinearLayout { } public void show() { - fade(View.VISIBLE, 0.0f, 1.0f); + if (ZoomRingController.useOldZoom(mContext)) { + fade(View.VISIBLE, 0.0f, 1.0f); + } } public void hide() { diff --git a/core/java/android/widget/ZoomRing.java b/core/java/android/widget/ZoomRing.java new file mode 100644 index 0000000..20d6056 --- /dev/null +++ b/core/java/android/widget/ZoomRing.java @@ -0,0 +1,423 @@ +package android.widget; + +import com.android.internal.R; + +import android.content.Context; +import android.content.res.Resources; +import android.graphics.Canvas; +import android.graphics.drawable.Drawable; +import android.os.Handler; +import android.util.AttributeSet; +import android.util.Log; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewConfiguration; + +/** + * @hide + */ +public class ZoomRing extends View { + + // TODO: move to ViewConfiguration? + private static final int DOUBLE_TAP_DISMISS_TIMEOUT = ViewConfiguration.getJumpTapTimeout(); + // TODO: get from theme + private static final int DISABLED_ALPHA = 160; + + private static final String TAG = "ZoomRing"; + + // TODO: xml + private static final int THUMB_DISTANCE = 63; + + /** To avoid floating point calculations, we multiply radians by this value. */ + public static final int RADIAN_INT_MULTIPLIER = 100000000; + /** PI using our multiplier. */ + public static final int PI_INT_MULTIPLIED = (int) (Math.PI * RADIAN_INT_MULTIPLIER); + /** PI/2 using our multiplier. */ + private static final int HALF_PI_INT_MULTIPLIED = PI_INT_MULTIPLIED / 2; + + private static final int THUMB_GRAB_SLOP = PI_INT_MULTIPLIED / 4; + + /** The cached X of our center. */ + private int mCenterX; + /** The cached Y of our center. */ + private int mCenterY; + + /** The angle of the thumb (in int radians) */ + private int mThumbAngle; + private boolean mIsThumbAngleValid; + private int mThumbCenterX; + private int mThumbCenterY; + private int mThumbHalfWidth; + private int mThumbHalfHeight; + + private int mCallbackThreshold = Integer.MAX_VALUE; + + /** The accumulated amount of drag for the thumb (in int radians). */ + private int mAcculumalatedThumbDrag = 0; + + /** The inner radius of the track. */ + private int mBoundInnerRadiusSquared = 0; + /** The outer radius of the track. */ + private int mBoundOuterRadiusSquared = Integer.MAX_VALUE; + + private int mPreviousWidgetDragX; + private int mPreviousWidgetDragY; + + private boolean mDrawThumb = true; + private Drawable mThumbDrawable; + + private static final int MODE_IDLE = 0; + private static final int MODE_DRAG_THUMB = 1; + private static final int MODE_MOVE_ZOOM_RING = 2; + private static final int MODE_TAP_DRAG = 3; + private int mMode; + + private long mPreviousTapTime; + + private Handler mHandler = new Handler(); + + private Disabler mDisabler = new Disabler(); + + private OnZoomRingCallback mCallback; + + private boolean mResetThumbAutomatically = true; + private int mThumbDragStartAngle; + + public ZoomRing(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + // TODO get drawable from style instead + Resources res = context.getResources(); + mThumbDrawable = res.getDrawable(R.drawable.zoom_ring_thumb); + + // TODO: add padding to drawable + setBackgroundResource(R.drawable.zoom_ring_track); + // TODO get from style + setBounds(30, Integer.MAX_VALUE); + + mThumbHalfHeight = mThumbDrawable.getIntrinsicHeight() / 2; + mThumbHalfWidth = mThumbDrawable.getIntrinsicWidth() / 2; + + mCallbackThreshold = PI_INT_MULTIPLIED / 6; + } + + public ZoomRing(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public ZoomRing(Context context) { + this(context, null); + } + + public void setCallback(OnZoomRingCallback callback) { + mCallback = callback; + } + + // TODO: rename + public void setCallbackThreshold(int callbackThreshold) { + mCallbackThreshold = callbackThreshold; + } + + // TODO: from XML too + public void setBounds(int innerRadius, int outerRadius) { + mBoundInnerRadiusSquared = innerRadius * innerRadius; + if (mBoundInnerRadiusSquared < innerRadius) { + // Prevent overflow + mBoundInnerRadiusSquared = Integer.MAX_VALUE; + } + + mBoundOuterRadiusSquared = outerRadius * outerRadius; + if (mBoundOuterRadiusSquared < outerRadius) { + // Prevent overflow + mBoundOuterRadiusSquared = Integer.MAX_VALUE; + } + } + + public void setThumbAngle(int angle) { + mThumbAngle = angle; + mThumbCenterX = (int) (Math.cos(1f * angle / RADIAN_INT_MULTIPLIER) * THUMB_DISTANCE) + + mCenterX; + mThumbCenterY = (int) (Math.sin(1f * angle / RADIAN_INT_MULTIPLIER) * THUMB_DISTANCE) + * -1 + mCenterY; + invalidate(); + } + + public void resetThumbAngle() { + if (mResetThumbAutomatically) { + setThumbAngle(HALF_PI_INT_MULTIPLIED); + } + } + + public void setResetThumbAutomatically(boolean resetThumbAutomatically) { + mResetThumbAutomatically = resetThumbAutomatically; + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + setMeasuredDimension(resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec), + resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec)); + } + + @Override + protected void onLayout(boolean changed, int left, int top, int right, + int bottom) { + super.onLayout(changed, left, top, right, bottom); + + // Cache the center point + mCenterX = (right - left) / 2; + mCenterY = (bottom - top) / 2; + + // Done here since we now have center, which is needed to calculate some + // aux info for thumb angle + if (mThumbAngle == Integer.MIN_VALUE) { + resetThumbAngle(); + } + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + return handleTouch(event.getAction(), event.getEventTime(), + (int) event.getX(), (int) event.getY(), (int) event.getRawX(), + (int) event.getRawY()); + } + + private void resetState() { + mMode = MODE_IDLE; + mPreviousWidgetDragX = mPreviousWidgetDragY = Integer.MIN_VALUE; + mAcculumalatedThumbDrag = 0; + mIsThumbAngleValid = false; + } + + public void setTapDragMode(boolean tapDragMode, int x, int y) { + resetState(); + mMode = tapDragMode ? MODE_TAP_DRAG : MODE_IDLE; + mIsThumbAngleValid = false; + + if (tapDragMode && mCallback != null) { + onThumbDragStarted(getAngle(x - mCenterX, y - mCenterY)); + } + } + + public boolean handleTouch(int action, long time, int x, int y, int rawX, int rawY) { + switch (action) { + + case MotionEvent.ACTION_DOWN: + if (mPreviousTapTime + DOUBLE_TAP_DISMISS_TIMEOUT >= time) { + if (mCallback != null) { + mCallback.onZoomRingDismissed(); + } + } else { + mPreviousTapTime = time; + } + resetState(); + return true; + + case MotionEvent.ACTION_MOVE: + // Fall through to code below switch + break; + + case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_UP: + if (mCallback != null) { + if (mMode == MODE_MOVE_ZOOM_RING) { + mCallback.onZoomRingMovingStopped(); + } else if (mMode == MODE_DRAG_THUMB || mMode == MODE_TAP_DRAG) { + onThumbDragStopped(getAngle(x - mCenterX, y - mCenterY)); + } + } + mDisabler.setEnabling(true); + return true; + + default: + return false; + } + + // local{X,Y} will be where the center of the widget is (0,0) + int localX = x - mCenterX; + int localY = y - mCenterY; + boolean isTouchingThumb = true; + boolean isInBounds = true; + int touchAngle = getAngle(localX, localY); + + int radiusSquared = localX * localX + localY * localY; + if (radiusSquared < mBoundInnerRadiusSquared || + radiusSquared > mBoundOuterRadiusSquared) { + // Out-of-bounds + isTouchingThumb = false; + isInBounds = false; + } + + int deltaThumbAndTouch = getDelta(touchAngle, mThumbAngle); + int absoluteDeltaThumbAndTouch = deltaThumbAndTouch >= 0 ? + deltaThumbAndTouch : -deltaThumbAndTouch; + if (isTouchingThumb && + absoluteDeltaThumbAndTouch > THUMB_GRAB_SLOP) { + // Didn't grab close enough to the thumb + isTouchingThumb = false; + } + + if (mMode == MODE_IDLE) { + mMode = isTouchingThumb ? MODE_DRAG_THUMB : MODE_MOVE_ZOOM_RING; + + if (mCallback != null) { + if (mMode == MODE_DRAG_THUMB) { + onThumbDragStarted(touchAngle); + } else if (mMode == MODE_MOVE_ZOOM_RING) { + mCallback.onZoomRingMovingStarted(); + } + } + } + + if (mMode == MODE_DRAG_THUMB || mMode == MODE_TAP_DRAG) { + if (isInBounds) { + onThumbDragged(touchAngle, mIsThumbAngleValid ? deltaThumbAndTouch : 0); + } else { + mIsThumbAngleValid = false; + } + } else if (mMode == MODE_MOVE_ZOOM_RING) { + onZoomRingMoved(rawX, rawY); + } + + return true; + } + + private int getDelta(int angle1, int angle2) { + int delta = angle1 - angle2; + + // Assume this is a result of crossing over the discontinuous 0 -> 2pi + if (delta > PI_INT_MULTIPLIED || delta < -PI_INT_MULTIPLIED) { + // Bring both the radians and previous angle onto a continuous range + if (angle1 < HALF_PI_INT_MULTIPLIED) { + // Same as deltaRadians = (radians + 2PI) - previousAngle + delta += PI_INT_MULTIPLIED * 2; + } else if (angle2 < HALF_PI_INT_MULTIPLIED) { + // Same as deltaRadians = radians - (previousAngle + 2PI) + delta -= PI_INT_MULTIPLIED * 2; + } + } + + return delta; + } + + private void onThumbDragStarted(int startAngle) { + mThumbDragStartAngle = startAngle; + mCallback.onZoomRingThumbDraggingStarted(startAngle); + } + + private void onThumbDragged(int touchAngle, int deltaAngle) { + mAcculumalatedThumbDrag += deltaAngle; + if (mAcculumalatedThumbDrag > mCallbackThreshold + || mAcculumalatedThumbDrag < -mCallbackThreshold) { + if (mCallback != null) { + boolean canStillZoom = mCallback.onZoomRingThumbDragged( + mAcculumalatedThumbDrag / mCallbackThreshold, + mAcculumalatedThumbDrag, mThumbDragStartAngle, touchAngle); + mDisabler.setEnabling(canStillZoom); + } + mAcculumalatedThumbDrag = 0; + } + + setThumbAngle(touchAngle); + mIsThumbAngleValid = true; + } + + private void onThumbDragStopped(int stopAngle) { + mCallback.onZoomRingThumbDraggingStopped(stopAngle); + } + + private void onZoomRingMoved(int x, int y) { + if (mPreviousWidgetDragX != Integer.MIN_VALUE) { + int deltaX = x - mPreviousWidgetDragX; + int deltaY = y - mPreviousWidgetDragY; + + if (mCallback != null) { + mCallback.onZoomRingMoved(deltaX, deltaY); + } + } + + mPreviousWidgetDragX = x; + mPreviousWidgetDragY = y; + } + + @Override + public void onWindowFocusChanged(boolean hasWindowFocus) { + super.onWindowFocusChanged(hasWindowFocus); + + if (!hasWindowFocus && mCallback != null) { + mCallback.onZoomRingDismissed(); + } + } + + private int getAngle(int localX, int localY) { + int radians = (int) (Math.atan2(localY, localX) * RADIAN_INT_MULTIPLIER); + + // Convert from [-pi,pi] to {0,2pi] + if (radians < 0) { + return -radians; + } else if (radians > 0) { + return 2 * PI_INT_MULTIPLIED - radians; + } else { + return 0; + } + } + + @Override + protected void onDraw(Canvas canvas) { + super.onDraw(canvas); + + if (mDrawThumb) { + mThumbDrawable.setBounds(mThumbCenterX - mThumbHalfWidth, mThumbCenterY + - mThumbHalfHeight, mThumbCenterX + mThumbHalfWidth, mThumbCenterY + + mThumbHalfHeight); + mThumbDrawable.draw(canvas); + } + } + + private class Disabler implements Runnable { + private static final int DELAY = 15; + private static final float ENABLE_RATE = 1.05f; + private static final float DISABLE_RATE = 0.95f; + + private int mAlpha = 255; + private boolean mEnabling; + + public int getAlpha() { + return mAlpha; + } + + public void setEnabling(boolean enabling) { + if ((enabling && mAlpha != 255) || (!enabling && mAlpha != DISABLED_ALPHA)) { + mEnabling = enabling; + post(this); + } + } + + public void run() { + mAlpha *= mEnabling ? ENABLE_RATE : DISABLE_RATE; + if (mAlpha < DISABLED_ALPHA) { + mAlpha = DISABLED_ALPHA; + } else if (mAlpha > 255) { + mAlpha = 255; + } else { + // Still more to go + postDelayed(this, DELAY); + } + + getBackground().setAlpha(mAlpha); + invalidate(); + } + } + + public interface OnZoomRingCallback { + void onZoomRingMovingStarted(); + boolean onZoomRingMoved(int deltaX, int deltaY); + void onZoomRingMovingStopped(); + + void onZoomRingThumbDraggingStarted(int startAngle); + boolean onZoomRingThumbDragged(int numLevels, int dragAmount, int startAngle, int curAngle); + void onZoomRingThumbDraggingStopped(int endAngle); + + void onZoomRingDismissed(); + } + +} diff --git a/core/java/android/widget/ZoomRingController.java b/core/java/android/widget/ZoomRingController.java new file mode 100644 index 0000000..2ca0374 --- /dev/null +++ b/core/java/android/widget/ZoomRingController.java @@ -0,0 +1,819 @@ +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.widget; + +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.graphics.PixelFormat; +import android.graphics.Rect; +import android.os.Handler; +import android.os.Message; +import android.os.SystemClock; +import android.provider.Settings; +import android.util.Log; +import android.view.Gravity; +import android.view.KeyEvent; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.WindowManager; +import android.view.WindowManager.LayoutParams; +import android.view.animation.Animation; +import android.view.animation.AnimationUtils; +import android.view.animation.DecelerateInterpolator; + +// TODO: make sure no px values exist, only dip (scale if necessary from Viewconfiguration) + +/** + * TODO: Docs + * @hide + */ +public class ZoomRingController implements ZoomRing.OnZoomRingCallback, + View.OnTouchListener, View.OnKeyListener { + + private static final int SHOW_TUTORIAL_TOAST_DELAY = 1000; + + private static final int ZOOM_RING_RECENTERING_DURATION = 500; + + private static final String TAG = "ZoomRing"; + + public static final boolean USE_OLD_ZOOM = false; + public static boolean useOldZoom(Context context) { + return Settings.System.getInt(context.getContentResolver(), "zoom", 1) == 0; + } + + private static final int ZOOM_CONTROLS_TIMEOUT = + (int) ViewConfiguration.getZoomControlsTimeout(); + + // TODO: move these to ViewConfiguration or re-use existing ones + // TODO: scale px values based on latest from ViewConfiguration + private static final int SECOND_TAP_TIMEOUT = 500; + private static final int ZOOM_RING_DISMISS_DELAY = SECOND_TAP_TIMEOUT / 2; + private static final int SECOND_TAP_SLOP = 70; + private static final int SECOND_TAP_MOVE_SLOP = 15; + private static final int MAX_PAN_GAP = 30; + + private static final String SETTING_NAME_SHOWN_TOAST = "shown_zoom_ring_toast"; + + private Context mContext; + private WindowManager mWindowManager; + + /** + * The view that is being zoomed by this zoom ring. + */ + private View mOwnerView; + + /** + * The bounds of the owner view in global coordinates. This is recalculated + * each time the zoom ring is shown. + */ + private Rect mOwnerViewBounds = new Rect(); + + /** + * The container that is added as a window. + */ + private FrameLayout mContainer; + private LayoutParams mContainerLayoutParams; + + /* + * Tap-drag is an interaction where the user first taps and then (quickly) + * does the clockwise or counter-clockwise drag. In reality, this is: (down, + * up, down, move in circles, up). This differs from the usual events of: + * (down, up, down, up, down, move in circles, up). While the only + * difference is the omission of an (up, down), for power-users this is a + * pretty big improvement as it now only requires them to focus on the + * screen once (for the first tap down) instead of twice (for the first tap + * down and then to grab the thumb). + */ + private int mTapDragStartX; + private int mTapDragStartY; + + private static final int TOUCH_MODE_IDLE = 0; + private static final int TOUCH_MODE_WAITING_FOR_SECOND_TAP = 1; + private static final int TOUCH_MODE_WAITING_FOR_TAP_DRAG_MOVEMENT = 2; + private static final int TOUCH_MODE_FORWARDING_FOR_TAP_DRAG = 3; + private int mTouchMode; + + private boolean mIsZoomRingVisible; + + private ZoomRing mZoomRing; + private int mZoomRingWidth; + private int mZoomRingHeight; + + /** Invokes panning of owner view if the zoom ring is touching an edge. */ + private Panner mPanner = new Panner(); + + private ImageView mPanningArrows; + private Animation mPanningArrowsEnterAnimation; + private Animation mPanningArrowsExitAnimation; + + private Rect mTempRect = new Rect(); + + private OnZoomListener mCallback; + + private ViewConfiguration mViewConfig; + + /** + * When the zoom ring is centered on screen, this will be the x value used + * for the container's layout params. + */ + private int mCenteredContainerX = Integer.MIN_VALUE; + + /** + * When the zoom ring is centered on screen, this will be the y value used + * for the container's layout params. + */ + private int mCenteredContainerY = Integer.MIN_VALUE; + + /** + * Scroller used to re-center the zoom ring if the user had dragged it to a + * corner and then double-taps any point on the owner view (the owner view + * will center the double-tapped point, but we should re-center the zoom + * ring). + * <p> + * The (x,y) of the scroller is the (x,y) of the container's layout params. + */ + private Scroller mScroller; + + /** + * When showing the zoom ring, we add the view as a new window. However, + * there is logic that needs to know the size of the zoom ring which is + * determined after it's laid out. Therefore, we must post this logic onto + * the UI thread so it will be exceuted AFTER the layout. This is the logic. + */ + private Runnable mPostedVisibleInitializer; + + // TODO: need a better way to persist this value, becuase right now this + // requires the WRITE_SETTINGS perimssion which the app may not have +// private Runnable mShowTutorialToast = new Runnable() { +// public void run() { +// if (Settings.System.getInt(mContext.getContentResolver(), +// SETTING_NAME_SHOWN_TOAST, 0) == 1) { +// return; +// } +// try { +// Settings.System.putInt(mContext.getContentResolver(), SETTING_NAME_SHOWN_TOAST, 1); +// } catch (SecurityException e) { +// // The app does not have permission to clear this flag, oh well! +// } +// +// Toast.makeText(mContext, +// com.android.internal.R.string.tutorial_double_tap_to_zoom_message, +// Toast.LENGTH_LONG).show(); +// } +// }; + + private IntentFilter mConfigurationChangedFilter = + new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED); + + private BroadcastReceiver mConfigurationChangedReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (!mIsZoomRingVisible) return; + + mHandler.removeMessages(MSG_POST_CONFIGURATION_CHANGED); + mHandler.sendEmptyMessage(MSG_POST_CONFIGURATION_CHANGED); + } + }; + + /** Keeps the scroller going (or starts it). */ + private static final int MSG_SCROLLER_TICK = 1; + /** When configuration changes, this is called after the UI thread is idle. */ + private static final int MSG_POST_CONFIGURATION_CHANGED = 2; + /** Used to delay the zoom ring dismissal. */ + private static final int MSG_DISMISS_ZOOM_RING = 3; + + private Handler mHandler = new Handler() { + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MSG_SCROLLER_TICK: + onScrollerTick(); + break; + + case MSG_POST_CONFIGURATION_CHANGED: + onPostConfigurationChanged(); + break; + + case MSG_DISMISS_ZOOM_RING: + setVisible(false); + break; + } + + } + }; + + public ZoomRingController(Context context, View ownerView) { + mContext = context; + mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); + + mOwnerView = ownerView; + + mZoomRing = new ZoomRing(context); + mZoomRing.setLayoutParams(new FrameLayout.LayoutParams( + FrameLayout.LayoutParams.WRAP_CONTENT, + FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CENTER)); + mZoomRing.setCallback(this); + + createPanningArrows(); + + mContainer = new FrameLayout(context); + mContainer.setMeasureAllChildren(true); + mContainer.setOnTouchListener(this); + + mContainer.addView(mZoomRing); + mContainer.addView(mPanningArrows); + mContainer.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); + + mContainerLayoutParams = new LayoutParams(); + mContainerLayoutParams.gravity = Gravity.LEFT | Gravity.TOP; + mContainerLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL | + LayoutParams.FLAG_NOT_FOCUSABLE | + LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | LayoutParams.FLAG_LAYOUT_NO_LIMITS; + mContainerLayoutParams.height = LayoutParams.WRAP_CONTENT; + mContainerLayoutParams.width = LayoutParams.WRAP_CONTENT; + mContainerLayoutParams.type = LayoutParams.TYPE_APPLICATION_PANEL; + mContainerLayoutParams.format = PixelFormat.TRANSLUCENT; + // TODO: make a new animation for this + mContainerLayoutParams.windowAnimations = com.android.internal.R.style.Animation_Dialog; + + mScroller = new Scroller(context, new DecelerateInterpolator()); + + mViewConfig = ViewConfiguration.get(context); + +// mHandler.postDelayed(mShowTutorialToast, SHOW_TUTORIAL_TOAST_DELAY); + } + + private void createPanningArrows() { + // TODO: style + mPanningArrows = new ImageView(mContext); + mPanningArrows.setImageResource(com.android.internal.R.drawable.zoom_ring_arrows); + mPanningArrows.setLayoutParams(new FrameLayout.LayoutParams( + FrameLayout.LayoutParams.WRAP_CONTENT, + FrameLayout.LayoutParams.WRAP_CONTENT, + Gravity.CENTER)); + mPanningArrows.setVisibility(View.GONE); + + mPanningArrowsEnterAnimation = AnimationUtils.loadAnimation(mContext, + com.android.internal.R.anim.fade_in); + mPanningArrowsExitAnimation = AnimationUtils.loadAnimation(mContext, + com.android.internal.R.anim.fade_out); + } + + /** + * Sets the angle (in radians) a user must travel in order for the client to + * get a callback. Once there is a callback, the accumulator resets. For + * example, if you set this to PI/6, it will give a callback every time the + * user moves PI/6 amount on the ring. + * + * @param callbackThreshold The angle for the callback threshold, in radians + */ + public void setZoomCallbackThreshold(float callbackThreshold) { + mZoomRing.setCallbackThreshold((int) (callbackThreshold * ZoomRing.RADIAN_INT_MULTIPLIER)); + } + + public void setCallback(OnZoomListener callback) { + mCallback = callback; + } + + public void setThumbAngle(float angle) { + mZoomRing.setThumbAngle((int) (angle * ZoomRing.RADIAN_INT_MULTIPLIER)); + } + + public void setResetThumbAutomatically(boolean resetThumbAutomatically) { + mZoomRing.setResetThumbAutomatically(resetThumbAutomatically); + } + + public boolean isVisible() { + return mIsZoomRingVisible; + } + + public void setVisible(boolean visible) { + + if (useOldZoom(mContext)) return; + + if (visible) { + dismissZoomRingDelayed(ZOOM_CONTROLS_TIMEOUT); + } else { + mPanner.stop(); + } + + if (mIsZoomRingVisible == visible) { + return; + } + + if (visible) { + if (mContainerLayoutParams.token == null) { + mContainerLayoutParams.token = mOwnerView.getWindowToken(); + } + + mWindowManager.addView(mContainer, mContainerLayoutParams); + + if (mPostedVisibleInitializer == null) { + mPostedVisibleInitializer = new Runnable() { + public void run() { + refreshPositioningVariables(); + resetZoomRing(); + + // TODO: remove this 'update' and just center zoom ring before the + // 'add', but need to make sure we have the width and height (which + // probably can only be retrieved after it's measured, which happens + // after it's added). + mWindowManager.updateViewLayout(mContainer, mContainerLayoutParams); + } + }; + } + + mHandler.post(mPostedVisibleInitializer); + + // Handle configuration changes when visible + mContext.registerReceiver(mConfigurationChangedReceiver, mConfigurationChangedFilter); + + // Steal key events from the owner + mOwnerView.setOnKeyListener(this); + + } else { + // Don't want to steal any more keys + mOwnerView.setOnKeyListener(null); + + // No longer care about configuration changes + mContext.unregisterReceiver(mConfigurationChangedReceiver); + + mWindowManager.removeView(mContainer); + } + + mIsZoomRingVisible = visible; + + if (mCallback != null) { + mCallback.onVisibilityChanged(visible); + } + } + + private void dismissZoomRingDelayed(int delay) { + mHandler.removeMessages(MSG_DISMISS_ZOOM_RING); + mHandler.sendEmptyMessageDelayed(MSG_DISMISS_ZOOM_RING, delay); + } + + private void resetZoomRing() { + mScroller.abortAnimation(); + + mContainerLayoutParams.x = mCenteredContainerX; + mContainerLayoutParams.y = mCenteredContainerY; + + // Reset the thumb + mZoomRing.resetThumbAngle(); + } + + /** + * Should be called by the client for each event belonging to the second tap + * (the down, move, up, and cancel events). + * + * @param event The event belonging to the second tap. + * @return Whether the event was consumed. + */ + public boolean handleDoubleTapEvent(MotionEvent event) { + int action = event.getAction(); + + if (action == MotionEvent.ACTION_DOWN) { + mTouchMode = TOUCH_MODE_WAITING_FOR_TAP_DRAG_MOVEMENT; + int x = (int) event.getX(); + int y = (int) event.getY(); + + refreshPositioningVariables(); + setVisible(true); + centerPoint(x, y); + ensureZoomRingIsCentered(); + + // Tap drag mode stuff + mTapDragStartX = x; + mTapDragStartY = y; + + } else if (action == MotionEvent.ACTION_CANCEL) { + mTouchMode = TOUCH_MODE_IDLE; + + } else { // action is move or up + switch (mTouchMode) { + case TOUCH_MODE_WAITING_FOR_TAP_DRAG_MOVEMENT: { + switch (action) { + case MotionEvent.ACTION_MOVE: + int x = (int) event.getX(); + int y = (int) event.getY(); + if (Math.abs(x - mTapDragStartX) > mViewConfig.getScaledTouchSlop() || + Math.abs(y - mTapDragStartY) > + mViewConfig.getScaledTouchSlop()) { + mZoomRing.setTapDragMode(true, x, y); + mTouchMode = TOUCH_MODE_FORWARDING_FOR_TAP_DRAG; + } + return true; + + case MotionEvent.ACTION_UP: + mTouchMode = TOUCH_MODE_IDLE; + break; + } + break; + } + + case TOUCH_MODE_FORWARDING_FOR_TAP_DRAG: { + switch (action) { + case MotionEvent.ACTION_MOVE: + giveTouchToZoomRing(event); + return true; + + case MotionEvent.ACTION_UP: + mTouchMode = TOUCH_MODE_IDLE; + mZoomRing.setTapDragMode(false, (int) event.getX(), (int) event.getY()); + break; + } + break; + } + } + } + + return true; + } + + private void ensureZoomRingIsCentered() { + LayoutParams lp = mContainerLayoutParams; + + if (lp.x != mCenteredContainerX || lp.y != mCenteredContainerY) { + int width = mContainer.getWidth(); + int height = mContainer.getHeight(); + mScroller.startScroll(lp.x, lp.y, mCenteredContainerX - lp.x, + mCenteredContainerY - lp.y, ZOOM_RING_RECENTERING_DURATION); + mHandler.sendEmptyMessage(MSG_SCROLLER_TICK); + } + } + + private void refreshPositioningVariables() { + mZoomRingWidth = mZoomRing.getWidth(); + mZoomRingHeight = mZoomRing.getHeight(); + + // Calculate the owner view's bounds + mOwnerView.getGlobalVisibleRect(mOwnerViewBounds); + + // Get the center + Gravity.apply(Gravity.CENTER, mContainer.getWidth(), mContainer.getHeight(), + mOwnerViewBounds, mTempRect); + mCenteredContainerX = mTempRect.left; + mCenteredContainerY = mTempRect.top; + + } + + // MOVE ALL THIS TO GESTURE DETECTOR +// public boolean onTouch(View v, MotionEvent event) { +// int action = event.getAction(); +// +// if (mListenForInvocation) { +// switch (mTouchMode) { +// case TOUCH_MODE_IDLE: { +// if (action == MotionEvent.ACTION_DOWN) { +// setFirstTap(event); +// } +// break; +// } +// +// case TOUCH_MODE_WAITING_FOR_SECOND_TAP: { +// switch (action) { +// case MotionEvent.ACTION_DOWN: +// if (isSecondTapWithinSlop(event)) { +// handleDoubleTapEvent(event); +// } else { +// setFirstTap(event); +// } +// break; +// +// case MotionEvent.ACTION_MOVE: +// int deltaX = (int) event.getX() - mFirstTapX; +// if (deltaX < -SECOND_TAP_MOVE_SLOP || +// deltaX > SECOND_TAP_MOVE_SLOP) { +// mTouchMode = TOUCH_MODE_IDLE; +// } else { +// int deltaY = (int) event.getY() - mFirstTapY; +// if (deltaY < -SECOND_TAP_MOVE_SLOP || +// deltaY > SECOND_TAP_MOVE_SLOP) { +// mTouchMode = TOUCH_MODE_IDLE; +// } +// } +// break; +// } +// break; +// } +// +// case TOUCH_MODE_WAITING_FOR_TAP_DRAG_MOVEMENT: +// case TOUCH_MODE_FORWARDING_FOR_TAP_DRAG: { +// handleDoubleTapEvent(event); +// break; +// } +// } +// +// if (action == MotionEvent.ACTION_CANCEL) { +// mTouchMode = TOUCH_MODE_IDLE; +// } +// } +// +// return false; +// } +// +// private void setFirstTap(MotionEvent event) { +// mFirstTapTime = event.getEventTime(); +// mFirstTapX = (int) event.getX(); +// mFirstTapY = (int) event.getY(); +// mTouchMode = TOUCH_MODE_WAITING_FOR_SECOND_TAP; +// } +// +// private boolean isSecondTapWithinSlop(MotionEvent event) { +// return mFirstTapTime + SECOND_TAP_TIMEOUT > event.getEventTime() && +// Math.abs((int) event.getX() - mFirstTapX) < SECOND_TAP_SLOP && +// Math.abs((int) event.getY() - mFirstTapY) < SECOND_TAP_SLOP; +// } + + /** + * Centers the point (in owner view's coordinates). + */ + private void centerPoint(int x, int y) { + if (mCallback != null) { + mCallback.onCenter(x, y); + } + } + + private void giveTouchToZoomRing(MotionEvent event) { + int rawX = (int) event.getRawX(); + int rawY = (int) event.getRawY(); + int x = rawX - mContainerLayoutParams.x - mZoomRing.getLeft(); + int y = rawY - mContainerLayoutParams.y - mZoomRing.getTop(); + mZoomRing.handleTouch(event.getAction(), event.getEventTime(), x, y, rawX, rawY); + } + + public void onZoomRingMovingStarted() { + mHandler.removeMessages(MSG_DISMISS_ZOOM_RING); + mScroller.abortAnimation(); + setPanningArrowsVisible(true); + } + + private void setPanningArrowsVisible(boolean visible) { + mPanningArrows.startAnimation(visible ? mPanningArrowsEnterAnimation + : mPanningArrowsExitAnimation); + mPanningArrows.setVisibility(visible ? View.VISIBLE : View.GONE); + } + + public boolean onZoomRingMoved(int deltaX, int deltaY) { + WindowManager.LayoutParams lp = mContainerLayoutParams; + Rect ownerBounds = mOwnerViewBounds; + + int zoomRingLeft = mZoomRing.getLeft(); + int zoomRingTop = mZoomRing.getTop(); + + int newX = lp.x + deltaX; + int newZoomRingX = newX + zoomRingLeft; + newZoomRingX = (newZoomRingX <= ownerBounds.left) ? ownerBounds.left : + (newZoomRingX + mZoomRingWidth > ownerBounds.right) ? + ownerBounds.right - mZoomRingWidth : newZoomRingX; + lp.x = newZoomRingX - zoomRingLeft; + + int newY = lp.y + deltaY; + int newZoomRingY = newY + zoomRingTop; + newZoomRingY = (newZoomRingY <= ownerBounds.top) ? ownerBounds.top : + (newZoomRingY + mZoomRingHeight > ownerBounds.bottom) ? + ownerBounds.bottom - mZoomRingHeight : newZoomRingY; + lp.y = newZoomRingY - zoomRingTop; + + mWindowManager.updateViewLayout(mContainer, lp); + + // Check for pan + int leftGap = newZoomRingX - ownerBounds.left; + if (leftGap < MAX_PAN_GAP) { + mPanner.setHorizontalStrength(-getStrengthFromGap(leftGap)); + } else { + int rightGap = ownerBounds.right - (lp.x + mZoomRingWidth + zoomRingLeft); + if (rightGap < MAX_PAN_GAP) { + mPanner.setHorizontalStrength(getStrengthFromGap(rightGap)); + } else { + mPanner.setHorizontalStrength(0); + } + } + + int topGap = newZoomRingY - ownerBounds.top; + if (topGap < MAX_PAN_GAP) { + mPanner.setVerticalStrength(-getStrengthFromGap(topGap)); + } else { + int bottomGap = ownerBounds.bottom - (lp.y + mZoomRingHeight + zoomRingTop); + if (bottomGap < MAX_PAN_GAP) { + mPanner.setVerticalStrength(getStrengthFromGap(bottomGap)); + } else { + mPanner.setVerticalStrength(0); + } + } + + return true; + } + + public void onZoomRingMovingStopped() { + dismissZoomRingDelayed(ZOOM_CONTROLS_TIMEOUT); + mPanner.stop(); + setPanningArrowsVisible(false); + } + + private int getStrengthFromGap(int gap) { + return gap > MAX_PAN_GAP ? 0 : + (MAX_PAN_GAP - gap) * 100 / MAX_PAN_GAP; + } + + public void onZoomRingThumbDraggingStarted(int startAngle) { + mHandler.removeMessages(MSG_DISMISS_ZOOM_RING); + if (mCallback != null) { + mCallback.onBeginDrag((float) startAngle / ZoomRing.RADIAN_INT_MULTIPLIER); + } + } + + public boolean onZoomRingThumbDragged(int numLevels, int dragAmount, int startAngle, + int curAngle) { + if (mCallback != null) { + int deltaZoomLevel = -numLevels; + int globalZoomCenterX = mContainerLayoutParams.x + mZoomRing.getLeft() + + mZoomRingWidth / 2; + int globalZoomCenterY = mContainerLayoutParams.y + mZoomRing.getTop() + + mZoomRingHeight / 2; + + return mCallback.onDragZoom(deltaZoomLevel, globalZoomCenterX - mOwnerViewBounds.left, + globalZoomCenterY - mOwnerViewBounds.top, + (float) startAngle / ZoomRing.RADIAN_INT_MULTIPLIER, + (float) curAngle / ZoomRing.RADIAN_INT_MULTIPLIER); + } + + return false; + } + + public void onZoomRingThumbDraggingStopped(int endAngle) { + dismissZoomRingDelayed(ZOOM_CONTROLS_TIMEOUT); + if (mCallback != null) { + mCallback.onEndDrag((float) endAngle / ZoomRing.RADIAN_INT_MULTIPLIER); + } + } + + public void onZoomRingDismissed() { + dismissZoomRingDelayed(ZOOM_RING_DISMISS_DELAY); + } + + public boolean onTouch(View v, MotionEvent event) { + if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { + // If the user touches outside of the zoom ring, dismiss the zoom ring + dismissZoomRingDelayed(ZOOM_RING_DISMISS_DELAY); + return true; + } + + return false; + } + + /** Steals key events from the owner view. */ + public boolean onKey(View v, int keyCode, KeyEvent event) { + switch (keyCode) { + case KeyEvent.KEYCODE_DPAD_LEFT: + case KeyEvent.KEYCODE_DPAD_RIGHT: + // Eat these + return true; + + case KeyEvent.KEYCODE_DPAD_UP: + case KeyEvent.KEYCODE_DPAD_DOWN: + // Keep the zoom alive a little longer + dismissZoomRingDelayed(ZOOM_CONTROLS_TIMEOUT); + + if (mCallback != null && event.getAction() == KeyEvent.ACTION_DOWN) { + mCallback.onSimpleZoom(keyCode == KeyEvent.KEYCODE_DPAD_UP); + } + + return true; + } + + return false; + } + + private void onScrollerTick() { + if (!mScroller.computeScrollOffset() || !mIsZoomRingVisible) return; + + mContainerLayoutParams.x = mScroller.getCurrX(); + mContainerLayoutParams.y = mScroller.getCurrY(); + mWindowManager.updateViewLayout(mContainer, mContainerLayoutParams); + + mHandler.sendEmptyMessage(MSG_SCROLLER_TICK); + } + + private void onPostConfigurationChanged() { + dismissZoomRingDelayed(ZOOM_CONTROLS_TIMEOUT); + refreshPositioningVariables(); + ensureZoomRingIsCentered(); + } + + private class Panner implements Runnable { + private static final int RUN_DELAY = 15; + private static final float STOP_SLOWDOWN = 0.8f; + + private final Handler mUiHandler = new Handler(); + + private int mVerticalStrength; + private int mHorizontalStrength; + + private boolean mStopping; + + /** The time this current pan started. */ + private long mStartTime; + + /** The time of the last callback to pan the map/browser/etc. */ + private long mPreviousCallbackTime; + + /** -100 (full left) to 0 (none) to 100 (full right) */ + public void setHorizontalStrength(int horizontalStrength) { + if (mHorizontalStrength == 0 && mVerticalStrength == 0 && horizontalStrength != 0) { + start(); + } else if (mVerticalStrength == 0 && horizontalStrength == 0) { + stop(); + } + + mHorizontalStrength = horizontalStrength; + mStopping = false; + } + + /** -100 (full up) to 0 (none) to 100 (full down) */ + public void setVerticalStrength(int verticalStrength) { + if (mHorizontalStrength == 0 && mVerticalStrength == 0 && verticalStrength != 0) { + start(); + } else if (mHorizontalStrength == 0 && verticalStrength == 0) { + stop(); + } + + mVerticalStrength = verticalStrength; + mStopping = false; + } + + private void start() { + mUiHandler.post(this); + mPreviousCallbackTime = 0; + mStartTime = 0; + } + + public void stop() { + mStopping = true; + } + + public void run() { + if (mStopping) { + mHorizontalStrength *= STOP_SLOWDOWN; + mVerticalStrength *= STOP_SLOWDOWN; + } + + if (mHorizontalStrength == 0 && mVerticalStrength == 0) { + return; + } + + boolean firstRun = mPreviousCallbackTime == 0; + long curTime = SystemClock.elapsedRealtime(); + int panAmount = getPanAmount(mStartTime, mPreviousCallbackTime, curTime); + mPreviousCallbackTime = curTime; + + if (firstRun) { + mStartTime = curTime; + } else { + int panX = panAmount * mHorizontalStrength / 100; + int panY = panAmount * mVerticalStrength / 100; + + if (mCallback != null) { + mCallback.onPan(panX, panY); + } + } + + mUiHandler.postDelayed(this, RUN_DELAY); + } + + // TODO make setter for this value so zoom clients can have different pan rates, if they want + private static final int PAN_VELOCITY_PX_S = 30; + private int getPanAmount(long startTime, long previousTime, long currentTime) { + return (int) ((currentTime - previousTime) * PAN_VELOCITY_PX_S / 100); + } + } + + public interface OnZoomListener { + void onBeginDrag(float startAngle); + boolean onDragZoom(int deltaZoomLevel, int centerX, int centerY, float startAngle, + float curAngle); + void onEndDrag(float endAngle); + void onSimpleZoom(boolean deltaZoomLevel); + boolean onPan(int deltaX, int deltaY); + void onCenter(int x, int y); + void onVisibilityChanged(boolean visible); + } +} |