From 07f9f65561c2b81bcd189b895b31bb2ad0438d74 Mon Sep 17 00:00:00 2001 From: Jason Monk Date: Thu, 19 Oct 2017 18:17:25 +0000 Subject: Revert "Import Android SDK Platform P [4402356]" This reverts commit d439404c9988df6001e4ff8bce31537e2692660e. Change-Id: I825790bdf38523800388bc1bb531cecfcd7e60bd --- .../accessibilityservice/GestureDescription.java | 12 - android/app/Activity.java | 8 +- android/app/ActivityManager.java | 294 +- android/app/ActivityOptions.java | 43 +- android/app/KeyguardManager.java | 2 + android/app/NotificationChannel.java | 2 - android/app/NotificationManager.java | 9 - android/app/StatusBarManager.java | 5 +- android/app/TaskStackListener.java | 7 +- android/app/WallpaperManager.java | 31 +- android/app/WindowConfiguration.java | 3 +- android/app/assist/AssistStructure.java | 57 - android/app/job/JobScheduler.java | 41 +- android/app/job/JobService.java | 102 +- android/app/slice/Slice.java | 417 --- android/app/slice/SliceItem.java | 346 --- android/app/slice/SliceProvider.java | 182 -- android/app/slice/SliceQuery.java | 150 - android/app/slice/views/ActionRow.java | 201 -- android/app/slice/views/GridView.java | 186 -- android/app/slice/views/LargeSliceAdapter.java | 224 -- android/app/slice/views/LargeTemplateView.java | 115 - android/app/slice/views/MessageView.java | 77 - android/app/slice/views/RemoteInputView.java | 445 --- android/app/slice/views/ShortcutView.java | 110 - android/app/slice/views/SliceView.java | 251 -- android/app/slice/views/SliceViewUtil.java | 182 -- android/app/slice/views/SmallTemplateView.java | 211 -- android/app/usage/UsageStatsManager.java | 19 +- .../arch/lifecycle/ActivityFullLifecycleTest.java | 58 +- android/arch/lifecycle/AndroidViewModel.java | 7 +- android/arch/lifecycle/ClassesInfoCache.java | 16 +- android/arch/lifecycle/ComputableLiveData.java | 139 +- .../lifecycle/DispatcherActivityCallbackTest.java | 77 + android/arch/lifecycle/Lifecycle.java | 7 +- android/arch/lifecycle/LifecycleDispatcher.java | 182 ++ android/arch/lifecycle/LifecycleOwner.java | 3 - android/arch/lifecycle/LifecycleRegistry.java | 63 +- android/arch/lifecycle/LifecycleRegistryOwner.java | 3 - android/arch/lifecycle/LifecycleRegistryTest.java | 19 - .../lifecycle/LifecycleRuntimeTrojanProvider.java | 68 + android/arch/lifecycle/LiveData.java | 410 +-- .../lifecycle/LiveDataOnSaveInstanceStateTest.java | 177 -- android/arch/lifecycle/LiveDataTest.java | 224 +- android/arch/lifecycle/MediatorLiveData.java | 39 +- android/arch/lifecycle/MissingClassTest.java | 44 - .../lifecycle/PartiallyCoveredActivityTest.java | 200 -- android/arch/lifecycle/ProcessLifecycleOwner.java | 5 +- .../ProcessLifecycleOwnerInitializer.java | 67 - android/arch/lifecycle/ProcessOwnerTest.java | 24 - android/arch/lifecycle/ReportFragment.java | 1 + android/arch/lifecycle/TestUtils.java | 108 +- android/arch/lifecycle/Transformations.java | 8 +- android/arch/lifecycle/ViewModelProvider.java | 11 +- android/arch/lifecycle/ViewModelProviders.java | 3 +- android/arch/lifecycle/ViewModelStoreOwner.java | 3 - android/arch/lifecycle/ViewModelStores.java | 5 +- .../arch/lifecycle/testapp/CollectingActivity.java | 37 + .../testapp/CollectingLifecycleOwner.java | 36 - .../testapp/CollectingSupportActivity.java | 113 - .../testapp/CollectingSupportFragment.java | 104 - .../FrameworkLifecycleRegistryActivity.java | 32 +- .../testapp/FullLifecycleTestActivity.java | 88 + android/arch/lifecycle/testapp/MainActivity.java | 31 + .../testapp/NavigationDialogActivity.java | 6 - .../arch/lifecycle/testapp/NonSupportActivity.java | 85 - .../testapp/SupportLifecycleRegistryActivity.java | 95 + android/arch/lifecycle/testapp/TestEvent.java | 4 +- android/arch/lifecycle/testapp/TestObserver.java | 2 +- android/arch/paging/BoundedDataSource.java | 2 + android/arch/paging/ContiguousDataSource.java | 110 +- android/arch/paging/ContiguousDiffHelper.java | 175 ++ android/arch/paging/ContiguousDiffHelperTest.java | 128 + android/arch/paging/ContiguousPagedList.java | 408 ++- android/arch/paging/ContiguousPagedListTest.java | 62 +- android/arch/paging/DataSource.java | 14 +- android/arch/paging/KeyedDataSource.java | 15 +- android/arch/paging/LivePagedListProvider.java | 132 +- android/arch/paging/NullPaddedList.java | 75 +- android/arch/paging/Page.java | 51 - android/arch/paging/PageArrayList.java | 130 + android/arch/paging/PageArrayListTest.java | 49 + android/arch/paging/PageResult.java | 56 - android/arch/paging/PagedList.java | 145 +- android/arch/paging/PagedListAdapterHelper.java | 109 +- .../arch/paging/PagedListAdapterHelperTest.java | 59 - android/arch/paging/PagedStorage.java | 433 --- android/arch/paging/PagedStorageDiffHelper.java | 174 -- .../arch/paging/PagedStorageDiffHelperTest.java | 165 -- android/arch/paging/PositionalDataSource.java | 25 +- android/arch/paging/SnapshotPagedList.java | 64 - android/arch/paging/SparseDiffHelper.java | 99 + android/arch/paging/StringPagedList.java | 56 +- android/arch/paging/TestExecutor.java | 2 +- android/arch/paging/TiledDataSource.java | 58 +- android/arch/paging/TiledPagedList.java | 276 +- android/arch/paging/TiledPagedListTest.java | 124 +- .../arch/persistence/room/InvalidationTracker.java | 4 +- android/arch/persistence/room/Relation.java | 18 +- android/arch/persistence/room/Room.java | 2 - android/arch/persistence/room/RoomDatabase.java | 15 +- android/arch/persistence/room/RoomWarnings.java | 8 - android/arch/persistence/room/Transaction.java | 37 +- .../integration/testapp/RoomPagedListActivity.java | 1 - .../integration/testapp/database/CustomerDao.java | 2 +- .../integration/testapp/db/JDBCOpenHelper.java | 47 + .../integration/testapp/test/InvalidationTest.java | 120 +- .../testapp/test/QueryDataSourceTest.java | 8 +- .../testapp/test/QueryTransactionTest.java | 471 ---- .../arch/persistence/room/migration/Migration.java | 3 +- .../room/migration/bundle/ForeignKeyBundle.java | 5 - .../room/paging/LimitOffsetDataSource.java | 36 +- android/arch/persistence/room/util/StringUtil.java | 7 +- android/content/ContentProvider.java | 3 +- android/content/ContentResolver.java | 36 +- android/content/Intent.java | 52 - android/content/IntentFilter.java | 63 - android/content/pm/FeatureInfo.java | 13 - android/content/pm/LauncherApps.java | 51 +- android/content/pm/PackageManagerInternal.java | 5 +- android/content/pm/PackageParser.java | 23 +- android/content/pm/PermissionInfo.java | 5 - android/content/pm/ShortcutInfo.java | 207 +- android/content/pm/ShortcutServiceInternal.java | 7 +- android/content/res/ResourcesImpl.java | 2 +- android/database/SQLiteDatabaseIoPerfTest.java | 176 -- android/database/SQLiteDatabasePerfTest.java | 223 -- android/graphics/Bitmap.java | 2 - android/graphics/BitmapFactory.java | 3 - android/media/AudioAttributes.java | 23 - android/media/MediaMetadataRetriever.java | 2 +- android/media/MediaRecorder.java | 6 +- android/media/tv/TvInputManager.java | 7 +- android/net/LinkProperties.java | 30 +- android/net/ip/ConnectivityPacketTracker.java | 23 +- android/net/ip/IpManager.java | 26 +- android/net/util/SharedLog.java | 4 - android/os/BatteryStats.java | 757 +---- android/os/Debug.java | 20 +- android/os/ParcelFileDescriptor.java | 4 +- android/os/PatternMatcher.java | 16 +- android/os/ServiceManager.java | 105 +- android/os/SystemProperties.java | 6 + android/os/UserManager.java | 19 - android/preference/SeekBarVolumizer.java | 3 +- android/provider/Settings.java | 25 +- android/service/autofill/AutofillService.java | 77 +- android/service/autofill/SaveInfo.java | 88 +- android/service/autofill/SaveRequest.java | 12 +- android/service/notification/ZenModeConfig.java | 79 +- android/slice/Slice.java | 347 +++ android/slice/SliceItem.java | 344 +++ android/slice/SliceProvider.java | 156 ++ android/slice/SliceQuery.java | 151 + android/slice/views/ActionRow.java | 201 ++ android/slice/views/GridView.java | 186 ++ android/slice/views/LargeSliceAdapter.java | 224 ++ android/slice/views/LargeTemplateView.java | 116 + android/slice/views/MessageView.java | 77 + android/slice/views/RemoteInputView.java | 445 +++ android/slice/views/ShortcutView.java | 110 + android/slice/views/SliceView.java | 249 ++ android/slice/views/SliceViewUtil.java | 182 ++ android/slice/views/SmallTemplateView.java | 211 ++ android/support/LibraryVersions.java | 6 +- android/support/car/drawer/CarDrawerActivity.java | 152 - android/support/car/drawer/CarDrawerAdapter.java | 182 -- .../support/car/drawer/CarDrawerController.java | 306 -- .../car/drawer/DrawerItemClickListener.java | 29 - .../support/car/drawer/DrawerItemViewHolder.java | 87 - android/support/car/widget/PagedListView.java | 57 +- android/support/media/tv/BasePreviewProgram.java | 100 +- android/support/media/tv/BaseProgram.java | 23 +- android/support/media/tv/Program.java | 3 +- android/support/media/tv/TvContractCompat.java | 82 + android/support/media/tv/WatchNextProgram.java | 27 +- .../mediacompat/testlib/IntentConstants.java | 2 - .../mediacompat/testlib/MediaSessionConstants.java | 57 - android/support/transition/AutoTransition.java | 6 +- .../v17/leanback/widget/GridLayoutManager.java | 18 +- .../support/v4/content/res/ResourcesCompat.java | 4 +- android/support/v4/media/RatingCompat.java | 23 +- android/support/v4/media/RatingCompatKitkat.java | 67 + .../support/v4/provider/FontsContractCompat.java | 3 - android/support/v7/app/MediaRouteButton.java | 3 +- .../support/v7/app/MediaRouteChooserDialog.java | 6 +- .../support/v7/app/MediaRouteControllerDialog.java | 8 +- android/support/v7/app/MediaRouterThemeHelper.java | 110 +- android/support/v7/util/DiffUtil.java | 67 - android/support/v7/widget/AppCompatTextHelper.java | 37 +- android/support/v7/widget/TintTypedArray.java | 5 +- android/telephony/CarrierConfigManager.java | 34 - android/telephony/MbmsDownloadSession.java | 41 +- android/telephony/NetworkScanRequest.java | 105 +- android/telephony/ServiceState.java | 9 + android/telephony/mbms/DownloadRequest.java | 30 +- android/telephony/mbms/MbmsDownloadReceiver.java | 11 +- .../mbms/vendor/MbmsDownloadServiceBase.java | 18 - .../mbms/vendor/MbmsStreamingServiceBase.java | 8 - android/text/BoringLayoutCreateDrawPerfTest.java | 2 +- android/text/BoringLayoutIsBoringPerfTest.java | 2 +- android/text/DynamicLayout.java | 6 +- android/text/Hyphenator.java | 251 +- android/text/Layout.java | 14 +- android/text/PaintMeasureDrawPerfTest.java | 2 +- android/text/StaticLayout.java | 74 +- android/text/StaticLayoutCreateDrawPerfTest.java | 2 +- android/text/StaticLayout_Delegate.java | 26 +- android/text/TextLine.java | 10 +- android/text/TextViewSetTextMeasurePerfTest.java | 4 +- android/util/Log.java | 295 +- android/util/LruCache.java | 25 +- android/util/StatsLog.java | 76 + android/util/StatsLogKey.java | 48 + android/util/StatsLogTag.java | 32 + android/util/StatsLogValue.java | 54 + android/view/SurfaceControl.java | 538 +--- android/view/SurfaceView.java | 1135 +++++++- android/view/View.java | 262 +- android/view/ViewDebug.java | 167 +- android/view/ViewGroup.java | 98 - android/view/ViewRootImpl.java | 758 +++-- android/view/ViewStructure.java | 24 - android/view/WindowManagerInternal.java | 4 +- android/view/WindowManagerPolicy.java | 7 +- android/view/accessibility/AccessibilityCache.java | 2 + .../view/accessibility/AccessibilityManager.java | 916 +++++- android/view/autofill/AutofillManager.java | 149 +- android/view/textclassifier/TextClassifier.java | 8 - .../textclassifier/TextClassifierConstants.java | 90 - .../view/textclassifier/TextClassifierImpl.java | 14 +- android/view/textservice/TextServicesManager.java | 200 +- android/webkit/WebView.java | 2948 +++++++++++++++++++- android/widget/Editor.java | 21 +- android/widget/RemoteViews.java | 6 +- android/widget/SelectionActionModeHelper.java | 30 +- android/widget/TextView.java | 41 - 237 files changed, 12657 insertions(+), 12928 deletions(-) delete mode 100644 android/app/slice/Slice.java delete mode 100644 android/app/slice/SliceItem.java delete mode 100644 android/app/slice/SliceProvider.java delete mode 100644 android/app/slice/SliceQuery.java delete mode 100644 android/app/slice/views/ActionRow.java delete mode 100644 android/app/slice/views/GridView.java delete mode 100644 android/app/slice/views/LargeSliceAdapter.java delete mode 100644 android/app/slice/views/LargeTemplateView.java delete mode 100644 android/app/slice/views/MessageView.java delete mode 100644 android/app/slice/views/RemoteInputView.java delete mode 100644 android/app/slice/views/ShortcutView.java delete mode 100644 android/app/slice/views/SliceView.java delete mode 100644 android/app/slice/views/SliceViewUtil.java delete mode 100644 android/app/slice/views/SmallTemplateView.java create mode 100644 android/arch/lifecycle/DispatcherActivityCallbackTest.java create mode 100644 android/arch/lifecycle/LifecycleDispatcher.java create mode 100644 android/arch/lifecycle/LifecycleRuntimeTrojanProvider.java delete mode 100644 android/arch/lifecycle/LiveDataOnSaveInstanceStateTest.java delete mode 100644 android/arch/lifecycle/MissingClassTest.java delete mode 100644 android/arch/lifecycle/PartiallyCoveredActivityTest.java delete mode 100644 android/arch/lifecycle/ProcessLifecycleOwnerInitializer.java create mode 100644 android/arch/lifecycle/testapp/CollectingActivity.java delete mode 100644 android/arch/lifecycle/testapp/CollectingLifecycleOwner.java delete mode 100644 android/arch/lifecycle/testapp/CollectingSupportActivity.java delete mode 100644 android/arch/lifecycle/testapp/CollectingSupportFragment.java create mode 100644 android/arch/lifecycle/testapp/FullLifecycleTestActivity.java create mode 100644 android/arch/lifecycle/testapp/MainActivity.java delete mode 100644 android/arch/lifecycle/testapp/NonSupportActivity.java create mode 100644 android/arch/lifecycle/testapp/SupportLifecycleRegistryActivity.java create mode 100644 android/arch/paging/ContiguousDiffHelper.java create mode 100644 android/arch/paging/ContiguousDiffHelperTest.java delete mode 100644 android/arch/paging/Page.java create mode 100644 android/arch/paging/PageArrayList.java create mode 100644 android/arch/paging/PageArrayListTest.java delete mode 100644 android/arch/paging/PageResult.java delete mode 100644 android/arch/paging/PagedStorage.java delete mode 100644 android/arch/paging/PagedStorageDiffHelper.java delete mode 100644 android/arch/paging/PagedStorageDiffHelperTest.java delete mode 100644 android/arch/paging/SnapshotPagedList.java create mode 100644 android/arch/paging/SparseDiffHelper.java create mode 100644 android/arch/persistence/room/integration/testapp/db/JDBCOpenHelper.java delete mode 100644 android/arch/persistence/room/integration/testapp/test/QueryTransactionTest.java delete mode 100644 android/database/SQLiteDatabaseIoPerfTest.java delete mode 100644 android/database/SQLiteDatabasePerfTest.java create mode 100644 android/slice/Slice.java create mode 100644 android/slice/SliceItem.java create mode 100644 android/slice/SliceProvider.java create mode 100644 android/slice/SliceQuery.java create mode 100644 android/slice/views/ActionRow.java create mode 100644 android/slice/views/GridView.java create mode 100644 android/slice/views/LargeSliceAdapter.java create mode 100644 android/slice/views/LargeTemplateView.java create mode 100644 android/slice/views/MessageView.java create mode 100644 android/slice/views/RemoteInputView.java create mode 100644 android/slice/views/ShortcutView.java create mode 100644 android/slice/views/SliceView.java create mode 100644 android/slice/views/SliceViewUtil.java create mode 100644 android/slice/views/SmallTemplateView.java delete mode 100644 android/support/car/drawer/CarDrawerActivity.java delete mode 100644 android/support/car/drawer/CarDrawerAdapter.java delete mode 100644 android/support/car/drawer/CarDrawerController.java delete mode 100644 android/support/car/drawer/DrawerItemClickListener.java delete mode 100644 android/support/car/drawer/DrawerItemViewHolder.java delete mode 100644 android/support/mediacompat/testlib/MediaSessionConstants.java create mode 100644 android/support/v4/media/RatingCompatKitkat.java create mode 100644 android/util/StatsLog.java create mode 100644 android/util/StatsLogKey.java create mode 100644 android/util/StatsLogTag.java create mode 100644 android/util/StatsLogValue.java delete mode 100644 android/view/textclassifier/TextClassifierConstants.java (limited to 'android') diff --git a/android/accessibilityservice/GestureDescription.java b/android/accessibilityservice/GestureDescription.java index 56f4ae2b..92567d75 100644 --- a/android/accessibilityservice/GestureDescription.java +++ b/android/accessibilityservice/GestureDescription.java @@ -427,18 +427,6 @@ public final class GestureDescription { mY = other.mY; } - @Override - public String toString() { - return "TouchPoint{" - + "mStrokeId=" + mStrokeId - + ", mContinuedStrokeId=" + mContinuedStrokeId - + ", mIsStartOfPath=" + mIsStartOfPath - + ", mIsEndOfPath=" + mIsEndOfPath - + ", mX=" + mX - + ", mY=" + mY - + '}'; - } - @Override public int describeContents() { return 0; diff --git a/android/app/Activity.java b/android/app/Activity.java index 85f73bb7..e0ac9113 100644 --- a/android/app/Activity.java +++ b/android/app/Activity.java @@ -542,9 +542,9 @@ import java.util.List; * * - * - *

Customizing the autofill save UI

- * - *

The service can also customize some aspects of the autofill save UI: + *

The service can also customize some aspects of the save UI affordance: *

    *
  • Add a simple subtitle by calling {@link Builder#setDescription(CharSequence)}. *
  • Add a customized subtitle by calling @@ -219,25 +212,16 @@ public final class SaveInfo implements Parcelable { @interface SaveDataType{} /** - * Usually, a save request is only automatically triggered - * once the {@link Activity} finishes. If this flag is set, it is triggered once all saved views - * become invisible. + * Usually {@link AutofillService#onSaveRequest(SaveRequest, SaveCallback)} + * is called once the {@link Activity} finishes. If this flag is set it is called once all + * saved views become invisible. */ public static final int FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE = 0x1; - /** - * By default, a save request is automatically triggered - * once the {@link Activity} finishes. If this flag is set, finishing the activity doesn't - * trigger a save request. - * - *

    This flag is typically used in conjunction with {@link Builder#setTriggerId(AutofillId)}. - */ - public static final int FLAG_DONT_SAVE_ON_FINISH = 0x2; - /** @hide */ @IntDef( flag = true, - value = {FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE, FLAG_DONT_SAVE_ON_FINISH}) + value = {FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE}) @Retention(RetentionPolicy.SOURCE) @interface SaveInfoFlags{} @@ -252,7 +236,6 @@ public final class SaveInfo implements Parcelable { private final InternalValidator mValidator; private final InternalSanitizer[] mSanitizerKeys; private final AutofillId[][] mSanitizerValues; - private final AutofillId mTriggerId; private SaveInfo(Builder builder) { mType = builder.mType; @@ -276,7 +259,6 @@ public final class SaveInfo implements Parcelable { mSanitizerValues[i] = builder.mSanitizers.valueAt(i); } } - mTriggerId = builder.mTriggerId; } /** @hide */ @@ -338,12 +320,6 @@ public final class SaveInfo implements Parcelable { return mSanitizerValues; } - /** @hide */ - @Nullable - public AutofillId getTriggerId() { - return mTriggerId; - } - /** * A builder for {@link SaveInfo} objects. */ @@ -362,7 +338,6 @@ public final class SaveInfo implements Parcelable { private ArrayMap mSanitizers; // Set used to validate against duplicate ids. private ArraySet mSanitizerIds; - private AutofillId mTriggerId; /** * Creates a new builder. @@ -419,15 +394,13 @@ public final class SaveInfo implements Parcelable { /** * Sets flags changing the save behavior. * - * @param flags {@link #FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE}, - * {@link #FLAG_DONT_SAVE_ON_FINISH}, or {@code 0}. + * @param flags {@link #FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE} or {@code 0}. * @return This builder. */ public @NonNull Builder setFlags(@SaveInfoFlags int flags) { throwIfDestroyed(); - mFlags = Preconditions.checkFlagsArgument(flags, - FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE | FLAG_DONT_SAVE_ON_FINISH); + mFlags = Preconditions.checkFlagsArgument(flags, FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE); return this; } @@ -520,8 +493,8 @@ public final class SaveInfo implements Parcelable { } /** - * Sets an object used to validate the user input - if the input is not valid, the - * autofill save UI is not shown. + * Sets an object used to validate the user input - if the input is not valid, the Save UI + * affordance is not shown. * *

    Typically used to validate credit card numbers. Examples: * @@ -547,7 +520,7 @@ public final class SaveInfo implements Parcelable { * ); * * - *

    Note: the example above is just for illustrative purposes; the same validator + *

    NOTE: the example above is just for illustrative purposes; the same validator * could be created using a single regex for the {@code OR} part: * *

    @@ -642,27 +615,6 @@ public final class SaveInfo implements Parcelable {
                 return this;
             }
     
    -       /**
    -         * Explicitly defines the view that should commit the autofill context when clicked.
    -         *
    -         * 

    Usually, the save request is only automatically - * triggered after the activity is - * finished or all relevant views become invisible, but there are scenarios where the - * autofill context is automatically commited too late - * —for example, when the activity manually clears the autofillable views when a - * button is tapped. This method can be used to trigger the autofill save UI earlier in - * these scenarios. - * - *

    Note: This method should only be used in scenarios where the automatic workflow - * is not enough, otherwise it could trigger the autofill save UI when it should not— - * for example, when the user entered invalid credentials for the autofillable views. - */ - public @NonNull Builder setTriggerId(@NonNull AutofillId id) { - throwIfDestroyed(); - mTriggerId = Preconditions.checkNotNull(id); - return this; - } - /** * Builds a new {@link SaveInfo} instance. * @@ -700,14 +652,13 @@ public final class SaveInfo implements Parcelable { .append(", description=").append(mDescription) .append(DebugUtils.flagsToString(SaveInfo.class, "NEGATIVE_BUTTON_STYLE_", mNegativeButtonStyle)) - .append(", flags=").append(mFlags) - .append(", customDescription=").append(mCustomDescription) - .append(", validator=").append(mValidator) + .append(", mFlags=").append(mFlags) + .append(", mCustomDescription=").append(mCustomDescription) + .append(", validation=").append(mValidator) .append(", sanitizerKeys=") .append(mSanitizerKeys == null ? "N/A:" : mSanitizerKeys.length) .append(", sanitizerValues=") .append(mSanitizerValues == null ? "N/A:" : mSanitizerValues.length) - .append(", triggerId=").append(mTriggerId) .append("]").toString(); } @@ -736,7 +687,6 @@ public final class SaveInfo implements Parcelable { parcel.writeParcelableArray(mSanitizerValues[i], flags); } } - parcel.writeParcelable(mTriggerId, flags); parcel.writeInt(mFlags); } @@ -777,10 +727,6 @@ public final class SaveInfo implements Parcelable { builder.addSanitizer(sanitizers[i], autofillIds); } } - final AutofillId triggerId = parcel.readParcelable(null); - if (triggerId != null) { - builder.setTriggerId(triggerId); - } builder.setFlags(parcel.readInt()); return builder.build(); } diff --git a/android/service/autofill/SaveRequest.java b/android/service/autofill/SaveRequest.java index f53967bd..65fdb5c4 100644 --- a/android/service/autofill/SaveRequest.java +++ b/android/service/autofill/SaveRequest.java @@ -19,6 +19,7 @@ package android.service.autofill; import android.annotation.NonNull; import android.annotation.Nullable; import android.os.Bundle; +import android.os.CancellationSignal; import android.os.Parcel; import android.os.Parcelable; @@ -59,14 +60,9 @@ public final class SaveRequest implements Parcelable { } /** - * Gets the latest client state extra returned from the service. - * - *

    Note: Prior to Android {@link android.os.Build.VERSION_CODES#P}, only client state - * bundles set by {@link FillResponse.Builder#setClientState(Bundle)} where considered. On - * Android {@link android.os.Build.VERSION_CODES#P} and higher, bundles set in the result of - * an authenticated request through the - * {@link android.view.autofill.AutofillManager#EXTRA_CLIENT_STATE} extra are - * also considered (and take precedence when set). + * Gets the extra client state returned from the last {@link + * AutofillService#onFillRequest(FillRequest, CancellationSignal, FillCallback)} + * fill request}. * * @return The client state. */ diff --git a/android/service/notification/ZenModeConfig.java b/android/service/notification/ZenModeConfig.java index c5615ae6..7bec898a 100644 --- a/android/service/notification/ZenModeConfig.java +++ b/android/service/notification/ZenModeConfig.java @@ -76,13 +76,10 @@ public class ZenModeConfig implements Parcelable { private static final int DAY_MINUTES = 24 * 60; private static final int ZERO_VALUE_MS = 10 * SECONDS_MS; - // Default allow categories set in readXml() from default_zen_mode_config.xml, fallback values: - private static final boolean DEFAULT_ALLOW_ALARMS = true; - private static final boolean DEFAULT_ALLOW_MEDIA_SYSTEM_OTHER = true; - private static final boolean DEFAULT_ALLOW_CALLS = false; + private static final boolean DEFAULT_ALLOW_CALLS = true; private static final boolean DEFAULT_ALLOW_MESSAGES = false; - private static final boolean DEFAULT_ALLOW_REMINDERS = false; - private static final boolean DEFAULT_ALLOW_EVENTS = false; + private static final boolean DEFAULT_ALLOW_REMINDERS = true; + private static final boolean DEFAULT_ALLOW_EVENTS = true; private static final boolean DEFAULT_ALLOW_REPEAT_CALLERS = false; private static final boolean DEFAULT_ALLOW_SCREEN_OFF = true; private static final boolean DEFAULT_ALLOW_SCREEN_ON = true; @@ -92,8 +89,6 @@ public class ZenModeConfig implements Parcelable { private static final String ZEN_ATT_VERSION = "version"; private static final String ZEN_ATT_USER = "user"; private static final String ALLOW_TAG = "allow"; - private static final String ALLOW_ATT_ALARMS = "alarms"; - private static final String ALLOW_ATT_MEDIA = "media_system_other"; private static final String ALLOW_ATT_CALLS = "calls"; private static final String ALLOW_ATT_REPEAT_CALLERS = "repeatCallers"; private static final String ALLOW_ATT_MESSAGES = "messages"; @@ -105,6 +100,8 @@ public class ZenModeConfig implements Parcelable { private static final String ALLOW_ATT_SCREEN_OFF = "visualScreenOff"; private static final String ALLOW_ATT_SCREEN_ON = "visualScreenOn"; + private static final String CONDITION_TAG = "condition"; + private static final String CONDITION_ATT_COMPONENT = "component"; private static final String CONDITION_ATT_ID = "id"; private static final String CONDITION_ATT_SUMMARY = "summary"; private static final String CONDITION_ATT_LINE1 = "line1"; @@ -126,8 +123,6 @@ public class ZenModeConfig implements Parcelable { private static final String RULE_ATT_CREATION_TIME = "creationTime"; private static final String RULE_ATT_ENABLER = "enabler"; - public boolean allowAlarms = DEFAULT_ALLOW_ALARMS; - public boolean allowMediaSystemOther = DEFAULT_ALLOW_MEDIA_SYSTEM_OTHER; public boolean allowCalls = DEFAULT_ALLOW_CALLS; public boolean allowRepeatCallers = DEFAULT_ALLOW_REPEAT_CALLERS; public boolean allowMessages = DEFAULT_ALLOW_MESSAGES; @@ -166,8 +161,6 @@ public class ZenModeConfig implements Parcelable { } allowWhenScreenOff = source.readInt() == 1; allowWhenScreenOn = source.readInt() == 1; - allowAlarms = source.readInt() == 1; - allowMediaSystemOther = source.readInt() == 1; } @Override @@ -197,23 +190,19 @@ public class ZenModeConfig implements Parcelable { } dest.writeInt(allowWhenScreenOff ? 1 : 0); dest.writeInt(allowWhenScreenOn ? 1 : 0); - dest.writeInt(allowAlarms ? 1 : 0); - dest.writeInt(allowMediaSystemOther ? 1 : 0); } @Override public String toString() { return new StringBuilder(ZenModeConfig.class.getSimpleName()).append('[') .append("user=").append(user) - .append(",allowAlarms=").append(allowAlarms) - .append(",allowMediaSystemOther=").append(allowMediaSystemOther) - .append(",allowReminders=").append(allowReminders) - .append(",allowEvents=").append(allowEvents) .append(",allowCalls=").append(allowCalls) .append(",allowRepeatCallers=").append(allowRepeatCallers) .append(",allowMessages=").append(allowMessages) .append(",allowCallsFrom=").append(sourceToString(allowCallsFrom)) .append(",allowMessagesFrom=").append(sourceToString(allowMessagesFrom)) + .append(",allowReminders=").append(allowReminders) + .append(",allowEvents=").append(allowEvents) .append(",allowWhenScreenOff=").append(allowWhenScreenOff) .append(",allowWhenScreenOn=").append(allowWhenScreenOn) .append(",automaticRules=").append(automaticRules) @@ -229,21 +218,9 @@ public class ZenModeConfig implements Parcelable { if (user != to.user) { d.addLine("user", user, to.user); } - if (allowAlarms != to.allowAlarms) { - d.addLine("allowAlarms", allowAlarms, to.allowAlarms); - } - if (allowMediaSystemOther != to.allowMediaSystemOther) { - d.addLine("allowMediaSystemOther", allowMediaSystemOther, to.allowMediaSystemOther); - } if (allowCalls != to.allowCalls) { d.addLine("allowCalls", allowCalls, to.allowCalls); } - if (allowReminders != to.allowReminders) { - d.addLine("allowReminders", allowReminders, to.allowReminders); - } - if (allowEvents != to.allowEvents) { - d.addLine("allowEvents", allowEvents, to.allowEvents); - } if (allowRepeatCallers != to.allowRepeatCallers) { d.addLine("allowRepeatCallers", allowRepeatCallers, to.allowRepeatCallers); } @@ -256,6 +233,12 @@ public class ZenModeConfig implements Parcelable { if (allowMessagesFrom != to.allowMessagesFrom) { d.addLine("allowMessagesFrom", allowMessagesFrom, to.allowMessagesFrom); } + if (allowReminders != to.allowReminders) { + d.addLine("allowReminders", allowReminders, to.allowReminders); + } + if (allowEvents != to.allowEvents) { + d.addLine("allowEvents", allowEvents, to.allowEvents); + } if (allowWhenScreenOff != to.allowWhenScreenOff) { d.addLine("allowWhenScreenOff", allowWhenScreenOff, to.allowWhenScreenOff); } @@ -352,9 +335,7 @@ public class ZenModeConfig implements Parcelable { if (!(o instanceof ZenModeConfig)) return false; if (o == this) return true; final ZenModeConfig other = (ZenModeConfig) o; - return other.allowAlarms == allowAlarms - && other.allowMediaSystemOther == allowMediaSystemOther - && other.allowCalls == allowCalls + return other.allowCalls == allowCalls && other.allowRepeatCallers == allowRepeatCallers && other.allowMessages == allowMessages && other.allowCallsFrom == allowCallsFrom @@ -370,10 +351,10 @@ public class ZenModeConfig implements Parcelable { @Override public int hashCode() { - return Objects.hash(allowAlarms, allowMediaSystemOther, allowCalls, - allowRepeatCallers, allowMessages, - allowCallsFrom, allowMessagesFrom, allowReminders, allowEvents, - allowWhenScreenOff, allowWhenScreenOn, user, automaticRules, manualRule); + return Objects.hash(allowCalls, allowRepeatCallers, allowMessages, allowCallsFrom, + allowMessagesFrom, allowReminders, allowEvents, allowWhenScreenOff, + allowWhenScreenOn, + user, automaticRules, manualRule); } private static String toDayList(int[] days) { @@ -432,12 +413,10 @@ public class ZenModeConfig implements Parcelable { } if (type == XmlPullParser.START_TAG) { if (ALLOW_TAG.equals(tag)) { - rt.allowCalls = safeBoolean(parser, ALLOW_ATT_CALLS, - DEFAULT_ALLOW_CALLS); + rt.allowCalls = safeBoolean(parser, ALLOW_ATT_CALLS, false); rt.allowRepeatCallers = safeBoolean(parser, ALLOW_ATT_REPEAT_CALLERS, DEFAULT_ALLOW_REPEAT_CALLERS); - rt.allowMessages = safeBoolean(parser, ALLOW_ATT_MESSAGES, - DEFAULT_ALLOW_MESSAGES); + rt.allowMessages = safeBoolean(parser, ALLOW_ATT_MESSAGES, false); rt.allowReminders = safeBoolean(parser, ALLOW_ATT_REMINDERS, DEFAULT_ALLOW_REMINDERS); rt.allowEvents = safeBoolean(parser, ALLOW_ATT_EVENTS, DEFAULT_ALLOW_EVENTS); @@ -459,9 +438,6 @@ public class ZenModeConfig implements Parcelable { safeBoolean(parser, ALLOW_ATT_SCREEN_OFF, DEFAULT_ALLOW_SCREEN_OFF); rt.allowWhenScreenOn = safeBoolean(parser, ALLOW_ATT_SCREEN_ON, DEFAULT_ALLOW_SCREEN_ON); - rt.allowAlarms = safeBoolean(parser, ALLOW_ATT_ALARMS, DEFAULT_ALLOW_ALARMS); - rt.allowMediaSystemOther = safeBoolean(parser, ALLOW_ATT_MEDIA, - DEFAULT_ALLOW_MEDIA_SYSTEM_OTHER); } else if (MANUAL_TAG.equals(tag)) { rt.manualRule = readRuleXml(parser); } else if (AUTOMATIC_TAG.equals(tag)) { @@ -492,8 +468,6 @@ public class ZenModeConfig implements Parcelable { out.attribute(null, ALLOW_ATT_MESSAGES_FROM, Integer.toString(allowMessagesFrom)); out.attribute(null, ALLOW_ATT_SCREEN_OFF, Boolean.toString(allowWhenScreenOff)); out.attribute(null, ALLOW_ATT_SCREEN_ON, Boolean.toString(allowWhenScreenOn)); - out.attribute(null, ALLOW_ATT_ALARMS, Boolean.toString(allowAlarms)); - out.attribute(null, ALLOW_ATT_ALARMS, Boolean.toString(allowMediaSystemOther)); out.endTag(null, ALLOW_TAG); if (manualRule != null) { @@ -680,12 +654,6 @@ public class ZenModeConfig implements Parcelable { if (!allowWhenScreenOn) { suppressedVisualEffects |= Policy.SUPPRESSED_EFFECT_SCREEN_ON; } - if (allowAlarms) { - priorityCategories |= Policy.PRIORITY_CATEGORY_ALARMS; - } - if (allowMediaSystemOther) { - priorityCategories |= Policy.PRIORITY_CATEGORY_MEDIA_SYSTEM_OTHER; - } priorityCallSenders = sourceToPrioritySenders(allowCallsFrom, priorityCallSenders); priorityMessageSenders = sourceToPrioritySenders(allowMessagesFrom, priorityMessageSenders); return new Policy(priorityCategories, priorityCallSenders, priorityMessageSenders, @@ -712,13 +680,10 @@ public class ZenModeConfig implements Parcelable { public void applyNotificationPolicy(Policy policy) { if (policy == null) return; - allowAlarms = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_ALARMS) != 0; - allowMediaSystemOther = (policy.priorityCategories - & Policy.PRIORITY_CATEGORY_MEDIA_SYSTEM_OTHER) != 0; - allowEvents = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_EVENTS) != 0; - allowReminders = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_REMINDERS) != 0; allowCalls = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_CALLS) != 0; allowMessages = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_MESSAGES) != 0; + allowEvents = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_EVENTS) != 0; + allowReminders = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_REMINDERS) != 0; allowRepeatCallers = (policy.priorityCategories & Policy.PRIORITY_CATEGORY_REPEAT_CALLERS) != 0; allowCallsFrom = prioritySendersToSource(policy.priorityCallSenders, allowCallsFrom); diff --git a/android/slice/Slice.java b/android/slice/Slice.java new file mode 100644 index 00000000..57686548 --- /dev/null +++ b/android/slice/Slice.java @@ -0,0 +1,347 @@ +/* + * Copyright (C) 2017 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.slice; + +import static android.slice.SliceItem.TYPE_ACTION; +import static android.slice.SliceItem.TYPE_COLOR; +import static android.slice.SliceItem.TYPE_IMAGE; +import static android.slice.SliceItem.TYPE_REMOTE_INPUT; +import static android.slice.SliceItem.TYPE_REMOTE_VIEW; +import static android.slice.SliceItem.TYPE_SLICE; +import static android.slice.SliceItem.TYPE_TEXT; +import static android.slice.SliceItem.TYPE_TIMESTAMP; + +import android.annotation.NonNull; +import android.annotation.StringDef; +import android.app.PendingIntent; +import android.app.RemoteInput; +import android.graphics.drawable.Icon; +import android.net.Uri; +import android.os.Parcel; +import android.os.Parcelable; +import android.widget.RemoteViews; + +import com.android.internal.util.ArrayUtils; + +import java.util.ArrayList; +import java.util.Arrays; + +/** + * A slice is a piece of app content and actions that can be surfaced outside of the app. + * + *

    They are constructed using {@link Builder} in a tree structure + * that provides the OS some information about how the content should be displayed. + * @hide + */ +public final class Slice implements Parcelable { + + /** + * @hide + */ + @StringDef({HINT_TITLE, HINT_LIST, HINT_LIST_ITEM, HINT_LARGE, HINT_ACTIONS, HINT_SELECTED, + HINT_SOURCE, HINT_MESSAGE, HINT_HORIZONTAL, HINT_NO_TINT}) + public @interface SliceHint{ } + + /** + * Hint that this content is a title of other content in the slice. + */ + public static final String HINT_TITLE = "title"; + /** + * Hint that all sub-items/sub-slices within this content should be considered + * to have {@link #HINT_LIST_ITEM}. + */ + public static final String HINT_LIST = "list"; + /** + * Hint that this item is part of a list and should be formatted as if is part + * of a list. + */ + public static final String HINT_LIST_ITEM = "list_item"; + /** + * Hint that this content is important and should be larger when displayed if + * possible. + */ + public static final String HINT_LARGE = "large"; + /** + * Hint that this slice contains a number of actions that can be grouped together + * in a sort of controls area of the UI. + */ + public static final String HINT_ACTIONS = "actions"; + /** + * Hint indicating that this item (and its sub-items) are the current selection. + */ + public static final String HINT_SELECTED = "selected"; + /** + * Hint to indicate that this is a message as part of a communication + * sequence in this slice. + */ + public static final String HINT_MESSAGE = "message"; + /** + * Hint to tag the source (i.e. sender) of a {@link #HINT_MESSAGE}. + */ + public static final String HINT_SOURCE = "source"; + /** + * Hint that list items within this slice or subslice would appear better + * if organized horizontally. + */ + public static final String HINT_HORIZONTAL = "horizontal"; + /** + * Hint to indicate that this content should not be tinted. + */ + public static final String HINT_NO_TINT = "no_tint"; + + // These two are coming over from prototyping, but we probably don't want in + // public API, at least not right now. + /** + * @hide + */ + public static final String HINT_ALT = "alt"; + /** + * @hide + */ + public static final String HINT_PARTIAL = "partial"; + + private final SliceItem[] mItems; + private final @SliceHint String[] mHints; + private Uri mUri; + + /** + * @hide + */ + public Slice(ArrayList items, @SliceHint String[] hints, Uri uri) { + mHints = hints; + mItems = items.toArray(new SliceItem[items.size()]); + mUri = uri; + } + + protected Slice(Parcel in) { + mHints = in.readStringArray(); + int n = in.readInt(); + mItems = new SliceItem[n]; + for (int i = 0; i < n; i++) { + mItems[i] = SliceItem.CREATOR.createFromParcel(in); + } + mUri = Uri.CREATOR.createFromParcel(in); + } + + /** + * @return The Uri that this Slice represents. + */ + public Uri getUri() { + return mUri; + } + + /** + * @return All child {@link SliceItem}s that this Slice contains. + */ + public SliceItem[] getItems() { + return mItems; + } + + /** + * @return All hints associated with this Slice. + */ + public @SliceHint String[] getHints() { + return mHints; + } + + /** + * @hide + */ + public SliceItem getPrimaryIcon() { + for (SliceItem item : getItems()) { + if (item.getType() == TYPE_IMAGE) { + return item; + } + if (!(item.getType() == TYPE_SLICE && item.hasHint(Slice.HINT_LIST)) + && !item.hasHint(Slice.HINT_ACTIONS) + && !item.hasHint(Slice.HINT_LIST_ITEM) + && (item.getType() != TYPE_ACTION)) { + SliceItem icon = SliceQuery.find(item, TYPE_IMAGE); + if (icon != null) return icon; + } + } + return null; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeStringArray(mHints); + dest.writeInt(mItems.length); + for (int i = 0; i < mItems.length; i++) { + mItems[i].writeToParcel(dest, flags); + } + mUri.writeToParcel(dest, 0); + } + + @Override + public int describeContents() { + return 0; + } + + /** + * @hide + */ + public boolean hasHint(@SliceHint String hint) { + return ArrayUtils.contains(mHints, hint); + } + + /** + * A Builder used to construct {@link Slice}s + */ + public static class Builder { + + private final Uri mUri; + private ArrayList mItems = new ArrayList<>(); + private @SliceHint ArrayList mHints = new ArrayList<>(); + + /** + * Create a builder which will construct a {@link Slice} for the Given Uri. + * @param uri Uri to tag for this slice. + */ + public Builder(@NonNull Uri uri) { + mUri = uri; + } + + /** + * Create a builder for a {@link Slice} that is a sub-slice of the slice + * being constructed by the provided builder. + * @param parent The builder constructing the parent slice + */ + public Builder(@NonNull Slice.Builder parent) { + mUri = parent.mUri.buildUpon().appendPath("_gen") + .appendPath(String.valueOf(mItems.size())).build(); + } + + /** + * Add hints to the Slice being constructed + */ + public Builder addHints(@SliceHint String... hints) { + mHints.addAll(Arrays.asList(hints)); + return this; + } + + /** + * Add a sub-slice to the slice being constructed + */ + public Builder addSubSlice(@NonNull Slice slice) { + mItems.add(new SliceItem(slice, TYPE_SLICE, slice.getHints())); + return this; + } + + /** + * Add an action to the slice being constructed + */ + public Slice.Builder addAction(@NonNull PendingIntent action, @NonNull Slice s) { + mItems.add(new SliceItem(action, s, TYPE_ACTION, new String[0])); + return this; + } + + /** + * Add text to the slice being constructed + */ + public Builder addText(CharSequence text, @SliceHint String... hints) { + mItems.add(new SliceItem(text, TYPE_TEXT, hints)); + return this; + } + + /** + * Add an image to the slice being constructed + */ + public Builder addIcon(Icon icon, @SliceHint String... hints) { + mItems.add(new SliceItem(icon, TYPE_IMAGE, hints)); + return this; + } + + /** + * @hide This isn't final + */ + public Builder addRemoteView(RemoteViews remoteView, @SliceHint String... hints) { + mItems.add(new SliceItem(remoteView, TYPE_REMOTE_VIEW, hints)); + return this; + } + + /** + * Add remote input to the slice being constructed + */ + public Slice.Builder addRemoteInput(RemoteInput remoteInput, @SliceHint String... hints) { + mItems.add(new SliceItem(remoteInput, TYPE_REMOTE_INPUT, hints)); + return this; + } + + /** + * Add a color to the slice being constructed + */ + public Builder addColor(int color, @SliceHint String... hints) { + mItems.add(new SliceItem(color, TYPE_COLOR, hints)); + return this; + } + + /** + * Add a timestamp to the slice being constructed + */ + public Slice.Builder addTimestamp(long time, @SliceHint String... hints) { + mItems.add(new SliceItem(time, TYPE_TIMESTAMP, hints)); + return this; + } + + /** + * Construct the slice. + */ + public Slice build() { + return new Slice(mItems, mHints.toArray(new String[mHints.size()]), mUri); + } + } + + public static final Creator CREATOR = new Creator() { + @Override + public Slice createFromParcel(Parcel in) { + return new Slice(in); + } + + @Override + public Slice[] newArray(int size) { + return new Slice[size]; + } + }; + + /** + * @hide + * @return A string representation of this slice. + */ + public String getString() { + return getString(""); + } + + private String getString(String indent) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < mItems.length; i++) { + sb.append(indent); + if (mItems[i].getType() == TYPE_SLICE) { + sb.append("slice:\n"); + sb.append(mItems[i].getSlice().getString(indent + " ")); + } else if (mItems[i].getType() == TYPE_TEXT) { + sb.append("text: "); + sb.append(mItems[i].getText()); + sb.append("\n"); + } else { + sb.append(SliceItem.typeToString(mItems[i].getType())); + sb.append("\n"); + } + } + return sb.toString(); + } +} diff --git a/android/slice/SliceItem.java b/android/slice/SliceItem.java new file mode 100644 index 00000000..2827ab9d --- /dev/null +++ b/android/slice/SliceItem.java @@ -0,0 +1,344 @@ +/* + * Copyright (C) 2017 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.slice; + +import android.annotation.IntDef; +import android.annotation.NonNull; +import android.app.PendingIntent; +import android.app.RemoteInput; +import android.graphics.drawable.Icon; +import android.os.Parcel; +import android.os.Parcelable; +import android.slice.Slice.SliceHint; +import android.text.TextUtils; +import android.util.Pair; +import android.widget.RemoteViews; + +import com.android.internal.util.ArrayUtils; + + +/** + * A SliceItem is a single unit in the tree structure of a {@link Slice}. + * + * A SliceItem a piece of content and some hints about what that content + * means or how it should be displayed. The types of content can be: + *

  • {@link #TYPE_SLICE}
  • + *
  • {@link #TYPE_TEXT}
  • + *
  • {@link #TYPE_IMAGE}
  • + *
  • {@link #TYPE_ACTION}
  • + *
  • {@link #TYPE_COLOR}
  • + *
  • {@link #TYPE_TIMESTAMP}
  • + *
  • {@link #TYPE_REMOTE_INPUT}
  • + * + * The hints that a {@link SliceItem} are a set of strings which annotate + * the content. The hints that are guaranteed to be understood by the system + * are defined on {@link Slice}. + * @hide + */ +public final class SliceItem implements Parcelable { + + /** + * @hide + */ + @IntDef({TYPE_SLICE, TYPE_TEXT, TYPE_IMAGE, TYPE_ACTION, TYPE_COLOR, + TYPE_TIMESTAMP, TYPE_REMOTE_INPUT}) + public @interface SliceType {} + + /** + * A {@link SliceItem} that contains a {@link Slice} + */ + public static final int TYPE_SLICE = 1; + /** + * A {@link SliceItem} that contains a {@link CharSequence} + */ + public static final int TYPE_TEXT = 2; + /** + * A {@link SliceItem} that contains an {@link Icon} + */ + public static final int TYPE_IMAGE = 3; + /** + * A {@link SliceItem} that contains a {@link PendingIntent} + * + * Note: Actions contain 2 pieces of data, In addition to the pending intent, the + * item contains a {@link Slice} that the action applies to. + */ + public static final int TYPE_ACTION = 4; + /** + * @hide This isn't final + */ + public static final int TYPE_REMOTE_VIEW = 5; + /** + * A {@link SliceItem} that contains a Color int. + */ + public static final int TYPE_COLOR = 6; + /** + * A {@link SliceItem} that contains a timestamp. + */ + public static final int TYPE_TIMESTAMP = 8; + /** + * A {@link SliceItem} that contains a {@link RemoteInput}. + */ + public static final int TYPE_REMOTE_INPUT = 9; + + /** + * @hide + */ + protected @SliceHint String[] mHints; + private final int mType; + private final Object mObj; + + /** + * @hide + */ + public SliceItem(Object obj, @SliceType int type, @SliceHint String[] hints) { + mHints = hints; + mType = type; + mObj = obj; + } + + /** + * @hide + */ + public SliceItem(PendingIntent intent, Slice slice, int type, @SliceHint String[] hints) { + this(new Pair<>(intent, slice), type, hints); + } + + /** + * Gets all hints associated with this SliceItem. + * @return Array of hints. + */ + public @NonNull @SliceHint String[] getHints() { + return mHints; + } + + /** + * @hide + */ + public void addHint(@SliceHint String hint) { + mHints = ArrayUtils.appendElement(String.class, mHints, hint); + } + + /** + * @hide + */ + public void removeHint(String hint) { + ArrayUtils.removeElement(String.class, mHints, hint); + } + + public @SliceType int getType() { + return mType; + } + + /** + * @return The text held by this {@link #TYPE_TEXT} SliceItem + */ + public CharSequence getText() { + return (CharSequence) mObj; + } + + /** + * @return The icon held by this {@link #TYPE_IMAGE} SliceItem + */ + public Icon getIcon() { + return (Icon) mObj; + } + + /** + * @return The pending intent held by this {@link #TYPE_ACTION} SliceItem + */ + public PendingIntent getAction() { + return ((Pair) mObj).first; + } + + /** + * @hide This isn't final + */ + public RemoteViews getRemoteView() { + return (RemoteViews) mObj; + } + + /** + * @return The remote input held by this {@link #TYPE_REMOTE_INPUT} SliceItem + */ + public RemoteInput getRemoteInput() { + return (RemoteInput) mObj; + } + + /** + * @return The color held by this {@link #TYPE_COLOR} SliceItem + */ + public int getColor() { + return (Integer) mObj; + } + + /** + * @return The slice held by this {@link #TYPE_ACTION} or {@link #TYPE_SLICE} SliceItem + */ + public Slice getSlice() { + if (getType() == TYPE_ACTION) { + return ((Pair) mObj).second; + } + return (Slice) mObj; + } + + /** + * @return The timestamp held by this {@link #TYPE_TIMESTAMP} SliceItem + */ + public long getTimestamp() { + return (Long) mObj; + } + + /** + * @param hint The hint to check for + * @return true if this item contains the given hint + */ + public boolean hasHint(@SliceHint String hint) { + return ArrayUtils.contains(mHints, hint); + } + + /** + * @hide + */ + public SliceItem(Parcel in) { + mHints = in.readStringArray(); + mType = in.readInt(); + mObj = readObj(mType, in); + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeStringArray(mHints); + dest.writeInt(mType); + writeObj(dest, flags, mObj, mType); + } + + /** + * @hide + */ + public boolean hasHints(@SliceHint String[] hints) { + if (hints == null) return true; + for (String hint : hints) { + if (!TextUtils.isEmpty(hint) && !ArrayUtils.contains(mHints, hint)) { + return false; + } + } + return true; + } + + /** + * @hide + */ + public boolean hasAnyHints(@SliceHint String[] hints) { + if (hints == null) return false; + for (String hint : hints) { + if (ArrayUtils.contains(mHints, hint)) { + return true; + } + } + return false; + } + + private void writeObj(Parcel dest, int flags, Object obj, int type) { + switch (type) { + case TYPE_SLICE: + case TYPE_REMOTE_VIEW: + case TYPE_IMAGE: + case TYPE_REMOTE_INPUT: + ((Parcelable) obj).writeToParcel(dest, flags); + break; + case TYPE_ACTION: + ((Pair) obj).first.writeToParcel(dest, flags); + ((Pair) obj).second.writeToParcel(dest, flags); + break; + case TYPE_TEXT: + TextUtils.writeToParcel((CharSequence) mObj, dest, flags); + break; + case TYPE_COLOR: + dest.writeInt((Integer) mObj); + break; + case TYPE_TIMESTAMP: + dest.writeLong((Long) mObj); + break; + } + } + + private static Object readObj(int type, Parcel in) { + switch (type) { + case TYPE_SLICE: + return Slice.CREATOR.createFromParcel(in); + case TYPE_TEXT: + return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); + case TYPE_IMAGE: + return Icon.CREATOR.createFromParcel(in); + case TYPE_ACTION: + return new Pair( + PendingIntent.CREATOR.createFromParcel(in), + Slice.CREATOR.createFromParcel(in)); + case TYPE_REMOTE_VIEW: + return RemoteViews.CREATOR.createFromParcel(in); + case TYPE_COLOR: + return in.readInt(); + case TYPE_TIMESTAMP: + return in.readLong(); + case TYPE_REMOTE_INPUT: + return RemoteInput.CREATOR.createFromParcel(in); + } + throw new RuntimeException("Unsupported type " + type); + } + + public static final Creator CREATOR = new Creator() { + @Override + public SliceItem createFromParcel(Parcel in) { + return new SliceItem(in); + } + + @Override + public SliceItem[] newArray(int size) { + return new SliceItem[size]; + } + }; + + /** + * @hide + */ + public static String typeToString(int type) { + switch (type) { + case TYPE_SLICE: + return "Slice"; + case TYPE_TEXT: + return "Text"; + case TYPE_IMAGE: + return "Image"; + case TYPE_ACTION: + return "Action"; + case TYPE_REMOTE_VIEW: + return "RemoteView"; + case TYPE_COLOR: + return "Color"; + case TYPE_TIMESTAMP: + return "Timestamp"; + case TYPE_REMOTE_INPUT: + return "RemoteInput"; + } + return "Unrecognized type: " + type; + } +} diff --git a/android/slice/SliceProvider.java b/android/slice/SliceProvider.java new file mode 100644 index 00000000..4e21371b --- /dev/null +++ b/android/slice/SliceProvider.java @@ -0,0 +1,156 @@ +/* + * Copyright (C) 2017 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.slice; + +import android.Manifest.permission; +import android.content.ContentProvider; +import android.content.ContentResolver; +import android.content.ContentValues; +import android.database.ContentObserver; +import android.database.Cursor; +import android.net.Uri; +import android.os.Bundle; +import android.os.CancellationSignal; +import android.os.Handler; +import android.os.Looper; +import android.util.Log; + +import java.util.concurrent.CountDownLatch; + +/** + * A SliceProvider allows app to provide content to be displayed in system + * spaces. This content is templated and can contain actions, and the behavior + * of how it is surfaced is specific to the system surface. + * + *

    Slices are not currently live content. They are bound once and shown to the + * user. If the content changes due to a callback from user interaction, then + * {@link ContentResolver#notifyChange(Uri, ContentObserver)} + * should be used to notify the system.

    + * + *

    The provider needs to be declared in the manifest to provide the authority + * for the app. The authority for most slices is expected to match the package + * of the application.

    + *
    + * {@literal
    + * }
    + * 
    + * + * @see Slice + * @hide + */ +public abstract class SliceProvider extends ContentProvider { + + private static final String TAG = "SliceProvider"; + /** + * @hide + */ + public static final String EXTRA_BIND_URI = "slice_uri"; + /** + * @hide + */ + public static final String METHOD_SLICE = "bind_slice"; + /** + * @hide + */ + public static final String EXTRA_SLICE = "slice"; + + private static final boolean DEBUG = false; + + /** + * Implemented to create a slice. Will be called on the main thread. + * @see {@link Slice}. + */ + public abstract Slice onBindSlice(Uri sliceUri); + + @Override + public final int update(Uri uri, ContentValues values, String selection, + String[] selectionArgs) { + if (DEBUG) Log.d(TAG, "update " + uri); + return 0; + } + + @Override + public final int delete(Uri uri, String selection, String[] selectionArgs) { + if (DEBUG) Log.d(TAG, "delete " + uri); + return 0; + } + + @Override + public final Cursor query(Uri uri, String[] projection, String selection, + String[] selectionArgs, String sortOrder) { + if (DEBUG) Log.d(TAG, "query " + uri); + return null; + } + + @Override + public final Cursor query(Uri uri, String[] projection, String selection, String[] + selectionArgs, String sortOrder, CancellationSignal cancellationSignal) { + if (DEBUG) Log.d(TAG, "query " + uri); + return null; + } + + @Override + public final Cursor query(Uri uri, String[] projection, Bundle queryArgs, + CancellationSignal cancellationSignal) { + if (DEBUG) Log.d(TAG, "query " + uri); + return null; + } + + @Override + public final Uri insert(Uri uri, ContentValues values) { + if (DEBUG) Log.d(TAG, "insert " + uri); + return null; + } + + @Override + public final String getType(Uri uri) { + if (DEBUG) Log.d(TAG, "getType " + uri); + return null; + } + + @Override + public final Bundle call(String method, String arg, Bundle extras) { + if (method.equals(METHOD_SLICE)) { + getContext().enforceCallingPermission(permission.BIND_SLICE, + "Slice binding requires the permission BIND_SLICE"); + Uri uri = extras.getParcelable(EXTRA_BIND_URI); + + Slice s = handleBindSlice(uri); + Bundle b = new Bundle(); + b.putParcelable(EXTRA_SLICE, s); + return b; + } + return super.call(method, arg, extras); + } + + private Slice handleBindSlice(Uri sliceUri) { + Slice[] output = new Slice[1]; + CountDownLatch latch = new CountDownLatch(1); + Handler mainHandler = new Handler(Looper.getMainLooper()); + mainHandler.post(() -> { + output[0] = onBindSlice(sliceUri); + latch.countDown(); + }); + try { + latch.await(); + return output[0]; + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } +} diff --git a/android/slice/SliceQuery.java b/android/slice/SliceQuery.java new file mode 100644 index 00000000..d99b26a5 --- /dev/null +++ b/android/slice/SliceQuery.java @@ -0,0 +1,151 @@ +/* + * Copyright (C) 2017 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.slice; + +import static android.slice.SliceItem.TYPE_ACTION; +import static android.slice.SliceItem.TYPE_SLICE; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; +import java.util.Spliterators; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +/** + * A bunch of utilities for searching the contents of a slice. + * @hide + */ +public class SliceQuery { + private static final String TAG = "SliceQuery"; + + /** + * @hide + */ + public static SliceItem findNotContaining(SliceItem container, List list) { + SliceItem ret = null; + while (ret == null && list.size() != 0) { + SliceItem remove = list.remove(0); + if (!contains(container, remove)) { + ret = remove; + } + } + return ret; + } + + /** + * @hide + */ + private static boolean contains(SliceItem container, SliceItem item) { + if (container == null || item == null) return false; + return stream(container).filter(s -> (s == item)).findAny().isPresent(); + } + + /** + * @hide + */ + public static List findAll(SliceItem s, int type) { + return findAll(s, type, (String[]) null, null); + } + + /** + * @hide + */ + public static List findAll(SliceItem s, int type, String hints, String nonHints) { + return findAll(s, type, new String[]{ hints }, new String[]{ nonHints }); + } + + /** + * @hide + */ + public static List findAll(SliceItem s, int type, String[] hints, + String[] nonHints) { + return stream(s).filter(item -> (type == -1 || item.getType() == type) + && (item.hasHints(hints) && !item.hasAnyHints(nonHints))) + .collect(Collectors.toList()); + } + + /** + * @hide + */ + public static SliceItem find(Slice s, int type, String hints, String nonHints) { + return find(s, type, new String[]{ hints }, new String[]{ nonHints }); + } + + /** + * @hide + */ + public static SliceItem find(Slice s, int type) { + return find(s, type, (String[]) null, null); + } + + /** + * @hide + */ + public static SliceItem find(SliceItem s, int type) { + return find(s, type, (String[]) null, null); + } + + /** + * @hide + */ + public static SliceItem find(SliceItem s, int type, String hints, String nonHints) { + return find(s, type, new String[]{ hints }, new String[]{ nonHints }); + } + + /** + * @hide + */ + public static SliceItem find(Slice s, int type, String[] hints, String[] nonHints) { + return find(new SliceItem(s, TYPE_SLICE, s.getHints()), type, hints, nonHints); + } + + /** + * @hide + */ + public static SliceItem find(SliceItem s, int type, String[] hints, String[] nonHints) { + return stream(s).filter(item -> (item.getType() == type || type == -1) + && (item.hasHints(hints) && !item.hasAnyHints(nonHints))).findFirst().orElse(null); + } + + /** + * @hide + */ + public static Stream stream(SliceItem slice) { + Queue items = new LinkedList(); + items.add(slice); + Iterator iterator = new Iterator() { + @Override + public boolean hasNext() { + return items.size() != 0; + } + + @Override + public SliceItem next() { + SliceItem item = items.poll(); + if (item.getType() == TYPE_SLICE || item.getType() == TYPE_ACTION) { + items.addAll(Arrays.asList(item.getSlice().getItems())); + } + return item; + } + }; + return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false); + } +} diff --git a/android/slice/views/ActionRow.java b/android/slice/views/ActionRow.java new file mode 100644 index 00000000..93e9c035 --- /dev/null +++ b/android/slice/views/ActionRow.java @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2017 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.slice.views; + +import android.app.PendingIntent; +import android.app.PendingIntent.CanceledException; +import android.app.RemoteInput; +import android.content.Context; +import android.content.res.ColorStateList; +import android.graphics.Color; +import android.graphics.drawable.Icon; +import android.os.AsyncTask; +import android.slice.Slice; +import android.slice.SliceItem; +import android.slice.SliceQuery; +import android.util.TypedValue; +import android.view.View; +import android.view.ViewParent; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.ImageView.ScaleType; +import android.widget.LinearLayout; +import android.widget.TextView; + +/** + * @hide + */ +public class ActionRow extends FrameLayout { + + private static final int MAX_ACTIONS = 5; + private final int mSize; + private final int mIconPadding; + private final LinearLayout mActionsGroup; + private final boolean mFullActions; + private int mColor = Color.BLACK; + + public ActionRow(Context context, boolean fullActions) { + super(context); + mFullActions = fullActions; + mSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, + context.getResources().getDisplayMetrics()); + mIconPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 12, + context.getResources().getDisplayMetrics()); + mActionsGroup = new LinearLayout(context); + mActionsGroup.setOrientation(LinearLayout.HORIZONTAL); + mActionsGroup.setLayoutParams( + new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); + addView(mActionsGroup); + } + + private void setColor(int color) { + mColor = color; + for (int i = 0; i < mActionsGroup.getChildCount(); i++) { + View view = mActionsGroup.getChildAt(i); + SliceItem item = (SliceItem) view.getTag(); + boolean tint = !item.hasHint(Slice.HINT_NO_TINT); + if (tint) { + ((ImageView) view).setImageTintList(ColorStateList.valueOf(mColor)); + } + } + } + + private ImageView addAction(Icon icon, boolean allowTint, SliceItem image) { + ImageView imageView = new ImageView(getContext()); + imageView.setPadding(mIconPadding, mIconPadding, mIconPadding, mIconPadding); + imageView.setScaleType(ScaleType.FIT_CENTER); + imageView.setImageIcon(icon); + if (allowTint) { + imageView.setImageTintList(ColorStateList.valueOf(mColor)); + } + imageView.setBackground(SliceViewUtil.getDrawable(getContext(), + android.R.attr.selectableItemBackground)); + imageView.setTag(image); + addAction(imageView); + return imageView; + } + + /** + * Set the actions and color for this action row. + */ + public void setActions(SliceItem actionRow, SliceItem defColor) { + removeAllViews(); + mActionsGroup.removeAllViews(); + addView(mActionsGroup); + + SliceItem color = SliceQuery.find(actionRow, SliceItem.TYPE_COLOR); + if (color == null) { + color = defColor; + } + if (color != null) { + setColor(color.getColor()); + } + SliceQuery.findAll(actionRow, SliceItem.TYPE_ACTION).forEach(action -> { + if (mActionsGroup.getChildCount() >= MAX_ACTIONS) { + return; + } + SliceItem image = SliceQuery.find(action, SliceItem.TYPE_IMAGE); + if (image == null) { + return; + } + boolean tint = !image.hasHint(Slice.HINT_NO_TINT); + SliceItem input = SliceQuery.find(action, SliceItem.TYPE_REMOTE_INPUT); + if (input != null && input.getRemoteInput().getAllowFreeFormInput()) { + addAction(image.getIcon(), tint, image).setOnClickListener( + v -> handleRemoteInputClick(v, action.getAction(), input.getRemoteInput())); + createRemoteInputView(mColor, getContext()); + } else { + addAction(image.getIcon(), tint, image).setOnClickListener(v -> AsyncTask.execute( + () -> { + try { + action.getAction().send(); + } catch (CanceledException e) { + e.printStackTrace(); + } + })); + } + }); + setVisibility(getChildCount() != 0 ? View.VISIBLE : View.GONE); + } + + private void addAction(View child) { + mActionsGroup.addView(child, new LinearLayout.LayoutParams(mSize, mSize, 1)); + } + + private void createRemoteInputView(int color, Context context) { + View riv = RemoteInputView.inflate(context, this); + riv.setVisibility(View.INVISIBLE); + addView(riv, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); + riv.setBackgroundColor(color); + } + + private boolean handleRemoteInputClick(View view, PendingIntent pendingIntent, + RemoteInput input) { + if (input == null) { + return false; + } + + ViewParent p = view.getParent().getParent(); + RemoteInputView riv = null; + while (p != null) { + if (p instanceof View) { + View pv = (View) p; + riv = findRemoteInputView(pv); + if (riv != null) { + break; + } + } + p = p.getParent(); + } + if (riv == null) { + return false; + } + + int width = view.getWidth(); + if (view instanceof TextView) { + // Center the reveal on the text which might be off-center from the TextView + TextView tv = (TextView) view; + if (tv.getLayout() != null) { + int innerWidth = (int) tv.getLayout().getLineWidth(0); + innerWidth += tv.getCompoundPaddingLeft() + tv.getCompoundPaddingRight(); + width = Math.min(width, innerWidth); + } + } + int cx = view.getLeft() + width / 2; + int cy = view.getTop() + view.getHeight() / 2; + int w = riv.getWidth(); + int h = riv.getHeight(); + int r = Math.max( + Math.max(cx + cy, cx + (h - cy)), + Math.max((w - cx) + cy, (w - cx) + (h - cy))); + + riv.setRevealParameters(cx, cy, r); + riv.setPendingIntent(pendingIntent); + riv.setRemoteInput(new RemoteInput[] { + input + }, input); + riv.focusAnimated(); + return true; + } + + private RemoteInputView findRemoteInputView(View v) { + if (v == null) { + return null; + } + return (RemoteInputView) v.findViewWithTag(RemoteInputView.VIEW_TAG); + } +} diff --git a/android/slice/views/GridView.java b/android/slice/views/GridView.java new file mode 100644 index 00000000..18a90f7d --- /dev/null +++ b/android/slice/views/GridView.java @@ -0,0 +1,186 @@ +/* + * Copyright (C) 2017 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.slice.views; + +import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; +import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; + +import android.content.Context; +import android.graphics.Color; +import android.slice.Slice; +import android.slice.SliceItem; +import android.slice.views.LargeSliceAdapter.SliceListView; +import android.util.AttributeSet; +import android.util.TypedValue; +import android.view.Gravity; +import android.view.LayoutInflater; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.ImageView; +import android.widget.ImageView.ScaleType; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.android.internal.R; + +import java.util.ArrayList; +import java.util.Arrays; + +/** + * @hide + */ +public class GridView extends LinearLayout implements SliceListView { + + private static final String TAG = "GridView"; + + private static final int MAX_IMAGES = 3; + private static final int MAX_ALL = 5; + private boolean mIsAllImages; + + public GridView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + if (mIsAllImages) { + int width = MeasureSpec.getSize(widthMeasureSpec); + int height = width / getChildCount(); + heightMeasureSpec = MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY, + height); + getLayoutParams().height = height; + for (int i = 0; i < getChildCount(); i++) { + getChildAt(i).getLayoutParams().height = height; + } + } + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + } + + @Override + public void setSliceItem(SliceItem slice) { + mIsAllImages = true; + removeAllViews(); + int total = 1; + if (slice.getType() == SliceItem.TYPE_SLICE) { + SliceItem[] items = slice.getSlice().getItems(); + total = items.length; + for (int i = 0; i < total; i++) { + SliceItem item = items[i]; + if (isFull()) { + continue; + } + if (!addItem(item)) { + mIsAllImages = false; + } + } + } else { + if (!isFull()) { + if (!addItem(slice)) { + mIsAllImages = false; + } + } + } + if (total > getChildCount() && mIsAllImages) { + addExtraCount(total - getChildCount()); + } + } + + private void addExtraCount(int numExtra) { + View last = getChildAt(getChildCount() - 1); + FrameLayout frame = new FrameLayout(getContext()); + frame.setLayoutParams(last.getLayoutParams()); + + removeView(last); + frame.addView(last, new LayoutParams(MATCH_PARENT, MATCH_PARENT)); + + TextView v = new TextView(getContext()); + v.setTextColor(Color.WHITE); + v.setBackgroundColor(0x4d000000); + v.setText(getResources().getString(R.string.slice_more_content, numExtra)); + v.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); + v.setGravity(Gravity.CENTER); + frame.addView(v, new LayoutParams(MATCH_PARENT, MATCH_PARENT)); + + addView(frame); + } + + private boolean isFull() { + return getChildCount() >= (mIsAllImages ? MAX_IMAGES : MAX_ALL); + } + + /** + * Returns true if this item is just an image. + */ + private boolean addItem(SliceItem item) { + if (item.getType() == SliceItem.TYPE_IMAGE) { + ImageView v = new ImageView(getContext()); + v.setImageIcon(item.getIcon()); + v.setScaleType(ScaleType.CENTER_CROP); + addView(v, new LayoutParams(0, MATCH_PARENT, 1)); + return true; + } else { + LinearLayout v = new LinearLayout(getContext()); + int s = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, + 12, getContext().getResources().getDisplayMetrics()); + v.setPadding(0, s, 0, 0); + v.setOrientation(LinearLayout.VERTICAL); + v.setGravity(Gravity.CENTER_HORIZONTAL); + // TODO: Unify sporadic inflates that happen throughout the code. + ArrayList items = new ArrayList<>(); + if (item.getType() == SliceItem.TYPE_SLICE) { + items.addAll(Arrays.asList(item.getSlice().getItems())); + } + items.forEach(i -> { + Context context = getContext(); + switch (i.getType()) { + case SliceItem.TYPE_TEXT: + boolean title = false; + if ((item.hasAnyHints(new String[] { + Slice.HINT_LARGE, Slice.HINT_TITLE + }))) { + title = true; + } + TextView tv = (TextView) LayoutInflater.from(context).inflate( + title ? R.layout.slice_title : R.layout.slice_secondary_text, null); + tv.setText(i.getText()); + v.addView(tv); + break; + case SliceItem.TYPE_IMAGE: + ImageView iv = new ImageView(context); + iv.setImageIcon(i.getIcon()); + if (item.hasHint(Slice.HINT_LARGE)) { + iv.setLayoutParams(new LayoutParams(WRAP_CONTENT, WRAP_CONTENT)); + } else { + int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, + 48, context.getResources().getDisplayMetrics()); + iv.setLayoutParams(new LayoutParams(size, size)); + } + v.addView(iv); + break; + case SliceItem.TYPE_REMOTE_VIEW: + v.addView(i.getRemoteView().apply(context, v)); + break; + case SliceItem.TYPE_COLOR: + // TODO: Support color to tint stuff here. + break; + } + }); + addView(v, new LayoutParams(0, WRAP_CONTENT, 1)); + return false; + } + } +} diff --git a/android/slice/views/LargeSliceAdapter.java b/android/slice/views/LargeSliceAdapter.java new file mode 100644 index 00000000..e77a1b2a --- /dev/null +++ b/android/slice/views/LargeSliceAdapter.java @@ -0,0 +1,224 @@ +/* + * Copyright (C) 2017 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.slice.views; + +import android.content.Context; +import android.slice.Slice; +import android.slice.SliceItem; +import android.slice.SliceQuery; +import android.slice.views.LargeSliceAdapter.SliceViewHolder; +import android.util.ArrayMap; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewGroup.LayoutParams; +import android.widget.FrameLayout; + +import com.android.internal.R; +import com.android.internal.widget.RecyclerView; +import com.android.internal.widget.RecyclerView.ViewHolder; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * @hide + */ +public class LargeSliceAdapter extends RecyclerView.Adapter { + + public static final int TYPE_DEFAULT = 1; + public static final int TYPE_HEADER = 2; + public static final int TYPE_GRID = 3; + public static final int TYPE_MESSAGE = 4; + public static final int TYPE_MESSAGE_LOCAL = 5; + public static final int TYPE_REMOTE_VIEWS = 6; + + private final IdGenerator mIdGen = new IdGenerator(); + private final Context mContext; + private List mSlices = new ArrayList<>(); + private SliceItem mColor; + + public LargeSliceAdapter(Context context) { + mContext = context; + setHasStableIds(true); + } + + /** + * Set the {@link SliceItem}'s to be displayed in the adapter and the accent color. + */ + public void setSliceItems(List slices, SliceItem color) { + mColor = color; + mIdGen.resetUsage(); + mSlices = slices.stream().map(s -> new SliceWrapper(s, mIdGen)) + .collect(Collectors.toList()); + notifyDataSetChanged(); + } + + @Override + public SliceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + View v = inflateforType(viewType); + v.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); + return new SliceViewHolder(v); + } + + @Override + public int getItemViewType(int position) { + return mSlices.get(position).mType; + } + + @Override + public long getItemId(int position) { + return mSlices.get(position).mId; + } + + @Override + public int getItemCount() { + return mSlices.size(); + } + + @Override + public void onBindViewHolder(SliceViewHolder holder, int position) { + SliceWrapper slice = mSlices.get(position); + if (holder.mSliceView != null) { + holder.mSliceView.setColor(mColor); + holder.mSliceView.setSliceItem(slice.mItem); + } else if (slice.mType == TYPE_REMOTE_VIEWS) { + FrameLayout frame = (FrameLayout) holder.itemView; + frame.removeAllViews(); + frame.addView(slice.mItem.getRemoteView().apply(mContext, frame)); + } + } + + private View inflateforType(int viewType) { + switch (viewType) { + case TYPE_REMOTE_VIEWS: + return new FrameLayout(mContext); + case TYPE_GRID: + return LayoutInflater.from(mContext).inflate(R.layout.slice_grid, null); + case TYPE_MESSAGE: + return LayoutInflater.from(mContext).inflate(R.layout.slice_message, null); + case TYPE_MESSAGE_LOCAL: + return LayoutInflater.from(mContext).inflate(R.layout.slice_message_local, null); + } + return new SmallTemplateView(mContext); + } + + protected static class SliceWrapper { + private final SliceItem mItem; + private final int mType; + private final long mId; + + public SliceWrapper(SliceItem item, IdGenerator idGen) { + mItem = item; + mType = getType(item); + mId = idGen.getId(item); + } + + public static int getType(SliceItem item) { + if (item.getType() == SliceItem.TYPE_REMOTE_VIEW) { + return TYPE_REMOTE_VIEWS; + } + if (item.hasHint(Slice.HINT_MESSAGE)) { + // TODO: Better way to determine me or not? Something more like Messaging style. + if (SliceQuery.find(item, -1, Slice.HINT_SOURCE, null) != null) { + return TYPE_MESSAGE; + } else { + return TYPE_MESSAGE_LOCAL; + } + } + if (item.hasHint(Slice.HINT_HORIZONTAL)) { + return TYPE_GRID; + } + return TYPE_DEFAULT; + } + } + + /** + * A {@link ViewHolder} for presenting slices in {@link LargeSliceAdapter}. + */ + public static class SliceViewHolder extends ViewHolder { + public final SliceListView mSliceView; + + public SliceViewHolder(View itemView) { + super(itemView); + mSliceView = itemView instanceof SliceListView ? (SliceListView) itemView : null; + } + } + + /** + * View slices being displayed in {@link LargeSliceAdapter}. + */ + public interface SliceListView { + /** + * Set the slice item for this view. + */ + void setSliceItem(SliceItem slice); + + /** + * Set the color for the items in this view. + */ + default void setColor(SliceItem color) { + + } + } + + private static class IdGenerator { + private long mNextLong = 0; + private final ArrayMap mCurrentIds = new ArrayMap<>(); + private final ArrayMap mUsedIds = new ArrayMap<>(); + + public long getId(SliceItem item) { + String str = genString(item); + if (!mCurrentIds.containsKey(str)) { + mCurrentIds.put(str, mNextLong++); + } + long id = mCurrentIds.get(str); + int index = mUsedIds.getOrDefault(str, 0); + mUsedIds.put(str, index + 1); + return id + index * 10000; + } + + private String genString(SliceItem item) { + StringBuilder builder = new StringBuilder(); + SliceQuery.stream(item).forEach(i -> { + builder.append(i.getType()); + i.removeHint(Slice.HINT_SELECTED); + builder.append(i.getHints()); + switch (i.getType()) { + case SliceItem.TYPE_REMOTE_VIEW: + builder.append(i.getRemoteView()); + break; + case SliceItem.TYPE_IMAGE: + builder.append(i.getIcon()); + break; + case SliceItem.TYPE_TEXT: + builder.append(i.getText()); + break; + case SliceItem.TYPE_COLOR: + builder.append(i.getColor()); + break; + } + }); + return builder.toString(); + } + + public void resetUsage() { + mUsedIds.clear(); + } + } +} diff --git a/android/slice/views/LargeTemplateView.java b/android/slice/views/LargeTemplateView.java new file mode 100644 index 00000000..d53e8fcb --- /dev/null +++ b/android/slice/views/LargeTemplateView.java @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2017 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.slice.views; + +import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; + +import android.content.Context; +import android.slice.Slice; +import android.slice.SliceItem; +import android.slice.SliceQuery; +import android.slice.views.SliceView.SliceModeView; +import android.util.TypedValue; + +import com.android.internal.widget.LinearLayoutManager; +import com.android.internal.widget.RecyclerView; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * @hide + */ +public class LargeTemplateView extends SliceModeView { + private final LargeSliceAdapter mAdapter; + private final RecyclerView mRecyclerView; + private final int mDefaultHeight; + private final int mMaxHeight; + private Slice mSlice; + + public LargeTemplateView(Context context) { + super(context); + + mRecyclerView = new RecyclerView(getContext()); + mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); + mAdapter = new LargeSliceAdapter(context); + mRecyclerView.setAdapter(mAdapter); + addView(mRecyclerView); + int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 300, + getResources().getDisplayMetrics()); + setLayoutParams(new LayoutParams(width, WRAP_CONTENT)); + mDefaultHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, + getResources().getDisplayMetrics()); + mMaxHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, + getResources().getDisplayMetrics()); + } + + @Override + public String getMode() { + return SliceView.MODE_LARGE; + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + mRecyclerView.getLayoutParams().height = WRAP_CONTENT; + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + if (mRecyclerView.getMeasuredHeight() > mMaxHeight + || mSlice.hasHint(Slice.HINT_PARTIAL)) { + mRecyclerView.getLayoutParams().height = mDefaultHeight; + } else { + mRecyclerView.getLayoutParams().height = mRecyclerView.getMeasuredHeight(); + } + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + } + + @Override + public void setSlice(Slice slice) { + SliceItem color = SliceQuery.find(slice, SliceItem.TYPE_COLOR); + mSlice = slice; + List items = new ArrayList<>(); + boolean[] hasHeader = new boolean[1]; + if (slice.hasHint(Slice.HINT_LIST)) { + addList(slice, items); + } else { + Arrays.asList(slice.getItems()).forEach(item -> { + if (item.hasHint(Slice.HINT_ACTIONS)) { + return; + } else if (item.getType() == SliceItem.TYPE_COLOR) { + return; + } else if (item.getType() == SliceItem.TYPE_SLICE + && item.hasHint(Slice.HINT_LIST)) { + addList(item.getSlice(), items); + } else if (item.hasHint(Slice.HINT_LIST_ITEM)) { + items.add(item); + } else if (!hasHeader[0]) { + hasHeader[0] = true; + items.add(0, item); + } else { + item.addHint(Slice.HINT_LIST_ITEM); + items.add(item); + } + }); + } + mAdapter.setSliceItems(items, color); + } + + private void addList(Slice slice, List items) { + List sliceItems = Arrays.asList(slice.getItems()); + sliceItems.forEach(i -> i.addHint(Slice.HINT_LIST_ITEM)); + items.addAll(sliceItems); + } +} diff --git a/android/slice/views/MessageView.java b/android/slice/views/MessageView.java new file mode 100644 index 00000000..7b03e0bd --- /dev/null +++ b/android/slice/views/MessageView.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2017 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.slice.views; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.drawable.Drawable; +import android.slice.Slice; +import android.slice.SliceItem; +import android.slice.SliceQuery; +import android.slice.views.LargeSliceAdapter.SliceListView; +import android.text.SpannableStringBuilder; +import android.util.AttributeSet; +import android.util.TypedValue; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +/** + * @hide + */ +public class MessageView extends LinearLayout implements SliceListView { + + private TextView mDetails; + private ImageView mIcon; + + public MessageView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + @Override + protected void onFinishInflate() { + super.onFinishInflate(); + mDetails = findViewById(android.R.id.summary); + mIcon = findViewById(android.R.id.icon); + } + + @Override + public void setSliceItem(SliceItem slice) { + SliceItem source = SliceQuery.find(slice, SliceItem.TYPE_IMAGE, Slice.HINT_SOURCE, null); + if (source != null) { + final int iconSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, + 24, getContext().getResources().getDisplayMetrics()); + // TODO try and turn this into a drawable + Bitmap iconBm = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); + Canvas iconCanvas = new Canvas(iconBm); + Drawable d = source.getIcon().loadDrawable(getContext()); + d.setBounds(0, 0, iconSize, iconSize); + d.draw(iconCanvas); + mIcon.setImageBitmap(SliceViewUtil.getCircularBitmap(iconBm)); + } + SpannableStringBuilder builder = new SpannableStringBuilder(); + SliceQuery.findAll(slice, SliceItem.TYPE_TEXT).forEach(text -> { + if (builder.length() != 0) { + builder.append('\n'); + } + builder.append(text.getText()); + }); + mDetails.setText(builder.toString()); + } + +} diff --git a/android/slice/views/RemoteInputView.java b/android/slice/views/RemoteInputView.java new file mode 100644 index 00000000..a29bb5c0 --- /dev/null +++ b/android/slice/views/RemoteInputView.java @@ -0,0 +1,445 @@ +/* + * Copyright (C) 2017 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.slice.views; + +import android.animation.Animator; +import android.app.Notification; +import android.app.PendingIntent; +import android.app.RemoteInput; +import android.content.Context; +import android.content.Intent; +import android.content.pm.ShortcutManager; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.text.Editable; +import android.text.TextWatcher; +import android.util.AttributeSet; +import android.util.Log; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.view.ViewAnimationUtils; +import android.view.ViewGroup; +import android.view.accessibility.AccessibilityEvent; +import android.view.inputmethod.CompletionInfo; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputConnection; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import android.widget.ImageButton; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.TextView; +import android.widget.Toast; + +import com.android.internal.R; + +/** + * Host for the remote input. + * + * @hide + */ +// TODO this should be unified with SystemUI RemoteInputView (b/67527720) +public class RemoteInputView extends LinearLayout implements View.OnClickListener, TextWatcher { + + private static final String TAG = "RemoteInput"; + + /** + * A marker object that let's us easily find views of this class. + */ + public static final Object VIEW_TAG = new Object(); + + private RemoteEditText mEditText; + private ImageButton mSendButton; + private ProgressBar mProgressBar; + private PendingIntent mPendingIntent; + private RemoteInput[] mRemoteInputs; + private RemoteInput mRemoteInput; + + private int mRevealCx; + private int mRevealCy; + private int mRevealR; + private boolean mResetting; + + public RemoteInputView(Context context, AttributeSet attrs) { + super(context, attrs); + } + + @Override + protected void onFinishInflate() { + super.onFinishInflate(); + + mProgressBar = findViewById(R.id.remote_input_progress); + mSendButton = findViewById(R.id.remote_input_send); + mSendButton.setOnClickListener(this); + + mEditText = (RemoteEditText) getChildAt(0); + mEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { + @Override + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + final boolean isSoftImeEvent = event == null + && (actionId == EditorInfo.IME_ACTION_DONE + || actionId == EditorInfo.IME_ACTION_NEXT + || actionId == EditorInfo.IME_ACTION_SEND); + final boolean isKeyboardEnterKey = event != null + && KeyEvent.isConfirmKey(event.getKeyCode()) + && event.getAction() == KeyEvent.ACTION_DOWN; + + if (isSoftImeEvent || isKeyboardEnterKey) { + if (mEditText.length() > 0) { + sendRemoteInput(); + } + // Consume action to prevent IME from closing. + return true; + } + return false; + } + }); + mEditText.addTextChangedListener(this); + mEditText.setInnerFocusable(false); + mEditText.mRemoteInputView = this; + } + + private void sendRemoteInput() { + Bundle results = new Bundle(); + results.putString(mRemoteInput.getResultKey(), mEditText.getText().toString()); + Intent fillInIntent = new Intent().addFlags(Intent.FLAG_RECEIVER_FOREGROUND); + RemoteInput.addResultsToIntent(mRemoteInputs, fillInIntent, + results); + + mEditText.setEnabled(false); + mSendButton.setVisibility(INVISIBLE); + mProgressBar.setVisibility(VISIBLE); + mEditText.mShowImeOnInputConnection = false; + + // Tell ShortcutManager that this package has been "activated". ShortcutManager + // will reset the throttling for this package. + // Strictly speaking, the intent receiver may be different from the intent creator, + // but that's an edge case, and also because we can't always know which package will receive + // an intent, so we just reset for the creator. + getContext().getSystemService(ShortcutManager.class).onApplicationActive( + mPendingIntent.getCreatorPackage(), + getContext().getUserId()); + + try { + mPendingIntent.send(mContext, 0, fillInIntent); + reset(); + } catch (PendingIntent.CanceledException e) { + Log.i(TAG, "Unable to send remote input result", e); + Toast.makeText(mContext, "Failure sending pending intent for inline reply :(", + Toast.LENGTH_SHORT).show(); + reset(); + } + } + + /** + * Creates a remote input view. + */ + public static RemoteInputView inflate(Context context, ViewGroup root) { + RemoteInputView v = (RemoteInputView) LayoutInflater.from(context).inflate( + R.layout.slice_remote_input, root, false); + v.setTag(VIEW_TAG); + return v; + } + + @Override + public void onClick(View v) { + if (v == mSendButton) { + sendRemoteInput(); + } + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + super.onTouchEvent(event); + + // We never want for a touch to escape to an outer view or one we covered. + return true; + } + + private void onDefocus() { + setVisibility(INVISIBLE); + } + + /** + * Set the pending intent for remote input. + */ + public void setPendingIntent(PendingIntent pendingIntent) { + mPendingIntent = pendingIntent; + } + + /** + * Set the remote inputs for this view. + */ + public void setRemoteInput(RemoteInput[] remoteInputs, RemoteInput remoteInput) { + mRemoteInputs = remoteInputs; + mRemoteInput = remoteInput; + mEditText.setHint(mRemoteInput.getLabel()); + } + + /** + * Focuses the remote input view. + */ + public void focusAnimated() { + if (getVisibility() != VISIBLE) { + Animator animator = ViewAnimationUtils.createCircularReveal( + this, mRevealCx, mRevealCy, 0, mRevealR); + animator.setDuration(200); + animator.start(); + } + focus(); + } + + private void focus() { + setVisibility(VISIBLE); + mEditText.setInnerFocusable(true); + mEditText.mShowImeOnInputConnection = true; + mEditText.setSelection(mEditText.getText().length()); + mEditText.requestFocus(); + updateSendButton(); + } + + private void reset() { + mResetting = true; + + mEditText.getText().clear(); + mEditText.setEnabled(true); + mSendButton.setVisibility(VISIBLE); + mProgressBar.setVisibility(INVISIBLE); + updateSendButton(); + onDefocus(); + + mResetting = false; + } + + @Override + public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) { + if (mResetting && child == mEditText) { + // Suppress text events if it happens during resetting. Ideally this would be + // suppressed by the text view not being shown, but that doesn't work here because it + // needs to stay visible for the animation. + return false; + } + return super.onRequestSendAccessibilityEvent(child, event); + } + + private void updateSendButton() { + mSendButton.setEnabled(mEditText.getText().length() != 0); + } + + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } + + @Override + public void afterTextChanged(Editable s) { + updateSendButton(); + } + + /** + * Tries to find an action that matches the current pending intent of this view and updates its + * state to that of the found action + * + * @return true if a matching action was found, false otherwise + */ + public boolean updatePendingIntentFromActions(Notification.Action[] actions) { + if (mPendingIntent == null || actions == null) { + return false; + } + Intent current = mPendingIntent.getIntent(); + if (current == null) { + return false; + } + + for (Notification.Action a : actions) { + RemoteInput[] inputs = a.getRemoteInputs(); + if (a.actionIntent == null || inputs == null) { + continue; + } + Intent candidate = a.actionIntent.getIntent(); + if (!current.filterEquals(candidate)) { + continue; + } + + RemoteInput input = null; + for (RemoteInput i : inputs) { + if (i.getAllowFreeFormInput()) { + input = i; + } + } + if (input == null) { + continue; + } + setPendingIntent(a.actionIntent); + setRemoteInput(inputs, input); + return true; + } + return false; + } + + /** + * @hide + */ + public void setRevealParameters(int cx, int cy, int r) { + mRevealCx = cx; + mRevealCy = cy; + mRevealR = r; + } + + @Override + public void dispatchStartTemporaryDetach() { + super.dispatchStartTemporaryDetach(); + // Detach the EditText temporarily such that it doesn't get onDetachedFromWindow and + // won't lose IME focus. + detachViewFromParent(mEditText); + } + + @Override + public void dispatchFinishTemporaryDetach() { + if (isAttachedToWindow()) { + attachViewToParent(mEditText, 0, mEditText.getLayoutParams()); + } else { + removeDetachedView(mEditText, false /* animate */); + } + super.dispatchFinishTemporaryDetach(); + } + + /** + * An EditText that changes appearance based on whether it's focusable and becomes un-focusable + * whenever the user navigates away from it or it becomes invisible. + */ + public static class RemoteEditText extends EditText { + + private final Drawable mBackground; + private RemoteInputView mRemoteInputView; + boolean mShowImeOnInputConnection; + + public RemoteEditText(Context context, AttributeSet attrs) { + super(context, attrs); + mBackground = getBackground(); + } + + private void defocusIfNeeded(boolean animate) { + if (mRemoteInputView != null || isTemporarilyDetached()) { + if (isTemporarilyDetached()) { + // We might get reattached but then the other one of HUN / expanded might steal + // our focus, so we'll need to save our text here. + } + return; + } + if (isFocusable() && isEnabled()) { + setInnerFocusable(false); + if (mRemoteInputView != null) { + mRemoteInputView.onDefocus(); + } + mShowImeOnInputConnection = false; + } + } + + @Override + protected void onVisibilityChanged(View changedView, int visibility) { + super.onVisibilityChanged(changedView, visibility); + + if (!isShown()) { + defocusIfNeeded(false /* animate */); + } + } + + @Override + protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { + super.onFocusChanged(focused, direction, previouslyFocusedRect); + if (!focused) { + defocusIfNeeded(true /* animate */); + } + } + + @Override + public void getFocusedRect(Rect r) { + super.getFocusedRect(r); + r.top = mScrollY; + r.bottom = mScrollY + (mBottom - mTop); + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + // Eat the DOWN event here to prevent any default behavior. + return true; + } + return super.onKeyDown(keyCode, event); + } + + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + defocusIfNeeded(true /* animate */); + return true; + } + return super.onKeyUp(keyCode, event); + } + + @Override + public InputConnection onCreateInputConnection(EditorInfo outAttrs) { + final InputConnection inputConnection = super.onCreateInputConnection(outAttrs); + + if (mShowImeOnInputConnection && inputConnection != null) { + final InputMethodManager imm = InputMethodManager.getInstance(); + if (imm != null) { + // onCreateInputConnection is called by InputMethodManager in the middle of + // setting up the connection to the IME; wait with requesting the IME until that + // work has completed. + post(new Runnable() { + @Override + public void run() { + imm.viewClicked(RemoteEditText.this); + imm.showSoftInput(RemoteEditText.this, 0); + } + }); + } + } + + return inputConnection; + } + + @Override + public void onCommitCompletion(CompletionInfo text) { + clearComposingText(); + setText(text.getText()); + setSelection(getText().length()); + } + + void setInnerFocusable(boolean focusable) { + setFocusableInTouchMode(focusable); + setFocusable(focusable); + setCursorVisible(focusable); + + if (focusable) { + requestFocus(); + setBackground(mBackground); + } else { + setBackground(null); + } + + } + } +} diff --git a/android/slice/views/ShortcutView.java b/android/slice/views/ShortcutView.java new file mode 100644 index 00000000..8fe2f1ac --- /dev/null +++ b/android/slice/views/ShortcutView.java @@ -0,0 +1,110 @@ +/* + * Copyright (C) 2017 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.slice.views; + +import android.app.PendingIntent; +import android.app.PendingIntent.CanceledException; +import android.content.Context; +import android.content.Intent; +import android.graphics.Color; +import android.graphics.drawable.ShapeDrawable; +import android.graphics.drawable.shapes.OvalShape; +import android.net.Uri; +import android.slice.Slice; +import android.slice.SliceItem; +import android.slice.SliceQuery; +import android.slice.views.SliceView.SliceModeView; +import android.view.ViewGroup; + +import com.android.internal.R; + +/** + * @hide + */ +public class ShortcutView extends SliceModeView { + + private static final String TAG = "ShortcutView"; + + private PendingIntent mAction; + private Uri mUri; + private int mLargeIconSize; + private int mSmallIconSize; + + public ShortcutView(Context context) { + super(context); + mLargeIconSize = getContext().getResources() + .getDimensionPixelSize(R.dimen.slice_shortcut_size); + mSmallIconSize = getContext().getResources().getDimensionPixelSize(R.dimen.slice_icon_size); + setLayoutParams(new ViewGroup.LayoutParams(mLargeIconSize, mLargeIconSize)); + } + + @Override + public void setSlice(Slice slice) { + removeAllViews(); + SliceItem sliceItem = SliceQuery.find(slice, SliceItem.TYPE_ACTION); + SliceItem iconItem = slice.getPrimaryIcon(); + SliceItem textItem = sliceItem != null + ? SliceQuery.find(sliceItem, SliceItem.TYPE_TEXT) + : SliceQuery.find(slice, SliceItem.TYPE_TEXT); + SliceItem colorItem = sliceItem != null + ? SliceQuery.find(sliceItem, SliceItem.TYPE_COLOR) + : SliceQuery.find(slice, SliceItem.TYPE_COLOR); + if (colorItem == null) { + colorItem = SliceQuery.find(slice, SliceItem.TYPE_COLOR); + } + // TODO: pick better default colour + final int color = colorItem != null ? colorItem.getColor() : Color.GRAY; + ShapeDrawable circle = new ShapeDrawable(new OvalShape()); + circle.setTint(color); + setBackground(circle); + if (iconItem != null) { + final boolean isLarge = iconItem.hasHint(Slice.HINT_LARGE); + final int iconSize = isLarge ? mLargeIconSize : mSmallIconSize; + SliceViewUtil.createCircledIcon(getContext(), color, iconSize, iconItem.getIcon(), + isLarge, this /* parent */); + mAction = sliceItem != null ? sliceItem.getAction() + : null; + mUri = slice.getUri(); + setClickable(true); + } else { + setClickable(false); + } + } + + @Override + public String getMode() { + return SliceView.MODE_SHORTCUT; + } + + @Override + public boolean performClick() { + if (!callOnClick()) { + try { + if (mAction != null) { + mAction.send(); + } else { + Intent intent = new Intent(Intent.ACTION_VIEW).setData(mUri); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + getContext().startActivity(intent); + } + } catch (CanceledException e) { + e.printStackTrace(); + } + } + return true; + } +} diff --git a/android/slice/views/SliceView.java b/android/slice/views/SliceView.java new file mode 100644 index 00000000..f3792481 --- /dev/null +++ b/android/slice/views/SliceView.java @@ -0,0 +1,249 @@ +/* + * Copyright (C) 2017 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.slice.views; + +import android.annotation.StringDef; +import android.content.ContentResolver; +import android.content.Context; +import android.content.Intent; +import android.graphics.drawable.ColorDrawable; +import android.net.Uri; +import android.slice.Slice; +import android.slice.SliceItem; +import android.slice.SliceQuery; +import android.util.Log; +import android.view.MotionEvent; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.LinearLayout; + +/** + * A view that can display a {@link Slice} in different {@link SliceMode}'s. + * + * @hide + */ +public class SliceView extends LinearLayout { + + private static final String TAG = "SliceView"; + + /** + * @hide + */ + public abstract static class SliceModeView extends FrameLayout { + + public SliceModeView(Context context) { + super(context); + } + + /** + * @return the {@link SliceMode} of the slice being presented. + */ + public abstract String getMode(); + + /** + * @param slice the slice to show in this view. + */ + public abstract void setSlice(Slice slice); + } + + /** + * @hide + */ + @StringDef({ + MODE_SMALL, MODE_LARGE, MODE_SHORTCUT + }) + public @interface SliceMode {} + + /** + * Mode indicating this slice should be presented in small template format. + */ + public static final String MODE_SMALL = "SLICE_SMALL"; + /** + * Mode indicating this slice should be presented in large template format. + */ + public static final String MODE_LARGE = "SLICE_LARGE"; + /** + * Mode indicating this slice should be presented as an icon. + */ + public static final String MODE_SHORTCUT = "SLICE_ICON"; + + /** + * Will select the type of slice binding based on size of the View. TODO: Put in some info about + * that selection. + */ + private static final String MODE_AUTO = "auto"; + + private String mMode = MODE_AUTO; + private SliceModeView mCurrentView; + private final ActionRow mActions; + private Slice mCurrentSlice; + private boolean mShowActions = true; + + /** + * Simple constructor to create a slice view from code. + * + * @param context The context the view is running in. + */ + public SliceView(Context context) { + super(context); + setOrientation(LinearLayout.VERTICAL); + mActions = new ActionRow(mContext, true); + mActions.setBackground(new ColorDrawable(0xffeeeeee)); + mCurrentView = new LargeTemplateView(mContext); + addView(mCurrentView); + addView(mActions); + } + + /** + * @hide + */ + public void bindSlice(Intent intent) { + // TODO + } + + /** + * Binds this view to the {@link Slice} associated with the provided {@link Uri}. + */ + public void bindSlice(Uri sliceUri) { + validate(sliceUri); + Slice s = mContext.getContentResolver().bindSlice(sliceUri); + bindSlice(s); + } + + /** + * Binds this view to the provided {@link Slice}. + */ + public void bindSlice(Slice slice) { + mCurrentSlice = slice; + if (mCurrentSlice != null) { + reinflate(); + } + } + + /** + * Call to clean up the view. + */ + public void unbindSlice() { + mCurrentSlice = null; + } + + /** + * Set the {@link SliceMode} this view should present in. + */ + public void setMode(@SliceMode String mode) { + setMode(mode, false /* animate */); + } + + /** + * @hide + */ + public void setMode(@SliceMode String mode, boolean animate) { + if (animate) { + Log.e(TAG, "Animation not supported yet"); + } + mMode = mode; + reinflate(); + } + + /** + * @return the {@link SliceMode} this view is presenting in. + */ + public @SliceMode String getMode() { + if (mMode.equals(MODE_AUTO)) { + return MODE_LARGE; + } + return mMode; + } + + /** + * @hide + * + * Whether this view should show a row of actions with it. + */ + public void setShowActionRow(boolean show) { + mShowActions = show; + reinflate(); + } + + private SliceModeView createView(String mode) { + switch (mode) { + case MODE_SHORTCUT: + return new ShortcutView(getContext()); + case MODE_SMALL: + return new SmallTemplateView(getContext()); + } + return new LargeTemplateView(getContext()); + } + + @Override + protected void onDetachedFromWindow() { + super.onDetachedFromWindow(); + unbindSlice(); + } + + private void reinflate() { + if (mCurrentSlice == null) { + return; + } + // TODO: Smarter mapping here from one state to the next. + SliceItem color = SliceQuery.find(mCurrentSlice, SliceItem.TYPE_COLOR); + SliceItem[] items = mCurrentSlice.getItems(); + SliceItem actionRow = SliceQuery.find(mCurrentSlice, SliceItem.TYPE_SLICE, + Slice.HINT_ACTIONS, + Slice.HINT_ALT); + String mode = getMode(); + if (!mode.equals(mCurrentView.getMode())) { + removeAllViews(); + mCurrentView = createView(mode); + addView(mCurrentView); + addView(mActions); + } + if (items.length > 1 || (items.length != 0 && items[0] != actionRow)) { + mCurrentView.setVisibility(View.VISIBLE); + mCurrentView.setSlice(mCurrentSlice); + } else { + mCurrentView.setVisibility(View.GONE); + } + + boolean showActions = mShowActions && actionRow != null + && !mode.equals(MODE_SHORTCUT); + if (showActions) { + mActions.setActions(actionRow, color); + mActions.setVisibility(View.VISIBLE); + } else { + mActions.setVisibility(View.GONE); + } + } + + @Override + public boolean onInterceptTouchEvent(MotionEvent ev) { + // TODO -- may need to rethink for AGSA + if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) { + requestDisallowInterceptTouchEvent(true); + } + return super.onInterceptTouchEvent(ev); + } + + private static void validate(Uri sliceUri) { + if (!ContentResolver.SCHEME_SLICE.equals(sliceUri.getScheme())) { + throw new RuntimeException("Invalid uri " + sliceUri); + } + if (sliceUri.getPathSegments().size() == 0) { + throw new RuntimeException("Invalid uri " + sliceUri); + } + } +} diff --git a/android/slice/views/SliceViewUtil.java b/android/slice/views/SliceViewUtil.java new file mode 100644 index 00000000..1b5a6d1e --- /dev/null +++ b/android/slice/views/SliceViewUtil.java @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2017 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.slice.views; + +import android.annotation.ColorInt; +import android.content.Context; +import android.content.res.ColorStateList; +import android.content.res.TypedArray; +import android.graphics.Bitmap; +import android.graphics.Bitmap.Config; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Paint; +import android.graphics.PorterDuff.Mode; +import android.graphics.PorterDuffXfermode; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.graphics.drawable.Icon; +import android.view.Gravity; +import android.view.ViewGroup; +import android.widget.FrameLayout; +import android.widget.ImageView; + +/** + * A bunch of utilities for slice UI. + * + * @hide + */ +public class SliceViewUtil { + + /** + * @hide + */ + @ColorInt + public static int getColorAccent(Context context) { + return getColorAttr(context, android.R.attr.colorAccent); + } + + /** + * @hide + */ + @ColorInt + public static int getColorError(Context context) { + return getColorAttr(context, android.R.attr.colorError); + } + + /** + * @hide + */ + @ColorInt + public static int getDefaultColor(Context context, int resId) { + final ColorStateList list = context.getResources().getColorStateList(resId, + context.getTheme()); + + return list.getDefaultColor(); + } + + /** + * @hide + */ + @ColorInt + public static int getDisabled(Context context, int inputColor) { + return applyAlphaAttr(context, android.R.attr.disabledAlpha, inputColor); + } + + /** + * @hide + */ + @ColorInt + public static int applyAlphaAttr(Context context, int attr, int inputColor) { + TypedArray ta = context.obtainStyledAttributes(new int[] { + attr + }); + float alpha = ta.getFloat(0, 0); + ta.recycle(); + return applyAlpha(alpha, inputColor); + } + + /** + * @hide + */ + @ColorInt + public static int applyAlpha(float alpha, int inputColor) { + alpha *= Color.alpha(inputColor); + return Color.argb((int) (alpha), Color.red(inputColor), Color.green(inputColor), + Color.blue(inputColor)); + } + + /** + * @hide + */ + @ColorInt + public static int getColorAttr(Context context, int attr) { + TypedArray ta = context.obtainStyledAttributes(new int[] { + attr + }); + @ColorInt + int colorAccent = ta.getColor(0, 0); + ta.recycle(); + return colorAccent; + } + + /** + * @hide + */ + public static int getThemeAttr(Context context, int attr) { + TypedArray ta = context.obtainStyledAttributes(new int[] { + attr + }); + int theme = ta.getResourceId(0, 0); + ta.recycle(); + return theme; + } + + /** + * @hide + */ + public static Drawable getDrawable(Context context, int attr) { + TypedArray ta = context.obtainStyledAttributes(new int[] { + attr + }); + Drawable drawable = ta.getDrawable(0); + ta.recycle(); + return drawable; + } + + /** + * @hide + */ + public static void createCircledIcon(Context context, int color, int iconSize, Icon icon, + boolean isLarge, ViewGroup parent) { + ImageView v = new ImageView(context); + v.setImageIcon(icon); + parent.addView(v); + FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) v.getLayoutParams(); + if (isLarge) { + // XXX better way to convert from icon -> bitmap or crop an icon (?) + Bitmap iconBm = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); + Canvas iconCanvas = new Canvas(iconBm); + v.layout(0, 0, iconSize, iconSize); + v.draw(iconCanvas); + v.setImageBitmap(getCircularBitmap(iconBm)); + } else { + v.setColorFilter(Color.WHITE); + } + lp.width = iconSize; + lp.height = iconSize; + lp.gravity = Gravity.CENTER; + } + + /** + * @hide + */ + public static Bitmap getCircularBitmap(Bitmap bitmap) { + Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), + bitmap.getHeight(), Config.ARGB_8888); + Canvas canvas = new Canvas(output); + final Paint paint = new Paint(); + final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); + paint.setAntiAlias(true); + canvas.drawARGB(0, 0, 0, 0); + canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, + bitmap.getWidth() / 2, paint); + paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); + canvas.drawBitmap(bitmap, rect, rect, paint); + return output; + } +} diff --git a/android/slice/views/SmallTemplateView.java b/android/slice/views/SmallTemplateView.java new file mode 100644 index 00000000..b0b181ed --- /dev/null +++ b/android/slice/views/SmallTemplateView.java @@ -0,0 +1,211 @@ +/* + * Copyright (C) 2017 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.slice.views; + +import android.app.PendingIntent.CanceledException; +import android.content.Context; +import android.os.AsyncTask; +import android.slice.Slice; +import android.slice.SliceItem; +import android.slice.SliceQuery; +import android.slice.views.LargeSliceAdapter.SliceListView; +import android.slice.views.SliceView.SliceModeView; +import android.view.View; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.android.internal.R; + +import java.text.Format; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +/** + * Small template is also used to construct list items for use with {@link LargeTemplateView}. + * + * @hide + */ +public class SmallTemplateView extends SliceModeView implements SliceListView { + + private static final String TAG = "SmallTemplateView"; + + private int mIconSize; + private int mPadding; + + private LinearLayout mStartContainer; + private TextView mTitleText; + private TextView mSecondaryText; + private LinearLayout mEndContainer; + + public SmallTemplateView(Context context) { + super(context); + inflate(context, R.layout.slice_small_template, this); + mIconSize = getContext().getResources().getDimensionPixelSize(R.dimen.slice_icon_size); + mPadding = getContext().getResources().getDimensionPixelSize(R.dimen.slice_padding); + + mStartContainer = (LinearLayout) findViewById(android.R.id.icon_frame); + mTitleText = (TextView) findViewById(android.R.id.title); + mSecondaryText = (TextView) findViewById(android.R.id.summary); + mEndContainer = (LinearLayout) findViewById(android.R.id.widget_frame); + } + + @Override + public String getMode() { + return SliceView.MODE_SMALL; + } + + @Override + public void setSliceItem(SliceItem slice) { + resetViews(); + SliceItem colorItem = SliceQuery.find(slice, SliceItem.TYPE_COLOR); + int color = colorItem != null ? colorItem.getColor() : -1; + + // Look for any title elements + List titleItems = SliceQuery.findAll(slice, -1, Slice.HINT_TITLE, + null); + boolean hasTitleText = false; + boolean hasTitleItem = false; + for (int i = 0; i < titleItems.size(); i++) { + SliceItem item = titleItems.get(i); + if (!hasTitleItem) { + // icon, action icon, or timestamp + if (item.getType() == SliceItem.TYPE_ACTION) { + hasTitleItem = addIcon(item, color, mStartContainer); + } else if (item.getType() == SliceItem.TYPE_IMAGE) { + addIcon(item, color, mStartContainer); + hasTitleItem = true; + } else if (item.getType() == SliceItem.TYPE_TIMESTAMP) { + TextView tv = new TextView(getContext()); + tv.setText(convertTimeToString(item.getTimestamp())); + hasTitleItem = true; + } + } + if (!hasTitleText && item.getType() == SliceItem.TYPE_TEXT) { + mTitleText.setText(item.getText()); + hasTitleText = true; + } + if (hasTitleText && hasTitleItem) { + break; + } + } + mTitleText.setVisibility(hasTitleText ? View.VISIBLE : View.GONE); + mStartContainer.setVisibility(hasTitleItem ? View.VISIBLE : View.GONE); + + if (slice.getType() != SliceItem.TYPE_SLICE) { + return; + } + + // Deal with remaining items + int itemCount = 0; + boolean hasSummary = false; + ArrayList sliceItems = new ArrayList( + Arrays.asList(slice.getSlice().getItems())); + for (int i = 0; i < sliceItems.size(); i++) { + SliceItem item = sliceItems.get(i); + if (!hasSummary && item.getType() == SliceItem.TYPE_TEXT + && !item.hasHint(Slice.HINT_TITLE)) { + // TODO -- Should combine all text items? + mSecondaryText.setText(item.getText()); + hasSummary = true; + } + if (itemCount <= 3) { + if (item.getType() == SliceItem.TYPE_ACTION) { + if (addIcon(item, color, mEndContainer)) { + itemCount++; + } + } else if (item.getType() == SliceItem.TYPE_IMAGE) { + addIcon(item, color, mEndContainer); + itemCount++; + } else if (item.getType() == SliceItem.TYPE_TIMESTAMP) { + TextView tv = new TextView(getContext()); + tv.setText(convertTimeToString(item.getTimestamp())); + mEndContainer.addView(tv); + itemCount++; + } else if (item.getType() == SliceItem.TYPE_SLICE) { + SliceItem[] subItems = item.getSlice().getItems(); + for (int j = 0; j < subItems.length; j++) { + sliceItems.add(subItems[j]); + } + } + } + } + } + + @Override + public void setSlice(Slice slice) { + setSliceItem(new SliceItem(slice, SliceItem.TYPE_SLICE, slice.getHints())); + } + + /** + * @return Whether an icon was added. + */ + private boolean addIcon(SliceItem sliceItem, int color, LinearLayout container) { + SliceItem image = null; + SliceItem action = null; + if (sliceItem.getType() == SliceItem.TYPE_ACTION) { + image = SliceQuery.find(sliceItem.getSlice(), SliceItem.TYPE_IMAGE); + action = sliceItem; + } else if (sliceItem.getType() == SliceItem.TYPE_IMAGE) { + image = sliceItem; + } + if (image != null) { + ImageView iv = new ImageView(getContext()); + iv.setImageIcon(image.getIcon()); + if (action != null) { + final SliceItem sliceAction = action; + iv.setOnClickListener(v -> AsyncTask.execute( + () -> { + try { + sliceAction.getAction().send(); + } catch (CanceledException e) { + e.printStackTrace(); + } + })); + iv.setBackground(SliceViewUtil.getDrawable(getContext(), + android.R.attr.selectableItemBackground)); + } + if (color != -1 && !sliceItem.hasHint(Slice.HINT_NO_TINT)) { + iv.setColorFilter(color); + } + container.addView(iv); + LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) iv.getLayoutParams(); + lp.width = mIconSize; + lp.height = mIconSize; + lp.setMarginStart(mPadding); + return true; + } + return false; + } + + private String convertTimeToString(long time) { + // TODO -- figure out what format(s) we support + Date date = new Date(time); + Format format = new SimpleDateFormat("MM dd yyyy HH:mm:ss"); + return format.format(date); + } + + private void resetViews() { + mStartContainer.removeAllViews(); + mEndContainer.removeAllViews(); + mTitleText.setText(null); + mSecondaryText.setText(null); + } +} diff --git a/android/support/LibraryVersions.java b/android/support/LibraryVersions.java index 72f7fb18..a046d95e 100644 --- a/android/support/LibraryVersions.java +++ b/android/support/LibraryVersions.java @@ -45,17 +45,15 @@ public class LibraryVersions { */ public static final Version PAGING = new Version("1.0.0-alpha3"); - private static final Version LIFECYCLES = new Version("1.0.2"); - /** * Version code for Lifecycle libs that are required by the support library */ - public static final Version LIFECYCLES_CORE = LIFECYCLES; + public static final Version LIFECYCLES_CORE = new Version("1.0.2"); /** * Version code for Lifecycle runtime libs that are required by the support library */ - public static final Version LIFECYCLES_RUNTIME = LIFECYCLES; + public static final Version LIFECYCLES_RUNTIME = new Version("1.0.0"); /** * Version code for shared code of flatfoot diff --git a/android/support/car/drawer/CarDrawerActivity.java b/android/support/car/drawer/CarDrawerActivity.java deleted file mode 100644 index 7100218a..00000000 --- a/android/support/car/drawer/CarDrawerActivity.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright (C) 2017 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.support.car.drawer; - -import android.content.res.Configuration; -import android.os.Bundle; -import android.support.annotation.LayoutRes; -import android.support.annotation.Nullable; -import android.support.car.R; -import android.support.v4.widget.DrawerLayout; -import android.support.v7.app.ActionBarDrawerToggle; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.Toolbar; -import android.view.LayoutInflater; -import android.view.MenuItem; -import android.view.View; -import android.view.ViewGroup; - -/** - * Common base Activity for car apps that need to present a Drawer. - * - *

    This Activity manages the overall layout. To use it, sub-classes need to: - * - *

      - *
    • Provide the root-items for the Drawer by implementing {@link #getRootAdapter()}. - *
    • Add their main content using {@link #setMainContent(int)} or {@link #setMainContent(View)}. - * They can also add fragments to the main-content container by obtaining its id using - * {@link #getContentContainerId()} - *
    - * - *

    This class will take care of drawer toggling and display. - * - *

    The rootAdapter can implement nested-navigation, in its click-handling, by passing the - * CarDrawerAdapter for the next level to - * {@link CarDrawerController#switchToAdapter(CarDrawerAdapter)}. - * - *

    Any Activity's based on this class need to set their theme to CarDrawerActivityTheme or a - * derivative. - */ -public abstract class CarDrawerActivity extends AppCompatActivity { - private CarDrawerController mDrawerController; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setContentView(R.layout.car_drawer_activity); - - DrawerLayout drawerLayout = findViewById(R.id.drawer_layout); - ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle( - this /* activity */, - drawerLayout, /* DrawerLayout object */ - R.string.car_drawer_open, - R.string.car_drawer_close); - - Toolbar toolbar = findViewById(R.id.car_toolbar); - setSupportActionBar(toolbar); - - mDrawerController = new CarDrawerController(toolbar, drawerLayout, drawerToggle); - mDrawerController.setRootAdapter(getRootAdapter()); - - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setHomeButtonEnabled(true); - } - - /** - * Returns the {@link CarDrawerController} that is responsible for handling events relating - * to the drawer in this Activity. - * - * @return The {@link CarDrawerController} linked to this Activity. This value will be - * {@code null} if this method is called before {@code onCreate()} has been called. - */ - @Nullable - protected CarDrawerController getDrawerController() { - return mDrawerController; - } - - @Override - protected void onPostCreate(Bundle savedInstanceState) { - super.onPostCreate(savedInstanceState); - mDrawerController.syncState(); - } - - /** - * @return Adapter for root content of the Drawer. - */ - protected abstract CarDrawerAdapter getRootAdapter(); - - /** - * Set main content to display in this Activity. It will be added to R.id.content_frame in - * car_drawer_activity.xml. NOTE: Do not use {@link #setContentView(View)}. - * - * @param view View to display as main content. - */ - public void setMainContent(View view) { - ViewGroup parent = findViewById(getContentContainerId()); - parent.addView(view); - } - - /** - * Set main content to display in this Activity. It will be added to R.id.content_frame in - * car_drawer_activity.xml. NOTE: Do not use {@link #setContentView(int)}. - * - * @param resourceId Layout to display as main content. - */ - public void setMainContent(@LayoutRes int resourceId) { - ViewGroup parent = findViewById(getContentContainerId()); - LayoutInflater inflater = getLayoutInflater(); - inflater.inflate(resourceId, parent, true); - } - - /** - * Get the id of the main content Container which is a FrameLayout. Subclasses can add their own - * content/fragments inside here. - * - * @return Id of FrameLayout where main content of the subclass Activity can be added. - */ - protected int getContentContainerId() { - return R.id.content_frame; - } - - @Override - protected void onStop() { - super.onStop(); - mDrawerController.closeDrawer(); - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - mDrawerController.onConfigurationChanged(newConfig); - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - return mDrawerController.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); - } -} diff --git a/android/support/car/drawer/CarDrawerAdapter.java b/android/support/car/drawer/CarDrawerAdapter.java deleted file mode 100644 index b0fd965d..00000000 --- a/android/support/car/drawer/CarDrawerAdapter.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (C) 2017 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.support.car.drawer; - -import android.content.Context; -import android.graphics.PorterDuff; -import android.graphics.drawable.Drawable; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.car.R; -import android.support.car.widget.PagedListView; -import android.support.v7.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -/** - * Base adapter for displaying items in the car navigation drawer, which uses a - * {@link PagedListView}. - * - *

    Subclasses must set the title that will be displayed when displaying the contents of the - * drawer via {@link #setTitle(CharSequence)}. The title can be updated at any point later on. The - * title of the root adapter will also be the main title showed in the toolbar when the drawer is - * closed. See {@link CarDrawerController#setRootAdapter(CarDrawerAdapter)} for more information. - * - *

    This class also takes care of implementing the PageListView.ItemCamp contract and subclasses - * should implement {@link #getActualItemCount()}. - */ -public abstract class CarDrawerAdapter extends RecyclerView.Adapter - implements PagedListView.ItemCap, DrawerItemClickListener { - private final boolean mShowDisabledListOnEmpty; - private final Drawable mEmptyListDrawable; - private int mMaxItems = PagedListView.ItemCap.UNLIMITED; - private CharSequence mTitle; - private TitleChangeListener mTitleChangeListener; - - /** - * Interface for a class that will be notified a new title has been set on this adapter. - */ - interface TitleChangeListener { - /** - * Called when {@link #setTitle(CharSequence)} has been called and the title has been - * changed. - */ - void onTitleChanged(CharSequence newTitle); - } - - protected CarDrawerAdapter(Context context, boolean showDisabledListOnEmpty) { - mShowDisabledListOnEmpty = showDisabledListOnEmpty; - - mEmptyListDrawable = context.getDrawable(R.drawable.ic_list_view_disable); - mEmptyListDrawable.setColorFilter(context.getColor(R.color.car_tint), - PorterDuff.Mode.SRC_IN); - } - - /** Returns the title set via {@link #setTitle(CharSequence)}. */ - CharSequence getTitle() { - return mTitle; - } - - /** Updates the title to display in the toolbar for this Adapter. */ - public final void setTitle(@NonNull CharSequence title) { - if (title == null) { - throw new IllegalArgumentException("setTitle() cannot be passed a null title!"); - } - - mTitle = title; - - if (mTitleChangeListener != null) { - mTitleChangeListener.onTitleChanged(mTitle); - } - } - - /** Sets a listener to be notified whenever the title of this adapter has been changed. */ - void setTitleChangeListener(@Nullable TitleChangeListener listener) { - mTitleChangeListener = listener; - } - - @Override - public final void setMaxItems(int maxItems) { - mMaxItems = maxItems; - } - - @Override - public final int getItemCount() { - if (shouldShowDisabledListItem()) { - return 1; - } - return mMaxItems >= 0 ? Math.min(mMaxItems, getActualItemCount()) : getActualItemCount(); - } - - /** - * Returns the absolute number of items that can be displayed in the list. - * - *

    A class should implement this method to supply the number of items to be displayed. - * Returning 0 from this method will cause an empty list icon to be displayed in the drawer. - * - *

    A class should override this method rather than {@link #getItemCount()} because that - * method is handling the logic of when to display the empty list icon. It will return 1 when - * {@link #getActualItemCount()} returns 0. - * - * @return The number of items to be displayed in the list. - */ - protected abstract int getActualItemCount(); - - @Override - public final int getItemViewType(int position) { - if (shouldShowDisabledListItem()) { - return R.layout.car_drawer_list_item_empty; - } - - return usesSmallLayout(position) - ? R.layout.car_drawer_list_item_small - : R.layout.car_drawer_list_item_normal; - } - - /** - * Used to indicate the layout used for the Drawer item at given position. Subclasses can - * override this to use normal layout which includes text element below title. - * - *

    A small layout is presented by the layout {@code R.layout.car_drawer_list_item_small}. - * Otherwise, the layout {@code R.layout.car_drawer_list_item_normal} will be used. - * - * @param position Adapter position of item. - * @return Whether the item at this position will use a small layout (default) or normal layout. - */ - protected boolean usesSmallLayout(int position) { - return true; - } - - @Override - public final DrawerItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - View view = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false); - return new DrawerItemViewHolder(view); - } - - @Override - public final void onBindViewHolder(DrawerItemViewHolder holder, int position) { - if (shouldShowDisabledListItem()) { - holder.getTitle().setText(null); - holder.getIcon().setImageDrawable(mEmptyListDrawable); - holder.setItemClickListener(null); - } else { - holder.setItemClickListener(this); - populateViewHolder(holder, position); - } - } - - /** - * Whether or not this adapter should be displaying an empty list icon. The icon is shown if it - * has been configured to show and there are no items to be displayed. - */ - private boolean shouldShowDisabledListItem() { - return mShowDisabledListOnEmpty && getActualItemCount() == 0; - } - - /** - * Subclasses should set all elements in {@code holder} to populate the drawer-item. If some - * element is not used, it should be nulled out since these ViewHolder/View's are recycled. - */ - protected abstract void populateViewHolder(DrawerItemViewHolder holder, int position); - - /** - * Called when this adapter has been popped off the stack and is no longer needed. Subclasses - * can override to do any necessary cleanup. - */ - public void cleanup() {} -} diff --git a/android/support/car/drawer/CarDrawerController.java b/android/support/car/drawer/CarDrawerController.java deleted file mode 100644 index 4d9f4e99..00000000 --- a/android/support/car/drawer/CarDrawerController.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (C) 2017 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.support.car.drawer; - -import android.content.Context; -import android.content.res.Configuration; -import android.os.Bundle; -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.car.R; -import android.support.car.widget.PagedListView; -import android.support.v4.widget.DrawerLayout; -import android.support.v7.app.ActionBarDrawerToggle; -import android.support.v7.widget.Toolbar; -import android.view.Gravity; -import android.view.MenuItem; -import android.view.View; -import android.widget.ProgressBar; - -import java.util.Stack; - -/** - * A controller that will handle the set up of the navigation drawer. It will hook up the - * necessary buttons for up navigation, as well as expose methods to allow for a drill down - * navigation. - */ -public class CarDrawerController { - /** The amount that the drawer has been opened before its color should be switched. */ - private static final float COLOR_SWITCH_SLIDE_OFFSET = 0.25f; - - /** - * A representation of the hierarchy of navigation being displayed in the list. The ordering of - * this stack is the order that the user has visited each level. When the user navigates up, - * the adapters are poopped from this list. - */ - private final Stack mAdapterStack = new Stack<>(); - - private final Context mContext; - - private final Toolbar mToolbar; - private final DrawerLayout mDrawerLayout; - private final ActionBarDrawerToggle mDrawerToggle; - - private final PagedListView mDrawerList; - private final ProgressBar mProgressBar; - private final View mDrawerContent; - - /** - * Creates a {@link CarDrawerController} that will control the navigation of the drawer given by - * {@code drawerLayout}. - * - *

    The given {@code drawerLayout} should either have a child View that is inflated from - * {@code R.layout.car_drawer} or ensure that it three children that have the IDs found in that - * layout. - * - * @param toolbar The {@link Toolbar} that will serve as the action bar for an Activity. - * @param drawerLayout The top-level container for the window content that shows the - * interactive drawer. - * @param drawerToggle The {@link ActionBarDrawerToggle} that bridges the given {@code toolbar} - * and {@code drawerLayout}. - */ - public CarDrawerController(Toolbar toolbar, - DrawerLayout drawerLayout, - ActionBarDrawerToggle drawerToggle) { - mToolbar = toolbar; - mContext = drawerLayout.getContext(); - - mDrawerLayout = drawerLayout; - - mDrawerContent = drawerLayout.findViewById(R.id.drawer_content); - mDrawerList = drawerLayout.findViewById(R.id.drawer_list); - mDrawerList.setMaxPages(PagedListView.ItemCap.UNLIMITED); - - mProgressBar = drawerLayout.findViewById(R.id.drawer_progress); - - mDrawerToggle = drawerToggle; - setupDrawerToggling(); - } - - /** - * Sets the {@link CarDrawerAdapter} that will function as the root adapter. The contents of - * this root adapter are shown when the drawer is first opened. It is also the top-most level of - * navigation in the drawer. - * - * @param rootAdapter The adapter that will act as the root. If this value is {@code null}, then - * this method will do nothing. - */ - public void setRootAdapter(@Nullable CarDrawerAdapter rootAdapter) { - if (rootAdapter == null) { - return; - } - - mAdapterStack.push(rootAdapter); - setToolbarTitleFrom(rootAdapter); - mDrawerList.setAdapter(rootAdapter); - } - - /** - * Switches to use the given {@link CarDrawerAdapter} as the one to supply the list to display - * in the navigation drawer. The title will also be updated from the adapter. - * - *

    This switch is treated as a navigation to the next level in the drawer. Navigation away - * from this level will pop the given adapter off and surface contents of the previous adapter - * that was set via this method. If no such adapter exists, then the root adapter set by - * {@link #setRootAdapter(CarDrawerAdapter)} will be used instead. - * - * @param adapter Adapter for next level of content in the drawer. - */ - public final void switchToAdapter(CarDrawerAdapter adapter) { - mAdapterStack.peek().setTitleChangeListener(null); - mAdapterStack.push(adapter); - switchToAdapterInternal(adapter); - } - - /** Close the drawer. */ - public void closeDrawer() { - if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { - mDrawerLayout.closeDrawer(Gravity.LEFT); - } - } - - /** Opens the drawer. */ - public void openDrawer() { - if (!mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { - mDrawerLayout.openDrawer(Gravity.LEFT); - } - } - - /** Sets a listener to be notified of Drawer events. */ - public void addDrawerListener(@NonNull DrawerLayout.DrawerListener listener) { - mDrawerLayout.addDrawerListener(listener); - } - - /** Removes a listener to be notified of Drawer events. */ - public void removeDrawerListener(@NonNull DrawerLayout.DrawerListener listener) { - mDrawerLayout.removeDrawerListener(listener); - } - - /** - * Sets whether the loading progress bar is displayed in the navigation drawer. If {@code true}, - * the progress bar is displayed and the navigation list is hidden and vice versa. - */ - public void showLoadingProgressBar(boolean show) { - mDrawerList.setVisibility(show ? View.INVISIBLE : View.VISIBLE); - mProgressBar.setVisibility(show ? View.VISIBLE : View.GONE); - } - - /** Scroll to given position in the list. */ - public void scrollToPosition(int position) { - mDrawerList.getRecyclerView().smoothScrollToPosition(position); - } - - /** - * Retrieves the title from the given {@link CarDrawerAdapter} and set its as the title of this - * controller's internal Toolbar. - */ - private void setToolbarTitleFrom(CarDrawerAdapter adapter) { - if (adapter.getTitle() == null) { - throw new RuntimeException("CarDrawerAdapter must supply a title via setTitle()"); - } - - mToolbar.setTitle(adapter.getTitle()); - adapter.setTitleChangeListener(mToolbar::setTitle); - } - - /** - * Sets up the necessary listeners for {@link DrawerLayout} so that the navigation drawer - * hierarchy is properly displayed. - */ - private void setupDrawerToggling() { - mDrawerLayout.addDrawerListener(mDrawerToggle); - mDrawerLayout.addDrawerListener( - new DrawerLayout.DrawerListener() { - @Override - public void onDrawerSlide(View drawerView, float slideOffset) { - // Correctly set the title and arrow colors as they are different between - // the open and close states. - updateTitleAndArrowColor(slideOffset >= COLOR_SWITCH_SLIDE_OFFSET); - } - - @Override - public void onDrawerClosed(View drawerView) { - // If drawer is closed, revert stack/drawer to initial root state. - cleanupStackAndShowRoot(); - scrollToPosition(0); - } - - @Override - public void onDrawerOpened(View drawerView) {} - - @Override - public void onDrawerStateChanged(int newState) {} - }); - } - - /** Sets the title and arrow color of the drawer depending on if it is open or not. */ - private void updateTitleAndArrowColor(boolean drawerOpen) { - // When the drawer is open, use car_title, which resolves to appropriate color depending on - // day-night mode. When drawer is closed, we always use light color. - int titleColorResId = drawerOpen ? R.color.car_title : R.color.car_title_light; - int titleColor = mContext.getColor(titleColorResId); - mToolbar.setTitleTextColor(titleColor); - mDrawerToggle.getDrawerArrowDrawable().setColor(titleColor); - } - - /** - * Synchronizes the display of the drawer with its linked {@link DrawerLayout}. - * - *

    This should be called from the associated Activity's - * {@link android.support.v7.app.AppCompatActivity#onPostCreate(Bundle)} method to synchronize - * after teh DRawerLayout's instance state has been restored, and any other time when the - * state may have diverged in such a way that this controller's associated - * {@link ActionBarDrawerToggle} had not been notified. - */ - public void syncState() { - mDrawerToggle.syncState(); - - // In case we're restarting after a config change (e.g. day, night switch), set colors - // again. Doing it here so that Drawer state is fully synced and we know if its open or not. - // NOTE: isDrawerOpen must be passed the second child of the DrawerLayout. - updateTitleAndArrowColor(mDrawerLayout.isDrawerOpen(mDrawerContent)); - } - - /** - * Notify this controller that device configurations may have changed. - * - *

    This method should be called from the associated Activity's - * {@code onConfigurationChanged()} method. - */ - public void onConfigurationChanged(Configuration newConfig) { - // Pass any configuration change to the drawer toggle. - mDrawerToggle.onConfigurationChanged(newConfig); - } - - /** - * An analog to an Activity's {@code onOptionsItemSelected()}. This method should be called - * when the Activity's method is called and will return {@code true} if the selection has - * been handled. - * - * @return {@code true} if the item processing was handled by this class. - */ - public boolean onOptionsItemSelected(MenuItem item) { - // Handle home-click and see if we can navigate up in the drawer. - if (item != null && item.getItemId() == android.R.id.home && maybeHandleUpClick()) { - return true; - } - - // DrawerToggle gets next chance to handle up-clicks (and any other clicks). - return mDrawerToggle.onOptionsItemSelected(item); - } - - /** - * Sets the navigation drawer's title to be the one supplied by the given adapter and updates - * the navigation drawer list with the adapter's contents. - */ - private void switchToAdapterInternal(CarDrawerAdapter adapter) { - setToolbarTitleFrom(adapter); - // NOTE: We don't use swapAdapter() since different levels in the Drawer may switch between - // car_drawer_list_item_normal, car_drawer_list_item_small and car_list_empty layouts. - mDrawerList.getRecyclerView().setAdapter(adapter); - scrollToPosition(0); - } - - /** - * Switches to the previous level in the drawer hierarchy if the current list being displayed - * is not the root adapter. This is analogous to a navigate up. - * - * @return {@code true} if a navigate up was possible and executed. {@code false} otherwise. - */ - private boolean maybeHandleUpClick() { - // Check if already at the root level. - if (mAdapterStack.size() <= 1) { - return false; - } - - CarDrawerAdapter adapter = mAdapterStack.pop(); - adapter.setTitleChangeListener(null); - adapter.cleanup(); - switchToAdapterInternal(mAdapterStack.peek()); - return true; - } - - /** Clears stack down to root adapter and switches to root adapter. */ - private void cleanupStackAndShowRoot() { - while (mAdapterStack.size() > 1) { - CarDrawerAdapter adapter = mAdapterStack.pop(); - adapter.setTitleChangeListener(null); - adapter.cleanup(); - } - switchToAdapterInternal(mAdapterStack.peek()); - } -} diff --git a/android/support/car/drawer/DrawerItemClickListener.java b/android/support/car/drawer/DrawerItemClickListener.java deleted file mode 100644 index d707dbd0..00000000 --- a/android/support/car/drawer/DrawerItemClickListener.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2017 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.support.car.drawer; - -/** - * Listener for handling clicks on items/views managed by {@link DrawerItemViewHolder}. - */ -public interface DrawerItemClickListener { - /** - * Callback when item is clicked. - * - * @param position Adapter position of the clicked item. - */ - void onItemClick(int position); -} diff --git a/android/support/car/drawer/DrawerItemViewHolder.java b/android/support/car/drawer/DrawerItemViewHolder.java deleted file mode 100644 index d016b2de..00000000 --- a/android/support/car/drawer/DrawerItemViewHolder.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2017 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.support.car.drawer; - -import android.support.annotation.NonNull; -import android.support.annotation.Nullable; -import android.support.car.R; -import android.support.v7.widget.RecyclerView; -import android.view.View; -import android.widget.ImageView; -import android.widget.TextView; - -/** - * Re-usable {@link RecyclerView.ViewHolder} for displaying items in the - * {@link android.support.car.drawer.CarDrawerAdapter}. - */ -public class DrawerItemViewHolder extends RecyclerView.ViewHolder { - private final ImageView mIcon; - private final TextView mTitle; - private final TextView mText; - private final ImageView mEndIcon; - - DrawerItemViewHolder(View view) { - super(view); - mIcon = view.findViewById(R.id.icon); - if (mIcon == null) { - throw new IllegalArgumentException("Icon view cannot be null!"); - } - - mTitle = view.findViewById(R.id.title); - if (mTitle == null) { - throw new IllegalArgumentException("Title view cannot be null!"); - } - - // Next two are optional and may be null. - mText = view.findViewById(R.id.text); - mEndIcon = view.findViewById(R.id.end_icon); - } - - /** Returns the view that should be used to display the main icon. */ - @NonNull - public ImageView getIcon() { - return mIcon; - } - - /** Returns the view that will display the main title. */ - @NonNull - public TextView getTitle() { - return mTitle; - } - - /** Returns the view that is used for text that is smaller than the title text. */ - @Nullable - public TextView getText() { - return mText; - } - - /** Returns the icon that is displayed at the end of the view. */ - @Nullable - public ImageView getEndIcon() { - return mEndIcon; - } - - /** - * Sets the listener that will be notified when the view held by this ViewHolder has been - * clicked. Passing {@code null} will clear any previously set listeners. - */ - void setItemClickListener(@Nullable DrawerItemClickListener listener) { - itemView.setOnClickListener(listener != null - ? v -> listener.onItemClick(getAdapterPosition()) - : null); - } -} diff --git a/android/support/car/widget/PagedListView.java b/android/support/car/widget/PagedListView.java index 46527001..8527c659 100644 --- a/android/support/car/widget/PagedListView.java +++ b/android/support/car/widget/PagedListView.java @@ -27,6 +27,7 @@ import android.os.Handler; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; +import android.support.annotation.Px; import android.support.annotation.RestrictTo; import android.support.annotation.UiThread; import android.support.car.R; @@ -60,6 +61,7 @@ public class PagedListView extends FrameLayout { protected final CarLayoutManager mLayoutManager; protected final Handler mHandler = new Handler(); private final boolean mScrollBarEnabled; + private final boolean mRightGutterEnabled; private final PagedScrollBarView mScrollBarView; private int mRowsPerPage = -1; @@ -95,11 +97,6 @@ public class PagedListView extends FrameLayout { * }

    */ public interface ItemCap { - /** - * A value to pass to {@link #setMaxItems(int)} that indicates there should be no limit. - */ - int UNLIMITED = -1; - /** * Sets the maximum number of items available in the adapter. A value less than '0' means * the list should not be capped. @@ -142,6 +139,7 @@ public class PagedListView extends FrameLayout { } LayoutInflater.from(context).inflate(layoutId, this /*root*/, true /*attachToRoot*/); + FrameLayout maxWidthLayout = (FrameLayout) findViewById(R.id.recycler_view_container); TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.PagedListView, defStyleAttrs, defStyleRes); mRecyclerView = (CarRecyclerView) findViewById(R.id.recycler_view); @@ -158,16 +156,6 @@ public class PagedListView extends FrameLayout { mRecyclerView.getRecycledViewPool().setMaxRecycledViews(0, 12); mRecyclerView.setItemAnimator(new CarItemAnimator(mLayoutManager)); - boolean offsetScrollBar = a.getBoolean(R.styleable.PagedListView_offsetScrollBar, false); - if (offsetScrollBar) { - MarginLayoutParams params = (MarginLayoutParams) mRecyclerView.getLayoutParams(); - params.setMarginStart(getResources().getDimensionPixelSize( - R.dimen.car_screen_margin_size)); - params.setMarginEnd( - a.getDimensionPixelSize(R.styleable.PagedListView_listEndMargin, 0)); - mRecyclerView.setLayoutParams(params); - } - if (a.getBoolean(R.styleable.PagedListView_showPagedListViewDivider, true)) { int dividerStartMargin = a.getDimensionPixelSize( R.styleable.PagedListView_dividerStartMargin, 0); @@ -211,20 +199,47 @@ public class PagedListView extends FrameLayout { } } }); - mScrollBarView.setVisibility(mScrollBarEnabled ? VISIBLE : GONE); - // Modify the layout the Scroll Bar is not visible. - if (!mScrollBarEnabled) { - MarginLayoutParams params = (MarginLayoutParams) mRecyclerView.getLayoutParams(); - params.setMarginStart(0); - mRecyclerView.setLayoutParams(params); + // Modify the layout if the Gutter or the Scroll Bar are not visible. + mRightGutterEnabled = a.getBoolean(R.styleable.PagedListView_rightGutterEnabled, false); + if (mRightGutterEnabled || !mScrollBarEnabled) { + FrameLayout.LayoutParams maxWidthLayoutLayoutParams = + (FrameLayout.LayoutParams) maxWidthLayout.getLayoutParams(); + if (mRightGutterEnabled) { + maxWidthLayoutLayoutParams.rightMargin = + getResources().getDimensionPixelSize(R.dimen.car_card_margin); + } + if (!mScrollBarEnabled) { + maxWidthLayoutLayoutParams.setMarginStart(0); + } + maxWidthLayout.setLayoutParams(maxWidthLayoutLayoutParams); } setDayNightStyle(DayNightStyle.AUTO); a.recycle(); } + /** + * Sets the starting and ending padding for each view in the list. + * + * @param start The start padding. + * @param end The end padding. + */ + public void setListViewStartEndPadding(@Px int start, @Px int end) { + int carCardMargin = getResources().getDimensionPixelSize(R.dimen.car_card_margin); + int startGutter = mScrollBarEnabled ? carCardMargin : 0; + int startPadding = Math.max(start - startGutter, 0); + int endGutter = mRightGutterEnabled ? carCardMargin : 0; + int endPadding = Math.max(end - endGutter, 0); + mRecyclerView.setPaddingRelative(startPadding, mRecyclerView.getPaddingTop(), + endPadding, mRecyclerView.getPaddingBottom()); + + // Since we're setting padding we'll need to set the clip to padding to the same + // value as clip children to ensure that the cards fly off the screen. + mRecyclerView.setClipToPadding(mRecyclerView.getClipChildren()); + } + @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); diff --git a/android/support/media/tv/BasePreviewProgram.java b/android/support/media/tv/BasePreviewProgram.java index 39c30140..1423d9d6 100644 --- a/android/support/media/tv/BasePreviewProgram.java +++ b/android/support/media/tv/BasePreviewProgram.java @@ -23,13 +23,14 @@ import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; -import android.support.annotation.IntDef; import android.support.annotation.RestrictTo; import android.support.media.tv.TvContractCompat.PreviewProgramColumns; +import android.support.media.tv.TvContractCompat.PreviewProgramColumns.AspectRatio; +import android.support.media.tv.TvContractCompat.PreviewProgramColumns.Availability; +import android.support.media.tv.TvContractCompat.PreviewProgramColumns.InteractionType; +import android.support.media.tv.TvContractCompat.PreviewProgramColumns.Type; import android.support.media.tv.TvContractCompat.PreviewPrograms; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; import java.net.URISyntaxException; import java.text.SimpleDateFormat; import java.util.Date; @@ -54,89 +55,6 @@ public abstract class BasePreviewProgram extends BaseProgram { private static final int IS_LIVE = 1; private static final int IS_BROWSABLE = 1; - /** @hide */ - @IntDef({ - TYPE_UNKNOWN, - PreviewProgramColumns.TYPE_MOVIE, - PreviewProgramColumns.TYPE_TV_SERIES, - PreviewProgramColumns.TYPE_TV_SEASON, - PreviewProgramColumns.TYPE_TV_EPISODE, - PreviewProgramColumns.TYPE_CLIP, - PreviewProgramColumns.TYPE_EVENT, - PreviewProgramColumns.TYPE_CHANNEL, - PreviewProgramColumns.TYPE_TRACK, - PreviewProgramColumns.TYPE_ALBUM, - PreviewProgramColumns.TYPE_ARTIST, - PreviewProgramColumns.TYPE_PLAYLIST, - PreviewProgramColumns.TYPE_STATION, - PreviewProgramColumns.TYPE_GAME - }) - @Retention(RetentionPolicy.SOURCE) - @RestrictTo(LIBRARY_GROUP) - public @interface Type {} - - /** - * The unknown program type. - */ - private static final int TYPE_UNKNOWN = -1; - - /** @hide */ - @IntDef({ - ASPECT_RATIO_UNKNOWN, - PreviewProgramColumns.ASPECT_RATIO_16_9, - PreviewProgramColumns.ASPECT_RATIO_3_2, - PreviewProgramColumns.ASPECT_RATIO_4_3, - PreviewProgramColumns.ASPECT_RATIO_1_1, - PreviewProgramColumns.ASPECT_RATIO_2_3, - PreviewProgramColumns.ASPECT_RATIO_MOVIE_POSTER - }) - @Retention(RetentionPolicy.SOURCE) - @RestrictTo(LIBRARY_GROUP) - public @interface AspectRatio {} - - /** - * The aspect ratio for unknown aspect ratios. - */ - private static final int ASPECT_RATIO_UNKNOWN = -1; - - /** @hide */ - @IntDef({ - AVAILABILITY_UNKNOWN, - PreviewProgramColumns.AVAILABILITY_AVAILABLE, - PreviewProgramColumns.AVAILABILITY_FREE_WITH_SUBSCRIPTION, - PreviewProgramColumns.AVAILABILITY_PAID_CONTENT, - PreviewProgramColumns.AVAILABILITY_PURCHASED, - PreviewProgramColumns.AVAILABILITY_FREE - }) - @Retention(RetentionPolicy.SOURCE) - @RestrictTo(LIBRARY_GROUP) - public @interface Availability {} - - /** - * The unknown availability. - */ - private static final int AVAILABILITY_UNKNOWN = -1; - - /** @hide */ - @IntDef({ - INTERACTION_TYPE_UNKNOWN, - PreviewProgramColumns.INTERACTION_TYPE_VIEWS, - PreviewProgramColumns.INTERACTION_TYPE_LISTENS, - PreviewProgramColumns.INTERACTION_TYPE_FOLLOWERS, - PreviewProgramColumns.INTERACTION_TYPE_FANS, - PreviewProgramColumns.INTERACTION_TYPE_LIKES, - PreviewProgramColumns.INTERACTION_TYPE_THUMBS, - PreviewProgramColumns.INTERACTION_TYPE_VIEWERS, - }) - @Retention(RetentionPolicy.SOURCE) - @RestrictTo(LIBRARY_GROUP) - public @interface InteractionType {} - - /** - * The unknown interaction type. - */ - private static final int INTERACTION_TYPE_UNKNOWN = -1; - BasePreviewProgram(Builder builder) { super(builder); } @@ -209,7 +127,7 @@ public abstract class BasePreviewProgram extends BaseProgram { */ public @Type int getType() { Integer i = mValues.getAsInteger(PreviewPrograms.COLUMN_TYPE); - return i == null ? TYPE_UNKNOWN : i; + return i == null ? INVALID_INT_VALUE : i; } /** @@ -219,7 +137,7 @@ public abstract class BasePreviewProgram extends BaseProgram { */ public @AspectRatio int getPosterArtAspectRatio() { Integer i = mValues.getAsInteger(PreviewPrograms.COLUMN_POSTER_ART_ASPECT_RATIO); - return i == null ? ASPECT_RATIO_UNKNOWN : i; + return i == null ? INVALID_INT_VALUE : i; } /** @@ -229,7 +147,7 @@ public abstract class BasePreviewProgram extends BaseProgram { */ public @AspectRatio int getThumbnailAspectRatio() { Integer i = mValues.getAsInteger(PreviewPrograms.COLUMN_THUMBNAIL_ASPECT_RATIO); - return i == null ? ASPECT_RATIO_UNKNOWN : i; + return i == null ? INVALID_INT_VALUE : i; } /** @@ -247,7 +165,7 @@ public abstract class BasePreviewProgram extends BaseProgram { */ public @Availability int getAvailability() { Integer i = mValues.getAsInteger(PreviewPrograms.COLUMN_AVAILABILITY); - return i == null ? AVAILABILITY_UNKNOWN : i; + return i == null ? INVALID_INT_VALUE : i; } /** @@ -298,7 +216,7 @@ public abstract class BasePreviewProgram extends BaseProgram { */ public @InteractionType int getInteractionType() { Integer i = mValues.getAsInteger(PreviewPrograms.COLUMN_INTERACTION_TYPE); - return i == null ? INTERACTION_TYPE_UNKNOWN : i; + return i == null ? INVALID_INT_VALUE : i; } /** diff --git a/android/support/media/tv/BaseProgram.java b/android/support/media/tv/BaseProgram.java index 23b5cf9c..e4ce9d1f 100644 --- a/android/support/media/tv/BaseProgram.java +++ b/android/support/media/tv/BaseProgram.java @@ -22,16 +22,13 @@ import android.database.Cursor; import android.media.tv.TvContentRating; import android.net.Uri; import android.os.Build; -import android.support.annotation.IntDef; import android.support.annotation.RestrictTo; import android.support.media.tv.TvContractCompat.BaseTvColumns; import android.support.media.tv.TvContractCompat.ProgramColumns; +import android.support.media.tv.TvContractCompat.ProgramColumns.ReviewRatingStyle; import android.support.media.tv.TvContractCompat.Programs; import android.support.media.tv.TvContractCompat.Programs.Genres.Genre; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - /** * Base class for derived classes that want to have common fields for programs defined in * {@link TvContractCompat}. @@ -48,22 +45,6 @@ public abstract class BaseProgram { private static final int INVALID_INT_VALUE = -1; private static final int IS_SEARCHABLE = 1; - /** @hide */ - @IntDef({ - REVIEW_RATING_STYLE_UNKNOWN, - ProgramColumns.REVIEW_RATING_STYLE_STARS, - ProgramColumns.REVIEW_RATING_STYLE_THUMBS_UP_DOWN, - ProgramColumns.REVIEW_RATING_STYLE_PERCENTAGE, - }) - @Retention(RetentionPolicy.SOURCE) - @RestrictTo(LIBRARY_GROUP) - @interface ReviewRatingStyle {} - - /** - * The unknown review rating style. - */ - private static final int REVIEW_RATING_STYLE_UNKNOWN = -1; - /** @hide */ @RestrictTo(LIBRARY_GROUP) protected ContentValues mValues; @@ -273,7 +254,7 @@ public abstract class BaseProgram { */ public @ReviewRatingStyle int getReviewRatingStyle() { Integer i = mValues.getAsInteger(Programs.COLUMN_REVIEW_RATING_STYLE); - return i == null ? REVIEW_RATING_STYLE_UNKNOWN : i; + return i == null ? INVALID_INT_VALUE : i; } /** diff --git a/android/support/media/tv/Program.java b/android/support/media/tv/Program.java index 233f1bab..4e3bd7ac 100644 --- a/android/support/media/tv/Program.java +++ b/android/support/media/tv/Program.java @@ -25,7 +25,6 @@ import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.RestrictTo; import android.support.media.tv.TvContractCompat.Programs; -import android.support.media.tv.TvContractCompat.Programs.Genres.Genre; /** * A convenience class to access {@link TvContractCompat.Programs} entries in the system content @@ -283,7 +282,7 @@ public final class Program extends BaseProgram implements Comparable { * @return This Builder object to allow for chaining of calls to builder methods. * @see Programs#COLUMN_BROADCAST_GENRE */ - public Builder setBroadcastGenres(@Genre String[] genres) { + public Builder setBroadcastGenres(String[] genres) { mValues.put(Programs.COLUMN_BROADCAST_GENRE, Programs.Genres.encode(genres)); return this; } diff --git a/android/support/media/tv/TvContractCompat.java b/android/support/media/tv/TvContractCompat.java index de4fd04f..5a46e791 100644 --- a/android/support/media/tv/TvContractCompat.java +++ b/android/support/media/tv/TvContractCompat.java @@ -30,6 +30,7 @@ import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.BaseColumns; +import android.support.annotation.IntDef; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; @@ -605,6 +606,16 @@ public final class TvContractCompat { */ @RestrictTo(LIBRARY_GROUP) interface ProgramColumns { + /** @hide */ + @IntDef({ + REVIEW_RATING_STYLE_STARS, + REVIEW_RATING_STYLE_THUMBS_UP_DOWN, + REVIEW_RATING_STYLE_PERCENTAGE, + }) + @Retention(RetentionPolicy.SOURCE) + @RestrictTo(LIBRARY_GROUP) + @interface ReviewRatingStyle {} + /** * The review rating style for five star rating. * @@ -923,6 +934,27 @@ public final class TvContractCompat { */ @RestrictTo(LIBRARY_GROUP) public interface PreviewProgramColumns { + + /** @hide */ + @IntDef({ + TYPE_MOVIE, + TYPE_TV_SERIES, + TYPE_TV_SEASON, + TYPE_TV_EPISODE, + TYPE_CLIP, + TYPE_EVENT, + TYPE_CHANNEL, + TYPE_TRACK, + TYPE_ALBUM, + TYPE_ARTIST, + TYPE_PLAYLIST, + TYPE_STATION, + TYPE_GAME + }) + @Retention(RetentionPolicy.SOURCE) + @RestrictTo(LIBRARY_GROUP) + public @interface Type {} + /** * The program type for movie. * @@ -1014,6 +1046,19 @@ public final class TvContractCompat { */ int TYPE_GAME = 12; + /** @hide */ + @IntDef({ + ASPECT_RATIO_16_9, + ASPECT_RATIO_3_2, + ASPECT_RATIO_4_3, + ASPECT_RATIO_1_1, + ASPECT_RATIO_2_3, + ASPECT_RATIO_MOVIE_POSTER, + }) + @Retention(RetentionPolicy.SOURCE) + @RestrictTo(LIBRARY_GROUP) + public @interface AspectRatio {} + /** * The aspect ratio for 16:9. * @@ -1062,6 +1107,18 @@ public final class TvContractCompat { */ int ASPECT_RATIO_MOVIE_POSTER = 5; + /** @hide */ + @IntDef({ + AVAILABILITY_AVAILABLE, + AVAILABILITY_FREE_WITH_SUBSCRIPTION, + AVAILABILITY_PAID_CONTENT, + AVAILABILITY_PURCHASED, + AVAILABILITY_FREE, + }) + @Retention(RetentionPolicy.SOURCE) + @RestrictTo(LIBRARY_GROUP) + public @interface Availability {} + /** * The availability for "available to this user". * @@ -1098,6 +1155,20 @@ public final class TvContractCompat { */ int AVAILABILITY_FREE = 4; + /** @hide */ + @IntDef({ + INTERACTION_TYPE_VIEWS, + INTERACTION_TYPE_LISTENS, + INTERACTION_TYPE_FOLLOWERS, + INTERACTION_TYPE_FANS, + INTERACTION_TYPE_LIKES, + INTERACTION_TYPE_THUMBS, + INTERACTION_TYPE_VIEWERS, + }) + @Retention(RetentionPolicy.SOURCE) + @RestrictTo(LIBRARY_GROUP) + public @interface InteractionType {} + /** * The interaction type for "views". * @@ -2824,6 +2895,17 @@ public final class TvContractCompat { /** The MIME type of a single preview TV program. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/watch_next_program"; + /** @hide */ + @IntDef({ + WATCH_NEXT_TYPE_CONTINUE, + WATCH_NEXT_TYPE_NEXT, + WATCH_NEXT_TYPE_NEW, + WATCH_NEXT_TYPE_WATCHLIST, + }) + @Retention(RetentionPolicy.SOURCE) + @RestrictTo(LIBRARY_GROUP) + public @interface WatchNextType {} + /** * The watch next type for CONTINUE. Use this type when the user has already watched more * than 1 minute of this content. diff --git a/android/support/media/tv/WatchNextProgram.java b/android/support/media/tv/WatchNextProgram.java index c192745c..f4665846 100644 --- a/android/support/media/tv/WatchNextProgram.java +++ b/android/support/media/tv/WatchNextProgram.java @@ -22,15 +22,12 @@ import android.content.ContentValues; import android.database.Cursor; import android.media.tv.TvContentRating; // For javadoc gen of super class import android.os.Build; -import android.support.annotation.IntDef; import android.support.annotation.RestrictTo; import android.support.media.tv.TvContractCompat.PreviewPrograms; // For javadoc gen of super class import android.support.media.tv.TvContractCompat.Programs; // For javadoc gen of super class import android.support.media.tv.TvContractCompat.Programs.Genres; // For javadoc gen of super class import android.support.media.tv.TvContractCompat.WatchNextPrograms; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; +import android.support.media.tv.TvContractCompat.WatchNextPrograms.WatchNextType; /** * A convenience class to access {@link WatchNextPrograms} entries in the system content @@ -90,34 +87,16 @@ public final class WatchNextProgram extends BasePreviewProgram { private static final long INVALID_LONG_VALUE = -1; private static final int INVALID_INT_VALUE = -1; - /** @hide */ - @IntDef({ - WATCH_NEXT_TYPE_UNKNOWN, - WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE, - WatchNextPrograms.WATCH_NEXT_TYPE_NEXT, - WatchNextPrograms.WATCH_NEXT_TYPE_NEW, - WatchNextPrograms.WATCH_NEXT_TYPE_WATCHLIST, - }) - @Retention(RetentionPolicy.SOURCE) - @RestrictTo(LIBRARY_GROUP) - public @interface WatchNextType {} - - /** - * The unknown watch next type. Use this type when the actual type is not known. - */ - public static final int WATCH_NEXT_TYPE_UNKNOWN = -1; - private WatchNextProgram(Builder builder) { super(builder); } /** - * @return The value of {@link WatchNextPrograms#COLUMN_WATCH_NEXT_TYPE} for the program, - * or {@link #WATCH_NEXT_TYPE_UNKNOWN} if it's unknown. + * @return The value of {@link WatchNextPrograms#COLUMN_WATCH_NEXT_TYPE} for the program. */ public @WatchNextType int getWatchNextType() { Integer i = mValues.getAsInteger(WatchNextPrograms.COLUMN_WATCH_NEXT_TYPE); - return i == null ? WATCH_NEXT_TYPE_UNKNOWN : i; + return i == null ? INVALID_INT_VALUE : i; } /** diff --git a/android/support/mediacompat/testlib/IntentConstants.java b/android/support/mediacompat/testlib/IntentConstants.java index 57db43e7..bc35935e 100644 --- a/android/support/mediacompat/testlib/IntentConstants.java +++ b/android/support/mediacompat/testlib/IntentConstants.java @@ -22,8 +22,6 @@ package android.support.mediacompat.testlib; public class IntentConstants { public static final String ACTION_CALL_MEDIA_BROWSER_SERVICE_METHOD = "android.support.mediacompat.service.action.CALL_MEDIA_BROWSER_SERVICE_METHOD"; - public static final String ACTION_CALL_MEDIA_SESSION_METHOD = - "android.support.mediacompat.service.action.CALL_MEDIA_SESSION_METHOD"; public static final String KEY_METHOD_ID = "method_id"; public static final String KEY_ARGUMENT = "argument"; } diff --git a/android/support/mediacompat/testlib/MediaSessionConstants.java b/android/support/mediacompat/testlib/MediaSessionConstants.java deleted file mode 100644 index 82b5c59a..00000000 --- a/android/support/mediacompat/testlib/MediaSessionConstants.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2017 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.support.mediacompat.testlib; - -/** - * Constants for testing the media session and controller. - */ -public class MediaSessionConstants { - - // MediaSessionCompat methods. - public static final int SET_EXTRAS = 101; - public static final int SET_FLAGS = 102; - public static final int SET_METADATA = 103; - public static final int SET_PLAYBACK_STATE = 104; - public static final int SET_QUEUE = 105; - public static final int SET_QUEUE_TITLE = 106; - public static final int SET_SESSION_ACTIVITY = 107; - public static final int SET_CAPTIONING_ENABLED = 108; - public static final int SET_REPEAT_MODE = 109; - public static final int SET_SHUFFLE_MODE = 110; - public static final int SEND_SESSION_EVENT = 112; - public static final int SET_ACTIVE = 113; - public static final int RELEASE = 114; - public static final int SET_PLAYBACK_TO_LOCAL = 115; - public static final int SET_PLAYBACK_TO_REMOTE = 116; - public static final int SET_RATING_TYPE = 117; - - public static final String SERVICE_PACKAGE_NAME = "android.support.mediacompat.service.test"; - public static final String TEST_KEY = "test-key"; - public static final String TEST_VALUE = "test-val"; - public static final String TEST_SESSION_EVENT = "test-session-event"; - public static final int TEST_FLAGS = 5; - public static final int TEST_CURRENT_VOLUME = 10; - public static final int TEST_MAX_VOLUME = 11; - public static final long TEST_QUEUE_ID_1 = 10L; - public static final long TEST_QUEUE_ID_2 = 20L; - public static final String TEST_MEDIA_ID_1 = "media_id_1"; - public static final String TEST_MEDIA_ID_2 = "media_id_2"; - public static final long TEST_ACTION = 55L; - - public static final int TEST_ERROR_CODE = 0x3; - public static final String TEST_ERROR_MSG = "test-error-msg"; -} diff --git a/android/support/transition/AutoTransition.java b/android/support/transition/AutoTransition.java index bf39c3c3..02b49e26 100644 --- a/android/support/transition/AutoTransition.java +++ b/android/support/transition/AutoTransition.java @@ -45,9 +45,9 @@ public class AutoTransition extends TransitionSet { private void init() { setOrdering(ORDERING_SEQUENTIAL); - addTransition(new Fade(Fade.OUT)) - .addTransition(new ChangeBounds()) - .addTransition(new Fade(Fade.IN)); + addTransition(new Fade(Fade.OUT)). + addTransition(new ChangeBounds()). + addTransition(new Fade(Fade.IN)); } } diff --git a/android/support/v17/leanback/widget/GridLayoutManager.java b/android/support/v17/leanback/widget/GridLayoutManager.java index af37f77a..81431972 100644 --- a/android/support/v17/leanback/widget/GridLayoutManager.java +++ b/android/support/v17/leanback/widget/GridLayoutManager.java @@ -2240,24 +2240,10 @@ final class GridLayoutManager extends RecyclerView.LayoutManager { focusToViewInLayout(hadFocus, scrollToFocus, -deltaPrimary, -deltaSecondary); appendVisibleItems(); prependVisibleItems(); - // b/67370222: do not removeInvisibleViewsAtFront/End() in the loop, otherwise - // loop may bounce between scroll forward and scroll backward forever. Example: - // Assuming there are 19 items, child#18 and child#19 are both in RV, we are - // trying to focus to child#18 and there are 200px remaining scroll distance. - // 1 focusToViewInLayout() tries scroll forward 50 px to align focused child#18 on - // right edge, but there to compensate remaining scroll 200px, also scroll - // backward 200px, 150px pushes last child#19 out side of right edge. - // 2 removeInvisibleViewsAtEnd() remove last child#19, updateScrollLimits() - // invalidates scroll max - // 3 In next iteration, when scroll max/min is unknown, focusToViewInLayout() will - // align focused child#18 at center of screen. - // 4 Because #18 is aligned at center, appendVisibleItems() will fill child#19 to - // the right. - // 5 (back to 1 and loop forever) + removeInvisibleViewsAtFront(); + removeInvisibleViewsAtEnd(); } while (mGrid.getFirstVisibleIndex() != oldFirstVisible || mGrid.getLastVisibleIndex() != oldLastVisible); - removeInvisibleViewsAtFront(); - removeInvisibleViewsAtEnd(); if (state.willRunPredictiveAnimations()) { fillScrapViewsInPostLayout(); diff --git a/android/support/v4/content/res/ResourcesCompat.java b/android/support/v4/content/res/ResourcesCompat.java index 15b8ce9a..4c70ce93 100644 --- a/android/support/v4/content/res/ResourcesCompat.java +++ b/android/support/v4/content/res/ResourcesCompat.java @@ -307,11 +307,11 @@ public final class ResourcesCompat { */ @RestrictTo(LIBRARY_GROUP) public static Typeface getFont(@NonNull Context context, @FontRes int id, TypedValue value, - int style, @Nullable FontCallback fontCallback) throws NotFoundException { + int style) throws NotFoundException { if (context.isRestricted()) { return null; } - return loadFont(context, id, value, style, fontCallback, null /* handler */, + return loadFont(context, id, value, style, null /* callback */, null /* handler */, true /* isXmlRequest */); } diff --git a/android/support/v4/media/RatingCompat.java b/android/support/v4/media/RatingCompat.java index e70243f8..b538cac4 100644 --- a/android/support/v4/media/RatingCompat.java +++ b/android/support/v4/media/RatingCompat.java @@ -18,7 +18,6 @@ package android.support.v4.media; import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP; -import android.media.Rating; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; @@ -327,25 +326,25 @@ public final class RatingCompat implements Parcelable { */ public static RatingCompat fromRating(Object ratingObj) { if (ratingObj != null && Build.VERSION.SDK_INT >= 19) { - final int ratingStyle = ((Rating) ratingObj).getRatingStyle(); + final int ratingStyle = RatingCompatKitkat.getRatingStyle(ratingObj); final RatingCompat rating; - if (((Rating) ratingObj).isRated()) { + if (RatingCompatKitkat.isRated(ratingObj)) { switch (ratingStyle) { case RATING_HEART: - rating = newHeartRating(((Rating) ratingObj).hasHeart()); + rating = newHeartRating(RatingCompatKitkat.hasHeart(ratingObj)); break; case RATING_THUMB_UP_DOWN: - rating = newThumbRating(((Rating) ratingObj).isThumbUp()); + rating = newThumbRating(RatingCompatKitkat.isThumbUp(ratingObj)); break; case RATING_3_STARS: case RATING_4_STARS: case RATING_5_STARS: rating = newStarRating(ratingStyle, - ((Rating) ratingObj).getStarRating()); + RatingCompatKitkat.getStarRating(ratingObj)); break; case RATING_PERCENTAGE: rating = newPercentageRating( - ((Rating) ratingObj).getPercentRating()); + RatingCompatKitkat.getPercentRating(ratingObj)); break; default: return null; @@ -373,25 +372,25 @@ public final class RatingCompat implements Parcelable { if (isRated()) { switch (mRatingStyle) { case RATING_HEART: - mRatingObj = Rating.newHeartRating(hasHeart()); + mRatingObj = RatingCompatKitkat.newHeartRating(hasHeart()); break; case RATING_THUMB_UP_DOWN: - mRatingObj = Rating.newThumbRating(isThumbUp()); + mRatingObj = RatingCompatKitkat.newThumbRating(isThumbUp()); break; case RATING_3_STARS: case RATING_4_STARS: case RATING_5_STARS: - mRatingObj = Rating.newStarRating(mRatingStyle, + mRatingObj = RatingCompatKitkat.newStarRating(mRatingStyle, getStarRating()); break; case RATING_PERCENTAGE: - mRatingObj = Rating.newPercentageRating(getPercentRating()); + mRatingObj = RatingCompatKitkat.newPercentageRating(getPercentRating()); break; default: return null; } } else { - mRatingObj = Rating.newUnratedRating(mRatingStyle); + mRatingObj = RatingCompatKitkat.newUnratedRating(mRatingStyle); } } return mRatingObj; diff --git a/android/support/v4/media/RatingCompatKitkat.java b/android/support/v4/media/RatingCompatKitkat.java new file mode 100644 index 00000000..1d3fa505 --- /dev/null +++ b/android/support/v4/media/RatingCompatKitkat.java @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2014 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.support.v4.media; + +import android.media.Rating; +import android.support.annotation.RequiresApi; + +@RequiresApi(19) +class RatingCompatKitkat { + public static Object newUnratedRating(int ratingStyle) { + return Rating.newUnratedRating(ratingStyle); + } + + public static Object newHeartRating(boolean hasHeart) { + return Rating.newHeartRating(hasHeart); + } + + public static Object newThumbRating(boolean thumbIsUp) { + return Rating.newThumbRating(thumbIsUp); + } + + public static Object newStarRating(int starRatingStyle, float starRating) { + return Rating.newStarRating(starRatingStyle, starRating); + } + + public static Object newPercentageRating(float percent) { + return Rating.newPercentageRating(percent); + } + + public static boolean isRated(Object ratingObj) { + return ((Rating)ratingObj).isRated(); + } + + public static int getRatingStyle(Object ratingObj) { + return ((Rating)ratingObj).getRatingStyle(); + } + + public static boolean hasHeart(Object ratingObj) { + return ((Rating)ratingObj).hasHeart(); + } + + public static boolean isThumbUp(Object ratingObj) { + return ((Rating)ratingObj).isThumbUp(); + } + + public static float getStarRating(Object ratingObj) { + return ((Rating)ratingObj).getStarRating(); + } + + public static float getPercentRating(Object ratingObj) { + return ((Rating)ratingObj).getPercentRating(); + } +} diff --git a/android/support/v4/provider/FontsContractCompat.java b/android/support/v4/provider/FontsContractCompat.java index 09261869..9ef1b0b0 100644 --- a/android/support/v4/provider/FontsContractCompat.java +++ b/android/support/v4/provider/FontsContractCompat.java @@ -303,9 +303,6 @@ public class FontsContractCompat { final ArrayList> replies; synchronized (sLock) { replies = sPendingReplies.get(id); - if (replies == null) { - return; // Nobody requested replies. Do nothing. - } sPendingReplies.remove(id); } for (int i = 0; i < replies.size(); ++i) { diff --git a/android/support/v7/app/MediaRouteButton.java b/android/support/v7/app/MediaRouteButton.java index fdbcf9ad..d3f7020b 100644 --- a/android/support/v7/app/MediaRouteButton.java +++ b/android/support/v7/app/MediaRouteButton.java @@ -121,7 +121,8 @@ public class MediaRouteButton extends View { } public MediaRouteButton(Context context, AttributeSet attrs, int defStyleAttr) { - super(MediaRouterThemeHelper.createThemedButtonContext(context), attrs, defStyleAttr); + super(MediaRouterThemeHelper.createThemedContext(context, defStyleAttr), attrs, + defStyleAttr); context = getContext(); mRouter = MediaRouter.getInstance(context); diff --git a/android/support/v7/app/MediaRouteChooserDialog.java b/android/support/v7/app/MediaRouteChooserDialog.java index 17364efb..0ab2eb11 100644 --- a/android/support/v7/app/MediaRouteChooserDialog.java +++ b/android/support/v7/app/MediaRouteChooserDialog.java @@ -92,8 +92,10 @@ public class MediaRouteChooserDialog extends AppCompatDialog { } public MediaRouteChooserDialog(Context context, int theme) { - super(context = MediaRouterThemeHelper.createThemedDialogContext(context, theme, false), - MediaRouterThemeHelper.createThemedDialogStyle(context)); + // If we pass theme ID of 0 to AppCompatDialog, it will apply dialogTheme on the context, + // which may override our style settings. Passes our uppermost theme ID to prevent this. + super(MediaRouterThemeHelper.createThemedContext(context, theme), + theme == 0 ? MediaRouterThemeHelper.createThemeForDialog(context, theme) : theme); context = getContext(); mRouter = MediaRouter.getInstance(context); diff --git a/android/support/v7/app/MediaRouteControllerDialog.java b/android/support/v7/app/MediaRouteControllerDialog.java index d89bf21e..4b9a17a3 100644 --- a/android/support/v7/app/MediaRouteControllerDialog.java +++ b/android/support/v7/app/MediaRouteControllerDialog.java @@ -201,8 +201,12 @@ public class MediaRouteControllerDialog extends AlertDialog { } public MediaRouteControllerDialog(Context context, int theme) { - super(context = MediaRouterThemeHelper.createThemedDialogContext(context, theme, true), - MediaRouterThemeHelper.createThemedDialogStyle(context)); + // If we pass theme ID of 0 to AppCompatDialog, it will apply dialogTheme on the context, + // which may override our style settings. Passes our uppermost theme ID to prevent this. + super(MediaRouterThemeHelper.createThemedContext(context, + MediaRouterThemeHelper.getAlertDialogResolvedTheme(context, theme)), theme == 0 + ? MediaRouterThemeHelper.createThemeForDialog(context, MediaRouterThemeHelper + .getAlertDialogResolvedTheme(context, theme)) : theme); mContext = getContext(); mControllerCallback = new MediaControllerCallback(); diff --git a/android/support/v7/app/MediaRouterThemeHelper.java b/android/support/v7/app/MediaRouterThemeHelper.java index 69e40ac7..9ef218e0 100644 --- a/android/support/v7/app/MediaRouterThemeHelper.java +++ b/android/support/v7/app/MediaRouterThemeHelper.java @@ -42,76 +42,47 @@ final class MediaRouterThemeHelper { private MediaRouterThemeHelper() { } - static Context createThemedButtonContext(Context context) { - // Apply base Media Router theme. - context = new ContextThemeWrapper(context, getRouterThemeId(context)); - - // Apply custom Media Router theme. - int style = getThemeResource(context, R.attr.mediaRouteTheme); - if (style != 0) { - context = new ContextThemeWrapper(context, style); - } - - return context; - } - - /* - * The following two methods are to be used in conjunction. They should be used to prepare - * the context and theme for a super class constructor (the latter method relies on the - * former method to properly prepare the context): - * super(context = createThemedDialogContext(context, theme), - * createThemedDialogStyle(context)); + /** + * Creates a themed context based on the explicit style resource or the parent context's default + * theme. + *

    + * The theme which will be applied on top of the parent {@code context}'s theme is determined + * by the primary color defined in the given {@code style}, or in the parent {@code context}. * - * It will apply theme in the following order (style lookups will be done in reverse): - * 1) Current theme - * 2) Supplied theme - * 3) Base Media Router theme - * 4) Custom Media Router theme, if provided + * @param context the parent context + * @param style the resource ID of the style against which to inflate this context, or + * {@code 0} to use the parent {@code context}'s default theme. + * @return The themed context. */ - static Context createThemedDialogContext(Context context, int theme, boolean alertDialog) { - // 1) Current theme is already applied to the context - - // 2) If no theme is supplied, look it up from the context (dialogTheme/alertDialogTheme) - if (theme == 0) { - theme = getThemeResource(context, !alertDialog - ? android.support.v7.appcompat.R.attr.dialogTheme - : android.support.v7.appcompat.R.attr.alertDialogTheme); - } - // Apply it - context = new ContextThemeWrapper(context, theme); - - // 3) If a custom Media Router theme is provided then apply the base theme - if (getThemeResource(context, R.attr.mediaRouteTheme) != 0) { - context = new ContextThemeWrapper(context, getRouterThemeId(context)); - } - - return context; + static Context createThemedContext(Context context, int style) { + // First, apply dialog property overlay. + Context themedContext = + new ContextThemeWrapper(context, getStyledRouterThemeId(context, style)); + int customizedThemeId = getThemeResource(context, R.attr.mediaRouteTheme); + return customizedThemeId == 0 ? themedContext + : new ContextThemeWrapper(themedContext, customizedThemeId); } - // This method should be used in conjunction with the previous method. - static int createThemedDialogStyle(Context context) { - // 4) Apply the custom Media Router theme - int theme = getThemeResource(context, R.attr.mediaRouteTheme); - if (theme == 0) { - // 3) No custom MediaRouther theme was provided so apply the base theme instead - theme = getRouterThemeId(context); - } - return theme; + /** + * Creates the theme resource ID intended to be used by dialogs. + */ + static int createThemeForDialog(Context context, int style) { + int customizedThemeId = getThemeResource(context, R.attr.mediaRouteTheme); + return customizedThemeId != 0 ? customizedThemeId : getStyledRouterThemeId(context, style); } - // END. Previous two methods should be used in conjunction. - static int getThemeResource(Context context, int attr) { + public static int getThemeResource(Context context, int attr) { TypedValue value = new TypedValue(); return context.getTheme().resolveAttribute(attr, value, true) ? value.resourceId : 0; } - static float getDisabledAlpha(Context context) { + public static float getDisabledAlpha(Context context) { TypedValue value = new TypedValue(); return context.getTheme().resolveAttribute(android.R.attr.disabledAlpha, value, true) ? value.getFloat() : 0.5f; } - static @ControllerColorType int getControllerColor(Context context, int style) { + public static @ControllerColorType int getControllerColor(Context context, int style) { int primaryColor = getThemeColor(context, style, android.support.v7.appcompat.R.attr.colorPrimary); if (ColorUtils.calculateContrast(COLOR_WHITE_ON_DARK_BACKGROUND, primaryColor) @@ -121,7 +92,7 @@ final class MediaRouterThemeHelper { return COLOR_DARK_ON_LIGHT_BACKGROUND; } - static int getButtonTextColor(Context context) { + public static int getButtonTextColor(Context context) { int primaryColor = getThemeColor(context, 0, android.support.v7.appcompat.R.attr.colorPrimary); int backgroundColor = getThemeColor(context, 0, android.R.attr.colorBackground); @@ -133,7 +104,7 @@ final class MediaRouterThemeHelper { return primaryColor; } - static void setMediaControlsBackgroundColor( + public static void setMediaControlsBackgroundColor( Context context, View mainControls, View groupControls, boolean hasGroup) { int primaryColor = getThemeColor(context, 0, android.support.v7.appcompat.R.attr.colorPrimary); @@ -153,7 +124,7 @@ final class MediaRouterThemeHelper { groupControls.setTag(primaryDarkColor); } - static void setVolumeSliderColor( + public static void setVolumeSliderColor( Context context, MediaRouteVolumeSlider volumeSlider, View backgroundView) { int controllerColor = getControllerColor(context, 0); if (Color.alpha(controllerColor) != 0xFF) { @@ -165,10 +136,23 @@ final class MediaRouterThemeHelper { volumeSlider.setColor(controllerColor); } + // This is copied from {@link AlertDialog#resolveDialogTheme} to pre-evaluate theme in advance. + public static int getAlertDialogResolvedTheme(Context context, int themeResId) { + if (themeResId >= 0x01000000) { // start of real resource IDs. + return themeResId; + } else { + TypedValue outValue = new TypedValue(); + context.getTheme().resolveAttribute( + android.support.v7.appcompat.R.attr.alertDialogTheme, outValue, true); + return outValue.resourceId; + } + } + private static boolean isLightTheme(Context context) { TypedValue value = new TypedValue(); - return context.getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.isLightTheme, - value, true) && value.data != 0; + return context.getTheme().resolveAttribute( + android.support.v7.appcompat.R.attr.isLightTheme, value, true) + && value.data != 0; } private static int getThemeColor(Context context, int style, int attr) { @@ -189,16 +173,16 @@ final class MediaRouterThemeHelper { return value.data; } - private static int getRouterThemeId(Context context) { + private static int getStyledRouterThemeId(Context context, int style) { int themeId; if (isLightTheme(context)) { - if (getControllerColor(context, 0) == COLOR_DARK_ON_LIGHT_BACKGROUND) { + if (getControllerColor(context, style) == COLOR_DARK_ON_LIGHT_BACKGROUND) { themeId = R.style.Theme_MediaRouter_Light; } else { themeId = R.style.Theme_MediaRouter_Light_DarkControlPanel; } } else { - if (getControllerColor(context, 0) == COLOR_DARK_ON_LIGHT_BACKGROUND) { + if (getControllerColor(context, style) == COLOR_DARK_ON_LIGHT_BACKGROUND) { themeId = R.style.Theme_MediaRouter_LightControlPanel; } else { themeId = R.style.Theme_MediaRouter; diff --git a/android/support/v7/util/DiffUtil.java b/android/support/v7/util/DiffUtil.java index ebc33f31..6302666f 100644 --- a/android/support/v7/util/DiffUtil.java +++ b/android/support/v7/util/DiffUtil.java @@ -16,7 +16,6 @@ package android.support.v7.util; -import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import android.support.v7.widget.RecyclerView; @@ -348,72 +347,6 @@ public class DiffUtil { } } - /** - * Callback for calculating the diff between two non-null items in a list. - *

    - * {@link Callback} serves two roles - list indexing, and item diffing. ItemCallback handles - * just the second of these, which allows separation of code that indexes into an array or List - * from the presentation-layer and content specific diffing code. - * - * @param Type of items to compare. - */ - public abstract static class ItemCallback { - /** - * Called to check whether two objects represent the same item. - *

    - * For example, if your items have unique ids, this method should check their id equality. - * - * @param oldItem The item in the old list. - * @param newItem The item in the new list. - * @return True if the two items represent the same object or false if they are different. - * - * @see Callback#areItemsTheSame(int, int) - */ - public abstract boolean areItemsTheSame(@NonNull T oldItem, @NonNull T newItem); - - /** - * Called to check whether two items have the same data. - *

    - * This information is used to detect if the contents of an item have changed. - *

    - * This method to check equality instead of {@link Object#equals(Object)} so that you can - * change its behavior depending on your UI. - *

    - * For example, if you are using DiffUtil with a - * {@link android.support.v7.widget.RecyclerView.Adapter RecyclerView.Adapter}, you should - * return whether the items' visual representations are the same. - *

    - * This method is called only if {@link #areItemsTheSame(T, T)} returns {@code true} for - * these items. - * - * @param oldItem The item in the old list. - * @param newItem The item in the new list. - * @return True if the contents of the items are the same or false if they are different. - * - * @see Callback#areContentsTheSame(int, int) - */ - public abstract boolean areContentsTheSame(@NonNull T oldItem, @NonNull T newItem); - - /** - * When {@link #areItemsTheSame(T, T)} returns {@code true} for two items and - * {@link #areContentsTheSame(T, T)} returns false for them, this method is called to - * get a payload about the change. - *

    - * For example, if you are using DiffUtil with {@link RecyclerView}, you can return the - * particular field that changed in the item and your - * {@link android.support.v7.widget.RecyclerView.ItemAnimator ItemAnimator} can use that - * information to run the correct animation. - *

    - * Default implementation returns {@code null}. - * - * @see Callback#getChangePayload(int, int) - */ - @SuppressWarnings({"WeakerAccess", "unused"}) - public Object getChangePayload(@NonNull T oldItem, @NonNull T newItem) { - return null; - } - } - /** * Snakes represent a match between two lists. It is optionally prefixed or postfixed with an * add or remove operation. See the Myers' paper for details. diff --git a/android/support/v7/widget/AppCompatTextHelper.java b/android/support/v7/widget/AppCompatTextHelper.java index fa6196f5..51510aa2 100644 --- a/android/support/v7/widget/AppCompatTextHelper.java +++ b/android/support/v7/widget/AppCompatTextHelper.java @@ -29,7 +29,6 @@ import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.annotation.RestrictTo; -import android.support.v4.content.res.ResourcesCompat; import android.support.v4.widget.TextViewCompat; import android.support.v7.appcompat.R; import android.text.method.PasswordTransformationMethod; @@ -37,8 +36,6 @@ import android.util.AttributeSet; import android.util.TypedValue; import android.widget.TextView; -import java.lang.ref.WeakReference; - @RequiresApi(9) class AppCompatTextHelper { @@ -66,7 +63,6 @@ class AppCompatTextHelper { private int mStyle = Typeface.NORMAL; private Typeface mFontTypeface; - private boolean mAsyncFontPending; AppCompatTextHelper(TextView view) { mView = view; @@ -217,23 +213,8 @@ class AppCompatTextHelper { ? R.styleable.TextAppearance_android_fontFamily : R.styleable.TextAppearance_fontFamily; if (!context.isRestricted()) { - final WeakReference textViewWeak = new WeakReference<>(mView); - ResourcesCompat.FontCallback replyCallback = new ResourcesCompat.FontCallback() { - @Override - public void onFontRetrieved(@NonNull Typeface typeface) { - onAsyncTypefaceReceived(textViewWeak, typeface); - } - - @Override - public void onFontRetrievalFailed(int reason) { - // Do nothing. - } - }; try { - // Note the callback will be triggered on the UI thread. - mFontTypeface = a.getFont(fontFamilyId, mStyle, replyCallback); - // If this call gave us an immediate result, ignore any pending callbacks. - mAsyncFontPending = mFontTypeface == null; + mFontTypeface = a.getFont(fontFamilyId, mStyle); } catch (UnsupportedOperationException | Resources.NotFoundException e) { // Expected if it is not a font resource. } @@ -241,16 +222,12 @@ class AppCompatTextHelper { if (mFontTypeface == null) { // Try with String. This is done by TextView JB+, but fails in ICS String fontFamilyName = a.getString(fontFamilyId); - if (fontFamilyName != null) { - mFontTypeface = Typeface.create(fontFamilyName, mStyle); - } + mFontTypeface = Typeface.create(fontFamilyName, mStyle); } return; } if (a.hasValue(R.styleable.TextAppearance_android_typeface)) { - // Ignore previous pending fonts - mAsyncFontPending = false; int typefaceIndex = a.getInt(R.styleable.TextAppearance_android_typeface, SANS); switch (typefaceIndex) { case SANS: @@ -268,16 +245,6 @@ class AppCompatTextHelper { } } - private void onAsyncTypefaceReceived(WeakReference textViewWeak, Typeface typeface) { - if (mAsyncFontPending) { - mFontTypeface = typeface; - final TextView textView = textViewWeak.get(); - if (textView != null) { - textView.setTypeface(typeface, mStyle); - } - } - } - void onSetTextAppearance(Context context, int resId) { final TintTypedArray a = TintTypedArray.obtainStyledAttributes(context, resId, R.styleable.TextAppearance); diff --git a/android/support/v7/widget/TintTypedArray.java b/android/support/v7/widget/TintTypedArray.java index 384c4615..22709551 100644 --- a/android/support/v7/widget/TintTypedArray.java +++ b/android/support/v7/widget/TintTypedArray.java @@ -106,8 +106,7 @@ public class TintTypedArray { * not a font resource. */ @Nullable - public Typeface getFont(@StyleableRes int index, int style, - @Nullable ResourcesCompat.FontCallback fontCallback) { + public Typeface getFont(@StyleableRes int index, int style) { final int resourceId = mWrapped.getResourceId(index, 0); if (resourceId == 0) { return null; @@ -115,7 +114,7 @@ public class TintTypedArray { if (mTypedValue == null) { mTypedValue = new TypedValue(); } - return ResourcesCompat.getFont(mContext, resourceId, mTypedValue, style, fontCallback); + return ResourcesCompat.getFont(mContext, resourceId, mTypedValue, style); } public int length() { diff --git a/android/telephony/CarrierConfigManager.java b/android/telephony/CarrierConfigManager.java index de980b2f..689ce954 100644 --- a/android/telephony/CarrierConfigManager.java +++ b/android/telephony/CarrierConfigManager.java @@ -762,18 +762,6 @@ public class CarrierConfigManager { */ public static final String KEY_CDMA_DTMF_TONE_DELAY_INT = "cdma_dtmf_tone_delay_int"; - /** - * Some carriers will send call forwarding responses for voicemail in a format that is not 3gpp - * compliant, which causes issues during parsing. This causes the - * {@link com.android.internal.telephony.CallForwardInfo#number} to contain non-numerical - * characters instead of a number. - * - * If true, we will detect the non-numerical characters and replace them with "Voicemail". - * @hide - */ - public static final String KEY_CALL_FORWARDING_MAP_NON_NUMBER_TO_VOICEMAIL_BOOL = - "call_forwarding_map_non_number_to_voicemail_bool"; - /** * Determines whether conference calls are supported by a carrier. When {@code true}, * conference calling is supported, {@code false otherwise}. @@ -1585,25 +1573,6 @@ public class CarrierConfigManager { public static final String KEY_SHOW_IMS_REGISTRATION_STATUS_BOOL = "show_ims_registration_status_bool"; - /** - * The flag to disable the popup dialog which warns the user of data charges. - * @hide - */ - public static final String KEY_DISABLE_CHARGE_INDICATION_BOOL = - "disable_charge_indication_bool"; - - /** - * Boolean indicating whether to skip the call forwarding (CF) fail-to-disable dialog. - * The logic used to determine whether we succeeded in disabling is carrier specific, - * so the dialog may not always be accurate. - * {@code false} - show CF fail-to-disable dialog. - * {@code true} - skip showing CF fail-to-disable dialog. - * - * @hide - */ - public static final String KEY_SKIP_CF_FAIL_TO_DISABLE_DIALOG_BOOL = - "skip_cf_fail_to_disable_dialog_bool"; - /** The default value for every variable. */ private final static PersistableBundle sDefaults; @@ -1734,7 +1703,6 @@ public class CarrierConfigManager { sDefaults.putInt(KEY_GSM_DTMF_TONE_DELAY_INT, 0); sDefaults.putInt(KEY_IMS_DTMF_TONE_DELAY_INT, 0); sDefaults.putInt(KEY_CDMA_DTMF_TONE_DELAY_INT, 100); - sDefaults.putBoolean(KEY_CALL_FORWARDING_MAP_NON_NUMBER_TO_VOICEMAIL_BOOL, false); sDefaults.putInt(KEY_CDMA_3WAYCALL_FLASH_DELAY_INT , 0); sDefaults.putBoolean(KEY_SUPPORT_CONFERENCE_CALL_BOOL, true); sDefaults.putBoolean(KEY_SUPPORT_IMS_CONFERENCE_CALL_BOOL, true); @@ -1758,7 +1726,6 @@ public class CarrierConfigManager { sDefaults.putString(KEY_CARRIER_NAME_STRING, ""); sDefaults.putBoolean(KEY_SUPPORT_DIRECT_FDN_DIALING_BOOL, false); sDefaults.putBoolean(KEY_CARRIER_DEFAULT_DATA_ROAMING_ENABLED_BOOL, false); - sDefaults.putBoolean(KEY_SKIP_CF_FAIL_TO_DISABLE_DIALOG_BOOL, false); // MMS defaults sDefaults.putBoolean(KEY_MMS_ALIAS_ENABLED_BOOL, false); @@ -1873,7 +1840,6 @@ public class CarrierConfigManager { sDefaults.putStringArray(KEY_NON_ROAMING_OPERATOR_STRING_ARRAY, null); sDefaults.putStringArray(KEY_ROAMING_OPERATOR_STRING_ARRAY, null); sDefaults.putBoolean(KEY_SHOW_IMS_REGISTRATION_STATUS_BOOL, false); - sDefaults.putBoolean(KEY_DISABLE_CHARGE_INDICATION_BOOL, false); } /** diff --git a/android/telephony/MbmsDownloadSession.java b/android/telephony/MbmsDownloadSession.java index 9a9877a8..764b7b22 100644 --- a/android/telephony/MbmsDownloadSession.java +++ b/android/telephony/MbmsDownloadSession.java @@ -77,9 +77,8 @@ public class MbmsDownloadSession implements AutoCloseable { * Integer extra that Android will attach to the intent supplied via * {@link android.telephony.mbms.DownloadRequest.Builder#setAppIntent(Intent)} * Indicates the result code of the download. One of - * {@link #RESULT_SUCCESSFUL}, {@link #RESULT_EXPIRED}, {@link #RESULT_CANCELLED}, - * {@link #RESULT_IO_ERROR}, {@link #RESULT_DOWNLOAD_FAILURE}, {@link #RESULT_OUT_OF_STORAGE}, - * {@link #RESULT_SERVICE_ID_NOT_DEFINED}, or {@link #RESULT_FILE_ROOT_UNREACHABLE}. + * {@link #RESULT_SUCCESSFUL}, {@link #RESULT_EXPIRED}, {@link #RESULT_CANCELLED}, or + * {@link #RESULT_IO_ERROR}. * * This extra may also be used by the middleware when it is sending intents to the app. */ @@ -143,41 +142,11 @@ public class MbmsDownloadSession implements AutoCloseable { /** * Indicates that the download will not be completed due to an I/O error incurred while - * writing to temp files. - * - * This is likely a transient error and another {@link DownloadRequest} should be sent to try - * the download again. + * writing to temp files. This commonly indicates that the device is out of storage space, + * but may indicate other conditions as well (such as an SD card being removed). */ public static final int RESULT_IO_ERROR = 4; - - /** - * Indicates that the Service ID specified in the {@link DownloadRequest} is incorrect due to - * the Id being incorrect, stale, expired, or similar. - */ - public static final int RESULT_SERVICE_ID_NOT_DEFINED = 5; - - /** - * Indicates that there was an error while processing downloaded files, such as a file repair or - * file decoding error and is not due to a file I/O error. - * - * This is likely a transient error and another {@link DownloadRequest} should be sent to try - * the download again. - */ - public static final int RESULT_DOWNLOAD_FAILURE = 6; - - /** - * Indicates that the file system is full and the {@link DownloadRequest} can not complete. - * Either space must be made on the current file system or the temp file root location must be - * changed to a location that is not full to download the temp files. - */ - public static final int RESULT_OUT_OF_STORAGE = 7; - - /** - * Indicates that the file root that was set is currently unreachable. This can happen if the - * temp files are set to be stored on external storage and the SD card was removed, for example. - * The temp file root should be changed before sending another DownloadRequest. - */ - public static final int RESULT_FILE_ROOT_UNREACHABLE = 8; + // TODO - more results! /** @hide */ @Retention(RetentionPolicy.SOURCE) diff --git a/android/telephony/NetworkScanRequest.java b/android/telephony/NetworkScanRequest.java index 9674c930..d2aef200 100644 --- a/android/telephony/NetworkScanRequest.java +++ b/android/telephony/NetworkScanRequest.java @@ -19,7 +19,6 @@ package android.telephony; import android.os.Parcel; import android.os.Parcelable; -import java.util.ArrayList; import java.util.Arrays; /** @@ -39,20 +38,6 @@ public final class NetworkScanRequest implements Parcelable { public static final int MAX_BANDS = 8; /** @hide */ public static final int MAX_CHANNELS = 32; - /** @hide */ - public static final int MAX_MCC_MNC_LIST_SIZE = 20; - /** @hide */ - public static final int MIN_SEARCH_PERIODICITY_SEC = 5; - /** @hide */ - public static final int MAX_SEARCH_PERIODICITY_SEC = 300; - /** @hide */ - public static final int MIN_SEARCH_MAX_SEC = 60; - /** @hide */ - public static final int MAX_SEARCH_MAX_SEC = 3600; - /** @hide */ - public static final int MIN_INCREMENTAL_PERIODICITY_SEC = 1; - /** @hide */ - public static final int MAX_INCREMENTAL_PERIODICITY_SEC = 10; /** Performs the scan only once */ public static final int SCAN_TYPE_ONE_SHOT = 0; @@ -61,84 +46,24 @@ public final class NetworkScanRequest implements Parcelable { * * The modem will start new scans periodically, and the interval between two scans is usually * multiple minutes. - */ + * */ public static final int SCAN_TYPE_PERIODIC = 1; /** Defines the type of the scan. */ public int scanType; - /** - * Search periodicity (in seconds). - * Expected range for the input is [5s - 300s] - * This value must be less than or equal to maxSearchTime - */ - public int searchPeriodicity; - - /** - * Maximum duration of the periodic search (in seconds). - * Expected range for the input is [60s - 3600s] - * If the search lasts this long, it will be terminated. - */ - public int maxSearchTime; - - /** - * Indicates whether the modem should report incremental - * results of the network scan to the client. - * FALSE – Incremental results are not reported. - * TRUE (default) – Incremental results are reported - */ - public boolean incrementalResults; - - /** - * Indicates the periodicity with which the modem should - * report incremental results to the client (in seconds). - * Expected range for the input is [1s - 10s] - * This value must be less than or equal to maxSearchTime - */ - public int incrementalResultsPeriodicity; - /** Describes the radio access technologies with bands or channels that need to be scanned. */ public RadioAccessSpecifier[] specifiers; - /** - * Describes the List of PLMN ids (MCC-MNC) - * If any PLMN of this list is found, search should end at that point and - * results with all PLMN found till that point should be sent as response. - * If list not sent, search to be completed till end and all PLMNs found to be reported. - * Max size of array is MAX_MCC_MNC_LIST_SIZE - */ - public ArrayList mccMncs; - /** * Creates a new NetworkScanRequest with scanType and network specifiers * * @param scanType The type of the scan * @param specifiers the radio network with bands / channels to be scanned - * @param searchPeriodicity Search periodicity (in seconds) - * @param maxSearchTime Maximum duration of the periodic search (in seconds) - * @param incrementalResults Indicates whether the modem should report incremental - * results of the network scan to the client - * @param incrementalResultsPeriodicity Indicates the periodicity with which the modem should - * report incremental results to the client (in seconds) - * @param mccMncs Describes the List of PLMN ids (MCC-MNC) */ - public NetworkScanRequest(int scanType, RadioAccessSpecifier[] specifiers, - int searchPeriodicity, - int maxSearchTime, - boolean incrementalResults, - int incrementalResultsPeriodicity, - ArrayList mccMncs) { + public NetworkScanRequest(int scanType, RadioAccessSpecifier[] specifiers) { this.scanType = scanType; this.specifiers = specifiers; - this.searchPeriodicity = searchPeriodicity; - this.maxSearchTime = maxSearchTime; - this.incrementalResults = incrementalResults; - this.incrementalResultsPeriodicity = incrementalResultsPeriodicity; - if (mccMncs != null) { - this.mccMncs = mccMncs; - } else { - this.mccMncs = new ArrayList<>(); - } } @Override @@ -150,11 +75,6 @@ public final class NetworkScanRequest implements Parcelable { public void writeToParcel(Parcel dest, int flags) { dest.writeInt(scanType); dest.writeParcelableArray(specifiers, flags); - dest.writeInt(searchPeriodicity); - dest.writeInt(maxSearchTime); - dest.writeBoolean(incrementalResults); - dest.writeInt(incrementalResultsPeriodicity); - dest.writeStringList(mccMncs); } private NetworkScanRequest(Parcel in) { @@ -162,12 +82,6 @@ public final class NetworkScanRequest implements Parcelable { specifiers = (RadioAccessSpecifier[]) in.readParcelableArray( Object.class.getClassLoader(), RadioAccessSpecifier.class); - searchPeriodicity = in.readInt(); - maxSearchTime = in.readInt(); - incrementalResults = in.readBoolean(); - incrementalResultsPeriodicity = in.readInt(); - mccMncs = new ArrayList<>(); - in.readStringList(mccMncs); } @Override @@ -185,24 +99,13 @@ public final class NetworkScanRequest implements Parcelable { } return (scanType == nsr.scanType - && Arrays.equals(specifiers, nsr.specifiers) - && searchPeriodicity == nsr.searchPeriodicity - && maxSearchTime == nsr.maxSearchTime - && incrementalResults == nsr.incrementalResults - && incrementalResultsPeriodicity == nsr.incrementalResultsPeriodicity - && (((mccMncs != null) - && mccMncs.equals(nsr.mccMncs)))); + && Arrays.equals(specifiers, nsr.specifiers)); } @Override public int hashCode () { return ((scanType * 31) - + (Arrays.hashCode(specifiers)) * 37 - + (searchPeriodicity * 41) - + (maxSearchTime * 43) - + ((incrementalResults == true? 1 : 0) * 47) - + (incrementalResultsPeriodicity * 53) - + (mccMncs.hashCode() * 59)); + + (Arrays.hashCode(specifiers)) * 37); } public static final Creator CREATOR = diff --git a/android/telephony/ServiceState.java b/android/telephony/ServiceState.java index 116e711e..e448fb2a 100644 --- a/android/telephony/ServiceState.java +++ b/android/telephony/ServiceState.java @@ -1197,6 +1197,15 @@ public class ServiceState implements Parcelable { } } + /** + * @Deprecated to be removed Q3 2013 use {@link #getVoiceNetworkType} + * @hide + */ + public int getNetworkType() { + Rlog.e(LOG_TAG, "ServiceState.getNetworkType() DEPRECATED will be removed *******"); + return rilRadioTechnologyToNetworkType(mRilVoiceRadioTechnology); + } + /** @hide */ public int getDataNetworkType() { return rilRadioTechnologyToNetworkType(mRilDataRadioTechnology); diff --git a/android/telephony/mbms/DownloadRequest.java b/android/telephony/mbms/DownloadRequest.java index f0d60b68..5a57f322 100644 --- a/android/telephony/mbms/DownloadRequest.java +++ b/android/telephony/mbms/DownloadRequest.java @@ -16,7 +16,6 @@ package android.telephony.mbms; -import android.annotation.NonNull; import android.annotation.SystemApi; import android.content.Intent; import android.net.Uri; @@ -27,6 +26,7 @@ import android.util.Log; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; @@ -71,19 +71,6 @@ public final class DownloadRequest implements Parcelable { private String appIntent; private int version = CURRENT_VERSION; - - /** - * Builds a new DownloadRequest. - * @param sourceUri the source URI for the DownloadRequest to be built. This URI should - * never be null. - */ - public Builder(@NonNull Uri sourceUri) { - if (sourceUri == null) { - throw new IllegalArgumentException("Source URI must be non-null."); - } - source = sourceUri; - } - /** * Sets the service from which the download request to be built will download from. * @param serviceInfo @@ -104,6 +91,15 @@ public final class DownloadRequest implements Parcelable { return this; } + /** + * Sets the source URI for the download request to be built. + * @param source + */ + public Builder setSource(Uri source) { + this.source = source; + return this; + } + /** * Set the subscription ID on which the file(s) should be downloaded. * @param subscriptionId @@ -320,11 +316,9 @@ public final class DownloadRequest implements Parcelable { throw new RuntimeException("Could not get sha256 hash object"); } if (version >= 1) { - // Hash the source URI and the app intent + // Hash the source URI, destination URI, and the app intent digest.update(sourceUri.toString().getBytes(StandardCharsets.UTF_8)); - if (serializedResultIntentForApp != null) { - digest.update(serializedResultIntentForApp.getBytes(StandardCharsets.UTF_8)); - } + digest.update(serializedResultIntentForApp.getBytes(StandardCharsets.UTF_8)); } // Add updates for future versions here return Base64.encodeToString(digest.digest(), Base64.URL_SAFE | Base64.NO_WRAP); diff --git a/android/telephony/mbms/MbmsDownloadReceiver.java b/android/telephony/mbms/MbmsDownloadReceiver.java index 9af1eb9e..fe275372 100644 --- a/android/telephony/mbms/MbmsDownloadReceiver.java +++ b/android/telephony/mbms/MbmsDownloadReceiver.java @@ -287,7 +287,7 @@ public class MbmsDownloadReceiver extends BroadcastReceiver { return; } - List tempFiles = intent.getParcelableArrayListExtra(VendorUtils.EXTRA_TEMP_LIST); + List tempFiles = intent.getParcelableExtra(VendorUtils.EXTRA_TEMP_LIST); if (tempFiles == null) { return; } @@ -309,7 +309,7 @@ public class MbmsDownloadReceiver extends BroadcastReceiver { return; } int fdCount = intent.getIntExtra(VendorUtils.EXTRA_FD_COUNT, 0); - List pausedList = intent.getParcelableArrayListExtra(VendorUtils.EXTRA_PAUSED_LIST); + List pausedList = intent.getParcelableExtra(VendorUtils.EXTRA_PAUSED_LIST); if (fdCount == 0 && (pausedList == null || pausedList.size() == 0)) { Log.i(LOG_TAG, "No temp files actually requested. Ending."); @@ -492,14 +492,9 @@ public class MbmsDownloadReceiver extends BroadcastReceiver { } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException("Package manager couldn't find " + context.getPackageName()); } - if (appInfo.metaData == null) { - throw new RuntimeException("App must declare the file provider authority as metadata " + - "in the manifest."); - } String authority = appInfo.metaData.getString(MBMS_FILE_PROVIDER_META_DATA_KEY); if (authority == null) { - throw new RuntimeException("App must declare the file provider authority as metadata " + - "in the manifest."); + throw new RuntimeException("Must declare the file provider authority as meta data"); } return authority; } diff --git a/android/telephony/mbms/vendor/MbmsDownloadServiceBase.java b/android/telephony/mbms/vendor/MbmsDownloadServiceBase.java index c3b2c482..2f85a1df 100644 --- a/android/telephony/mbms/vendor/MbmsDownloadServiceBase.java +++ b/android/telephony/mbms/vendor/MbmsDownloadServiceBase.java @@ -113,10 +113,6 @@ public class MbmsDownloadServiceBase extends IMbmsDownloadService.Stub { @Override public final int initialize(final int subscriptionId, final IMbmsDownloadSessionCallback callback) throws RemoteException { - if (callback == null) { - throw new NullPointerException("Callback must not be null"); - } - final int uid = Binder.getCallingUid(); callback.asBinder().linkToDeath(new DeathRecipient() { @Override @@ -244,13 +240,6 @@ public class MbmsDownloadServiceBase extends IMbmsDownloadService.Stub { public final int registerStateCallback(final DownloadRequest downloadRequest, final IDownloadStateCallback callback, int flags) throws RemoteException { final int uid = Binder.getCallingUid(); - if (downloadRequest == null) { - throw new NullPointerException("Download request must not be null"); - } - if (callback == null) { - throw new NullPointerException("Callback must not be null"); - } - DeathRecipient deathRecipient = new DeathRecipient() { @Override public void binderDied() { @@ -303,13 +292,6 @@ public class MbmsDownloadServiceBase extends IMbmsDownloadService.Stub { public final int unregisterStateCallback( final DownloadRequest downloadRequest, final IDownloadStateCallback callback) throws RemoteException { - if (downloadRequest == null) { - throw new NullPointerException("Download request must not be null"); - } - if (callback == null) { - throw new NullPointerException("Callback must not be null"); - } - DeathRecipient deathRecipient = mDownloadCallbackDeathRecipients.remove(callback.asBinder()); if (deathRecipient == null) { diff --git a/android/telephony/mbms/vendor/MbmsStreamingServiceBase.java b/android/telephony/mbms/vendor/MbmsStreamingServiceBase.java index 65b726df..f8f370a5 100644 --- a/android/telephony/mbms/vendor/MbmsStreamingServiceBase.java +++ b/android/telephony/mbms/vendor/MbmsStreamingServiceBase.java @@ -65,10 +65,6 @@ public class MbmsStreamingServiceBase extends IMbmsStreamingService.Stub { @Override public final int initialize(final IMbmsStreamingSessionCallback callback, final int subscriptionId) throws RemoteException { - if (callback == null) { - throw new NullPointerException("Callback must not be null"); - } - final int uid = Binder.getCallingUid(); callback.asBinder().linkToDeath(new DeathRecipient() { @Override @@ -156,10 +152,6 @@ public class MbmsStreamingServiceBase extends IMbmsStreamingService.Stub { @Override public int startStreaming(final int subscriptionId, String serviceId, final IStreamingServiceCallback callback) throws RemoteException { - if (callback == null) { - throw new NullPointerException("Callback must not be null"); - } - final int uid = Binder.getCallingUid(); callback.asBinder().linkToDeath(new DeathRecipient() { @Override diff --git a/android/text/BoringLayoutCreateDrawPerfTest.java b/android/text/BoringLayoutCreateDrawPerfTest.java index 586c3852..47dd257b 100644 --- a/android/text/BoringLayoutCreateDrawPerfTest.java +++ b/android/text/BoringLayoutCreateDrawPerfTest.java @@ -46,7 +46,7 @@ public class BoringLayoutCreateDrawPerfTest { private static final float SPACING_ADD = 10f; private static final float SPACING_MULT = 1.5f; - @Parameterized.Parameters(name = "cached={3},{1}chars,{0}") + @Parameterized.Parameters(name = "cached={3},{1} chars,{0}") public static Collection cases() { final List params = new ArrayList<>(); for (int length : new int[]{128}) { diff --git a/android/text/BoringLayoutIsBoringPerfTest.java b/android/text/BoringLayoutIsBoringPerfTest.java index 9d11f295..34de65de 100644 --- a/android/text/BoringLayoutIsBoringPerfTest.java +++ b/android/text/BoringLayoutIsBoringPerfTest.java @@ -40,7 +40,7 @@ public class BoringLayoutIsBoringPerfTest { private static final boolean[] BOOLEANS = new boolean[]{false, true}; - @Parameterized.Parameters(name = "cached={4},{1}chars,{0}") + @Parameterized.Parameters(name = "cached={4},{1} chars,{0}") public static Collection cases() { final List params = new ArrayList<>(); for (int length : new int[]{128}) { diff --git a/android/text/DynamicLayout.java b/android/text/DynamicLayout.java index fba358cf..24260c4f 100644 --- a/android/text/DynamicLayout.java +++ b/android/text/DynamicLayout.java @@ -299,7 +299,7 @@ public class DynamicLayout extends Layout private final Paint.FontMetricsInt mFontMetricsInt = new Paint.FontMetricsInt(); - private static final SynchronizedPool sPool = new SynchronizedPool<>(3); + private static final SynchronizedPool sPool = new SynchronizedPool(3); } /** @@ -440,7 +440,7 @@ public class DynamicLayout extends Layout mEllipsizeAt = null; } - mObjects = new PackedObjectVector<>(1); + mObjects = new PackedObjectVector(1); // Initial state is a single line with 0 characters (0 to 0), with top at 0 and bottom at // whatever is natural, and undefined ellipsis. @@ -1050,7 +1050,7 @@ public class DynamicLayout extends Layout private static class ChangeWatcher implements TextWatcher, SpanWatcher { public ChangeWatcher(DynamicLayout layout) { - mLayout = new WeakReference<>(layout); + mLayout = new WeakReference(layout); } private void reflow(CharSequence s, int where, int before, int after) { diff --git a/android/text/Hyphenator.java b/android/text/Hyphenator.java index 4f1488e1..ad26f23a 100644 --- a/android/text/Hyphenator.java +++ b/android/text/Hyphenator.java @@ -16,15 +16,258 @@ package android.text; +import android.annotation.IntRange; +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.system.ErrnoException; +import android.system.Os; +import android.system.OsConstants; +import android.util.Log; + +import com.android.internal.annotations.GuardedBy; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.util.HashMap; +import java.util.Locale; + /** - * Hyphenator just initializes the native implementation of automatic hyphenation, + * Hyphenator is a wrapper class for a native implementation of automatic hyphenation, * in essence finding valid hyphenation opportunities in a word. * * @hide */ public class Hyphenator { - public static void init() { - nInit(); + private static String TAG = "Hyphenator"; + + private final static Object sLock = new Object(); + + @GuardedBy("sLock") + final static HashMap sMap = new HashMap(); + + private final long mNativePtr; + private final HyphenationData mData; + + private Hyphenator(long nativePtr, HyphenationData data) { + mNativePtr = nativePtr; + mData = data; + } + + public long getNativePtr() { + return mNativePtr; } - private static native void nInit(); + + public static Hyphenator get(@Nullable Locale locale) { + synchronized (sLock) { + Hyphenator result = sMap.get(locale); + if (result != null) { + return result; + } + + // If there's a variant, fall back to language+variant only, if available + final String variant = locale.getVariant(); + if (!variant.isEmpty()) { + final Locale languageAndVariantOnlyLocale = + new Locale(locale.getLanguage(), "", variant); + result = sMap.get(languageAndVariantOnlyLocale); + if (result != null) { + return putAlias(locale, result); + } + } + + // Fall back to language-only, if available + final Locale languageOnlyLocale = new Locale(locale.getLanguage()); + result = sMap.get(languageOnlyLocale); + if (result != null) { + return putAlias(locale, result); + } + + // Fall back to script-only, if available + final String script = locale.getScript(); + if (!script.equals("")) { + final Locale scriptOnlyLocale = new Locale.Builder() + .setLanguage("und") + .setScript(script) + .build(); + result = sMap.get(scriptOnlyLocale); + if (result != null) { + return putAlias(locale, result); + } + } + + return putEmptyAlias(locale); + } + } + + private static class HyphenationData { + private static final String SYSTEM_HYPHENATOR_LOCATION = "/system/usr/hyphen-data"; + + public final int mMinPrefix, mMinSuffix; + public final long mDataAddress; + + // Reasonable enough values for cases where we have no hyphenation patterns but may be able + // to do some automatic hyphenation based on characters. These values would be used very + // rarely. + private static final int DEFAULT_MIN_PREFIX = 2; + private static final int DEFAULT_MIN_SUFFIX = 2; + + public static final HyphenationData sEmptyData = + new HyphenationData(DEFAULT_MIN_PREFIX, DEFAULT_MIN_SUFFIX); + + // Create empty HyphenationData. + private HyphenationData(int minPrefix, int minSuffix) { + mMinPrefix = minPrefix; + mMinSuffix = minSuffix; + mDataAddress = 0; + } + + HyphenationData(String languageTag, int minPrefix, int minSuffix) { + mMinPrefix = minPrefix; + mMinSuffix = minSuffix; + + final String patternFilename = "hyph-" + languageTag.toLowerCase(Locale.US) + ".hyb"; + final File patternFile = new File(SYSTEM_HYPHENATOR_LOCATION, patternFilename); + if (!patternFile.canRead()) { + Log.e(TAG, "hyphenation patterns for " + patternFile + " not found or unreadable"); + mDataAddress = 0; + } else { + long address; + try (RandomAccessFile f = new RandomAccessFile(patternFile, "r")) { + address = Os.mmap(0, f.length(), OsConstants.PROT_READ, + OsConstants.MAP_SHARED, f.getFD(), 0 /* offset */); + } catch (IOException | ErrnoException e) { + Log.e(TAG, "error loading hyphenation " + patternFile, e); + address = 0; + } + mDataAddress = address; + } + } + } + + // Do not call this method outside of init method. + private static Hyphenator putNewHyphenator(Locale loc, HyphenationData data) { + final Hyphenator hyphenator = new Hyphenator(nBuildHyphenator( + data.mDataAddress, loc.getLanguage(), data.mMinPrefix, data.mMinSuffix), data); + sMap.put(loc, hyphenator); + return hyphenator; + } + + // Do not call this method outside of init method. + private static void loadData(String langTag, int minPrefix, int maxPrefix) { + final HyphenationData data = new HyphenationData(langTag, minPrefix, maxPrefix); + putNewHyphenator(Locale.forLanguageTag(langTag), data); + } + + // Caller must acquire sLock before calling this method. + // The Hyphenator for the baseLangTag must exists. + private static Hyphenator addAliasByTag(String langTag, String baseLangTag) { + return putAlias(Locale.forLanguageTag(langTag), + sMap.get(Locale.forLanguageTag(baseLangTag))); + } + + // Caller must acquire sLock before calling this method. + private static Hyphenator putAlias(Locale locale, Hyphenator base) { + return putNewHyphenator(locale, base.mData); + } + + // Caller must acquire sLock before calling this method. + private static Hyphenator putEmptyAlias(Locale locale) { + return putNewHyphenator(locale, HyphenationData.sEmptyData); + } + + // TODO: Confirm that these are the best values. Various sources suggest (1, 1), but + // that appears too small. + private static final int INDIC_MIN_PREFIX = 2; + private static final int INDIC_MIN_SUFFIX = 2; + + /** + * Load hyphenation patterns at initialization time. We want to have patterns + * for all locales loaded and ready to use so we don't have to do any file IO + * on the UI thread when drawing text in different locales. + * + * @hide + */ + public static void init() { + synchronized (sLock) { + sMap.put(null, null); + + loadData("as", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Assamese + loadData("bg", 2, 2); // Bulgarian + loadData("bn", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Bengali + loadData("cu", 1, 2); // Church Slavonic + loadData("cy", 2, 3); // Welsh + loadData("da", 2, 2); // Danish + loadData("de-1901", 2, 2); // German 1901 orthography + loadData("de-1996", 2, 2); // German 1996 orthography + loadData("de-CH-1901", 2, 2); // Swiss High German 1901 orthography + loadData("en-GB", 2, 3); // British English + loadData("en-US", 2, 3); // American English + loadData("es", 2, 2); // Spanish + loadData("et", 2, 3); // Estonian + loadData("eu", 2, 2); // Basque + loadData("fr", 2, 3); // French + loadData("ga", 2, 3); // Irish + loadData("gu", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Gujarati + loadData("hi", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Hindi + loadData("hr", 2, 2); // Croatian + loadData("hu", 2, 2); // Hungarian + // texhyphen sources say Armenian may be (1, 2); but that it needs confirmation. + // Going with a more conservative value of (2, 2) for now. + loadData("hy", 2, 2); // Armenian + loadData("kn", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Kannada + loadData("ml", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Malayalam + loadData("mn-Cyrl", 2, 2); // Mongolian in Cyrillic script + loadData("mr", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Marathi + loadData("nb", 2, 2); // Norwegian Bokmål + loadData("nn", 2, 2); // Norwegian Nynorsk + loadData("or", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Oriya + loadData("pa", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Punjabi + loadData("pt", 2, 3); // Portuguese + loadData("sl", 2, 2); // Slovenian + loadData("ta", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Tamil + loadData("te", INDIC_MIN_PREFIX, INDIC_MIN_SUFFIX); // Telugu + loadData("tk", 2, 2); // Turkmen + loadData("und-Ethi", 1, 1); // Any language in Ethiopic script + + // English locales that fall back to en-US. The data is + // from CLDR. It's all English locales, minus the locales whose + // parent is en-001 (from supplementalData.xml, under ). + // TODO: Figure out how to get this from ICU. + addAliasByTag("en-AS", "en-US"); // English (American Samoa) + addAliasByTag("en-GU", "en-US"); // English (Guam) + addAliasByTag("en-MH", "en-US"); // English (Marshall Islands) + addAliasByTag("en-MP", "en-US"); // English (Northern Mariana Islands) + addAliasByTag("en-PR", "en-US"); // English (Puerto Rico) + addAliasByTag("en-UM", "en-US"); // English (United States Minor Outlying Islands) + addAliasByTag("en-VI", "en-US"); // English (Virgin Islands) + + // All English locales other than those falling back to en-US are mapped to en-GB. + addAliasByTag("en", "en-GB"); + + // For German, we're assuming the 1996 (and later) orthography by default. + addAliasByTag("de", "de-1996"); + // Liechtenstein uses the Swiss hyphenation rules for the 1901 orthography. + addAliasByTag("de-LI-1901", "de-CH-1901"); + + // Norwegian is very probably Norwegian Bokmål. + addAliasByTag("no", "nb"); + + // Use mn-Cyrl. According to CLDR's likelySubtags.xml, mn is most likely to be mn-Cyrl. + addAliasByTag("mn", "mn-Cyrl"); // Mongolian + + // Fall back to Ethiopic script for languages likely to be written in Ethiopic. + // Data is from CLDR's likelySubtags.xml. + // TODO: Convert this to a mechanism using ICU4J's ULocale#addLikelySubtags(). + addAliasByTag("am", "und-Ethi"); // Amharic + addAliasByTag("byn", "und-Ethi"); // Blin + addAliasByTag("gez", "und-Ethi"); // Geʻez + addAliasByTag("ti", "und-Ethi"); // Tigrinya + addAliasByTag("wal", "und-Ethi"); // Wolaytta + } + }; + + private static native long nBuildHyphenator(/* non-zero */ long dataAddress, + @NonNull String langTag, @IntRange(from = 1) int minPrefix, + @IntRange(from = 1) int minSuffix); } diff --git a/android/text/Layout.java b/android/text/Layout.java index ac5c2e92..60fff738 100644 --- a/android/text/Layout.java +++ b/android/text/Layout.java @@ -319,6 +319,8 @@ public abstract class Layout { private float getJustifyWidth(int lineNum) { Alignment paraAlign = mAlignment; + TabStops tabStops = null; + boolean tabStopsIsInitialized = false; int left = 0; int right = mWidth; @@ -369,6 +371,10 @@ public abstract class Layout { } } + if (getLineContainsTab(lineNum)) { + tabStops = new TabStops(TAB_INCREMENT, spans); + } + final Alignment align; if (paraAlign == Alignment.ALIGN_LEFT) { align = (dir == DIR_LEFT_TO_RIGHT) ? Alignment.ALIGN_NORMAL : Alignment.ALIGN_OPPOSITE; @@ -1417,6 +1423,7 @@ public abstract class Layout { float dist = Math.abs(getHorizontal(max, primary) - horiz); if (dist <= bestdist) { + bestdist = dist; best = max; } @@ -1563,7 +1570,7 @@ public abstract class Layout { // XXX: we don't care about tabs tl.set(mPaint, mText, lineStart, lineEnd, lineDir, directions, false, null); caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft); - TextLine.recycle(tl); + tl = TextLine.recycle(tl); return caret; } @@ -1887,7 +1894,10 @@ public abstract class Layout { int margin = 0; - boolean useFirstLineMargin = lineStart == 0 || spanned.charAt(lineStart - 1) == '\n'; + boolean isFirstParaLine = lineStart == 0 || + spanned.charAt(lineStart - 1) == '\n'; + + boolean useFirstLineMargin = isFirstParaLine; for (int i = 0; i < spans.length; i++) { if (spans[i] instanceof LeadingMarginSpan2) { int spStart = spanned.getSpanStart(spans[i]); diff --git a/android/text/PaintMeasureDrawPerfTest.java b/android/text/PaintMeasureDrawPerfTest.java index 67687985..00b60add 100644 --- a/android/text/PaintMeasureDrawPerfTest.java +++ b/android/text/PaintMeasureDrawPerfTest.java @@ -42,7 +42,7 @@ public class PaintMeasureDrawPerfTest { private static final boolean[] BOOLEANS = new boolean[]{false, true}; - @Parameterized.Parameters(name = "cached={1},{0}chars") + @Parameterized.Parameters(name = "cached={1},{0} chars") public static Collection cases() { final List params = new ArrayList<>(); for (int length : new int[]{128}) { diff --git a/android/text/StaticLayout.java b/android/text/StaticLayout.java index 5c60188d..961cd8ee 100644 --- a/android/text/StaticLayout.java +++ b/android/text/StaticLayout.java @@ -21,18 +21,21 @@ import android.annotation.IntRange; import android.annotation.NonNull; import android.annotation.Nullable; import android.graphics.Paint; +import android.os.LocaleList; import android.text.style.LeadingMarginSpan; import android.text.style.LeadingMarginSpan.LeadingMarginSpan2; import android.text.style.LineHeightSpan; import android.text.style.MetricAffectingSpan; import android.text.style.TabStopSpan; import android.util.Log; +import android.util.Pair; import android.util.Pools.SynchronizedPool; import com.android.internal.util.ArrayUtils; import com.android.internal.util.GrowingArrayUtils; import java.util.Arrays; +import java.util.Locale; /** * StaticLayout is a Layout for text that will not be edited after it @@ -98,6 +101,7 @@ public class StaticLayout extends Layout { b.mBreakStrategy = Layout.BREAK_STRATEGY_SIMPLE; b.mHyphenationFrequency = Layout.HYPHENATION_FREQUENCY_NONE; b.mJustificationMode = Layout.JUSTIFICATION_MODE_NONE; + b.mLocales = null; b.mMeasuredText = MeasuredText.obtain(); return b; @@ -114,6 +118,7 @@ public class StaticLayout extends Layout { b.mMeasuredText = null; b.mLeftIndents = null; b.mRightIndents = null; + b.mLocales = null; b.mLeftPaddings = null; b.mRightPaddings = null; nFinishBuilder(b.mNativePtr); @@ -404,6 +409,17 @@ public class StaticLayout extends Layout { return this; } + @NonNull + private long[] getHyphenators(@NonNull LocaleList locales) { + final int length = locales.size(); + final long[] result = new long[length]; + for (int i = 0; i < length; i++) { + final Locale locale = locales.get(i); + result[i] = Hyphenator.get(locale).getNativePtr(); + } + return result; + } + /** * Measurement and break iteration is done in native code. The protocol for using * the native code is as follows. @@ -417,17 +433,35 @@ public class StaticLayout extends Layout { * + addStyleRun (a text run, to be measured in native code) * + addReplacementRun (a replacement run, width is given) * + * After measurement, nGetWidths() is valid if the widths are needed (eg for ellipsis). * Run nComputeLineBreaks() to obtain line breaks for the paragraph. * * After all paragraphs, call finish() to release expensive buffers. */ + private Pair getLocaleAndHyphenatorIfChanged(TextPaint paint) { + final LocaleList locales = paint.getTextLocales(); + final String languageTags; + long[] hyphenators; + if (!locales.equals(mLocales)) { + mLocales = locales; + return new Pair(locales.toLanguageTags(), getHyphenators(locales)); + } else { + // passing null means keep current locale. + // TODO: move locale change detection to native. + return new Pair(null, null); + } + } + /* package */ void addStyleRun(TextPaint paint, int start, int end, boolean isRtl) { - nAddStyleRun(mNativePtr, paint.getNativeInstance(), start, end, isRtl); + Pair locHyph = getLocaleAndHyphenatorIfChanged(paint); + nAddStyleRun(mNativePtr, paint.getNativeInstance(), start, end, isRtl, locHyph.first, + locHyph.second); } /* package */ void addReplacementRun(TextPaint paint, int start, int end, float width) { - nAddReplacementRun(mNativePtr, paint.getNativeInstance(), start, end, width); + Pair locHyph = getLocaleAndHyphenatorIfChanged(paint); + nAddReplacementRun(mNativePtr, start, end, width, locHyph.first, locHyph.second); } /** @@ -485,7 +519,9 @@ public class StaticLayout extends Layout { // This will go away and be subsumed by native builder code private MeasuredText mMeasuredText; - private static final SynchronizedPool sPool = new SynchronizedPool<>(3); + private LocaleList mLocales; + + private static final SynchronizedPool sPool = new SynchronizedPool(3); } public StaticLayout(CharSequence source, TextPaint paint, @@ -774,6 +810,9 @@ public class StaticLayout extends Layout { } } + // TODO: Move locale tracking code to native. + b.mLocales = null; // Reset the locale tracking. + nSetupParagraph(b.mNativePtr, chs, paraEnd - paraStart, firstWidth, firstWidthLineCount, restWidth, variableTabStops, TAB_INCREMENT, b.mBreakStrategy, b.mHyphenationFrequency, @@ -827,9 +866,10 @@ public class StaticLayout extends Layout { spanEndCacheCount++; } + nGetWidths(b.mNativePtr, widths); int breakCount = nComputeLineBreaks(b.mNativePtr, lineBreaks, lineBreaks.breaks, lineBreaks.widths, lineBreaks.ascents, lineBreaks.descents, lineBreaks.flags, - lineBreaks.breaks.length, widths); + lineBreaks.breaks.length); final int[] breaks = lineBreaks.breaks; final float[] lineWidths = lineBreaks.widths; @@ -907,10 +947,10 @@ public class StaticLayout extends Layout { boolean moreChars = (endPos < bufEnd); final int ascent = fallbackLineSpacing - ? Math.min(fmAscent, Math.round(ascents[breakIndex])) + ? Math.min(fmAscent, (int) Math.round(ascents[breakIndex])) : fmAscent; final int descent = fallbackLineSpacing - ? Math.max(fmDescent, Math.round(descents[breakIndex])) + ? Math.max(fmDescent, (int) Math.round(descents[breakIndex])) : fmDescent; v = out(source, here, endPos, ascent, descent, fmTop, fmBottom, @@ -1137,7 +1177,7 @@ public class StaticLayout extends Layout { mWorkPaint.set(paint); do { final float ellipsizedWidth = guessEllipsis(text, lineStart, lineEnd, widths, - widthStart, tempAvail, where, line, mWorkPaint, forceEllipsis, dir); + widthStart, tempAvail, where, line, textWidth, mWorkPaint, forceEllipsis, dir); if (ellipsizedWidth <= avail) { lineFits = true; } else { @@ -1167,7 +1207,7 @@ public class StaticLayout extends Layout { // This method temporarily modifies the TextPaint passed to it, so the TextPaint passed to it // should not be accessed while the method is running. private float guessEllipsis(CharSequence text, int lineStart, int lineEnd, float[] widths, - int widthStart, float avail, TextUtils.TruncateAt where, int line, + int widthStart, float avail, TextUtils.TruncateAt where, int line, float textWidth, TextPaint paint, boolean forceEllipsis, int dir) { final int savedHyphenEdit = paint.getHyphenEdit(); paint.setHyphenEdit(0); @@ -1501,28 +1541,26 @@ public class StaticLayout extends Layout { @Nullable int[] indents, @Nullable int[] leftPaddings, @Nullable int[] rightPaddings, @IntRange(from = 0) int indentsOffset); - // TODO: Make this method CriticalNative once native code defers doing layouts. private static native void nAddStyleRun( /* non-zero */ long nativePtr, /* non-zero */ long nativePaint, - @IntRange(from = 0) int start, @IntRange(from = 0) int end, boolean isRtl); + @IntRange(from = 0) int start, @IntRange(from = 0) int end, boolean isRtl, + @Nullable String languageTags, @Nullable long[] hyphenators); - // TODO: Make this method CriticalNative once native code defers doing layouts. - private static native void nAddReplacementRun( - /* non-zero */ long nativePtr, /* non-zero */ long nativePaint, + private static native void nAddReplacementRun(/* non-zero */ long nativePtr, @IntRange(from = 0) int start, @IntRange(from = 0) int end, - @FloatRange(from = 0.0f) float width); + @FloatRange(from = 0.0f) float width, @Nullable String languageTags, + @Nullable long[] hyphenators); + + private static native void nGetWidths(long nativePtr, float[] widths); // populates LineBreaks and returns the number of breaks found // // the arrays inside the LineBreaks objects are passed in as well // to reduce the number of JNI calls in the common case where the // arrays do not have to be resized - // The individual character widths will be returned in charWidths. The length of charWidths must - // be at least the length of the text. private static native int nComputeLineBreaks(long nativePtr, LineBreaks recycle, int[] recycleBreaks, float[] recycleWidths, float[] recycleAscents, - float[] recycleDescents, int[] recycleFlags, int recycleLength, - float[] charWidths); + float[] recycleDescents, int[] recycleFlags, int recycleLength); private int mLineCount; private int mTopPadding, mBottomPadding; diff --git a/android/text/StaticLayoutCreateDrawPerfTest.java b/android/text/StaticLayoutCreateDrawPerfTest.java index bfdb7589..356e2e0d 100644 --- a/android/text/StaticLayoutCreateDrawPerfTest.java +++ b/android/text/StaticLayoutCreateDrawPerfTest.java @@ -50,7 +50,7 @@ public class StaticLayoutCreateDrawPerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameterized.Parameters(name = "cached={3},{1}chars,{0}") + @Parameterized.Parameters(name = "cached={3},{1} chars,{0}") public static Collection cases() { final List params = new ArrayList<>(); for (int length : new int[]{128}) { diff --git a/android/text/StaticLayout_Delegate.java b/android/text/StaticLayout_Delegate.java index def3c91c..63337f08 100644 --- a/android/text/StaticLayout_Delegate.java +++ b/android/text/StaticLayout_Delegate.java @@ -13,6 +13,7 @@ import android.icu.util.ULocale; import android.text.Primitive.PrimitiveType; import android.text.StaticLayout.LineBreaks; +import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -71,11 +72,13 @@ public class StaticLayout_Delegate { @LayoutlibDelegate /*package*/ static void nAddStyleRun(long nativeBuilder, long nativePaint, int start, - int end, boolean isRtl) { + int end, boolean isRtl, String languageTags, long[] hyphenators) { Builder builder = sBuilderManager.getDelegate(nativeBuilder); if (builder == null) { return; } + builder.mLocales = languageTags; + builder.mNativeHyphenators = hyphenators; int bidiFlags = isRtl ? Paint.BIDI_FORCE_RTL : Paint.BIDI_FORCE_LTR; measureText(nativePaint, builder.mText, start, end - start, builder.mWidths, @@ -83,20 +86,30 @@ public class StaticLayout_Delegate { } @LayoutlibDelegate - /*package*/ static void nAddReplacementRun(long nativeBuilder, long nativePaint, int start, - int end, float width) { + /*package*/ static void nAddReplacementRun(long nativeBuilder, int start, int end, float width, + String languageTags, long[] hyphenators) { Builder builder = sBuilderManager.getDelegate(nativeBuilder); if (builder == null) { return; } + builder.mLocales = languageTags; + builder.mNativeHyphenators = hyphenators; builder.mWidths[start] = width; Arrays.fill(builder.mWidths, start + 1, end, 0.0f); } + @LayoutlibDelegate + /*package*/ static void nGetWidths(long nativeBuilder, float[] floatsArray) { + Builder builder = sBuilderManager.getDelegate(nativeBuilder); + if (builder != null) { + System.arraycopy(builder.mWidths, 0, floatsArray, 0, builder.mWidths.length); + } + } + @LayoutlibDelegate /*package*/ static int nComputeLineBreaks(long nativeBuilder, LineBreaks recycle, int[] recycleBreaks, float[] recycleWidths, float[] recycleAscents, - float[] recycleDescents, int[] recycleFlags, int recycleLength, float[] charWidths) { + float[] recycleDescents, int[] recycleFlags, int recycleLength) { Builder builder = sBuilderManager.getDelegate(nativeBuilder); if (builder == null) { @@ -105,7 +118,7 @@ public class StaticLayout_Delegate { // compute all possible breakpoints. int length = builder.mWidths.length; - BreakIterator it = BreakIterator.getLineInstance(); + BreakIterator it = BreakIterator.getLineInstance(new ULocale(builder.mLocales)); it.setText(new Segment(builder.mText, 0, length)); // average word length in english is 5. So, initialize the possible breaks with a guess. @@ -136,7 +149,6 @@ public class StaticLayout_Delegate { builder.mTabStopCalculator); } builder.mLineBreaker.computeBreaks(recycle); - System.arraycopy(builder.mWidths, 0, charWidths, 0, builder.mWidths.length); return recycle.breaks.length; } @@ -194,9 +206,11 @@ public class StaticLayout_Delegate { * Java representation of the native Builder class. */ private static class Builder { + String mLocales; char[] mText; float[] mWidths; LineBreaker mLineBreaker; + long[] mNativeHyphenators; int mBreakStrategy; LineWidth mLineWidth; TabStops mTabStopCalculator; diff --git a/android/text/TextLine.java b/android/text/TextLine.java index 20c0ed87..2dbff100 100644 --- a/android/text/TextLine.java +++ b/android/text/TextLine.java @@ -73,7 +73,7 @@ class TextLine { new SpanSet(ReplacementSpan.class); private final DecorationInfo mDecorationInfo = new DecorationInfo(); - private final ArrayList mDecorations = new ArrayList<>(); + private final ArrayList mDecorations = new ArrayList(); private static final TextLine[] sCached = new TextLine[3]; @@ -340,14 +340,14 @@ class TextLine { boolean advance = (mDir == Layout.DIR_RIGHT_TO_LEFT) == runIsRtl; if (inSegment && advance) { - return h + measureRun(segstart, offset, j, runIsRtl, fmi); + return h += measureRun(segstart, offset, j, runIsRtl, fmi); } float w = measureRun(segstart, j, j, runIsRtl, fmi); h += advance ? w : -w; if (inSegment) { - return h + measureRun(segstart, offset, j, runIsRtl, null); + return h += measureRun(segstart, offset, j, runIsRtl, null); } if (codept == '\t') { @@ -828,14 +828,14 @@ class TextLine { } if (info.isUnderlineText) { final float thickness = - Math.max(wp.getUnderlineThickness(), 1.0f); + Math.max(((Paint) wp).getUnderlineThickness(), 1.0f); drawStroke(wp, c, wp.getColor(), wp.getUnderlinePosition(), thickness, decorationXLeft, decorationXRight, y); } if (info.isStrikeThruText) { final float thickness = - Math.max(wp.getStrikeThruThickness(), 1.0f); + Math.max(((Paint) wp).getStrikeThruThickness(), 1.0f); drawStroke(wp, c, wp.getColor(), wp.getStrikeThruPosition(), thickness, decorationXLeft, decorationXRight, y); } diff --git a/android/text/TextViewSetTextMeasurePerfTest.java b/android/text/TextViewSetTextMeasurePerfTest.java index ff2d57ed..a2bf33e1 100644 --- a/android/text/TextViewSetTextMeasurePerfTest.java +++ b/android/text/TextViewSetTextMeasurePerfTest.java @@ -40,7 +40,7 @@ import java.util.Locale; import java.util.Random; /** - * Performance test for {@link TextView} measure/draw. + * Performance test for multi line, single style {@link StaticLayout} creation/draw. */ @LargeTest @RunWith(Parameterized.class) @@ -51,7 +51,7 @@ public class TextViewSetTextMeasurePerfTest { @Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter(); - @Parameterized.Parameters(name = "cached={3},{1}chars,{0}") + @Parameterized.Parameters(name = "cached={3},{1} chars,{0}") public static Collection cases() { final List params = new ArrayList<>(); for (int length : new int[]{128}) { diff --git a/android/util/Log.java b/android/util/Log.java index b94e48b3..02998653 100644 --- a/android/util/Log.java +++ b/android/util/Log.java @@ -16,12 +16,45 @@ package android.util; +import android.os.DeadSystemException; + +import com.android.internal.os.RuntimeInit; +import com.android.internal.util.FastPrintWriter; +import com.android.internal.util.LineBreakBufferedWriter; + import java.io.PrintWriter; import java.io.StringWriter; +import java.io.Writer; import java.net.UnknownHostException; /** - * Mock Log implementation for testing on non android host. + * API for sending log output. + * + *

    Generally, you should use the {@link #v Log.v()}, {@link #d Log.d()}, + * {@link #i Log.i()}, {@link #w Log.w()}, and {@link #e Log.e()} methods to write logs. + * You can then view the logs in logcat. + * + *

    The order in terms of verbosity, from least to most is + * ERROR, WARN, INFO, DEBUG, VERBOSE. Verbose should never be compiled + * into an application except during development. Debug logs are compiled + * in but stripped at runtime. Error, warning and info logs are always kept. + * + *

    Tip: A good convention is to declare a TAG constant + * in your class: + * + *

    private static final String TAG = "MyActivity";
    + * + * and use that in subsequent calls to the log methods. + *

    + * + *

    Tip: Don't forget that when you make a call like + *

    Log.v(TAG, "index=" + i);
    + * that when you're building the string to pass into Log.d, the compiler uses a + * StringBuilder and at least three allocations occur: the StringBuilder + * itself, the buffer, and the String object. Realistically, there is also + * another buffer allocation and copy, and even more pressure on the gc. + * That means that if your log message is filtered out, you might be doing + * significant work and incurring significant overhead. */ public final class Log { @@ -55,6 +88,29 @@ public final class Log { */ public static final int ASSERT = 7; + /** + * Exception class used to capture a stack trace in {@link #wtf}. + * @hide + */ + public static class TerribleFailure extends Exception { + TerribleFailure(String msg, Throwable cause) { super(msg, cause); } + } + + /** + * Interface to handle terrible failures from {@link #wtf}. + * + * @hide + */ + public interface TerribleFailureHandler { + void onTerribleFailure(String tag, TerribleFailure what, boolean system); + } + + private static TerribleFailureHandler sWtfHandler = new TerribleFailureHandler() { + public void onTerribleFailure(String tag, TerribleFailure what, boolean system) { + RuntimeInit.wtf(tag, what, system); + } + }; + private Log() { } @@ -65,7 +121,7 @@ public final class Log { * @param msg The message you would like logged. */ public static int v(String tag, String msg) { - return println(LOG_ID_MAIN, VERBOSE, tag, msg); + return println_native(LOG_ID_MAIN, VERBOSE, tag, msg); } /** @@ -76,7 +132,7 @@ public final class Log { * @param tr An exception to log */ public static int v(String tag, String msg, Throwable tr) { - return println(LOG_ID_MAIN, VERBOSE, tag, msg + '\n' + getStackTraceString(tr)); + return printlns(LOG_ID_MAIN, VERBOSE, tag, msg, tr); } /** @@ -86,7 +142,7 @@ public final class Log { * @param msg The message you would like logged. */ public static int d(String tag, String msg) { - return println(LOG_ID_MAIN, DEBUG, tag, msg); + return println_native(LOG_ID_MAIN, DEBUG, tag, msg); } /** @@ -97,7 +153,7 @@ public final class Log { * @param tr An exception to log */ public static int d(String tag, String msg, Throwable tr) { - return println(LOG_ID_MAIN, DEBUG, tag, msg + '\n' + getStackTraceString(tr)); + return printlns(LOG_ID_MAIN, DEBUG, tag, msg, tr); } /** @@ -107,7 +163,7 @@ public final class Log { * @param msg The message you would like logged. */ public static int i(String tag, String msg) { - return println(LOG_ID_MAIN, INFO, tag, msg); + return println_native(LOG_ID_MAIN, INFO, tag, msg); } /** @@ -118,7 +174,7 @@ public final class Log { * @param tr An exception to log */ public static int i(String tag, String msg, Throwable tr) { - return println(LOG_ID_MAIN, INFO, tag, msg + '\n' + getStackTraceString(tr)); + return printlns(LOG_ID_MAIN, INFO, tag, msg, tr); } /** @@ -128,7 +184,7 @@ public final class Log { * @param msg The message you would like logged. */ public static int w(String tag, String msg) { - return println(LOG_ID_MAIN, WARN, tag, msg); + return println_native(LOG_ID_MAIN, WARN, tag, msg); } /** @@ -139,9 +195,31 @@ public final class Log { * @param tr An exception to log */ public static int w(String tag, String msg, Throwable tr) { - return println(LOG_ID_MAIN, WARN, tag, msg + '\n' + getStackTraceString(tr)); + return printlns(LOG_ID_MAIN, WARN, tag, msg, tr); } + /** + * Checks to see whether or not a log for the specified tag is loggable at the specified level. + * + * The default level of any tag is set to INFO. This means that any level above and including + * INFO will be logged. Before you make any calls to a logging method you should check to see + * if your tag should be logged. You can change the default level by setting a system property: + * 'setprop log.tag.<YOUR_LOG_TAG> <LEVEL>' + * Where level is either VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT, or SUPPRESS. SUPPRESS will + * turn off all logging for your tag. You can also create a local.prop file that with the + * following in it: + * 'log.tag.<YOUR_LOG_TAG>=<LEVEL>' + * and place that in /data/local.prop. + * + * @param tag The tag to check. + * @param level The level to check. + * @return Whether or not that this is allowed to be logged. + * @throws IllegalArgumentException is thrown if the tag.length() > 23 + * for Nougat (7.0) releases (API <= 23) and prior, there is no + * tag limit of concern after this API level. + */ + public static native boolean isLoggable(String tag, int level); + /* * Send a {@link #WARN} log message and log the exception. * @param tag Used to identify the source of a log message. It usually identifies @@ -149,7 +227,7 @@ public final class Log { * @param tr An exception to log */ public static int w(String tag, Throwable tr) { - return println(LOG_ID_MAIN, WARN, tag, getStackTraceString(tr)); + return printlns(LOG_ID_MAIN, WARN, tag, "", tr); } /** @@ -159,7 +237,7 @@ public final class Log { * @param msg The message you would like logged. */ public static int e(String tag, String msg) { - return println(LOG_ID_MAIN, ERROR, tag, msg); + return println_native(LOG_ID_MAIN, ERROR, tag, msg); } /** @@ -170,7 +248,82 @@ public final class Log { * @param tr An exception to log */ public static int e(String tag, String msg, Throwable tr) { - return println(LOG_ID_MAIN, ERROR, tag, msg + '\n' + getStackTraceString(tr)); + return printlns(LOG_ID_MAIN, ERROR, tag, msg, tr); + } + + /** + * What a Terrible Failure: Report a condition that should never happen. + * The error will always be logged at level ASSERT with the call stack. + * Depending on system configuration, a report may be added to the + * {@link android.os.DropBoxManager} and/or the process may be terminated + * immediately with an error dialog. + * @param tag Used to identify the source of a log message. + * @param msg The message you would like logged. + */ + public static int wtf(String tag, String msg) { + return wtf(LOG_ID_MAIN, tag, msg, null, false, false); + } + + /** + * Like {@link #wtf(String, String)}, but also writes to the log the full + * call stack. + * @hide + */ + public static int wtfStack(String tag, String msg) { + return wtf(LOG_ID_MAIN, tag, msg, null, true, false); + } + + /** + * What a Terrible Failure: Report an exception that should never happen. + * Similar to {@link #wtf(String, String)}, with an exception to log. + * @param tag Used to identify the source of a log message. + * @param tr An exception to log. + */ + public static int wtf(String tag, Throwable tr) { + return wtf(LOG_ID_MAIN, tag, tr.getMessage(), tr, false, false); + } + + /** + * What a Terrible Failure: Report an exception that should never happen. + * Similar to {@link #wtf(String, Throwable)}, with a message as well. + * @param tag Used to identify the source of a log message. + * @param msg The message you would like logged. + * @param tr An exception to log. May be null. + */ + public static int wtf(String tag, String msg, Throwable tr) { + return wtf(LOG_ID_MAIN, tag, msg, tr, false, false); + } + + static int wtf(int logId, String tag, String msg, Throwable tr, boolean localStack, + boolean system) { + TerribleFailure what = new TerribleFailure(msg, tr); + // Only mark this as ERROR, do not use ASSERT since that should be + // reserved for cases where the system is guaranteed to abort. + // The onTerribleFailure call does not always cause a crash. + int bytes = printlns(logId, ERROR, tag, msg, localStack ? what : tr); + sWtfHandler.onTerribleFailure(tag, what, system); + return bytes; + } + + static void wtfQuiet(int logId, String tag, String msg, boolean system) { + TerribleFailure what = new TerribleFailure(msg, null); + sWtfHandler.onTerribleFailure(tag, what, system); + } + + /** + * Sets the terrible failure handler, for testing. + * + * @return the old handler + * + * @hide + */ + public static TerribleFailureHandler setWtfHandler(TerribleFailureHandler handler) { + if (handler == null) { + throw new NullPointerException("handler == null"); + } + TerribleFailureHandler oldHandler = sWtfHandler; + sWtfHandler = handler; + return oldHandler; } /** @@ -193,7 +346,7 @@ public final class Log { } StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); + PrintWriter pw = new FastPrintWriter(sw, false, 256); tr.printStackTrace(pw); pw.flush(); return sw.toString(); @@ -208,7 +361,7 @@ public final class Log { * @return The number of bytes written. */ public static int println(int priority, String tag, String msg) { - return println(LOG_ID_MAIN, priority, tag, msg); + return println_native(LOG_ID_MAIN, priority, tag, msg); } /** @hide */ public static final int LOG_ID_MAIN = 0; @@ -217,9 +370,115 @@ public final class Log { /** @hide */ public static final int LOG_ID_SYSTEM = 3; /** @hide */ public static final int LOG_ID_CRASH = 4; - /** @hide */ @SuppressWarnings("unused") - public static int println(int bufID, - int priority, String tag, String msg) { - return 0; + /** @hide */ public static native int println_native(int bufID, + int priority, String tag, String msg); + + /** + * Return the maximum payload the log daemon accepts without truncation. + * @return LOGGER_ENTRY_MAX_PAYLOAD. + */ + private static native int logger_entry_max_payload_native(); + + /** + * Helper function for long messages. Uses the LineBreakBufferedWriter to break + * up long messages and stacktraces along newlines, but tries to write in large + * chunks. This is to avoid truncation. + * @hide + */ + public static int printlns(int bufID, int priority, String tag, String msg, + Throwable tr) { + ImmediateLogWriter logWriter = new ImmediateLogWriter(bufID, priority, tag); + // Acceptable buffer size. Get the native buffer size, subtract two zero terminators, + // and the length of the tag. + // Note: we implicitly accept possible truncation for Modified-UTF8 differences. It + // is too expensive to compute that ahead of time. + int bufferSize = PreloadHolder.LOGGER_ENTRY_MAX_PAYLOAD // Base. + - 2 // Two terminators. + - (tag != null ? tag.length() : 0) // Tag length. + - 32; // Some slack. + // At least assume you can print *some* characters (tag is not too large). + bufferSize = Math.max(bufferSize, 100); + + LineBreakBufferedWriter lbbw = new LineBreakBufferedWriter(logWriter, bufferSize); + + lbbw.println(msg); + + if (tr != null) { + // This is to reduce the amount of log spew that apps do in the non-error + // condition of the network being unavailable. + Throwable t = tr; + while (t != null) { + if (t instanceof UnknownHostException) { + break; + } + if (t instanceof DeadSystemException) { + lbbw.println("DeadSystemException: The system died; " + + "earlier logs will point to the root cause"); + break; + } + t = t.getCause(); + } + if (t == null) { + tr.printStackTrace(lbbw); + } + } + + lbbw.flush(); + + return logWriter.getWritten(); + } + + /** + * PreloadHelper class. Caches the LOGGER_ENTRY_MAX_PAYLOAD value to avoid + * a JNI call during logging. + */ + static class PreloadHolder { + public final static int LOGGER_ENTRY_MAX_PAYLOAD = + logger_entry_max_payload_native(); + } + + /** + * Helper class to write to the logcat. Different from LogWriter, this writes + * the whole given buffer and does not break along newlines. + */ + private static class ImmediateLogWriter extends Writer { + + private int bufID; + private int priority; + private String tag; + + private int written = 0; + + /** + * Create a writer that immediately writes to the log, using the given + * parameters. + */ + public ImmediateLogWriter(int bufID, int priority, String tag) { + this.bufID = bufID; + this.priority = priority; + this.tag = tag; + } + + public int getWritten() { + return written; + } + + @Override + public void write(char[] cbuf, int off, int len) { + // Note: using String here has a bit of overhead as a Java object is created, + // but using the char[] directly is not easier, as it needs to be translated + // to a C char[] for logging. + written += println_native(bufID, priority, tag, new String(cbuf, off, len)); + } + + @Override + public void flush() { + // Ignored. + } + + @Override + public void close() { + // Ignored. + } } } diff --git a/android/util/LruCache.java b/android/util/LruCache.java index 52086065..40154880 100644 --- a/android/util/LruCache.java +++ b/android/util/LruCache.java @@ -20,10 +20,6 @@ import java.util.LinkedHashMap; import java.util.Map; /** - * BEGIN LAYOUTLIB CHANGE - * This is a custom version that doesn't use the non standard LinkedHashMap#eldest. - * END LAYOUTLIB CHANGE - * * A cache that holds strong references to a limited number of values. Each time * a value is accessed, it is moved to the head of a queue. When a value is * added to a full cache, the value at the end of that queue is evicted and may @@ -91,9 +87,8 @@ public class LruCache { /** * Sets the size of the cache. - * @param maxSize The new maximum size. * - * @hide + * @param maxSize The new maximum size. */ public void resize(int maxSize) { if (maxSize <= 0) { @@ -190,10 +185,13 @@ public class LruCache { } /** + * Remove the eldest entries until the total of remaining entries is at or + * below the requested size. + * * @param maxSize the maximum size of the cache before returning. May be -1 - * to evict even 0-sized elements. + * to evict even 0-sized elements. */ - private void trimToSize(int maxSize) { + public void trimToSize(int maxSize) { while (true) { K key; V value; @@ -207,16 +205,7 @@ public class LruCache { break; } - // BEGIN LAYOUTLIB CHANGE - // get the last item in the linked list. - // This is not efficient, the goal here is to minimize the changes - // compared to the platform version. - Map.Entry toEvict = null; - for (Map.Entry entry : map.entrySet()) { - toEvict = entry; - } - // END LAYOUTLIB CHANGE - + Map.Entry toEvict = map.eldest(); if (toEvict == null) { break; } diff --git a/android/util/StatsLog.java b/android/util/StatsLog.java new file mode 100644 index 00000000..0be1a8cf --- /dev/null +++ b/android/util/StatsLog.java @@ -0,0 +1,76 @@ +/* + * 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.util; + +/** + * Logging access for platform metrics. + * + *

    This is not the main "logcat" debugging log ({@link android.util.Log})! + * These diagnostic stats are for system integrators, not application authors. + * + *

    Stats use integer tag codes. + * They carry a payload of one or more int, long, or String values. + * @hide + */ +public class StatsLog { + /** @hide */ public StatsLog() {} + + private static final String TAG = "StatsLog"; + + // We assume that the native methods deal with any concurrency issues. + + /** + * Records an stats log message. + * @param tag The stats type tag code + * @param value A value to log + * @return The number of bytes written + */ + public static native int writeInt(int tag, int value); + + /** + * Records an stats log message. + * @param tag The stats type tag code + * @param value A value to log + * @return The number of bytes written + */ + public static native int writeLong(int tag, long value); + + /** + * Records an stats log message. + * @param tag The stats type tag code + * @param value A value to log + * @return The number of bytes written + */ + public static native int writeFloat(int tag, float value); + + /** + * Records an stats log message. + * @param tag The stats type tag code + * @param str A value to log + * @return The number of bytes written + */ + public static native int writeString(int tag, String str); + + /** + * Records an stats log message. + * @param tag The stats type tag code + * @param list A list of values to log. All values should + * be of type int, long, float or String. + * @return The number of bytes written + */ + public static native int writeArray(int tag, Object... list); +} diff --git a/android/util/StatsLogKey.java b/android/util/StatsLogKey.java new file mode 100644 index 00000000..9ad0a23d --- /dev/null +++ b/android/util/StatsLogKey.java @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// THIS FILE IS AUTO-GENERATED. +// DO NOT MODIFY. + +package android.util; + +/** @hide */ +public class StatsLogKey { + private StatsLogKey() {} + + /** Constants for android.os.statsd.ScreenStateChange. */ + + /** display_state */ + public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE = 1; + + /** Constants for android.os.statsd.ProcessStateChange. */ + + /** state */ + public static final int PROCESS_STATE_CHANGE__STATE = 1; + + /** uid */ + public static final int PROCESS_STATE_CHANGE__UID = 2; + + /** package_name */ + public static final int PROCESS_STATE_CHANGE__PACKAGE_NAME = 1002; + + /** package_version */ + public static final int PROCESS_STATE_CHANGE__PACKAGE_VERSION = 3; + + /** package_version_string */ + public static final int PROCESS_STATE_CHANGE__PACKAGE_VERSION_STRING = 4; + +} diff --git a/android/util/StatsLogTag.java b/android/util/StatsLogTag.java new file mode 100644 index 00000000..5e5a8287 --- /dev/null +++ b/android/util/StatsLogTag.java @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// THIS FILE IS AUTO-GENERATED. +// DO NOT MODIFY. + +package android.util; + +/** @hide */ +public class StatsLogTag { + private StatsLogTag() {} + + /** android.os.statsd.ScreenStateChange. */ + public static final int SCREEN_STATE_CHANGE = 2; + + /** android.os.statsd.ProcessStateChange. */ + public static final int PROCESS_STATE_CHANGE = 1112; + +} diff --git a/android/util/StatsLogValue.java b/android/util/StatsLogValue.java new file mode 100644 index 00000000..05b9d933 --- /dev/null +++ b/android/util/StatsLogValue.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// THIS FILE IS AUTO-GENERATED. +// DO NOT MODIFY. + +package android.util; + +/** @hide */ +public class StatsLogValue { + private StatsLogValue() {} + + /** Constants for android.os.statsd.ScreenStateChange. */ + + /** display_state: STATE_UNKNOWN */ + public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_UNKNOWN = 0; + + /** display_state: STATE_OFF */ + public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_OFF = 1; + + /** display_state: STATE_ON */ + public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_ON = 2; + + /** display_state: STATE_DOZE */ + public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_DOZE = 3; + + /** display_state: STATE_DOZE_SUSPEND */ + public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_DOZE_SUSPEND = 4; + + /** display_state: STATE_VR */ + public static final int SCREEN_STATE_CHANGE__DISPLAY_STATE__STATE_VR = 5; + + /** Constants for android.os.statsd.ProcessStateChange. */ + + /** state: START */ + public static final int PROCESS_STATE_CHANGE__STATE__START = 1; + + /** state: CRASH */ + public static final int PROCESS_STATE_CHANGE__STATE__CRASH = 2; + +} diff --git a/android/view/SurfaceControl.java b/android/view/SurfaceControl.java index 54825895..31daefff 100644 --- a/android/view/SurfaceControl.java +++ b/android/view/SurfaceControl.java @@ -21,22 +21,15 @@ import static android.view.WindowManager.LayoutParams.INVALID_WINDOW_TYPE; import android.annotation.Size; import android.graphics.Bitmap; import android.graphics.GraphicBuffer; -import android.graphics.Point; -import android.graphics.PointF; import android.graphics.Rect; import android.graphics.Region; import android.os.Binder; -import android.os.Debug; import android.os.IBinder; import android.util.Log; import android.view.Surface.OutOfResourcesException; import dalvik.system.CloseGuard; -import java.io.Closeable; - -import libcore.util.NativeAllocationRegistry; - /** * SurfaceControl * @hide @@ -61,34 +54,25 @@ public class SurfaceControl { Rect sourceCrop, int width, int height, int minLayer, int maxLayer, boolean allLayers, boolean useIdentityTransform); - private static native long nativeCreateTransaction(); - private static native long nativeGetNativeTransactionFinalizer(); - private static native void nativeApplyTransaction(long transactionObj, boolean sync); - private static native void nativeSetAnimationTransaction(long transactionObj); - - private static native void nativeSetLayer(long transactionObj, long nativeObject, int zorder); - private static native void nativeSetRelativeLayer(long transactionObj, long nativeObject, - IBinder relativeTo, int zorder); - private static native void nativeSetPosition(long transactionObj, long nativeObject, - float x, float y); - private static native void nativeSetGeometryAppliesWithResize(long transactionObj, - long nativeObject); - private static native void nativeSetSize(long transactionObj, long nativeObject, int w, int h); - private static native void nativeSetTransparentRegionHint(long transactionObj, - long nativeObject, Region region); - private static native void nativeSetAlpha(long transactionObj, long nativeObject, float alpha); - private static native void nativeSetMatrix(long transactionObj, long nativeObject, - float dsdx, float dtdx, + private static native void nativeOpenTransaction(); + private static native void nativeCloseTransaction(boolean sync); + private static native void nativeSetAnimationTransaction(); + + private static native void nativeSetLayer(long nativeObject, int zorder); + private static native void nativeSetRelativeLayer(long nativeObject, IBinder relativeTo, + int zorder); + private static native void nativeSetPosition(long nativeObject, float x, float y); + private static native void nativeSetGeometryAppliesWithResize(long nativeObject); + private static native void nativeSetSize(long nativeObject, int w, int h); + private static native void nativeSetTransparentRegionHint(long nativeObject, Region region); + private static native void nativeSetAlpha(long nativeObject, float alpha); + private static native void nativeSetColor(long nativeObject, float[] color); + private static native void nativeSetMatrix(long nativeObject, float dsdx, float dtdx, float dtdy, float dsdy); - private static native void nativeSetColor(long transactionObj, long nativeObject, float[] color); - private static native void nativeSetFlags(long transactionObj, long nativeObject, - int flags, int mask); - private static native void nativeSetWindowCrop(long transactionObj, long nativeObject, - int l, int t, int r, int b); - private static native void nativeSetFinalCrop(long transactionObj, long nativeObject, - int l, int t, int r, int b); - private static native void nativeSetLayerStack(long transactionObj, long nativeObject, - int layerStack); + private static native void nativeSetFlags(long nativeObject, int flags, int mask); + private static native void nativeSetWindowCrop(long nativeObject, int l, int t, int r, int b); + private static native void nativeSetFinalCrop(long nativeObject, int l, int t, int r, int b); + private static native void nativeSetLayerStack(long nativeObject, int layerStack); private static native boolean nativeClearContentFrameStats(long nativeObject); private static native boolean nativeGetContentFrameStats(long nativeObject, WindowContentFrameStats outStats); @@ -98,16 +82,15 @@ public class SurfaceControl { private static native IBinder nativeGetBuiltInDisplay(int physicalDisplayId); private static native IBinder nativeCreateDisplay(String name, boolean secure); private static native void nativeDestroyDisplay(IBinder displayToken); - private static native void nativeSetDisplaySurface(long transactionObj, + private static native void nativeSetDisplaySurface( IBinder displayToken, long nativeSurfaceObject); - private static native void nativeSetDisplayLayerStack(long transactionObj, + private static native void nativeSetDisplayLayerStack( IBinder displayToken, int layerStack); - private static native void nativeSetDisplayProjection(long transactionObj, + private static native void nativeSetDisplayProjection( IBinder displayToken, int orientation, int l, int t, int r, int b, int L, int T, int R, int B); - private static native void nativeSetDisplaySize(long transactionObj, IBinder displayToken, - int width, int height); + private static native void nativeSetDisplaySize(IBinder displayToken, int width, int height); private static native SurfaceControl.PhysicalDisplayInfo[] nativeGetDisplayConfigs( IBinder displayToken); private static native int nativeGetActiveConfig(IBinder displayToken); @@ -118,17 +101,16 @@ public class SurfaceControl { int colorMode); private static native void nativeSetDisplayPowerMode( IBinder displayToken, int mode); - private static native void nativeDeferTransactionUntil(long transactionObj, long nativeObject, + private static native void nativeDeferTransactionUntil(long nativeObject, IBinder handle, long frame); - private static native void nativeDeferTransactionUntilSurface(long transactionObj, - long nativeObject, + private static native void nativeDeferTransactionUntilSurface(long nativeObject, long surfaceObject, long frame); - private static native void nativeReparentChildren(long transactionObj, long nativeObject, + private static native void nativeReparentChildren(long nativeObject, IBinder handle); - private static native void nativeReparent(long transactionObj, long nativeObject, + private static native void nativeReparent(long nativeObject, IBinder parentHandle); - private static native void nativeSeverChildren(long transactionObj, long nativeObject); - private static native void nativeSetOverrideScalingMode(long transactionObj, long nativeObject, + private static native void nativeSeverChildren(long nativeObject); + private static native void nativeSetOverrideScalingMode(long nativeObject, int scalingMode); private static native IBinder nativeGetHandle(long nativeObject); private static native boolean nativeGetTransformToDisplayInverse(long nativeObject); @@ -140,9 +122,6 @@ public class SurfaceControl { private final String mName; long mNativeObject; // package visibility only for Surface.java access - static Transaction sGlobalTransaction; - static long sTransactionNestCount = 0; - /* flags used in constructor (keep in sync with ISurfaceComposerClient.h) */ /** @@ -398,6 +377,11 @@ public class SurfaceControl { } } + @Override + public String toString() { + return "Surface(name=" + mName + ")"; + } + /** * Release the local reference to the server-side surface. * Always call release() when you're done with a Surface. @@ -445,141 +429,102 @@ public class SurfaceControl { /** start a transaction */ public static void openTransaction() { - synchronized (SurfaceControl.class) { - if (sGlobalTransaction == null) { - sGlobalTransaction = new Transaction(); - } - synchronized(SurfaceControl.class) { - sTransactionNestCount++; - } - } - } - - private static void closeTransaction(boolean sync) { - synchronized(SurfaceControl.class) { - if (sTransactionNestCount == 0) { - Log.e(TAG, "Call to SurfaceControl.closeTransaction without matching openTransaction"); - } else if (--sTransactionNestCount > 0) { - return; - } - sGlobalTransaction.apply(sync); - } + nativeOpenTransaction(); } /** end a transaction */ public static void closeTransaction() { - closeTransaction(false); + nativeCloseTransaction(false); } public static void closeTransactionSync() { - closeTransaction(true); + nativeCloseTransaction(true); } public void deferTransactionUntil(IBinder handle, long frame) { if (frame > 0) { - synchronized(SurfaceControl.class) { - sGlobalTransaction.deferTransactionUntil(this, handle, frame); - } + nativeDeferTransactionUntil(mNativeObject, handle, frame); } } public void deferTransactionUntil(Surface barrier, long frame) { if (frame > 0) { - synchronized(SurfaceControl.class) { - sGlobalTransaction.deferTransactionUntilSurface(this, barrier, frame); - } + nativeDeferTransactionUntilSurface(mNativeObject, barrier.mNativeObject, frame); } } public void reparentChildren(IBinder newParentHandle) { - synchronized(SurfaceControl.class) { - sGlobalTransaction.reparentChildren(this, newParentHandle); - } + nativeReparentChildren(mNativeObject, newParentHandle); } + /** Re-parents this layer to a new parent. */ public void reparent(IBinder newParentHandle) { - synchronized(SurfaceControl.class) { - sGlobalTransaction.reparent(this, newParentHandle); - } + nativeReparent(mNativeObject, newParentHandle); } public void detachChildren() { - synchronized(SurfaceControl.class) { - sGlobalTransaction.detachChildren(this); - } + nativeSeverChildren(mNativeObject); } public void setOverrideScalingMode(int scalingMode) { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.setOverrideScalingMode(this, scalingMode); - } + nativeSetOverrideScalingMode(mNativeObject, scalingMode); } public IBinder getHandle() { return nativeGetHandle(mNativeObject); } + /** flag the transaction as an animation */ public static void setAnimationTransaction() { - synchronized (SurfaceControl.class) { - sGlobalTransaction.setAnimationTransaction(); - } + nativeSetAnimationTransaction(); } public void setLayer(int zorder) { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.setLayer(this, zorder); - } + nativeSetLayer(mNativeObject, zorder); } public void setRelativeLayer(IBinder relativeTo, int zorder) { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.setRelativeLayer(this, relativeTo, zorder); - } + nativeSetRelativeLayer(mNativeObject, relativeTo, zorder); } public void setPosition(float x, float y) { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.setPosition(this, x, y); - } + nativeSetPosition(mNativeObject, x, y); } + /** + * If the buffer size changes in this transaction, position and crop updates specified + * in this transaction will not complete until a buffer of the new size + * arrives. As transform matrix and size are already frozen in this fashion, + * this enables totally freezing the surface until the resize has completed + * (at which point the geometry influencing aspects of this transaction will then occur) + */ public void setGeometryAppliesWithResize() { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.setGeometryAppliesWithResize(this); - } + nativeSetGeometryAppliesWithResize(mNativeObject); } public void setSize(int w, int h) { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.setSize(this, w, h); - } + nativeSetSize(mNativeObject, w, h); } public void hide() { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.hide(this); - } + nativeSetFlags(mNativeObject, SURFACE_HIDDEN, SURFACE_HIDDEN); } public void show() { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.show(this); - } + nativeSetFlags(mNativeObject, 0, SURFACE_HIDDEN); } public void setTransparentRegionHint(Region region) { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.setTransparentRegionHint(this, region); - } + nativeSetTransparentRegionHint(mNativeObject, region); } public boolean clearContentFrameStats() { @@ -600,70 +545,80 @@ public class SurfaceControl { return nativeGetAnimationFrameStats(outStats); } + /** + * Sets an alpha value for the entire Surface. This value is combined with the + * per-pixel alpha. It may be used with opaque Surfaces. + */ public void setAlpha(float alpha) { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.setAlpha(this, alpha); - } + nativeSetAlpha(mNativeObject, alpha); } + /** + * Sets a color for the Surface. + * @param color A float array with three values to represent r, g, b in range [0..1] + */ public void setColor(@Size(3) float[] color) { checkNotReleased(); - synchronized (SurfaceControl.class) { - sGlobalTransaction.setColor(this, color); - } + nativeSetColor(mNativeObject, color); } public void setMatrix(float dsdx, float dtdx, float dtdy, float dsdy) { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.setMatrix(this, dsdx, dtdx, dtdy, dsdy); - } + nativeSetMatrix(mNativeObject, dsdx, dtdx, dtdy, dsdy); } public void setWindowCrop(Rect crop) { checkNotReleased(); - synchronized (SurfaceControl.class) { - sGlobalTransaction.setWindowCrop(this, crop); + if (crop != null) { + nativeSetWindowCrop(mNativeObject, + crop.left, crop.top, crop.right, crop.bottom); + } else { + nativeSetWindowCrop(mNativeObject, 0, 0, 0, 0); } } public void setFinalCrop(Rect crop) { checkNotReleased(); - synchronized (SurfaceControl.class) { - sGlobalTransaction.setFinalCrop(this, crop); + if (crop != null) { + nativeSetFinalCrop(mNativeObject, + crop.left, crop.top, crop.right, crop.bottom); + } else { + nativeSetFinalCrop(mNativeObject, 0, 0, 0, 0); } } public void setLayerStack(int layerStack) { checkNotReleased(); - synchronized(SurfaceControl.class) { - sGlobalTransaction.setLayerStack(this, layerStack); - } + nativeSetLayerStack(mNativeObject, layerStack); } + /** + * Sets the opacity of the surface. Setting the flag is equivalent to creating the + * Surface with the {@link #OPAQUE} flag. + */ public void setOpaque(boolean isOpaque) { checkNotReleased(); - - synchronized (SurfaceControl.class) { - sGlobalTransaction.setOpaque(this, isOpaque); + if (isOpaque) { + nativeSetFlags(mNativeObject, SURFACE_OPAQUE, SURFACE_OPAQUE); + } else { + nativeSetFlags(mNativeObject, 0, SURFACE_OPAQUE); } } + /** + * Sets the security of the surface. Setting the flag is equivalent to creating the + * Surface with the {@link #SECURE} flag. + */ public void setSecure(boolean isSecure) { checkNotReleased(); - - synchronized (SurfaceControl.class) { - sGlobalTransaction.setSecure(this, isSecure); + if (isSecure) { + nativeSetFlags(mNativeObject, SECURE, SECURE); + } else { + nativeSetFlags(mNativeObject, 0, SECURE); } } - @Override - public String toString() { - return "Surface(name=" + mName + ")/@0x" + - Integer.toHexString(System.identityHashCode(this)); - } - /* * set display parameters. * needs to be inside open/closeTransaction block @@ -786,28 +741,50 @@ public class SurfaceControl { public static void setDisplayProjection(IBinder displayToken, int orientation, Rect layerStackRect, Rect displayRect) { - synchronized (SurfaceControl.class) { - sGlobalTransaction.setDisplayProjection(displayToken, orientation, - layerStackRect, displayRect); + if (displayToken == null) { + throw new IllegalArgumentException("displayToken must not be null"); + } + if (layerStackRect == null) { + throw new IllegalArgumentException("layerStackRect must not be null"); } + if (displayRect == null) { + throw new IllegalArgumentException("displayRect must not be null"); + } + nativeSetDisplayProjection(displayToken, orientation, + layerStackRect.left, layerStackRect.top, layerStackRect.right, layerStackRect.bottom, + displayRect.left, displayRect.top, displayRect.right, displayRect.bottom); } public static void setDisplayLayerStack(IBinder displayToken, int layerStack) { - synchronized (SurfaceControl.class) { - sGlobalTransaction.setDisplayLayerStack(displayToken, layerStack); + if (displayToken == null) { + throw new IllegalArgumentException("displayToken must not be null"); } + nativeSetDisplayLayerStack(displayToken, layerStack); } public static void setDisplaySurface(IBinder displayToken, Surface surface) { - synchronized (SurfaceControl.class) { - sGlobalTransaction.setDisplaySurface(displayToken, surface); + if (displayToken == null) { + throw new IllegalArgumentException("displayToken must not be null"); + } + + if (surface != null) { + synchronized (surface.mLock) { + nativeSetDisplaySurface(displayToken, surface.mNativeObject); + } + } else { + nativeSetDisplaySurface(displayToken, 0); } } public static void setDisplaySize(IBinder displayToken, int width, int height) { - synchronized (SurfaceControl.class) { - sGlobalTransaction.setDisplaySize(displayToken, width, height); + if (displayToken == null) { + throw new IllegalArgumentException("displayToken must not be null"); + } + if (width <= 0 || height <= 0) { + throw new IllegalArgumentException("width and height must be positive"); } + + nativeSetDisplaySize(displayToken, width, height); } public static Display.HdrCapabilities getHdrCapabilities(IBinder displayToken) { @@ -969,261 +946,4 @@ public class SurfaceControl { nativeScreenshot(display, consumer, sourceCrop, width, height, minLayer, maxLayer, allLayers, useIdentityTransform); } - - public static class Transaction implements Closeable { - public static final NativeAllocationRegistry sRegistry = new NativeAllocationRegistry( - Transaction.class.getClassLoader(), - nativeGetNativeTransactionFinalizer(), 512); - private long mNativeObject; - - Runnable mFreeNativeResources; - - public Transaction() { - mNativeObject = nativeCreateTransaction(); - mFreeNativeResources - = sRegistry.registerNativeAllocation(this, mNativeObject); - } - - /** - * Apply the transaction, clearing it's state, and making it usable - * as a new transaction. - */ - public void apply() { - apply(false); - } - - /** - * Close the transaction, if the transaction was not already applied this will cancel the - * transaction. - */ - @Override - public void close() { - mFreeNativeResources.run(); - mNativeObject = 0; - } - - /** - * Jankier version of apply. Avoid use (b/28068298). - */ - public void apply(boolean sync) { - nativeApplyTransaction(mNativeObject, sync); - } - - public Transaction show(SurfaceControl sc) { - nativeSetFlags(mNativeObject, sc.mNativeObject, 0, SURFACE_HIDDEN); - return this; - } - - public Transaction hide(SurfaceControl sc) { - nativeSetFlags(mNativeObject, sc.mNativeObject, SURFACE_HIDDEN, SURFACE_HIDDEN); - return this; - } - - public Transaction setPosition(SurfaceControl sc, float x, float y) { - nativeSetPosition(mNativeObject, sc.mNativeObject, x, y); - return this; - } - - public Transaction setSize(SurfaceControl sc, int w, int h) { - nativeSetSize(mNativeObject, sc.mNativeObject, - w, h); - return this; - } - - public Transaction setLayer(SurfaceControl sc, int z) { - nativeSetLayer(mNativeObject, sc.mNativeObject, z); - return this; - } - - public Transaction setRelativeLayer(SurfaceControl sc, IBinder relativeTo, int z) { - nativeSetRelativeLayer(mNativeObject, sc.mNativeObject, - relativeTo, z); - return this; - } - - public Transaction setTransparentRegionHint(SurfaceControl sc, Region transparentRegion) { - nativeSetTransparentRegionHint(mNativeObject, - sc.mNativeObject, transparentRegion); - return this; - } - - public Transaction setAlpha(SurfaceControl sc, float alpha) { - nativeSetAlpha(mNativeObject, sc.mNativeObject, alpha); - return this; - } - - public Transaction setMatrix(SurfaceControl sc, - float dsdx, float dtdx, float dtdy, float dsdy) { - nativeSetMatrix(mNativeObject, sc.mNativeObject, - dsdx, dtdx, dtdy, dsdy); - return this; - } - - public Transaction setWindowCrop(SurfaceControl sc, Rect crop) { - if (crop != null) { - nativeSetWindowCrop(mNativeObject, sc.mNativeObject, - crop.left, crop.top, crop.right, crop.bottom); - } else { - nativeSetWindowCrop(mNativeObject, sc.mNativeObject, 0, 0, 0, 0); - } - - return this; - } - - public Transaction setFinalCrop(SurfaceControl sc, Rect crop) { - if (crop != null) { - nativeSetFinalCrop(mNativeObject, sc.mNativeObject, - crop.left, crop.top, crop.right, crop.bottom); - } else { - nativeSetFinalCrop(mNativeObject, sc.mNativeObject, 0, 0, 0, 0); - } - - return this; - } - - public Transaction setLayerStack(SurfaceControl sc, int layerStack) { - nativeSetLayerStack(mNativeObject, sc.mNativeObject, layerStack); - return this; - } - - public Transaction deferTransactionUntil(SurfaceControl sc, IBinder handle, long frameNumber) { - nativeDeferTransactionUntil(mNativeObject, sc.mNativeObject, handle, frameNumber); - return this; - } - - public Transaction deferTransactionUntilSurface(SurfaceControl sc, Surface barrierSurface, - long frameNumber) { - nativeDeferTransactionUntilSurface(mNativeObject, sc.mNativeObject, - barrierSurface.mNativeObject, frameNumber); - return this; - } - - public Transaction reparentChildren(SurfaceControl sc, IBinder newParentHandle) { - nativeReparentChildren(mNativeObject, sc.mNativeObject, newParentHandle); - return this; - } - - /** Re-parents a specific child layer to a new parent */ - public Transaction reparent(SurfaceControl sc, IBinder newParentHandle) { - nativeReparent(mNativeObject, sc.mNativeObject, - newParentHandle); - return this; - } - - public Transaction detachChildren(SurfaceControl sc) { - nativeSeverChildren(mNativeObject, sc.mNativeObject); - return this; - } - - public Transaction setOverrideScalingMode(SurfaceControl sc, int overrideScalingMode) { - nativeSetOverrideScalingMode(mNativeObject, sc.mNativeObject, - overrideScalingMode); - return this; - } - - /** - * Sets a color for the Surface. - * @param color A float array with three values to represent r, g, b in range [0..1] - */ - public Transaction setColor(SurfaceControl sc, @Size(3) float[] color) { - nativeSetColor(mNativeObject, sc.mNativeObject, color); - return this; - } - - /** - * If the buffer size changes in this transaction, position and crop updates specified - * in this transaction will not complete until a buffer of the new size - * arrives. As transform matrix and size are already frozen in this fashion, - * this enables totally freezing the surface until the resize has completed - * (at which point the geometry influencing aspects of this transaction will then occur) - */ - public Transaction setGeometryAppliesWithResize(SurfaceControl sc) { - nativeSetGeometryAppliesWithResize(mNativeObject, sc.mNativeObject); - return this; - } - - /** - * Sets the security of the surface. Setting the flag is equivalent to creating the - * Surface with the {@link #SECURE} flag. - */ - Transaction setSecure(SurfaceControl sc, boolean isSecure) { - if (isSecure) { - nativeSetFlags(mNativeObject, sc.mNativeObject, SECURE, SECURE); - } else { - nativeSetFlags(mNativeObject, sc.mNativeObject, 0, SECURE); - } - return this; - } - - /** - * Sets the opacity of the surface. Setting the flag is equivalent to creating the - * Surface with the {@link #OPAQUE} flag. - */ - public Transaction setOpaque(SurfaceControl sc, boolean isOpaque) { - if (isOpaque) { - nativeSetFlags(mNativeObject, sc.mNativeObject, OPAQUE, OPAQUE); - } else { - nativeSetFlags(mNativeObject, sc.mNativeObject, 0, OPAQUE); - } - return this; - } - - public Transaction setDisplaySurface(IBinder displayToken, Surface surface) { - if (displayToken == null) { - throw new IllegalArgumentException("displayToken must not be null"); - } - - if (surface != null) { - synchronized (surface.mLock) { - nativeSetDisplaySurface(mNativeObject, displayToken, surface.mNativeObject); - } - } else { - nativeSetDisplaySurface(mNativeObject, displayToken, 0); - } - return this; - } - - public Transaction setDisplayLayerStack(IBinder displayToken, int layerStack) { - if (displayToken == null) { - throw new IllegalArgumentException("displayToken must not be null"); - } - nativeSetDisplayLayerStack(mNativeObject, displayToken, layerStack); - return this; - } - - public Transaction setDisplayProjection(IBinder displayToken, - int orientation, Rect layerStackRect, Rect displayRect) { - if (displayToken == null) { - throw new IllegalArgumentException("displayToken must not be null"); - } - if (layerStackRect == null) { - throw new IllegalArgumentException("layerStackRect must not be null"); - } - if (displayRect == null) { - throw new IllegalArgumentException("displayRect must not be null"); - } - nativeSetDisplayProjection(mNativeObject, displayToken, orientation, - layerStackRect.left, layerStackRect.top, layerStackRect.right, layerStackRect.bottom, - displayRect.left, displayRect.top, displayRect.right, displayRect.bottom); - return this; - } - - public Transaction setDisplaySize(IBinder displayToken, int width, int height) { - if (displayToken == null) { - throw new IllegalArgumentException("displayToken must not be null"); - } - if (width <= 0 || height <= 0) { - throw new IllegalArgumentException("width and height must be positive"); - } - - nativeSetDisplaySize(mNativeObject, displayToken, width, height); - return this; - } - - /** flag the transaction as an animation */ - public Transaction setAnimationTransaction() { - nativeSetAnimationTransaction(mNativeObject); - return this; - } - } } diff --git a/android/view/SurfaceView.java b/android/view/SurfaceView.java index ebb2af45..462dad3f 100644 --- a/android/view/SurfaceView.java +++ b/android/view/SurfaceView.java @@ -16,115 +16,1208 @@ package android.view; -import com.android.layoutlib.bridge.MockView; +import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_PANEL; +import static android.view.WindowManagerPolicy.APPLICATION_MEDIA_OVERLAY_SUBLAYER; +import static android.view.WindowManagerPolicy.APPLICATION_MEDIA_SUBLAYER; +import static android.view.WindowManagerPolicy.APPLICATION_PANEL_SUBLAYER; import android.content.Context; +import android.content.res.CompatibilityInfo.Translator; +import android.content.res.Configuration; import android.graphics.Canvas; +import android.graphics.PixelFormat; +import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.Region; +import android.os.Build; +import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; +import android.os.SystemClock; import android.util.AttributeSet; +import android.util.Log; + +import com.android.internal.view.SurfaceCallbackHelper; + +import java.util.ArrayList; +import java.util.concurrent.locks.ReentrantLock; /** - * Mock version of the SurfaceView. - * Only non override public methods from the real SurfaceView have been added in there. - * Methods that take an unknown class as parameter or as return object, have been removed for now. + * Provides a dedicated drawing surface embedded inside of a view hierarchy. + * You can control the format of this surface and, if you like, its size; the + * SurfaceView takes care of placing the surface at the correct location on the + * screen + * + *

    The surface is Z ordered so that it is behind the window holding its + * SurfaceView; the SurfaceView punches a hole in its window to allow its + * surface to be displayed. The view hierarchy will take care of correctly + * compositing with the Surface any siblings of the SurfaceView that would + * normally appear on top of it. This can be used to place overlays such as + * buttons on top of the Surface, though note however that it can have an + * impact on performance since a full alpha-blended composite will be performed + * each time the Surface changes. + * + *

    The transparent region that makes the surface visible is based on the + * layout positions in the view hierarchy. If the post-layout transform + * properties are used to draw a sibling view on top of the SurfaceView, the + * view may not be properly composited with the surface. * - * TODO: generate automatically. + *

    Access to the underlying surface is provided via the SurfaceHolder interface, + * which can be retrieved by calling {@link #getHolder}. * + *

    The Surface will be created for you while the SurfaceView's window is + * visible; you should implement {@link SurfaceHolder.Callback#surfaceCreated} + * and {@link SurfaceHolder.Callback#surfaceDestroyed} to discover when the + * Surface is created and destroyed as the window is shown and hidden. + * + *

    One of the purposes of this class is to provide a surface in which a + * secondary thread can render into the screen. If you are going to use it + * this way, you need to be aware of some threading semantics: + * + *

      + *
    • All SurfaceView and + * {@link SurfaceHolder.Callback SurfaceHolder.Callback} methods will be called + * from the thread running the SurfaceView's window (typically the main thread + * of the application). They thus need to correctly synchronize with any + * state that is also touched by the drawing thread. + *
    • You must ensure that the drawing thread only touches the underlying + * Surface while it is valid -- between + * {@link SurfaceHolder.Callback#surfaceCreated SurfaceHolder.Callback.surfaceCreated()} + * and + * {@link SurfaceHolder.Callback#surfaceDestroyed SurfaceHolder.Callback.surfaceDestroyed()}. + *
    + * + *

    Note: Starting in platform version + * {@link android.os.Build.VERSION_CODES#N}, SurfaceView's window position is + * updated synchronously with other View rendering. This means that translating + * and scaling a SurfaceView on screen will not cause rendering artifacts. Such + * artifacts may occur on previous versions of the platform when its window is + * positioned asynchronously.

    */ -public class SurfaceView extends MockView { +public class SurfaceView extends View implements ViewRootImpl.WindowStoppedCallback { + private static final String TAG = "SurfaceView"; + private static final boolean DEBUG = false; + + final ArrayList mCallbacks + = new ArrayList(); + + final int[] mLocation = new int[2]; + + final ReentrantLock mSurfaceLock = new ReentrantLock(); + final Surface mSurface = new Surface(); // Current surface in use + boolean mDrawingStopped = true; + // We use this to track if the application has produced a frame + // in to the Surface. Up until that point, we should be careful not to punch + // holes. + boolean mDrawFinished = false; + + final Rect mScreenRect = new Rect(); + SurfaceSession mSurfaceSession; + + SurfaceControl mSurfaceControl; + // In the case of format changes we switch out the surface in-place + // we need to preserve the old one until the new one has drawn. + SurfaceControl mDeferredDestroySurfaceControl; + final Rect mTmpRect = new Rect(); + final Configuration mConfiguration = new Configuration(); + + int mSubLayer = APPLICATION_MEDIA_SUBLAYER; + + boolean mIsCreating = false; + private volatile boolean mRtHandlingPositionUpdates = false; + + private final ViewTreeObserver.OnScrollChangedListener mScrollChangedListener + = new ViewTreeObserver.OnScrollChangedListener() { + @Override + public void onScrollChanged() { + updateSurface(); + } + }; + + private final ViewTreeObserver.OnPreDrawListener mDrawListener = + new ViewTreeObserver.OnPreDrawListener() { + @Override + public boolean onPreDraw() { + // reposition ourselves where the surface is + mHaveFrame = getWidth() > 0 && getHeight() > 0; + updateSurface(); + return true; + } + }; + + boolean mRequestedVisible = false; + boolean mWindowVisibility = false; + boolean mLastWindowVisibility = false; + boolean mViewVisibility = false; + boolean mWindowStopped = false; + + int mRequestedWidth = -1; + int mRequestedHeight = -1; + /* Set SurfaceView's format to 565 by default to maintain backward + * compatibility with applications assuming this format. + */ + int mRequestedFormat = PixelFormat.RGB_565; + + boolean mHaveFrame = false; + boolean mSurfaceCreated = false; + long mLastLockTime = 0; + + boolean mVisible = false; + int mWindowSpaceLeft = -1; + int mWindowSpaceTop = -1; + int mSurfaceWidth = -1; + int mSurfaceHeight = -1; + int mFormat = -1; + final Rect mSurfaceFrame = new Rect(); + int mLastSurfaceWidth = -1, mLastSurfaceHeight = -1; + private Translator mTranslator; + + private boolean mGlobalListenersAdded; + private boolean mAttachedToWindow; + + private int mSurfaceFlags = SurfaceControl.HIDDEN; + + private int mPendingReportDraws; public SurfaceView(Context context) { this(context, null); } public SurfaceView(Context context, AttributeSet attrs) { - this(context, attrs , 0); + this(context, attrs, 0); } - public SurfaceView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); + public SurfaceView(Context context, AttributeSet attrs, int defStyleAttr) { + this(context, attrs, defStyleAttr, 0); } public SurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); + mRenderNode.requestPositionUpdates(this); + + setWillNotDraw(true); + } + + /** + * Return the SurfaceHolder providing access and control over this + * SurfaceView's underlying surface. + * + * @return SurfaceHolder The holder of the surface. + */ + public SurfaceHolder getHolder() { + return mSurfaceHolder; + } + + private void updateRequestedVisibility() { + mRequestedVisible = mViewVisibility && mWindowVisibility && !mWindowStopped; + } + + /** @hide */ + @Override + public void windowStopped(boolean stopped) { + mWindowStopped = stopped; + updateRequestedVisibility(); + updateSurface(); } + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + + getViewRootImpl().addWindowStoppedCallback(this); + mWindowStopped = false; + + mViewVisibility = getVisibility() == VISIBLE; + updateRequestedVisibility(); + + mAttachedToWindow = true; + mParent.requestTransparentRegion(SurfaceView.this); + if (!mGlobalListenersAdded) { + ViewTreeObserver observer = getViewTreeObserver(); + observer.addOnScrollChangedListener(mScrollChangedListener); + observer.addOnPreDrawListener(mDrawListener); + mGlobalListenersAdded = true; + } + } + + @Override + protected void onWindowVisibilityChanged(int visibility) { + super.onWindowVisibilityChanged(visibility); + mWindowVisibility = visibility == VISIBLE; + updateRequestedVisibility(); + updateSurface(); + } + + @Override + public void setVisibility(int visibility) { + super.setVisibility(visibility); + mViewVisibility = visibility == VISIBLE; + boolean newRequestedVisible = mWindowVisibility && mViewVisibility && !mWindowStopped; + if (newRequestedVisible != mRequestedVisible) { + // our base class (View) invalidates the layout only when + // we go from/to the GONE state. However, SurfaceView needs + // to request a re-layout when the visibility changes at all. + // This is needed because the transparent region is computed + // as part of the layout phase, and it changes (obviously) when + // the visibility changes. + requestLayout(); + } + mRequestedVisible = newRequestedVisible; + updateSurface(); + } + + private void performDrawFinished() { + if (mPendingReportDraws > 0) { + mDrawFinished = true; + if (mAttachedToWindow) { + notifyDrawFinished(); + invalidate(); + } + } else { + Log.e(TAG, System.identityHashCode(this) + "finished drawing" + + " but no pending report draw (extra call" + + " to draw completion runnable?)"); + } + } + + void notifyDrawFinished() { + ViewRootImpl viewRoot = getViewRootImpl(); + if (viewRoot != null) { + viewRoot.pendingDrawFinished(); + } + mPendingReportDraws--; + } + + @Override + protected void onDetachedFromWindow() { + ViewRootImpl viewRoot = getViewRootImpl(); + // It's possible to create a SurfaceView using the default constructor and never + // attach it to a view hierarchy, this is a common use case when dealing with + // OpenGL. A developer will probably create a new GLSurfaceView, and let it manage + // the lifecycle. Instead of attaching it to a view, he/she can just pass + // the SurfaceHolder forward, most live wallpapers do it. + if (viewRoot != null) { + viewRoot.removeWindowStoppedCallback(this); + } + + mAttachedToWindow = false; + if (mGlobalListenersAdded) { + ViewTreeObserver observer = getViewTreeObserver(); + observer.removeOnScrollChangedListener(mScrollChangedListener); + observer.removeOnPreDrawListener(mDrawListener); + mGlobalListenersAdded = false; + } + + while (mPendingReportDraws > 0) { + notifyDrawFinished(); + } + + mRequestedVisible = false; + + updateSurface(); + if (mSurfaceControl != null) { + mSurfaceControl.destroy(); + } + mSurfaceControl = null; + + mHaveFrame = false; + + super.onDetachedFromWindow(); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + int width = mRequestedWidth >= 0 + ? resolveSizeAndState(mRequestedWidth, widthMeasureSpec, 0) + : getDefaultSize(0, widthMeasureSpec); + int height = mRequestedHeight >= 0 + ? resolveSizeAndState(mRequestedHeight, heightMeasureSpec, 0) + : getDefaultSize(0, heightMeasureSpec); + setMeasuredDimension(width, height); + } + + /** @hide */ + @Override + protected boolean setFrame(int left, int top, int right, int bottom) { + boolean result = super.setFrame(left, top, right, bottom); + updateSurface(); + return result; + } + + @Override public boolean gatherTransparentRegion(Region region) { - return false; + if (isAboveParent() || !mDrawFinished) { + return super.gatherTransparentRegion(region); + } + + boolean opaque = true; + if ((mPrivateFlags & PFLAG_SKIP_DRAW) == 0) { + // this view draws, remove it from the transparent region + opaque = super.gatherTransparentRegion(region); + } else if (region != null) { + int w = getWidth(); + int h = getHeight(); + if (w>0 && h>0) { + getLocationInWindow(mLocation); + // otherwise, punch a hole in the whole hierarchy + int l = mLocation[0]; + int t = mLocation[1]; + region.op(l, t, l+w, t+h, Region.Op.UNION); + } + } + if (PixelFormat.formatHasAlpha(mRequestedFormat)) { + opaque = false; + } + return opaque; } + @Override + public void draw(Canvas canvas) { + if (mDrawFinished && !isAboveParent()) { + // draw() is not called when SKIP_DRAW is set + if ((mPrivateFlags & PFLAG_SKIP_DRAW) == 0) { + // punch a whole in the view-hierarchy below us + canvas.drawColor(0, PorterDuff.Mode.CLEAR); + } + } + super.draw(canvas); + } + + @Override + protected void dispatchDraw(Canvas canvas) { + if (mDrawFinished && !isAboveParent()) { + // draw() is not called when SKIP_DRAW is set + if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) { + // punch a whole in the view-hierarchy below us + canvas.drawColor(0, PorterDuff.Mode.CLEAR); + } + } + super.dispatchDraw(canvas); + } + + /** + * Control whether the surface view's surface is placed on top of another + * regular surface view in the window (but still behind the window itself). + * This is typically used to place overlays on top of an underlying media + * surface view. + * + *

    Note that this must be set before the surface view's containing + * window is attached to the window manager. + * + *

    Calling this overrides any previous call to {@link #setZOrderOnTop}. + */ public void setZOrderMediaOverlay(boolean isMediaOverlay) { + mSubLayer = isMediaOverlay + ? APPLICATION_MEDIA_OVERLAY_SUBLAYER : APPLICATION_MEDIA_SUBLAYER; } + /** + * Control whether the surface view's surface is placed on top of its + * window. Normally it is placed behind the window, to allow it to + * (for the most part) appear to composite with the views in the + * hierarchy. By setting this, you cause it to be placed above the + * window. This means that none of the contents of the window this + * SurfaceView is in will be visible on top of its surface. + * + *

    Note that this must be set before the surface view's containing + * window is attached to the window manager. + * + *

    Calling this overrides any previous call to {@link #setZOrderMediaOverlay}. + */ public void setZOrderOnTop(boolean onTop) { + if (onTop) { + mSubLayer = APPLICATION_PANEL_SUBLAYER; + } else { + mSubLayer = APPLICATION_MEDIA_SUBLAYER; + } } + /** + * Control whether the surface view's content should be treated as secure, + * preventing it from appearing in screenshots or from being viewed on + * non-secure displays. + * + *

    Note that this must be set before the surface view's containing + * window is attached to the window manager. + * + *

    See {@link android.view.Display#FLAG_SECURE} for details. + * + * @param isSecure True if the surface view is secure. + */ public void setSecure(boolean isSecure) { + if (isSecure) { + mSurfaceFlags |= SurfaceControl.SECURE; + } else { + mSurfaceFlags &= ~SurfaceControl.SECURE; + } } - public SurfaceHolder getHolder() { - return mSurfaceHolder; + private void updateOpaqueFlag() { + if (!PixelFormat.formatHasAlpha(mRequestedFormat)) { + mSurfaceFlags |= SurfaceControl.OPAQUE; + } else { + mSurfaceFlags &= ~SurfaceControl.OPAQUE; + } } - private SurfaceHolder mSurfaceHolder = new SurfaceHolder() { + private Rect getParentSurfaceInsets() { + final ViewRootImpl root = getViewRootImpl(); + if (root == null) { + return null; + } else { + return root.mWindowAttributes.surfaceInsets; + } + } + + /** @hide */ + protected void updateSurface() { + if (!mHaveFrame) { + return; + } + ViewRootImpl viewRoot = getViewRootImpl(); + if (viewRoot == null || viewRoot.mSurface == null || !viewRoot.mSurface.isValid()) { + return; + } + + mTranslator = viewRoot.mTranslator; + if (mTranslator != null) { + mSurface.setCompatibilityTranslator(mTranslator); + } + + int myWidth = mRequestedWidth; + if (myWidth <= 0) myWidth = getWidth(); + int myHeight = mRequestedHeight; + if (myHeight <= 0) myHeight = getHeight(); + + final boolean formatChanged = mFormat != mRequestedFormat; + final boolean visibleChanged = mVisible != mRequestedVisible; + final boolean creating = (mSurfaceControl == null || formatChanged || visibleChanged) + && mRequestedVisible; + final boolean sizeChanged = mSurfaceWidth != myWidth || mSurfaceHeight != myHeight; + final boolean windowVisibleChanged = mWindowVisibility != mLastWindowVisibility; + boolean redrawNeeded = false; + + if (creating || formatChanged || sizeChanged || visibleChanged || windowVisibleChanged) { + getLocationInWindow(mLocation); + + if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + + "Changes: creating=" + creating + + " format=" + formatChanged + " size=" + sizeChanged + + " visible=" + visibleChanged + + " left=" + (mWindowSpaceLeft != mLocation[0]) + + " top=" + (mWindowSpaceTop != mLocation[1])); + + try { + final boolean visible = mVisible = mRequestedVisible; + mWindowSpaceLeft = mLocation[0]; + mWindowSpaceTop = mLocation[1]; + mSurfaceWidth = myWidth; + mSurfaceHeight = myHeight; + mFormat = mRequestedFormat; + mLastWindowVisibility = mWindowVisibility; + + mScreenRect.left = mWindowSpaceLeft; + mScreenRect.top = mWindowSpaceTop; + mScreenRect.right = mWindowSpaceLeft + getWidth(); + mScreenRect.bottom = mWindowSpaceTop + getHeight(); + if (mTranslator != null) { + mTranslator.translateRectInAppWindowToScreen(mScreenRect); + } + + final Rect surfaceInsets = getParentSurfaceInsets(); + mScreenRect.offset(surfaceInsets.left, surfaceInsets.top); + + if (creating) { + mSurfaceSession = new SurfaceSession(viewRoot.mSurface); + mDeferredDestroySurfaceControl = mSurfaceControl; + + updateOpaqueFlag(); + mSurfaceControl = new SurfaceControlWithBackground(mSurfaceSession, + "SurfaceView - " + viewRoot.getTitle().toString(), + mSurfaceWidth, mSurfaceHeight, mFormat, + mSurfaceFlags); + } else if (mSurfaceControl == null) { + return; + } + + boolean realSizeChanged = false; + + mSurfaceLock.lock(); + try { + mDrawingStopped = !visible; + + if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + + "Cur surface: " + mSurface); + + SurfaceControl.openTransaction(); + try { + mSurfaceControl.setLayer(mSubLayer); + if (mViewVisibility) { + mSurfaceControl.show(); + } else { + mSurfaceControl.hide(); + } + + // While creating the surface, we will set it's initial + // geometry. Outside of that though, we should generally + // leave it to the RenderThread. + // + // There is one more case when the buffer size changes we aren't yet + // prepared to sync (as even following the transaction applying + // we still need to latch a buffer). + // b/28866173 + if (sizeChanged || creating || !mRtHandlingPositionUpdates) { + mSurfaceControl.setPosition(mScreenRect.left, mScreenRect.top); + mSurfaceControl.setMatrix(mScreenRect.width() / (float) mSurfaceWidth, + 0.0f, 0.0f, + mScreenRect.height() / (float) mSurfaceHeight); + } + if (sizeChanged) { + mSurfaceControl.setSize(mSurfaceWidth, mSurfaceHeight); + } + } finally { + SurfaceControl.closeTransaction(); + } + + if (sizeChanged || creating) { + redrawNeeded = true; + } + + mSurfaceFrame.left = 0; + mSurfaceFrame.top = 0; + if (mTranslator == null) { + mSurfaceFrame.right = mSurfaceWidth; + mSurfaceFrame.bottom = mSurfaceHeight; + } else { + float appInvertedScale = mTranslator.applicationInvertedScale; + mSurfaceFrame.right = (int) (mSurfaceWidth * appInvertedScale + 0.5f); + mSurfaceFrame.bottom = (int) (mSurfaceHeight * appInvertedScale + 0.5f); + } + + final int surfaceWidth = mSurfaceFrame.right; + final int surfaceHeight = mSurfaceFrame.bottom; + realSizeChanged = mLastSurfaceWidth != surfaceWidth + || mLastSurfaceHeight != surfaceHeight; + mLastSurfaceWidth = surfaceWidth; + mLastSurfaceHeight = surfaceHeight; + } finally { + mSurfaceLock.unlock(); + } + + try { + redrawNeeded |= visible && !mDrawFinished; + + SurfaceHolder.Callback callbacks[] = null; + + final boolean surfaceChanged = creating; + if (mSurfaceCreated && (surfaceChanged || (!visible && visibleChanged))) { + mSurfaceCreated = false; + if (mSurface.isValid()) { + if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + + "visibleChanged -- surfaceDestroyed"); + callbacks = getSurfaceCallbacks(); + for (SurfaceHolder.Callback c : callbacks) { + c.surfaceDestroyed(mSurfaceHolder); + } + // Since Android N the same surface may be reused and given to us + // again by the system server at a later point. However + // as we didn't do this in previous releases, clients weren't + // necessarily required to clean up properly in + // surfaceDestroyed. This leads to problems for example when + // clients don't destroy their EGL context, and try + // and create a new one on the same surface following reuse. + // Since there is no valid use of the surface in-between + // surfaceDestroyed and surfaceCreated, we force a disconnect, + // so the next connect will always work if we end up reusing + // the surface. + if (mSurface.isValid()) { + mSurface.forceScopedDisconnect(); + } + } + } + + if (creating) { + mSurface.copyFrom(mSurfaceControl); + } + + if (sizeChanged && getContext().getApplicationInfo().targetSdkVersion + < Build.VERSION_CODES.O) { + // Some legacy applications use the underlying native {@link Surface} object + // as a key to whether anything has changed. In these cases, updates to the + // existing {@link Surface} will be ignored when the size changes. + // Therefore, we must explicitly recreate the {@link Surface} in these + // cases. + mSurface.createFrom(mSurfaceControl); + } + + if (visible && mSurface.isValid()) { + if (!mSurfaceCreated && (surfaceChanged || visibleChanged)) { + mSurfaceCreated = true; + mIsCreating = true; + if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + + "visibleChanged -- surfaceCreated"); + if (callbacks == null) { + callbacks = getSurfaceCallbacks(); + } + for (SurfaceHolder.Callback c : callbacks) { + c.surfaceCreated(mSurfaceHolder); + } + } + if (creating || formatChanged || sizeChanged + || visibleChanged || realSizeChanged) { + if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + + "surfaceChanged -- format=" + mFormat + + " w=" + myWidth + " h=" + myHeight); + if (callbacks == null) { + callbacks = getSurfaceCallbacks(); + } + for (SurfaceHolder.Callback c : callbacks) { + c.surfaceChanged(mSurfaceHolder, mFormat, myWidth, myHeight); + } + } + if (redrawNeeded) { + if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + + "surfaceRedrawNeeded"); + if (callbacks == null) { + callbacks = getSurfaceCallbacks(); + } + + mPendingReportDraws++; + viewRoot.drawPending(); + SurfaceCallbackHelper sch = + new SurfaceCallbackHelper(this::onDrawFinished); + sch.dispatchSurfaceRedrawNeededAsync(mSurfaceHolder, callbacks); + } + } + } finally { + mIsCreating = false; + if (mSurfaceControl != null && !mSurfaceCreated) { + mSurface.release(); + // If we are not in the stopped state, then the destruction of the Surface + // represents a visual change we need to display, and we should go ahead + // and destroy the SurfaceControl. However if we are in the stopped state, + // we can just leave the Surface around so it can be a part of animations, + // and we let the life-time be tied to the parent surface. + if (!mWindowStopped) { + mSurfaceControl.destroy(); + mSurfaceControl = null; + } + } + } + } catch (Exception ex) { + Log.e(TAG, "Exception configuring surface", ex); + } + if (DEBUG) Log.v( + TAG, "Layout: x=" + mScreenRect.left + " y=" + mScreenRect.top + + " w=" + mScreenRect.width() + " h=" + mScreenRect.height() + + ", frame=" + mSurfaceFrame); + } else { + // Calculate the window position in case RT loses the window + // and we need to fallback to a UI-thread driven position update + getLocationInSurface(mLocation); + final boolean positionChanged = mWindowSpaceLeft != mLocation[0] + || mWindowSpaceTop != mLocation[1]; + final boolean layoutSizeChanged = getWidth() != mScreenRect.width() + || getHeight() != mScreenRect.height(); + if (positionChanged || layoutSizeChanged) { // Only the position has changed + mWindowSpaceLeft = mLocation[0]; + mWindowSpaceTop = mLocation[1]; + // For our size changed check, we keep mScreenRect.width() and mScreenRect.height() + // in view local space. + mLocation[0] = getWidth(); + mLocation[1] = getHeight(); + + mScreenRect.set(mWindowSpaceLeft, mWindowSpaceTop, + mWindowSpaceLeft + mLocation[0], mWindowSpaceTop + mLocation[1]); + + if (mTranslator != null) { + mTranslator.translateRectInAppWindowToScreen(mScreenRect); + } + + if (mSurfaceControl == null) { + return; + } + + if (!isHardwareAccelerated() || !mRtHandlingPositionUpdates) { + try { + if (DEBUG) Log.d(TAG, String.format("%d updateSurfacePosition UI, " + + "postion = [%d, %d, %d, %d]", System.identityHashCode(this), + mScreenRect.left, mScreenRect.top, + mScreenRect.right, mScreenRect.bottom)); + setParentSpaceRectangle(mScreenRect, -1); + } catch (Exception ex) { + Log.e(TAG, "Exception configuring surface", ex); + } + } + } + } + } + + private void onDrawFinished() { + if (DEBUG) { + Log.i(TAG, System.identityHashCode(this) + " " + + "finishedDrawing"); + } + + if (mDeferredDestroySurfaceControl != null) { + mDeferredDestroySurfaceControl.destroy(); + mDeferredDestroySurfaceControl = null; + } + + runOnUiThread(() -> { + performDrawFinished(); + }); + } + + private void setParentSpaceRectangle(Rect position, long frameNumber) { + ViewRootImpl viewRoot = getViewRootImpl(); + + SurfaceControl.openTransaction(); + try { + if (frameNumber > 0) { + mSurfaceControl.deferTransactionUntil(viewRoot.mSurface, frameNumber); + } + mSurfaceControl.setPosition(position.left, position.top); + mSurfaceControl.setMatrix(position.width() / (float) mSurfaceWidth, + 0.0f, 0.0f, + position.height() / (float) mSurfaceHeight); + } finally { + SurfaceControl.closeTransaction(); + } + } + + private Rect mRTLastReportedPosition = new Rect(); + + /** + * Called by native by a Rendering Worker thread to update the window position + * @hide + */ + public final void updateSurfacePosition_renderWorker(long frameNumber, + int left, int top, int right, int bottom) { + if (mSurfaceControl == null) { + return; + } + + // TODO: This is teensy bit racey in that a brand new SurfaceView moving on + // its 2nd frame if RenderThread is running slowly could potentially see + // this as false, enter the branch, get pre-empted, then this comes along + // and reports a new position, then the UI thread resumes and reports + // its position. This could therefore be de-sync'd in that interval, but + // the synchronization would violate the rule that RT must never block + // on the UI thread which would open up potential deadlocks. The risk of + // a single-frame desync is therefore preferable for now. + mRtHandlingPositionUpdates = true; + if (mRTLastReportedPosition.left == left + && mRTLastReportedPosition.top == top + && mRTLastReportedPosition.right == right + && mRTLastReportedPosition.bottom == bottom) { + return; + } + try { + if (DEBUG) { + Log.d(TAG, String.format("%d updateSurfacePosition RenderWorker, frameNr = %d, " + + "postion = [%d, %d, %d, %d]", System.identityHashCode(this), + frameNumber, left, top, right, bottom)); + } + mRTLastReportedPosition.set(left, top, right, bottom); + setParentSpaceRectangle(mRTLastReportedPosition, frameNumber); + // Now overwrite mRTLastReportedPosition with our values + } catch (Exception ex) { + Log.e(TAG, "Exception from repositionChild", ex); + } + } + + /** + * Called by native on RenderThread to notify that the view is no longer in the + * draw tree. UI thread is blocked at this point. + * @hide + */ + public final void surfacePositionLost_uiRtSync(long frameNumber) { + if (DEBUG) { + Log.d(TAG, String.format("%d windowPositionLost, frameNr = %d", + System.identityHashCode(this), frameNumber)); + } + mRTLastReportedPosition.setEmpty(); + + if (mSurfaceControl == null) { + return; + } + if (mRtHandlingPositionUpdates) { + mRtHandlingPositionUpdates = false; + // This callback will happen while the UI thread is blocked, so we can + // safely access other member variables at this time. + // So do what the UI thread would have done if RT wasn't handling position + // updates. + if (!mScreenRect.isEmpty() && !mScreenRect.equals(mRTLastReportedPosition)) { + try { + if (DEBUG) Log.d(TAG, String.format("%d updateSurfacePosition, " + + "postion = [%d, %d, %d, %d]", System.identityHashCode(this), + mScreenRect.left, mScreenRect.top, + mScreenRect.right, mScreenRect.bottom)); + setParentSpaceRectangle(mScreenRect, frameNumber); + } catch (Exception ex) { + Log.e(TAG, "Exception configuring surface", ex); + } + } + } + } + + private SurfaceHolder.Callback[] getSurfaceCallbacks() { + SurfaceHolder.Callback callbacks[]; + synchronized (mCallbacks) { + callbacks = new SurfaceHolder.Callback[mCallbacks.size()]; + mCallbacks.toArray(callbacks); + } + return callbacks; + } + + /** + * This method still exists only for compatibility reasons because some applications have relied + * on this method via reflection. See Issue 36345857 for details. + * + * @deprecated No platform code is using this method anymore. + * @hide + */ + @Deprecated + public void setWindowType(int type) { + if (getContext().getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) { + throw new UnsupportedOperationException( + "SurfaceView#setWindowType() has never been a public API."); + } + + if (type == TYPE_APPLICATION_PANEL) { + Log.e(TAG, "If you are calling SurfaceView#setWindowType(TYPE_APPLICATION_PANEL) " + + "just to make the SurfaceView to be placed on top of its window, you must " + + "call setZOrderOnTop(true) instead.", new Throwable()); + setZOrderOnTop(true); + return; + } + Log.e(TAG, "SurfaceView#setWindowType(int) is deprecated and now does nothing. " + + "type=" + type, new Throwable()); + } + + private void runOnUiThread(Runnable runnable) { + Handler handler = getHandler(); + if (handler != null && handler.getLooper() != Looper.myLooper()) { + handler.post(runnable); + } else { + runnable.run(); + } + } + + /** + * Check to see if the surface has fixed size dimensions or if the surface's + * dimensions are dimensions are dependent on its current layout. + * + * @return true if the surface has dimensions that are fixed in size + * @hide + */ + public boolean isFixedSize() { + return (mRequestedWidth != -1 || mRequestedHeight != -1); + } + + private boolean isAboveParent() { + return mSubLayer >= 0; + } + + private final SurfaceHolder mSurfaceHolder = new SurfaceHolder() { + private static final String LOG_TAG = "SurfaceHolder"; @Override public boolean isCreating() { - return false; + return mIsCreating; } @Override public void addCallback(Callback callback) { + synchronized (mCallbacks) { + // This is a linear search, but in practice we'll + // have only a couple callbacks, so it doesn't matter. + if (mCallbacks.contains(callback) == false) { + mCallbacks.add(callback); + } + } } @Override public void removeCallback(Callback callback) { + synchronized (mCallbacks) { + mCallbacks.remove(callback); + } } @Override public void setFixedSize(int width, int height) { + if (mRequestedWidth != width || mRequestedHeight != height) { + mRequestedWidth = width; + mRequestedHeight = height; + requestLayout(); + } } @Override public void setSizeFromLayout() { + if (mRequestedWidth != -1 || mRequestedHeight != -1) { + mRequestedWidth = mRequestedHeight = -1; + requestLayout(); + } } @Override public void setFormat(int format) { + // for backward compatibility reason, OPAQUE always + // means 565 for SurfaceView + if (format == PixelFormat.OPAQUE) + format = PixelFormat.RGB_565; + + mRequestedFormat = format; + if (mSurfaceControl != null) { + updateSurface(); + } } + /** + * @deprecated setType is now ignored. + */ @Override - public void setType(int type) { - } + @Deprecated + public void setType(int type) { } @Override public void setKeepScreenOn(boolean screenOn) { + runOnUiThread(() -> SurfaceView.this.setKeepScreenOn(screenOn)); } + /** + * Gets a {@link Canvas} for drawing into the SurfaceView's Surface + * + * After drawing into the provided {@link Canvas}, the caller must + * invoke {@link #unlockCanvasAndPost} to post the new contents to the surface. + * + * The caller must redraw the entire surface. + * @return A canvas for drawing into the surface. + */ @Override public Canvas lockCanvas() { - return null; + return internalLockCanvas(null, false); } + /** + * Gets a {@link Canvas} for drawing into the SurfaceView's Surface + * + * After drawing into the provided {@link Canvas}, the caller must + * invoke {@link #unlockCanvasAndPost} to post the new contents to the surface. + * + * @param inOutDirty A rectangle that represents the dirty region that the caller wants + * to redraw. This function may choose to expand the dirty rectangle if for example + * the surface has been resized or if the previous contents of the surface were + * not available. The caller must redraw the entire dirty region as represented + * by the contents of the inOutDirty rectangle upon return from this function. + * The caller may also pass null instead, in the case where the + * entire surface should be redrawn. + * @return A canvas for drawing into the surface. + */ @Override - public Canvas lockCanvas(Rect dirty) { + public Canvas lockCanvas(Rect inOutDirty) { + return internalLockCanvas(inOutDirty, false); + } + + @Override + public Canvas lockHardwareCanvas() { + return internalLockCanvas(null, true); + } + + private Canvas internalLockCanvas(Rect dirty, boolean hardware) { + mSurfaceLock.lock(); + + if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + "Locking canvas... stopped=" + + mDrawingStopped + ", surfaceControl=" + mSurfaceControl); + + Canvas c = null; + if (!mDrawingStopped && mSurfaceControl != null) { + try { + if (hardware) { + c = mSurface.lockHardwareCanvas(); + } else { + c = mSurface.lockCanvas(dirty); + } + } catch (Exception e) { + Log.e(LOG_TAG, "Exception locking surface", e); + } + } + + if (DEBUG) Log.i(TAG, System.identityHashCode(this) + " " + "Returned canvas: " + c); + if (c != null) { + mLastLockTime = SystemClock.uptimeMillis(); + return c; + } + + // If the Surface is not ready to be drawn, then return null, + // but throttle calls to this function so it isn't called more + // than every 100ms. + long now = SystemClock.uptimeMillis(); + long nextTime = mLastLockTime + 100; + if (nextTime > now) { + try { + Thread.sleep(nextTime-now); + } catch (InterruptedException e) { + } + now = SystemClock.uptimeMillis(); + } + mLastLockTime = now; + mSurfaceLock.unlock(); + return null; } + /** + * Posts the new contents of the {@link Canvas} to the surface and + * releases the {@link Canvas}. + * + * @param canvas The canvas previously obtained from {@link #lockCanvas}. + */ @Override public void unlockCanvasAndPost(Canvas canvas) { + mSurface.unlockCanvasAndPost(canvas); + mSurfaceLock.unlock(); } @Override public Surface getSurface() { - return null; + return mSurface; } @Override public Rect getSurfaceFrame() { - return null; + return mSurfaceFrame; } }; -} + class SurfaceControlWithBackground extends SurfaceControl { + private SurfaceControl mBackgroundControl; + private boolean mOpaque = true; + public boolean mVisible = false; + + public SurfaceControlWithBackground(SurfaceSession s, + String name, int w, int h, int format, int flags) + throws Exception { + super(s, name, w, h, format, flags); + mBackgroundControl = new SurfaceControl(s, "Background for - " + name, w, h, + PixelFormat.OPAQUE, flags | SurfaceControl.FX_SURFACE_DIM); + mOpaque = (flags & SurfaceControl.OPAQUE) != 0; + } + + @Override + public void setAlpha(float alpha) { + super.setAlpha(alpha); + mBackgroundControl.setAlpha(alpha); + } + + @Override + public void setLayer(int zorder) { + super.setLayer(zorder); + // -3 is below all other child layers as SurfaceView never goes below -2 + mBackgroundControl.setLayer(-3); + } + + @Override + public void setPosition(float x, float y) { + super.setPosition(x, y); + mBackgroundControl.setPosition(x, y); + } + + @Override + public void setSize(int w, int h) { + super.setSize(w, h); + mBackgroundControl.setSize(w, h); + } + + @Override + public void setWindowCrop(Rect crop) { + super.setWindowCrop(crop); + mBackgroundControl.setWindowCrop(crop); + } + + @Override + public void setFinalCrop(Rect crop) { + super.setFinalCrop(crop); + mBackgroundControl.setFinalCrop(crop); + } + + @Override + public void setLayerStack(int layerStack) { + super.setLayerStack(layerStack); + mBackgroundControl.setLayerStack(layerStack); + } + + @Override + public void setOpaque(boolean isOpaque) { + super.setOpaque(isOpaque); + mOpaque = isOpaque; + updateBackgroundVisibility(); + } + + @Override + public void setSecure(boolean isSecure) { + super.setSecure(isSecure); + } + + @Override + public void setMatrix(float dsdx, float dtdx, float dsdy, float dtdy) { + super.setMatrix(dsdx, dtdx, dsdy, dtdy); + mBackgroundControl.setMatrix(dsdx, dtdx, dsdy, dtdy); + } + + @Override + public void hide() { + super.hide(); + mVisible = false; + updateBackgroundVisibility(); + } + + @Override + public void show() { + super.show(); + mVisible = true; + updateBackgroundVisibility(); + } + + @Override + public void destroy() { + super.destroy(); + mBackgroundControl.destroy(); + } + + @Override + public void release() { + super.release(); + mBackgroundControl.release(); + } + + @Override + public void setTransparentRegionHint(Region region) { + super.setTransparentRegionHint(region); + mBackgroundControl.setTransparentRegionHint(region); + } + + @Override + public void deferTransactionUntil(IBinder handle, long frame) { + super.deferTransactionUntil(handle, frame); + mBackgroundControl.deferTransactionUntil(handle, frame); + } + + @Override + public void deferTransactionUntil(Surface barrier, long frame) { + super.deferTransactionUntil(barrier, frame); + mBackgroundControl.deferTransactionUntil(barrier, frame); + } + + void updateBackgroundVisibility() { + if (mOpaque && mVisible) { + mBackgroundControl.show(); + } else { + mBackgroundControl.hide(); + } + } + } +} diff --git a/android/view/View.java b/android/view/View.java index c043dcac..b6be2961 100644 --- a/android/view/View.java +++ b/android/view/View.java @@ -1448,59 +1448,17 @@ public class View implements Drawable.Callback, KeyEvent.Callback, /** *

    Enables low quality mode for the drawing cache.

    - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public static final int DRAWING_CACHE_QUALITY_LOW = 0x00080000; /** *

    Enables high quality mode for the drawing cache.

    - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public static final int DRAWING_CACHE_QUALITY_HIGH = 0x00100000; /** *

    Enables automatic quality mode for the drawing cache.

    - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public static final int DRAWING_CACHE_QUALITY_AUTO = 0x00000000; private static final int[] DRAWING_CACHE_QUALITY_FLAGS = { @@ -2342,9 +2300,9 @@ public class View implements Drawable.Callback, KeyEvent.Callback, private static final int PFLAG_HOVERED = 0x10000000; /** - * Flag set by {@link AutofillManager} if it needs to be notified when this view is clicked. + * no longer needed, should be reused */ - private static final int PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK = 0x20000000; + private static final int PFLAG_DOES_NOTHING_REUSE_PLEASE = 0x20000000; /** {@hide} */ static final int PFLAG_ACTIVATED = 0x40000000; @@ -6397,42 +6355,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback, return null; } - /** @hide */ - public void setNotifyAutofillManagerOnClick(boolean notify) { - if (notify) { - mPrivateFlags |= PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK; - } else { - mPrivateFlags &= ~PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK; - } - } - - private void notifyAutofillManagerOnClick() { - if ((mPrivateFlags & PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK) != 0) { - try { - getAutofillManager().notifyViewClicked(this); - } finally { - // Set it to already called so it's not called twice when called by - // performClickInternal() - mPrivateFlags |= ~PFLAG_NOTIFY_AUTOFILL_MANAGER_ON_CLICK; - } - } - } - - /** - * Entry point for {@link #performClick()} - other methods on View should call it instead of - * {@code performClick()} directly to make sure the autofill manager is notified when - * necessary (as subclasses could extend {@code performClick()} without calling the parent's - * method). - */ - private boolean performClickInternal() { - // Must notify autofill manager before performing the click actions to avoid scenarios where - // the app has a click listener that changes the state of views the autofill service might - // be interested on. - notifyAutofillManagerOnClick(); - - return performClick(); - } - /** * Call this view's OnClickListener, if it is defined. Performs all normal * actions associated with clicking: reporting accessibility event, playing @@ -6441,14 +6363,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * @return True there was an assigned OnClickListener that was called, false * otherwise is returned. */ - // NOTE: other methods on View should not call this method directly, but performClickInternal() - // instead, to guarantee that the autofill manager is notified when necessary (as subclasses - // could extend this method without calling super.performClick()). public boolean performClick() { - // We still need to call this method to handle the cases where performClick() was called - // externally, instead of through performClickInternal() - notifyAutofillManagerOnClick(); - final boolean result; final ListenerInfo li = mListenerInfo; if (li != null && li.mOnClickListener != null) { @@ -8992,21 +8907,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * @see #isDrawingCacheEnabled() * * @attr ref android.R.styleable#View_drawingCacheQuality - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated @DrawingCacheQuality public int getDrawingCacheQuality() { return mViewFlags & DRAWING_CACHE_QUALITY_MASK; @@ -9024,21 +8925,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * @see #isDrawingCacheEnabled() * * @attr ref android.R.styleable#View_drawingCacheQuality - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public void setDrawingCacheQuality(@DrawingCacheQuality int quality) { setFlags(quality, DRAWING_CACHE_QUALITY_MASK); } @@ -11546,7 +11433,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, switch (action) { case AccessibilityNodeInfo.ACTION_CLICK: { if (isClickable()) { - performClickInternal(); + performClick(); return true; } } break; @@ -12658,7 +12545,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, // This is a tap, so remove the longpress check removeLongPressCallback(); if (!event.isCanceled()) { - return performClickInternal(); + return performClick(); } } } @@ -13230,7 +13117,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, mPerformClick = new PerformClick(); } if (!post(mPerformClick)) { - performClickInternal(); + performClick(); } } } @@ -18216,21 +18103,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * @see #getDrawingCache() * @see #buildDrawingCache() * @see #setLayerType(int, android.graphics.Paint) - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public void setDrawingCacheEnabled(boolean enabled) { mCachingFailed = false; setFlags(enabled ? DRAWING_CACHE_ENABLED : 0, DRAWING_CACHE_ENABLED); @@ -18243,21 +18116,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * * @see #setDrawingCacheEnabled(boolean) * @see #getDrawingCache() - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated @ViewDebug.ExportedProperty(category = "drawing") public boolean isDrawingCacheEnabled() { return (mViewFlags & DRAWING_CACHE_ENABLED) == DRAWING_CACHE_ENABLED; @@ -18271,11 +18130,10 @@ public class View implements Drawable.Callback, KeyEvent.Callback, */ @SuppressWarnings({"UnusedDeclaration"}) public void outputDirtyFlags(String indent, boolean clear, int clearMask) { - Log.d(VIEW_LOG_TAG, indent + this + " DIRTY(" - + (mPrivateFlags & View.PFLAG_DIRTY_MASK) - + ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" - + (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) - + ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); + Log.d("View", indent + this + " DIRTY(" + (mPrivateFlags & View.PFLAG_DIRTY_MASK) + + ") DRAWN(" + (mPrivateFlags & PFLAG_DRAWN) + ")" + " CACHE_VALID(" + + (mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) + + ") INVALIDATED(" + (mPrivateFlags & PFLAG_INVALIDATED) + ")"); if (clear) { mPrivateFlags &= clearMask; } @@ -18399,21 +18257,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * @return A non-scaled bitmap representing this view or null if cache is disabled. * * @see #getDrawingCache(boolean) - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public Bitmap getDrawingCache() { return getDrawingCache(false); } @@ -18444,21 +18288,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * @see #isDrawingCacheEnabled() * @see #buildDrawingCache(boolean) * @see #destroyDrawingCache() - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public Bitmap getDrawingCache(boolean autoScale) { if ((mViewFlags & WILL_NOT_CACHE_DRAWING) == WILL_NOT_CACHE_DRAWING) { return null; @@ -18478,21 +18308,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * @see #setDrawingCacheEnabled(boolean) * @see #buildDrawingCache() * @see #getDrawingCache() - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public void destroyDrawingCache() { if (mDrawingCache != null) { mDrawingCache.recycle(); @@ -18514,21 +18330,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * @see #setDrawingCacheEnabled(boolean) * @see #buildDrawingCache() * @see #getDrawingCache() - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public void setDrawingCacheBackgroundColor(@ColorInt int color) { if (color != mDrawingCacheBackgroundColor) { mDrawingCacheBackgroundColor = color; @@ -18540,21 +18342,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * @see #setDrawingCacheBackgroundColor(int) * * @return The background color to used for the drawing cache's bitmap - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated @ColorInt public int getDrawingCacheBackgroundColor() { return mDrawingCacheBackgroundColor; @@ -18564,21 +18352,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, *

    Calling this method is equivalent to calling buildDrawingCache(false).

    * * @see #buildDrawingCache(boolean) - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public void buildDrawingCache() { buildDrawingCache(false); } @@ -18605,21 +18379,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * * @see #getDrawingCache() * @see #destroyDrawingCache() - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public void buildDrawingCache(boolean autoScale) { if ((mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == 0 || (autoScale ? mDrawingCache == null : mUnscaledDrawingCache == null)) { @@ -20052,7 +19812,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, boolean changed = false; if (DBG) { - Log.d(VIEW_LOG_TAG, this + " View.setFrame(" + left + "," + top + "," + Log.d("View", this + " View.setFrame(" + left + "," + top + "," + right + "," + bottom + ")"); } @@ -25098,7 +24858,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, private final class PerformClick implements Runnable { @Override public void run() { - performClickInternal(); + performClick(); } } diff --git a/android/view/ViewDebug.java b/android/view/ViewDebug.java index afa94131..3426485e 100644 --- a/android/view/ViewDebug.java +++ b/android/view/ViewDebug.java @@ -528,23 +528,84 @@ public class ViewDebug { /** @hide */ public static void profileViewAndChildren(final View view, BufferedWriter out) throws IOException { - RenderNode node = RenderNode.create("ViewDebug", null); - profileViewAndChildren(view, node, out, true); - node.destroy(); + profileViewAndChildren(view, out, true); } - private static void profileViewAndChildren(View view, RenderNode node, BufferedWriter out, - boolean root) throws IOException { + private static void profileViewAndChildren(final View view, BufferedWriter out, boolean root) + throws IOException { + long durationMeasure = (root || (view.mPrivateFlags & View.PFLAG_MEASURED_DIMENSION_SET) != 0) - ? profileViewMeasure(view) : 0; + ? profileViewOperation(view, new ViewOperation() { + public Void[] pre() { + forceLayout(view); + return null; + } + + private void forceLayout(View view) { + view.forceLayout(); + if (view instanceof ViewGroup) { + ViewGroup group = (ViewGroup) view; + final int count = group.getChildCount(); + for (int i = 0; i < count; i++) { + forceLayout(group.getChildAt(i)); + } + } + } + + public void run(Void... data) { + view.measure(view.mOldWidthMeasureSpec, view.mOldHeightMeasureSpec); + } + + public void post(Void... data) { + } + }) + : 0; long durationLayout = (root || (view.mPrivateFlags & View.PFLAG_LAYOUT_REQUIRED) != 0) - ? profileViewLayout(view) : 0; + ? profileViewOperation(view, new ViewOperation() { + public Void[] pre() { + return null; + } + + public void run(Void... data) { + view.layout(view.mLeft, view.mTop, view.mRight, view.mBottom); + } + + public void post(Void... data) { + } + }) : 0; long durationDraw = (root || !view.willNotDraw() || (view.mPrivateFlags & View.PFLAG_DRAWN) != 0) - ? profileViewDraw(view, node) : 0; + ? profileViewOperation(view, new ViewOperation() { + public Object[] pre() { + final DisplayMetrics metrics = + (view != null && view.getResources() != null) ? + view.getResources().getDisplayMetrics() : null; + final Bitmap bitmap = metrics != null ? + Bitmap.createBitmap(metrics, metrics.widthPixels, + metrics.heightPixels, Bitmap.Config.RGB_565) : null; + final Canvas canvas = bitmap != null ? new Canvas(bitmap) : null; + return new Object[] { + bitmap, canvas + }; + } + public void run(Object... data) { + if (data[1] != null) { + view.draw((Canvas) data[1]); + } + } + + public void post(Object... data) { + if (data[1] != null) { + ((Canvas) data[1]).setBitmap(null); + } + if (data[0] != null) { + ((Bitmap) data[0]).recycle(); + } + } + }) : 0; out.write(String.valueOf(durationMeasure)); out.write(' '); out.write(String.valueOf(durationLayout)); @@ -555,86 +616,34 @@ public class ViewDebug { ViewGroup group = (ViewGroup) view; final int count = group.getChildCount(); for (int i = 0; i < count; i++) { - profileViewAndChildren(group.getChildAt(i), node, out, false); - } - } - } - - private static long profileViewMeasure(final View view) { - return profileViewOperation(view, new ViewOperation() { - @Override - public void pre() { - forceLayout(view); - } - - private void forceLayout(View view) { - view.forceLayout(); - if (view instanceof ViewGroup) { - ViewGroup group = (ViewGroup) view; - final int count = group.getChildCount(); - for (int i = 0; i < count; i++) { - forceLayout(group.getChildAt(i)); - } - } - } - - @Override - public void run() { - view.measure(view.mOldWidthMeasureSpec, view.mOldHeightMeasureSpec); - } - }); - } - - private static long profileViewLayout(View view) { - return profileViewOperation(view, - () -> view.layout(view.mLeft, view.mTop, view.mRight, view.mBottom)); - } - - private static long profileViewDraw(View view, RenderNode node) { - DisplayMetrics dm = view.getResources().getDisplayMetrics(); - if (dm == null) { - return 0; - } - - if (view.isHardwareAccelerated()) { - DisplayListCanvas canvas = node.start(dm.widthPixels, dm.heightPixels); - try { - return profileViewOperation(view, () -> view.draw(canvas)); - } finally { - node.end(canvas); - } - } else { - Bitmap bitmap = Bitmap.createBitmap( - dm, dm.widthPixels, dm.heightPixels, Bitmap.Config.RGB_565); - Canvas canvas = new Canvas(bitmap); - try { - return profileViewOperation(view, () -> view.draw(canvas)); - } finally { - canvas.setBitmap(null); - bitmap.recycle(); + profileViewAndChildren(group.getChildAt(i), out, false); } } } - interface ViewOperation { - default void pre() {} - - void run(); + interface ViewOperation { + T[] pre(); + void run(T... data); + void post(T... data); } - private static long profileViewOperation(View view, final ViewOperation operation) { + private static long profileViewOperation(View view, final ViewOperation operation) { final CountDownLatch latch = new CountDownLatch(1); final long[] duration = new long[1]; - view.post(() -> { - try { - operation.pre(); - long start = Debug.threadCpuTimeNanos(); - //noinspection unchecked - operation.run(); - duration[0] = Debug.threadCpuTimeNanos() - start; - } finally { - latch.countDown(); + view.post(new Runnable() { + public void run() { + try { + T[] data = operation.pre(); + long start = Debug.threadCpuTimeNanos(); + //noinspection unchecked + operation.run(data); + duration[0] = Debug.threadCpuTimeNanos() - start; + //noinspection unchecked + operation.post(data); + } finally { + latch.countDown(); + } } }); diff --git a/android/view/ViewGroup.java b/android/view/ViewGroup.java index 929beaea..b2e5a163 100644 --- a/android/view/ViewGroup.java +++ b/android/view/ViewGroup.java @@ -421,78 +421,22 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager /** * Used to indicate that no drawing cache should be kept in memory. - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public static final int PERSISTENT_NO_CACHE = 0x0; /** * Used to indicate that the animation drawing cache should be kept in memory. - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public static final int PERSISTENT_ANIMATION_CACHE = 0x1; /** * Used to indicate that the scrolling drawing cache should be kept in memory. - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public static final int PERSISTENT_SCROLLING_CACHE = 0x2; /** * Used to indicate that all drawing caches should be kept in memory. - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public static final int PERSISTENT_ALL_CACHES = 0x3; // Layout Modes @@ -3825,21 +3769,7 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager * Enables or disables the drawing cache for each child of this view group. * * @param enabled true to enable the cache, false to dispose of it - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated protected void setChildrenDrawingCacheEnabled(boolean enabled) { if (enabled || (mPersistentDrawingCache & PERSISTENT_ALL_CACHES) != PERSISTENT_ALL_CACHES) { final View[] children = mChildren; @@ -6401,21 +6331,7 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager * @return one or a combination of {@link #PERSISTENT_NO_CACHE}, * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} * and {@link #PERSISTENT_ALL_CACHES} - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated @ViewDebug.ExportedProperty(category = "drawing", mapping = { @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE, to = "NONE"), @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"), @@ -6436,21 +6352,7 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE}, * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} * and {@link #PERSISTENT_ALL_CACHES} - * - * @deprecated The view drawing cache was largely made obsolete with the introduction of - * hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache - * layers are largely unnecessary and can easily result in a net loss in performance due to the - * cost of creating and updating the layer. In the rare cases where caching layers are useful, - * such as for alpha animations, {@link #setLayerType(int, Paint)} handles this with hardware - * rendering. For software-rendered snapshots of a small part of the View hierarchy or - * individual Views it is recommended to create a {@link Canvas} from either a {@link Bitmap} or - * {@link android.graphics.Picture} and call {@link #draw(Canvas)} on the View. However these - * software-rendered usages are discouraged and have compatibility issues with hardware-only - * rendering features such as {@link android.graphics.Bitmap.Config#HARDWARE Config.HARDWARE} - * bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback - * reports or unit testing the {@link PixelCopy} API is recommended. */ - @Deprecated public void setPersistentDrawingCache(int drawingCacheToKeep) { mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES; } diff --git a/android/view/ViewRootImpl.java b/android/view/ViewRootImpl.java index 99438d87..71106ada 100644 --- a/android/view/ViewRootImpl.java +++ b/android/view/ViewRootImpl.java @@ -72,7 +72,6 @@ import android.util.DisplayMetrics; import android.util.Log; import android.util.MergedConfiguration; import android.util.Slog; -import android.util.SparseArray; import android.util.TimeUtils; import android.util.TypedValue; import android.view.Surface.OutOfResourcesException; @@ -1669,6 +1668,8 @@ public final class ViewRootImpl implements ViewParent, host.dispatchAttachedToWindow(mAttachInfo, 0); mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(true); dispatchApplyInsets(host); + //Log.i(mTag, "Screen on initialized: " + attachInfo.mKeepScreenOn); + } else { desiredWindowWidth = frame.width(); desiredWindowHeight = frame.height(); @@ -2826,7 +2827,7 @@ public final class ViewRootImpl implements ViewParent, try { mWindowDrawCountDown.await(); } catch (InterruptedException e) { - Log.e(mTag, "Window redraw count down interrupted!"); + Log.e(mTag, "Window redraw count down interruped!"); } mWindowDrawCountDown = null; } @@ -2896,6 +2897,8 @@ public final class ViewRootImpl implements ViewParent, final float appScale = mAttachInfo.mApplicationScale; final boolean scalingRequired = mAttachInfo.mScalingRequired; + int resizeAlpha = 0; + final Rect dirty = mDirty; if (mSurfaceHolder != null) { // The app owns the surface, we won't draw. @@ -3466,7 +3469,6 @@ public final class ViewRootImpl implements ViewParent, } void dispatchDetachedFromWindow() { - mFirstInputStage.onDetachedFromWindow(); if (mView != null && mView.mAttachInfo != null) { mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false); mView.dispatchDetachedFromWindow(); @@ -3729,273 +3731,266 @@ public final class ViewRootImpl implements ViewParent, @Override public void handleMessage(Message msg) { switch (msg.what) { - case MSG_INVALIDATE: - ((View) msg.obj).invalidate(); - break; - case MSG_INVALIDATE_RECT: - final View.AttachInfo.InvalidateInfo info = - (View.AttachInfo.InvalidateInfo) msg.obj; - info.target.invalidate(info.left, info.top, info.right, info.bottom); - info.recycle(); - break; - case MSG_PROCESS_INPUT_EVENTS: - mProcessInputEventsScheduled = false; - doProcessInputEvents(); - break; - case MSG_DISPATCH_APP_VISIBILITY: - handleAppVisibility(msg.arg1 != 0); - break; - case MSG_DISPATCH_GET_NEW_SURFACE: - handleGetNewSurface(); + case MSG_INVALIDATE: + ((View) msg.obj).invalidate(); + break; + case MSG_INVALIDATE_RECT: + final View.AttachInfo.InvalidateInfo info = (View.AttachInfo.InvalidateInfo) msg.obj; + info.target.invalidate(info.left, info.top, info.right, info.bottom); + info.recycle(); + break; + case MSG_PROCESS_INPUT_EVENTS: + mProcessInputEventsScheduled = false; + doProcessInputEvents(); + break; + case MSG_DISPATCH_APP_VISIBILITY: + handleAppVisibility(msg.arg1 != 0); + break; + case MSG_DISPATCH_GET_NEW_SURFACE: + handleGetNewSurface(); + break; + case MSG_RESIZED: { + // Recycled in the fall through... + SomeArgs args = (SomeArgs) msg.obj; + if (mWinFrame.equals(args.arg1) + && mPendingOverscanInsets.equals(args.arg5) + && mPendingContentInsets.equals(args.arg2) + && mPendingStableInsets.equals(args.arg6) + && mPendingVisibleInsets.equals(args.arg3) + && mPendingOutsets.equals(args.arg7) + && mPendingBackDropFrame.equals(args.arg8) + && args.arg4 == null + && args.argi1 == 0 + && mDisplay.getDisplayId() == args.argi3) { break; - case MSG_RESIZED: { - // Recycled in the fall through... + } + } // fall through... + case MSG_RESIZED_REPORT: + if (mAdded) { SomeArgs args = (SomeArgs) msg.obj; - if (mWinFrame.equals(args.arg1) - && mPendingOverscanInsets.equals(args.arg5) - && mPendingContentInsets.equals(args.arg2) - && mPendingStableInsets.equals(args.arg6) - && mPendingVisibleInsets.equals(args.arg3) - && mPendingOutsets.equals(args.arg7) - && mPendingBackDropFrame.equals(args.arg8) - && args.arg4 == null - && args.argi1 == 0 - && mDisplay.getDisplayId() == args.argi3) { - break; + + final int displayId = args.argi3; + MergedConfiguration mergedConfiguration = (MergedConfiguration) args.arg4; + final boolean displayChanged = mDisplay.getDisplayId() != displayId; + + if (!mLastReportedMergedConfiguration.equals(mergedConfiguration)) { + // If configuration changed - notify about that and, maybe, about move to + // display. + performConfigurationChange(mergedConfiguration, false /* force */, + displayChanged ? displayId : INVALID_DISPLAY /* same display */); + } else if (displayChanged) { + // Moved to display without config change - report last applied one. + onMovedToDisplay(displayId, mLastConfigurationFromResources); } - } // fall through... - case MSG_RESIZED_REPORT: - if (mAdded) { - SomeArgs args = (SomeArgs) msg.obj; - - final int displayId = args.argi3; - MergedConfiguration mergedConfiguration = (MergedConfiguration) args.arg4; - final boolean displayChanged = mDisplay.getDisplayId() != displayId; - - if (!mLastReportedMergedConfiguration.equals(mergedConfiguration)) { - // If configuration changed - notify about that and, maybe, - // about move to display. - performConfigurationChange(mergedConfiguration, false /* force */, - displayChanged - ? displayId : INVALID_DISPLAY /* same display */); - } else if (displayChanged) { - // Moved to display without config change - report last applied one. - onMovedToDisplay(displayId, mLastConfigurationFromResources); - } - final boolean framesChanged = !mWinFrame.equals(args.arg1) - || !mPendingOverscanInsets.equals(args.arg5) - || !mPendingContentInsets.equals(args.arg2) - || !mPendingStableInsets.equals(args.arg6) - || !mPendingVisibleInsets.equals(args.arg3) - || !mPendingOutsets.equals(args.arg7); - - mWinFrame.set((Rect) args.arg1); - mPendingOverscanInsets.set((Rect) args.arg5); - mPendingContentInsets.set((Rect) args.arg2); - mPendingStableInsets.set((Rect) args.arg6); - mPendingVisibleInsets.set((Rect) args.arg3); - mPendingOutsets.set((Rect) args.arg7); - mPendingBackDropFrame.set((Rect) args.arg8); - mForceNextWindowRelayout = args.argi1 != 0; - mPendingAlwaysConsumeNavBar = args.argi2 != 0; - - args.recycle(); - - if (msg.what == MSG_RESIZED_REPORT) { - reportNextDraw(); - } + final boolean framesChanged = !mWinFrame.equals(args.arg1) + || !mPendingOverscanInsets.equals(args.arg5) + || !mPendingContentInsets.equals(args.arg2) + || !mPendingStableInsets.equals(args.arg6) + || !mPendingVisibleInsets.equals(args.arg3) + || !mPendingOutsets.equals(args.arg7); + + mWinFrame.set((Rect) args.arg1); + mPendingOverscanInsets.set((Rect) args.arg5); + mPendingContentInsets.set((Rect) args.arg2); + mPendingStableInsets.set((Rect) args.arg6); + mPendingVisibleInsets.set((Rect) args.arg3); + mPendingOutsets.set((Rect) args.arg7); + mPendingBackDropFrame.set((Rect) args.arg8); + mForceNextWindowRelayout = args.argi1 != 0; + mPendingAlwaysConsumeNavBar = args.argi2 != 0; - if (mView != null && framesChanged) { - forceLayout(mView); - } - requestLayout(); + args.recycle(); + + if (msg.what == MSG_RESIZED_REPORT) { + reportNextDraw(); } - break; - case MSG_WINDOW_MOVED: - if (mAdded) { - final int w = mWinFrame.width(); - final int h = mWinFrame.height(); - final int l = msg.arg1; - final int t = msg.arg2; - mWinFrame.left = l; - mWinFrame.right = l + w; - mWinFrame.top = t; - mWinFrame.bottom = t + h; - - mPendingBackDropFrame.set(mWinFrame); - maybeHandleWindowMove(mWinFrame); + + if (mView != null && framesChanged) { + forceLayout(mView); } - break; - case MSG_WINDOW_FOCUS_CHANGED: { - final boolean hasWindowFocus = msg.arg1 != 0; - if (mAdded) { - mAttachInfo.mHasWindowFocus = hasWindowFocus; - - profileRendering(hasWindowFocus); - - if (hasWindowFocus) { - boolean inTouchMode = msg.arg2 != 0; - ensureTouchModeLocally(inTouchMode); - if (mAttachInfo.mThreadedRenderer != null && mSurface.isValid()) { - mFullRedrawNeeded = true; + requestLayout(); + } + break; + case MSG_WINDOW_MOVED: + if (mAdded) { + final int w = mWinFrame.width(); + final int h = mWinFrame.height(); + final int l = msg.arg1; + final int t = msg.arg2; + mWinFrame.left = l; + mWinFrame.right = l + w; + mWinFrame.top = t; + mWinFrame.bottom = t + h; + + mPendingBackDropFrame.set(mWinFrame); + maybeHandleWindowMove(mWinFrame); + } + break; + case MSG_WINDOW_FOCUS_CHANGED: { + if (mAdded) { + boolean hasWindowFocus = msg.arg1 != 0; + mAttachInfo.mHasWindowFocus = hasWindowFocus; + + profileRendering(hasWindowFocus); + + if (hasWindowFocus) { + boolean inTouchMode = msg.arg2 != 0; + ensureTouchModeLocally(inTouchMode); + + if (mAttachInfo.mThreadedRenderer != null && mSurface.isValid()){ + mFullRedrawNeeded = true; + try { + final WindowManager.LayoutParams lp = mWindowAttributes; + final Rect surfaceInsets = lp != null ? lp.surfaceInsets : null; + mAttachInfo.mThreadedRenderer.initializeIfNeeded( + mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets); + } catch (OutOfResourcesException e) { + Log.e(mTag, "OutOfResourcesException locking surface", e); try { - final WindowManager.LayoutParams lp = mWindowAttributes; - final Rect surfaceInsets = lp != null ? lp.surfaceInsets : null; - mAttachInfo.mThreadedRenderer.initializeIfNeeded( - mWidth, mHeight, mAttachInfo, mSurface, surfaceInsets); - } catch (OutOfResourcesException e) { - Log.e(mTag, "OutOfResourcesException locking surface", e); - try { - if (!mWindowSession.outOfMemory(mWindow)) { - Slog.w(mTag, "No processes killed for memory;" - + " killing self"); - Process.killProcess(Process.myPid()); - } - } catch (RemoteException ex) { + if (!mWindowSession.outOfMemory(mWindow)) { + Slog.w(mTag, "No processes killed for memory; killing self"); + Process.killProcess(Process.myPid()); } - // Retry in a bit. - sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), - 500); - return; + } catch (RemoteException ex) { } + // Retry in a bit. + sendMessageDelayed(obtainMessage(msg.what, msg.arg1, msg.arg2), 500); + return; } } + } - mLastWasImTarget = WindowManager.LayoutParams - .mayUseInputMethod(mWindowAttributes.flags); + mLastWasImTarget = WindowManager.LayoutParams + .mayUseInputMethod(mWindowAttributes.flags); - InputMethodManager imm = InputMethodManager.peekInstance(); - if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) { - imm.onPreWindowFocus(mView, hasWindowFocus); - } - if (mView != null) { - mAttachInfo.mKeyDispatchState.reset(); - mView.dispatchWindowFocusChanged(hasWindowFocus); - mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus); + InputMethodManager imm = InputMethodManager.peekInstance(); + if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) { + imm.onPreWindowFocus(mView, hasWindowFocus); + } + if (mView != null) { + mAttachInfo.mKeyDispatchState.reset(); + mView.dispatchWindowFocusChanged(hasWindowFocus); + mAttachInfo.mTreeObserver.dispatchOnWindowFocusChange(hasWindowFocus); - if (mAttachInfo.mTooltipHost != null) { - mAttachInfo.mTooltipHost.hideTooltip(); - } + if (mAttachInfo.mTooltipHost != null) { + mAttachInfo.mTooltipHost.hideTooltip(); } + } - // Note: must be done after the focus change callbacks, - // so all of the view state is set up correctly. - if (hasWindowFocus) { - if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) { - imm.onPostWindowFocus(mView, mView.findFocus(), - mWindowAttributes.softInputMode, - !mHasHadWindowFocus, mWindowAttributes.flags); - } - // Clear the forward bit. We can just do this directly, since - // the window manager doesn't care about it. - mWindowAttributes.softInputMode &= + // Note: must be done after the focus change callbacks, + // so all of the view state is set up correctly. + if (hasWindowFocus) { + if (imm != null && mLastWasImTarget && !isInLocalFocusMode()) { + imm.onPostWindowFocus(mView, mView.findFocus(), + mWindowAttributes.softInputMode, + !mHasHadWindowFocus, mWindowAttributes.flags); + } + // Clear the forward bit. We can just do this directly, since + // the window manager doesn't care about it. + mWindowAttributes.softInputMode &= + ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; + ((WindowManager.LayoutParams)mView.getLayoutParams()) + .softInputMode &= ~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION; - ((WindowManager.LayoutParams) mView.getLayoutParams()) - .softInputMode &= - ~WindowManager.LayoutParams - .SOFT_INPUT_IS_FORWARD_NAVIGATION; - mHasHadWindowFocus = true; - } else { - if (mPointerCapture) { - handlePointerCaptureChanged(false); - } + mHasHadWindowFocus = true; + } else { + if (mPointerCapture) { + handlePointerCaptureChanged(false); } } - mFirstInputStage.onWindowFocusChanged(hasWindowFocus); - } break; - case MSG_DIE: - doDie(); - break; - case MSG_DISPATCH_INPUT_EVENT: { - SomeArgs args = (SomeArgs) msg.obj; - InputEvent event = (InputEvent) args.arg1; - InputEventReceiver receiver = (InputEventReceiver) args.arg2; - enqueueInputEvent(event, receiver, 0, true); - args.recycle(); - } break; - case MSG_SYNTHESIZE_INPUT_EVENT: { - InputEvent event = (InputEvent) msg.obj; - enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true); - } break; - case MSG_DISPATCH_KEY_FROM_IME: { - if (LOCAL_LOGV) { - Log.v(TAG, "Dispatching key " + msg.obj + " from IME to " + mView); - } - KeyEvent event = (KeyEvent) msg.obj; - if ((event.getFlags() & KeyEvent.FLAG_FROM_SYSTEM) != 0) { - // The IME is trying to say this event is from the - // system! Bad bad bad! - //noinspection UnusedAssignment - event = KeyEvent.changeFlags(event, - event.getFlags() & ~KeyEvent.FLAG_FROM_SYSTEM); - } - enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); - } break; - case MSG_CHECK_FOCUS: { - InputMethodManager imm = InputMethodManager.peekInstance(); - if (imm != null) { - imm.checkFocus(); - } - } break; - case MSG_CLOSE_SYSTEM_DIALOGS: { - if (mView != null) { - mView.onCloseSystemDialogs((String) msg.obj); - } - } break; - case MSG_DISPATCH_DRAG_EVENT: { - } // fall through - case MSG_DISPATCH_DRAG_LOCATION_EVENT: { - DragEvent event = (DragEvent) msg.obj; - // only present when this app called startDrag() - event.mLocalState = mLocalDragState; - handleDragEvent(event); - } break; - case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { - handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj); - } break; - case MSG_UPDATE_CONFIGURATION: { - Configuration config = (Configuration) msg.obj; - if (config.isOtherSeqNewer( - mLastReportedMergedConfiguration.getMergedConfiguration())) { - // If we already have a newer merged config applied - use its global part. - config = mLastReportedMergedConfiguration.getGlobalConfiguration(); - } + } + } break; + case MSG_DIE: + doDie(); + break; + case MSG_DISPATCH_INPUT_EVENT: { + SomeArgs args = (SomeArgs)msg.obj; + InputEvent event = (InputEvent)args.arg1; + InputEventReceiver receiver = (InputEventReceiver)args.arg2; + enqueueInputEvent(event, receiver, 0, true); + args.recycle(); + } break; + case MSG_SYNTHESIZE_INPUT_EVENT: { + InputEvent event = (InputEvent)msg.obj; + enqueueInputEvent(event, null, QueuedInputEvent.FLAG_UNHANDLED, true); + } break; + case MSG_DISPATCH_KEY_FROM_IME: { + if (LOCAL_LOGV) Log.v( + TAG, "Dispatching key " + + msg.obj + " from IME to " + mView); + KeyEvent event = (KeyEvent)msg.obj; + if ((event.getFlags()&KeyEvent.FLAG_FROM_SYSTEM) != 0) { + // The IME is trying to say this event is from the + // system! Bad bad bad! + //noinspection UnusedAssignment + event = KeyEvent.changeFlags(event, event.getFlags() & + ~KeyEvent.FLAG_FROM_SYSTEM); + } + enqueueInputEvent(event, null, QueuedInputEvent.FLAG_DELIVER_POST_IME, true); + } break; + case MSG_CHECK_FOCUS: { + InputMethodManager imm = InputMethodManager.peekInstance(); + if (imm != null) { + imm.checkFocus(); + } + } break; + case MSG_CLOSE_SYSTEM_DIALOGS: { + if (mView != null) { + mView.onCloseSystemDialogs((String)msg.obj); + } + } break; + case MSG_DISPATCH_DRAG_EVENT: + case MSG_DISPATCH_DRAG_LOCATION_EVENT: { + DragEvent event = (DragEvent)msg.obj; + event.mLocalState = mLocalDragState; // only present when this app called startDrag() + handleDragEvent(event); + } break; + case MSG_DISPATCH_SYSTEM_UI_VISIBILITY: { + handleDispatchSystemUiVisibilityChanged((SystemUiVisibilityInfo) msg.obj); + } break; + case MSG_UPDATE_CONFIGURATION: { + Configuration config = (Configuration) msg.obj; + if (config.isOtherSeqNewer( + mLastReportedMergedConfiguration.getMergedConfiguration())) { + // If we already have a newer merged config applied - use its global part. + config = mLastReportedMergedConfiguration.getGlobalConfiguration(); + } - // Use the newer global config and last reported override config. - mPendingMergedConfiguration.setConfiguration(config, - mLastReportedMergedConfiguration.getOverrideConfiguration()); + // Use the newer global config and last reported override config. + mPendingMergedConfiguration.setConfiguration(config, + mLastReportedMergedConfiguration.getOverrideConfiguration()); - performConfigurationChange(mPendingMergedConfiguration, false /* force */, - INVALID_DISPLAY /* same display */); - } break; - case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { - setAccessibilityFocus(null, null); - } break; - case MSG_INVALIDATE_WORLD: { - if (mView != null) { - invalidateWorld(mView); - } - } break; - case MSG_DISPATCH_WINDOW_SHOWN: { - handleDispatchWindowShown(); - } break; - case MSG_REQUEST_KEYBOARD_SHORTCUTS: { - final IResultReceiver receiver = (IResultReceiver) msg.obj; - final int deviceId = msg.arg1; - handleRequestKeyboardShortcuts(receiver, deviceId); - } break; - case MSG_UPDATE_POINTER_ICON: { - MotionEvent event = (MotionEvent) msg.obj; - resetPointerIcon(event); - } break; - case MSG_POINTER_CAPTURE_CHANGED: { - final boolean hasCapture = msg.arg1 != 0; - handlePointerCaptureChanged(hasCapture); - } break; - case MSG_DRAW_FINISHED: { - pendingDrawFinished(); - } break; + performConfigurationChange(mPendingMergedConfiguration, false /* force */, + INVALID_DISPLAY /* same display */); + } break; + case MSG_CLEAR_ACCESSIBILITY_FOCUS_HOST: { + setAccessibilityFocus(null, null); + } break; + case MSG_INVALIDATE_WORLD: { + if (mView != null) { + invalidateWorld(mView); + } + } break; + case MSG_DISPATCH_WINDOW_SHOWN: { + handleDispatchWindowShown(); + } break; + case MSG_REQUEST_KEYBOARD_SHORTCUTS: { + final IResultReceiver receiver = (IResultReceiver) msg.obj; + final int deviceId = msg.arg1; + handleRequestKeyboardShortcuts(receiver, deviceId); + } break; + case MSG_UPDATE_POINTER_ICON: { + MotionEvent event = (MotionEvent) msg.obj; + resetPointerIcon(event); + } break; + case MSG_POINTER_CAPTURE_CHANGED: { + final boolean hasCapture = msg.arg1 != 0; + handlePointerCaptureChanged(hasCapture); + } break; + case MSG_DRAW_FINISHED: { + pendingDrawFinished(); + } break; } } } @@ -4208,18 +4203,6 @@ public final class ViewRootImpl implements ViewParent, } } - protected void onWindowFocusChanged(boolean hasWindowFocus) { - if (mNext != null) { - mNext.onWindowFocusChanged(hasWindowFocus); - } - } - - protected void onDetachedFromWindow() { - if (mNext != null) { - mNext.onDetachedFromWindow(); - } - } - protected boolean shouldDropInputEvent(QueuedInputEvent q) { if (mView == null || !mAdded) { Slog.w(mTag, "Dropping event due to root view being removed: " + q.mEvent); @@ -4973,9 +4956,9 @@ public final class ViewRootImpl implements ViewParent, final MotionEvent event = (MotionEvent)q.mEvent; final int source = event.getSource(); if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) { - mTrackball.cancel(); + mTrackball.cancel(event); } else if ((source & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) { - mJoystick.cancel(); + mJoystick.cancel(event); } else if ((source & InputDevice.SOURCE_TOUCH_NAVIGATION) == InputDevice.SOURCE_TOUCH_NAVIGATION) { mTouchNavigation.cancel(event); @@ -4984,18 +4967,6 @@ public final class ViewRootImpl implements ViewParent, } super.onDeliverToNext(q); } - - @Override - protected void onWindowFocusChanged(boolean hasWindowFocus) { - if (!hasWindowFocus) { - mJoystick.cancel(); - } - } - - @Override - protected void onDetachedFromWindow() { - mJoystick.cancel(); - } } /** @@ -5108,7 +5079,7 @@ public final class ViewRootImpl implements ViewParent, } } - public void cancel() { + public void cancel(MotionEvent event) { mLastTime = Integer.MIN_VALUE; // If we reach this, we consumed a trackball event. @@ -5292,11 +5263,14 @@ public final class ViewRootImpl implements ViewParent, * Creates dpad events from unhandled joystick movements. */ final class SyntheticJoystickHandler extends Handler { + private final static String TAG = "SyntheticJoystickHandler"; private final static int MSG_ENQUEUE_X_AXIS_KEY_REPEAT = 1; private final static int MSG_ENQUEUE_Y_AXIS_KEY_REPEAT = 2; - private final JoystickAxesState mJoystickAxesState = new JoystickAxesState(); - private final SparseArray mDeviceKeyEvents = new SparseArray<>(); + private int mLastXDirection; + private int mLastYDirection; + private int mLastXKeyCode; + private int mLastYKeyCode; public SyntheticJoystickHandler() { super(true); @@ -5307,10 +5281,11 @@ public final class ViewRootImpl implements ViewParent, switch (msg.what) { case MSG_ENQUEUE_X_AXIS_KEY_REPEAT: case MSG_ENQUEUE_Y_AXIS_KEY_REPEAT: { + KeyEvent oldEvent = (KeyEvent)msg.obj; + KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent, + SystemClock.uptimeMillis(), + oldEvent.getRepeatCount() + 1); if (mAttachInfo.mHasWindowFocus) { - KeyEvent oldEvent = (KeyEvent) msg.obj; - KeyEvent e = KeyEvent.changeTimeRepeat(oldEvent, - SystemClock.uptimeMillis(), oldEvent.getRepeatCount() + 1); enqueueInputEvent(e); Message m = obtainMessage(msg.what, e); m.setAsynchronous(true); @@ -5322,176 +5297,97 @@ public final class ViewRootImpl implements ViewParent, public void process(MotionEvent event) { switch(event.getActionMasked()) { - case MotionEvent.ACTION_CANCEL: - cancel(); - break; - case MotionEvent.ACTION_MOVE: - update(event); - break; - default: - Log.w(mTag, "Unexpected action: " + event.getActionMasked()); + case MotionEvent.ACTION_CANCEL: + cancel(event); + break; + case MotionEvent.ACTION_MOVE: + update(event, true); + break; + default: + Log.w(mTag, "Unexpected action: " + event.getActionMasked()); } } - private void cancel() { + private void cancel(MotionEvent event) { removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT); removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT); - for (int i = 0; i < mDeviceKeyEvents.size(); i++) { - final KeyEvent keyEvent = mDeviceKeyEvents.valueAt(i); - if (keyEvent != null) { - enqueueInputEvent(KeyEvent.changeTimeRepeat(keyEvent, - SystemClock.uptimeMillis(), 0)); - } - } - mDeviceKeyEvents.clear(); - mJoystickAxesState.resetState(); - } - - private void update(MotionEvent event) { - final int historySize = event.getHistorySize(); - for (int h = 0; h < historySize; h++) { - final long time = event.getHistoricalEventTime(h); - mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_X, - event.getHistoricalAxisValue(MotionEvent.AXIS_X, 0, h)); - mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_Y, - event.getHistoricalAxisValue(MotionEvent.AXIS_Y, 0, h)); - mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_HAT_X, - event.getHistoricalAxisValue(MotionEvent.AXIS_HAT_X, 0, h)); - mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_HAT_Y, - event.getHistoricalAxisValue(MotionEvent.AXIS_HAT_Y, 0, h)); - } - final long time = event.getEventTime(); - mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_X, - event.getAxisValue(MotionEvent.AXIS_X)); - mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_Y, - event.getAxisValue(MotionEvent.AXIS_Y)); - mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_HAT_X, - event.getAxisValue(MotionEvent.AXIS_HAT_X)); - mJoystickAxesState.updateStateForAxis(event, time, MotionEvent.AXIS_HAT_Y, - event.getAxisValue(MotionEvent.AXIS_HAT_Y)); + update(event, false); } - final class JoystickAxesState { - // State machine: from neutral state (no button press) can go into - // button STATE_UP_OR_LEFT or STATE_DOWN_OR_RIGHT state, emitting an ACTION_DOWN event. - // From STATE_UP_OR_LEFT or STATE_DOWN_OR_RIGHT state can go into neutral state, - // emitting an ACTION_UP event. - private static final int STATE_UP_OR_LEFT = -1; - private static final int STATE_NEUTRAL = 0; - private static final int STATE_DOWN_OR_RIGHT = 1; - - final int[] mAxisStatesHat = {STATE_NEUTRAL, STATE_NEUTRAL}; // {AXIS_HAT_X, AXIS_HAT_Y} - final int[] mAxisStatesStick = {STATE_NEUTRAL, STATE_NEUTRAL}; // {AXIS_X, AXIS_Y} - - void resetState() { - mAxisStatesHat[0] = STATE_NEUTRAL; - mAxisStatesHat[1] = STATE_NEUTRAL; - mAxisStatesStick[0] = STATE_NEUTRAL; - mAxisStatesStick[1] = STATE_NEUTRAL; - } - - void updateStateForAxis(MotionEvent event, long time, int axis, float value) { - // Emit KeyEvent if necessary - // axis can be AXIS_X, AXIS_Y, AXIS_HAT_X, AXIS_HAT_Y - final int axisStateIndex; - final int repeatMessage; - if (isXAxis(axis)) { - axisStateIndex = 0; - repeatMessage = MSG_ENQUEUE_X_AXIS_KEY_REPEAT; - } else if (isYAxis(axis)) { - axisStateIndex = 1; - repeatMessage = MSG_ENQUEUE_Y_AXIS_KEY_REPEAT; - } else { - Log.e(mTag, "Unexpected axis " + axis + " in updateStateForAxis!"); - return; - } - final int newState = joystickAxisValueToState(value); + private void update(MotionEvent event, boolean synthesizeNewKeys) { + final long time = event.getEventTime(); + final int metaState = event.getMetaState(); + final int deviceId = event.getDeviceId(); + final int source = event.getSource(); - final int currentState; - if (axis == MotionEvent.AXIS_X || axis == MotionEvent.AXIS_Y) { - currentState = mAxisStatesStick[axisStateIndex]; - } else { - currentState = mAxisStatesHat[axisStateIndex]; - } + int xDirection = joystickAxisValueToDirection( + event.getAxisValue(MotionEvent.AXIS_HAT_X)); + if (xDirection == 0) { + xDirection = joystickAxisValueToDirection(event.getX()); + } - if (currentState == newState) { - return; + int yDirection = joystickAxisValueToDirection( + event.getAxisValue(MotionEvent.AXIS_HAT_Y)); + if (yDirection == 0) { + yDirection = joystickAxisValueToDirection(event.getY()); + } + + if (xDirection != mLastXDirection) { + if (mLastXKeyCode != 0) { + removeMessages(MSG_ENQUEUE_X_AXIS_KEY_REPEAT); + enqueueInputEvent(new KeyEvent(time, time, + KeyEvent.ACTION_UP, mLastXKeyCode, 0, metaState, + deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); + mLastXKeyCode = 0; } - final int metaState = event.getMetaState(); - final int deviceId = event.getDeviceId(); - final int source = event.getSource(); + mLastXDirection = xDirection; - if (currentState == STATE_DOWN_OR_RIGHT || currentState == STATE_UP_OR_LEFT) { - // send a button release event - final int keyCode = joystickAxisAndStateToKeycode(axis, currentState); - if (keyCode != KeyEvent.KEYCODE_UNKNOWN) { - enqueueInputEvent(new KeyEvent(time, time, KeyEvent.ACTION_UP, keyCode, - 0, metaState, deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); - // remove the corresponding pending UP event if focus lost/view detached - mDeviceKeyEvents.put(deviceId, null); - } - removeMessages(repeatMessage); + if (xDirection != 0 && synthesizeNewKeys) { + mLastXKeyCode = xDirection > 0 + ? KeyEvent.KEYCODE_DPAD_RIGHT : KeyEvent.KEYCODE_DPAD_LEFT; + final KeyEvent e = new KeyEvent(time, time, + KeyEvent.ACTION_DOWN, mLastXKeyCode, 0, metaState, + deviceId, 0, KeyEvent.FLAG_FALLBACK, source); + enqueueInputEvent(e); + Message m = obtainMessage(MSG_ENQUEUE_X_AXIS_KEY_REPEAT, e); + m.setAsynchronous(true); + sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); } + } - if (newState == STATE_DOWN_OR_RIGHT || newState == STATE_UP_OR_LEFT) { - // send a button down event - final int keyCode = joystickAxisAndStateToKeycode(axis, newState); - if (keyCode != KeyEvent.KEYCODE_UNKNOWN) { - KeyEvent keyEvent = new KeyEvent(time, time, KeyEvent.ACTION_DOWN, keyCode, - 0, metaState, deviceId, 0, KeyEvent.FLAG_FALLBACK, source); - enqueueInputEvent(keyEvent); - Message m = obtainMessage(repeatMessage, keyEvent); - m.setAsynchronous(true); - sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); - // store the corresponding ACTION_UP event so that it can be sent - // if focus is lost or root view is removed - mDeviceKeyEvents.put(deviceId, - new KeyEvent(time, time, KeyEvent.ACTION_UP, keyCode, - 0, metaState, deviceId, 0, - KeyEvent.FLAG_FALLBACK | KeyEvent.FLAG_CANCELED, - source)); - } - } - if (axis == MotionEvent.AXIS_X || axis == MotionEvent.AXIS_Y) { - mAxisStatesStick[axisStateIndex] = newState; - } else { - mAxisStatesHat[axisStateIndex] = newState; + if (yDirection != mLastYDirection) { + if (mLastYKeyCode != 0) { + removeMessages(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT); + enqueueInputEvent(new KeyEvent(time, time, + KeyEvent.ACTION_UP, mLastYKeyCode, 0, metaState, + deviceId, 0, KeyEvent.FLAG_FALLBACK, source)); + mLastYKeyCode = 0; } - } - private boolean isXAxis(int axis) { - return axis == MotionEvent.AXIS_X || axis == MotionEvent.AXIS_HAT_X; - } - private boolean isYAxis(int axis) { - return axis == MotionEvent.AXIS_Y || axis == MotionEvent.AXIS_HAT_Y; - } + mLastYDirection = yDirection; - private int joystickAxisAndStateToKeycode(int axis, int state) { - if (isXAxis(axis) && state == STATE_UP_OR_LEFT) { - return KeyEvent.KEYCODE_DPAD_LEFT; - } - if (isXAxis(axis) && state == STATE_DOWN_OR_RIGHT) { - return KeyEvent.KEYCODE_DPAD_RIGHT; - } - if (isYAxis(axis) && state == STATE_UP_OR_LEFT) { - return KeyEvent.KEYCODE_DPAD_UP; + if (yDirection != 0 && synthesizeNewKeys) { + mLastYKeyCode = yDirection > 0 + ? KeyEvent.KEYCODE_DPAD_DOWN : KeyEvent.KEYCODE_DPAD_UP; + final KeyEvent e = new KeyEvent(time, time, + KeyEvent.ACTION_DOWN, mLastYKeyCode, 0, metaState, + deviceId, 0, KeyEvent.FLAG_FALLBACK, source); + enqueueInputEvent(e); + Message m = obtainMessage(MSG_ENQUEUE_Y_AXIS_KEY_REPEAT, e); + m.setAsynchronous(true); + sendMessageDelayed(m, ViewConfiguration.getKeyRepeatTimeout()); } - if (isYAxis(axis) && state == STATE_DOWN_OR_RIGHT) { - return KeyEvent.KEYCODE_DPAD_DOWN; - } - Log.e(mTag, "Unknown axis " + axis + " or direction " + state); - return KeyEvent.KEYCODE_UNKNOWN; // should never happen } + } - private int joystickAxisValueToState(float value) { - if (value >= 0.5f) { - return STATE_DOWN_OR_RIGHT; - } else if (value <= -0.5f) { - return STATE_UP_OR_LEFT; - } else { - return STATE_NEUTRAL; - } + private int joystickAxisValueToDirection(float value) { + if (value >= 0.5f) { + return 1; + } else if (value <= -0.5f) { + return -1; + } else { + return 0; } } } @@ -6212,6 +6108,7 @@ public final class ViewRootImpl implements ViewParent, if (DBG) Log.d(mTag, "WindowLayout in layoutWindow:" + params); } + //Log.d(mTag, ">>>>>> CALLING relayout"); if (params != null && mOrigWindowType != params.type) { // For compatibility with old apps, don't crash here. if (mTargetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { @@ -6232,6 +6129,7 @@ public final class ViewRootImpl implements ViewParent, mPendingAlwaysConsumeNavBar = (relayoutResult & WindowManagerGlobal.RELAYOUT_RES_CONSUME_ALWAYS_NAV_BAR) != 0; + //Log.d(mTag, "<<<<<< BACK FROM relayout"); if (restore) { params.restore(); } diff --git a/android/view/ViewStructure.java b/android/view/ViewStructure.java index 309366c6..f671c349 100644 --- a/android/view/ViewStructure.java +++ b/android/view/ViewStructure.java @@ -364,30 +364,6 @@ public abstract class ViewStructure { */ public abstract void setDataIsSensitive(boolean sensitive); - /** - * Sets the minimum width in ems of the text associated with this view, when supported. - * - *

    Should only be set when the node is used for autofill purposes - it will be ignored - * when used for Assist. - */ - public abstract void setMinTextEms(int minEms); - - /** - * Sets the maximum width in ems of the text associated with this view, when supported. - * - *

    Should only be set when the node is used for autofill purposes - it will be ignored - * when used for Assist. - */ - public abstract void setMaxTextEms(int maxEms); - - /** - * Sets the maximum length of the text associated with this view, when supported. - * - *

    Should only be set when the node is used for autofill purposes - it will be ignored - * when used for Assist. - */ - public abstract void setMaxTextLength(int maxLength); - /** * Call when done populating a {@link ViewStructure} returned by * {@link #asyncNewChild}. diff --git a/android/view/WindowManagerInternal.java b/android/view/WindowManagerInternal.java index 69cc1002..98f8dc8e 100644 --- a/android/view/WindowManagerInternal.java +++ b/android/view/WindowManagerInternal.java @@ -335,8 +335,8 @@ public abstract class WindowManagerInternal { public abstract void setOnHardKeyboardStatusChangeListener( OnHardKeyboardStatusChangeListener listener); - /** Returns true if a stack in the windowing mode is currently visible. */ - public abstract boolean isStackVisible(int windowingMode); + /** Returns true if the stack with the input Id is currently visible. */ + public abstract boolean isStackVisible(int stackId); /** * @return True if and only if the docked divider is currently in resize mode. diff --git a/android/view/WindowManagerPolicy.java b/android/view/WindowManagerPolicy.java index 137e551d..da72535d 100644 --- a/android/view/WindowManagerPolicy.java +++ b/android/view/WindowManagerPolicy.java @@ -467,8 +467,11 @@ public interface WindowManagerPolicy { */ public boolean isDimming(); - /** @return the current windowing mode of this window. */ - int getWindowingMode(); + /** + * @return the stack id this windows belongs to, or {@link StackId#INVALID_STACK_ID} if + * not attached to any stack. + */ + int getStackId(); /** * Returns true if the window is current in multi-windowing mode. i.e. it shares the diff --git a/android/view/accessibility/AccessibilityCache.java b/android/view/accessibility/AccessibilityCache.java index d7851171..0f21c5c8 100644 --- a/android/view/accessibility/AccessibilityCache.java +++ b/android/view/accessibility/AccessibilityCache.java @@ -329,6 +329,8 @@ public final class AccessibilityCache { final long oldParentId = oldInfo.getParentNodeId(); if (info.getParentNodeId() != oldParentId) { clearSubTreeLocked(windowId, oldParentId); + } else { + oldInfo.recycle(); } } diff --git a/android/view/accessibility/AccessibilityManager.java b/android/view/accessibility/AccessibilityManager.java index 11cb046a..0b9bc576 100644 --- a/android/view/accessibility/AccessibilityManager.java +++ b/android/view/accessibility/AccessibilityManager.java @@ -16,46 +16,152 @@ package android.view.accessibility; +import static android.accessibilityservice.AccessibilityServiceInfo.FLAG_ENABLE_ACCESSIBILITY_VOLUME; + +import android.Manifest; import android.accessibilityservice.AccessibilityServiceInfo; import android.annotation.NonNull; import android.annotation.Nullable; +import android.annotation.SdkConstant; +import android.annotation.SystemService; +import android.content.ComponentName; import android.content.Context; +import android.content.pm.PackageManager; import android.content.pm.ServiceInfo; +import android.content.res.Resources; +import android.os.Binder; import android.os.Handler; +import android.os.IBinder; +import android.os.Looper; +import android.os.Message; +import android.os.Process; +import android.os.RemoteException; +import android.os.ServiceManager; +import android.os.SystemClock; +import android.os.UserHandle; +import android.util.ArrayMap; +import android.util.Log; +import android.util.SparseArray; import android.view.IWindow; import android.view.View; +import com.android.internal.annotations.VisibleForTesting; +import com.android.internal.util.IntPair; + +import java.util.ArrayList; import java.util.Collections; import java.util.List; /** - * System level service that serves as an event dispatch for {@link AccessibilityEvent}s. - * Such events are generated when something notable happens in the user interface, + * System level service that serves as an event dispatch for {@link AccessibilityEvent}s, + * and provides facilities for querying the accessibility state of the system. + * Accessibility events are generated when something notable happens in the user interface, * for example an {@link android.app.Activity} starts, the focus or selection of a * {@link android.view.View} changes etc. Parties interested in handling accessibility * events implement and register an accessibility service which extends - * {@code android.accessibilityservice.AccessibilityService}. + * {@link android.accessibilityservice.AccessibilityService}. * * @see AccessibilityEvent - * @see android.content.Context#getSystemService + * @see AccessibilityNodeInfo + * @see android.accessibilityservice.AccessibilityService + * @see Context#getSystemService + * @see Context#ACCESSIBILITY_SERVICE */ -@SuppressWarnings("UnusedDeclaration") +@SystemService(Context.ACCESSIBILITY_SERVICE) public final class AccessibilityManager { + private static final boolean DEBUG = false; + + private static final String LOG_TAG = "AccessibilityManager"; + + /** @hide */ + public static final int STATE_FLAG_ACCESSIBILITY_ENABLED = 0x00000001; + + /** @hide */ + public static final int STATE_FLAG_TOUCH_EXPLORATION_ENABLED = 0x00000002; + + /** @hide */ + public static final int STATE_FLAG_HIGH_TEXT_CONTRAST_ENABLED = 0x00000004; + + /** @hide */ + public static final int DALTONIZER_DISABLED = -1; + + /** @hide */ + public static final int DALTONIZER_SIMULATE_MONOCHROMACY = 0; + + /** @hide */ + public static final int DALTONIZER_CORRECT_DEUTERANOMALY = 12; + + /** @hide */ + public static final int AUTOCLICK_DELAY_DEFAULT = 600; + + /** + * Activity action: Launch UI to manage which accessibility service or feature is assigned + * to the navigation bar Accessibility button. + *

    + * Input: Nothing. + *

    + *

    + * Output: Nothing. + *

    + * + * @hide + */ + @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION) + public static final String ACTION_CHOOSE_ACCESSIBILITY_BUTTON = + "com.android.internal.intent.action.CHOOSE_ACCESSIBILITY_BUTTON"; + + static final Object sInstanceSync = new Object(); + + private static AccessibilityManager sInstance; + + private final Object mLock = new Object(); + + private IAccessibilityManager mService; + + final int mUserId; + + final Handler mHandler; + + final Handler.Callback mCallback; + + boolean mIsEnabled; - private static AccessibilityManager sInstance = new AccessibilityManager(null, null, 0); + int mRelevantEventTypes = AccessibilityEvent.TYPES_ALL_MASK; + boolean mIsTouchExplorationEnabled; + + boolean mIsHighTextContrastEnabled; + + private final ArrayMap + mAccessibilityStateChangeListeners = new ArrayMap<>(); + + private final ArrayMap + mTouchExplorationStateChangeListeners = new ArrayMap<>(); + + private final ArrayMap + mHighTextContrastStateChangeListeners = new ArrayMap<>(); + + private final ArrayMap + mServicesStateChangeListeners = new ArrayMap<>(); + + /** + * Map from a view's accessibility id to the list of request preparers set for that view + */ + private SparseArray> mRequestPreparerLists; /** - * Listener for the accessibility state. + * Listener for the system accessibility state. To listen for changes to the + * accessibility state on the device, implement this interface and register + * it with the system by calling {@link #addAccessibilityStateChangeListener}. */ public interface AccessibilityStateChangeListener { /** - * Called back on change in the accessibility state. + * Called when the accessibility enabled state changes. * * @param enabled Whether accessibility is enabled. */ - public void onAccessibilityStateChanged(boolean enabled); + void onAccessibilityStateChanged(boolean enabled); } /** @@ -71,7 +177,24 @@ public final class AccessibilityManager { * * @param enabled Whether touch exploration is enabled. */ - public void onTouchExplorationStateChanged(boolean enabled); + void onTouchExplorationStateChanged(boolean enabled); + } + + /** + * Listener for changes to the state of accessibility services. Changes include services being + * enabled or disabled, or changes to the {@link AccessibilityServiceInfo} of a running service. + * {@see #addAccessibilityServicesStateChangeListener}. + * + * @hide + */ + public interface AccessibilityServicesStateChangeListener { + + /** + * Called when the state of accessibility services changes. + * + * @param manager The manager that is calling back + */ + void onAccessibilityServicesStateChanged(AccessibilityManager manager); } /** @@ -79,6 +202,8 @@ public final class AccessibilityManager { * the high text contrast state on the device, implement this interface and * register it with the system by calling * {@link #addHighTextContrastStateChangeListener}. + * + * @hide */ public interface HighTextContrastChangeListener { @@ -87,26 +212,72 @@ public final class AccessibilityManager { * * @param enabled Whether high text contrast is enabled. */ - public void onHighTextContrastStateChanged(boolean enabled); + void onHighTextContrastStateChanged(boolean enabled); } private final IAccessibilityManagerClient.Stub mClient = new IAccessibilityManagerClient.Stub() { - public void setState(int state) { - } + @Override + public void setState(int state) { + // We do not want to change this immediately as the application may + // have already checked that accessibility is on and fired an event, + // that is now propagating up the view tree, Hence, if accessibility + // is now off an exception will be thrown. We want to have the exception + // enforcement to guard against apps that fire unnecessary accessibility + // events when accessibility is off. + mHandler.obtainMessage(MyCallback.MSG_SET_STATE, state, 0).sendToTarget(); + } - public void notifyServicesStateChanged() { + @Override + public void notifyServicesStateChanged() { + final ArrayMap listeners; + synchronized (mLock) { + if (mServicesStateChangeListeners.isEmpty()) { + return; } + listeners = new ArrayMap<>(mServicesStateChangeListeners); + } - public void setRelevantEventTypes(int eventTypes) { - } - }; + int numListeners = listeners.size(); + for (int i = 0; i < numListeners; i++) { + final AccessibilityServicesStateChangeListener listener = + mServicesStateChangeListeners.keyAt(i); + mServicesStateChangeListeners.valueAt(i).post(() -> listener + .onAccessibilityServicesStateChanged(AccessibilityManager.this)); + } + } + + @Override + public void setRelevantEventTypes(int eventTypes) { + mRelevantEventTypes = eventTypes; + } + }; /** * Get an AccessibilityManager instance (create one if necessary). * + * @param context Context in which this manager operates. + * + * @hide */ public static AccessibilityManager getInstance(Context context) { + synchronized (sInstanceSync) { + if (sInstance == null) { + final int userId; + if (Binder.getCallingUid() == Process.SYSTEM_UID + || context.checkCallingOrSelfPermission( + Manifest.permission.INTERACT_ACROSS_USERS) + == PackageManager.PERMISSION_GRANTED + || context.checkCallingOrSelfPermission( + Manifest.permission.INTERACT_ACROSS_USERS_FULL) + == PackageManager.PERMISSION_GRANTED) { + userId = UserHandle.USER_CURRENT; + } else { + userId = UserHandle.myUserId(); + } + sInstance = new AccessibilityManager(context, null, userId); + } + } return sInstance; } @@ -114,21 +285,68 @@ public final class AccessibilityManager { * Create an instance. * * @param context A {@link Context}. + * @param service An interface to the backing service. + * @param userId User id under which to run. + * + * @hide */ public AccessibilityManager(Context context, IAccessibilityManager service, int userId) { + // Constructor can't be chained because we can't create an instance of an inner class + // before calling another constructor. + mCallback = new MyCallback(); + mHandler = new Handler(context.getMainLooper(), mCallback); + mUserId = userId; + synchronized (mLock) { + tryConnectToServiceLocked(service); + } + } + + /** + * Create an instance. + * + * @param handler The handler to use + * @param service An interface to the backing service. + * @param userId User id under which to run. + * + * @hide + */ + public AccessibilityManager(Handler handler, IAccessibilityManager service, int userId) { + mCallback = new MyCallback(); + mHandler = handler; + mUserId = userId; + synchronized (mLock) { + tryConnectToServiceLocked(service); + } } + /** + * @hide + */ public IAccessibilityManagerClient getClient() { return mClient; } /** - * Returns if the {@link AccessibilityManager} is enabled. + * @hide + */ + @VisibleForTesting + public Handler.Callback getCallback() { + return mCallback; + } + + /** + * Returns if the accessibility in the system is enabled. * - * @return True if this {@link AccessibilityManager} is enabled, false otherwise. + * @return True if accessibility is enabled, false otherwise. */ public boolean isEnabled() { - return false; + synchronized (mLock) { + IAccessibilityManager service = getServiceLocked(); + if (service == null) { + return false; + } + return mIsEnabled; + } } /** @@ -137,7 +355,13 @@ public final class AccessibilityManager { * @return True if touch exploration is enabled, false otherwise. */ public boolean isTouchExplorationEnabled() { - return true; + synchronized (mLock) { + IAccessibilityManager service = getServiceLocked(); + if (service == null) { + return false; + } + return mIsTouchExplorationEnabled; + } } /** @@ -147,35 +371,169 @@ public final class AccessibilityManager { * doing its own rendering and does not rely on the platform rendering pipeline. *

    * + * @return True if high text contrast is enabled, false otherwise. + * + * @hide */ public boolean isHighTextContrastEnabled() { - return false; + synchronized (mLock) { + IAccessibilityManager service = getServiceLocked(); + if (service == null) { + return false; + } + return mIsHighTextContrastEnabled; + } } /** * Sends an {@link AccessibilityEvent}. + * + * @param event The event to send. + * + * @throws IllegalStateException if accessibility is not enabled. + * + * Note: The preferred mechanism for sending custom accessibility + * events is through calling + * {@link android.view.ViewParent#requestSendAccessibilityEvent(View, AccessibilityEvent)} + * instead of this method to allow predecessors to augment/filter events sent by + * their descendants. */ public void sendAccessibilityEvent(AccessibilityEvent event) { + final IAccessibilityManager service; + final int userId; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return; + } + if (!mIsEnabled) { + Looper myLooper = Looper.myLooper(); + if (myLooper == Looper.getMainLooper()) { + throw new IllegalStateException( + "Accessibility off. Did you forget to check that?"); + } else { + // If we're not running on the thread with the main looper, it's possible for + // the state of accessibility to change between checking isEnabled and + // calling this method. So just log the error rather than throwing the + // exception. + Log.e(LOG_TAG, "AccessibilityEvent sent with accessibility disabled"); + return; + } + } + if ((event.getEventType() & mRelevantEventTypes) == 0) { + if (DEBUG) { + Log.i(LOG_TAG, "Not dispatching irrelevant event: " + event + + " that is not among " + + AccessibilityEvent.eventTypeToString(mRelevantEventTypes)); + } + return; + } + userId = mUserId; + } + try { + event.setEventTime(SystemClock.uptimeMillis()); + // it is possible that this manager is in the same process as the service but + // client using it is called through Binder from another process. Example: MMS + // app adds a SMS notification and the NotificationManagerService calls this method + long identityToken = Binder.clearCallingIdentity(); + service.sendAccessibilityEvent(event, userId); + Binder.restoreCallingIdentity(identityToken); + if (DEBUG) { + Log.i(LOG_TAG, event + " sent"); + } + } catch (RemoteException re) { + Log.e(LOG_TAG, "Error during sending " + event + " ", re); + } finally { + event.recycle(); + } } /** - * Requests interruption of the accessibility feedback from all accessibility services. + * Requests feedback interruption from all accessibility services. */ public void interrupt() { + final IAccessibilityManager service; + final int userId; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return; + } + if (!mIsEnabled) { + Looper myLooper = Looper.myLooper(); + if (myLooper == Looper.getMainLooper()) { + throw new IllegalStateException( + "Accessibility off. Did you forget to check that?"); + } else { + // If we're not running on the thread with the main looper, it's possible for + // the state of accessibility to change between checking isEnabled and + // calling this method. So just log the error rather than throwing the + // exception. + Log.e(LOG_TAG, "Interrupt called with accessibility disabled"); + return; + } + } + userId = mUserId; + } + try { + service.interrupt(userId); + if (DEBUG) { + Log.i(LOG_TAG, "Requested interrupt from all services"); + } + } catch (RemoteException re) { + Log.e(LOG_TAG, "Error while requesting interrupt from all services. ", re); + } } /** * Returns the {@link ServiceInfo}s of the installed accessibility services. * * @return An unmodifiable list with {@link ServiceInfo}s. + * + * @deprecated Use {@link #getInstalledAccessibilityServiceList()} */ @Deprecated public List getAccessibilityServiceList() { - return Collections.emptyList(); + List infos = getInstalledAccessibilityServiceList(); + List services = new ArrayList<>(); + final int infoCount = infos.size(); + for (int i = 0; i < infoCount; i++) { + AccessibilityServiceInfo info = infos.get(i); + services.add(info.getResolveInfo().serviceInfo); + } + return Collections.unmodifiableList(services); } + /** + * Returns the {@link AccessibilityServiceInfo}s of the installed accessibility services. + * + * @return An unmodifiable list with {@link AccessibilityServiceInfo}s. + */ public List getInstalledAccessibilityServiceList() { - return Collections.emptyList(); + final IAccessibilityManager service; + final int userId; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return Collections.emptyList(); + } + userId = mUserId; + } + + List services = null; + try { + services = service.getInstalledAccessibilityServiceList(userId); + if (DEBUG) { + Log.i(LOG_TAG, "Installed AccessibilityServices " + services); + } + } catch (RemoteException re) { + Log.e(LOG_TAG, "Error while obtaining the installed AccessibilityServices. ", re); + } + if (services != null) { + return Collections.unmodifiableList(services); + } else { + return Collections.emptyList(); + } } /** @@ -190,21 +548,48 @@ public final class AccessibilityManager { * @see AccessibilityServiceInfo#FEEDBACK_HAPTIC * @see AccessibilityServiceInfo#FEEDBACK_SPOKEN * @see AccessibilityServiceInfo#FEEDBACK_VISUAL + * @see AccessibilityServiceInfo#FEEDBACK_BRAILLE */ public List getEnabledAccessibilityServiceList( int feedbackTypeFlags) { - return Collections.emptyList(); + final IAccessibilityManager service; + final int userId; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return Collections.emptyList(); + } + userId = mUserId; + } + + List services = null; + try { + services = service.getEnabledAccessibilityServiceList(feedbackTypeFlags, userId); + if (DEBUG) { + Log.i(LOG_TAG, "Installed AccessibilityServices " + services); + } + } catch (RemoteException re) { + Log.e(LOG_TAG, "Error while obtaining the installed AccessibilityServices. ", re); + } + if (services != null) { + return Collections.unmodifiableList(services); + } else { + return Collections.emptyList(); + } } /** * Registers an {@link AccessibilityStateChangeListener} for changes in - * the global accessibility state of the system. + * the global accessibility state of the system. Equivalent to calling + * {@link #addAccessibilityStateChangeListener(AccessibilityStateChangeListener, Handler)} + * with a null handler. * * @param listener The listener. - * @return True if successfully registered. + * @return Always returns {@code true}. */ public boolean addAccessibilityStateChangeListener( - AccessibilityStateChangeListener listener) { + @NonNull AccessibilityStateChangeListener listener) { + addAccessibilityStateChangeListener(listener, null); return true; } @@ -218,22 +603,40 @@ public final class AccessibilityManager { * for a callback on the process's main handler. */ public void addAccessibilityStateChangeListener( - @NonNull AccessibilityStateChangeListener listener, @Nullable Handler handler) {} + @NonNull AccessibilityStateChangeListener listener, @Nullable Handler handler) { + synchronized (mLock) { + mAccessibilityStateChangeListeners + .put(listener, (handler == null) ? mHandler : handler); + } + } + /** + * Unregisters an {@link AccessibilityStateChangeListener}. + * + * @param listener The listener. + * @return True if the listener was previously registered. + */ public boolean removeAccessibilityStateChangeListener( - AccessibilityStateChangeListener listener) { - return true; + @NonNull AccessibilityStateChangeListener listener) { + synchronized (mLock) { + int index = mAccessibilityStateChangeListeners.indexOfKey(listener); + mAccessibilityStateChangeListeners.remove(listener); + return (index >= 0); + } } /** * Registers a {@link TouchExplorationStateChangeListener} for changes in - * the global touch exploration state of the system. + * the global touch exploration state of the system. Equivalent to calling + * {@link #addTouchExplorationStateChangeListener(TouchExplorationStateChangeListener, Handler)} + * with a null handler. * * @param listener The listener. - * @return True if successfully registered. + * @return Always returns {@code true}. */ public boolean addTouchExplorationStateChangeListener( @NonNull TouchExplorationStateChangeListener listener) { + addTouchExplorationStateChangeListener(listener, null); return true; } @@ -247,17 +650,103 @@ public final class AccessibilityManager { * for a callback on the process's main handler. */ public void addTouchExplorationStateChangeListener( - @NonNull TouchExplorationStateChangeListener listener, @Nullable Handler handler) {} + @NonNull TouchExplorationStateChangeListener listener, @Nullable Handler handler) { + synchronized (mLock) { + mTouchExplorationStateChangeListeners + .put(listener, (handler == null) ? mHandler : handler); + } + } /** * Unregisters a {@link TouchExplorationStateChangeListener}. * * @param listener The listener. - * @return True if successfully unregistered. + * @return True if listener was previously registered. */ public boolean removeTouchExplorationStateChangeListener( @NonNull TouchExplorationStateChangeListener listener) { - return true; + synchronized (mLock) { + int index = mTouchExplorationStateChangeListeners.indexOfKey(listener); + mTouchExplorationStateChangeListeners.remove(listener); + return (index >= 0); + } + } + + /** + * Registers a {@link AccessibilityServicesStateChangeListener}. + * + * @param listener The listener. + * @param handler The handler on which the listener should be called back, or {@code null} + * for a callback on the process's main handler. + * @hide + */ + public void addAccessibilityServicesStateChangeListener( + @NonNull AccessibilityServicesStateChangeListener listener, @Nullable Handler handler) { + synchronized (mLock) { + mServicesStateChangeListeners + .put(listener, (handler == null) ? mHandler : handler); + } + } + + /** + * Unregisters a {@link AccessibilityServicesStateChangeListener}. + * + * @param listener The listener. + * + * @hide + */ + public void removeAccessibilityServicesStateChangeListener( + @NonNull AccessibilityServicesStateChangeListener listener) { + // Final CopyOnWriteArrayList - no lock needed. + mServicesStateChangeListeners.remove(listener); + } + + /** + * Registers a {@link AccessibilityRequestPreparer}. + */ + public void addAccessibilityRequestPreparer(AccessibilityRequestPreparer preparer) { + if (mRequestPreparerLists == null) { + mRequestPreparerLists = new SparseArray<>(1); + } + int id = preparer.getView().getAccessibilityViewId(); + List requestPreparerList = mRequestPreparerLists.get(id); + if (requestPreparerList == null) { + requestPreparerList = new ArrayList<>(1); + mRequestPreparerLists.put(id, requestPreparerList); + } + requestPreparerList.add(preparer); + } + + /** + * Unregisters a {@link AccessibilityRequestPreparer}. + */ + public void removeAccessibilityRequestPreparer(AccessibilityRequestPreparer preparer) { + if (mRequestPreparerLists == null) { + return; + } + int viewId = preparer.getView().getAccessibilityViewId(); + List requestPreparerList = mRequestPreparerLists.get(viewId); + if (requestPreparerList != null) { + requestPreparerList.remove(preparer); + if (requestPreparerList.isEmpty()) { + mRequestPreparerLists.remove(viewId); + } + } + } + + /** + * Get the preparers that are registered for an accessibility ID + * + * @param id The ID of interest + * @return The list of preparers, or {@code null} if there are none. + * + * @hide + */ + public List getRequestPreparersForAccessibilityId(int id) { + if (mRequestPreparerLists == null) { + return null; + } + return mRequestPreparerLists.get(id); } /** @@ -269,7 +758,12 @@ public final class AccessibilityManager { * @hide */ public void addHighTextContrastStateChangeListener( - @NonNull HighTextContrastChangeListener listener, @Nullable Handler handler) {} + @NonNull HighTextContrastChangeListener listener, @Nullable Handler handler) { + synchronized (mLock) { + mHighTextContrastStateChangeListeners + .put(listener, (handler == null) ? mHandler : handler); + } + } /** * Unregisters a {@link HighTextContrastChangeListener}. @@ -279,7 +773,51 @@ public final class AccessibilityManager { * @hide */ public void removeHighTextContrastStateChangeListener( - @NonNull HighTextContrastChangeListener listener) {} + @NonNull HighTextContrastChangeListener listener) { + synchronized (mLock) { + mHighTextContrastStateChangeListeners.remove(listener); + } + } + + /** + * Check if the accessibility volume stream is active. + * + * @return True if accessibility volume is active (i.e. some service has requested it). False + * otherwise. + * @hide + */ + public boolean isAccessibilityVolumeStreamActive() { + List serviceInfos = + getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK); + for (int i = 0; i < serviceInfos.size(); i++) { + if ((serviceInfos.get(i).flags & FLAG_ENABLE_ACCESSIBILITY_VOLUME) != 0) { + return true; + } + } + return false; + } + + /** + * Report a fingerprint gesture to accessibility. Only available for the system process. + * + * @param keyCode The key code of the gesture + * @return {@code true} if accessibility consumes the event. {@code false} if not. + * @hide + */ + public boolean sendFingerprintGesture(int keyCode) { + final IAccessibilityManager service; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return false; + } + } + try { + return service.sendFingerprintGesture(keyCode); + } catch (RemoteException e) { + return false; + } + } /** * Sets the current state and notifies listeners, if necessary. @@ -287,14 +825,314 @@ public final class AccessibilityManager { * @param stateFlags The state flags. */ private void setStateLocked(int stateFlags) { + final boolean enabled = (stateFlags & STATE_FLAG_ACCESSIBILITY_ENABLED) != 0; + final boolean touchExplorationEnabled = + (stateFlags & STATE_FLAG_TOUCH_EXPLORATION_ENABLED) != 0; + final boolean highTextContrastEnabled = + (stateFlags & STATE_FLAG_HIGH_TEXT_CONTRAST_ENABLED) != 0; + + final boolean wasEnabled = mIsEnabled; + final boolean wasTouchExplorationEnabled = mIsTouchExplorationEnabled; + final boolean wasHighTextContrastEnabled = mIsHighTextContrastEnabled; + + // Ensure listeners get current state from isZzzEnabled() calls. + mIsEnabled = enabled; + mIsTouchExplorationEnabled = touchExplorationEnabled; + mIsHighTextContrastEnabled = highTextContrastEnabled; + + if (wasEnabled != enabled) { + notifyAccessibilityStateChanged(); + } + + if (wasTouchExplorationEnabled != touchExplorationEnabled) { + notifyTouchExplorationStateChanged(); + } + + if (wasHighTextContrastEnabled != highTextContrastEnabled) { + notifyHighTextContrastStateChanged(); + } } + /** + * Find an installed service with the specified {@link ComponentName}. + * + * @param componentName The name to match to the service. + * + * @return The info corresponding to the installed service, or {@code null} if no such service + * is installed. + * @hide + */ + public AccessibilityServiceInfo getInstalledServiceInfoWithComponentName( + ComponentName componentName) { + final List installedServiceInfos = + getInstalledAccessibilityServiceList(); + if ((installedServiceInfos == null) || (componentName == null)) { + return null; + } + for (int i = 0; i < installedServiceInfos.size(); i++) { + if (componentName.equals(installedServiceInfos.get(i).getComponentName())) { + return installedServiceInfos.get(i); + } + } + return null; + } + + /** + * Adds an accessibility interaction connection interface for a given window. + * @param windowToken The window token to which a connection is added. + * @param connection The connection. + * + * @hide + */ public int addAccessibilityInteractionConnection(IWindow windowToken, IAccessibilityInteractionConnection connection) { + final IAccessibilityManager service; + final int userId; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return View.NO_ID; + } + userId = mUserId; + } + try { + return service.addAccessibilityInteractionConnection(windowToken, connection, userId); + } catch (RemoteException re) { + Log.e(LOG_TAG, "Error while adding an accessibility interaction connection. ", re); + } return View.NO_ID; } + /** + * Removed an accessibility interaction connection interface for a given window. + * @param windowToken The window token to which a connection is removed. + * + * @hide + */ public void removeAccessibilityInteractionConnection(IWindow windowToken) { + final IAccessibilityManager service; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return; + } + } + try { + service.removeAccessibilityInteractionConnection(windowToken); + } catch (RemoteException re) { + Log.e(LOG_TAG, "Error while removing an accessibility interaction connection. ", re); + } + } + + /** + * Perform the accessibility shortcut if the caller has permission. + * + * @hide + */ + public void performAccessibilityShortcut() { + final IAccessibilityManager service; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return; + } + } + try { + service.performAccessibilityShortcut(); + } catch (RemoteException re) { + Log.e(LOG_TAG, "Error performing accessibility shortcut. ", re); + } + } + + /** + * Notifies that the accessibility button in the system's navigation area has been clicked + * + * @hide + */ + public void notifyAccessibilityButtonClicked() { + final IAccessibilityManager service; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return; + } + } + try { + service.notifyAccessibilityButtonClicked(); + } catch (RemoteException re) { + Log.e(LOG_TAG, "Error while dispatching accessibility button click", re); + } + } + + /** + * Notifies that the visibility of the accessibility button in the system's navigation area + * has changed. + * + * @param shown {@code true} if the accessibility button is visible within the system + * navigation area, {@code false} otherwise + * @hide + */ + public void notifyAccessibilityButtonVisibilityChanged(boolean shown) { + final IAccessibilityManager service; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return; + } + } + try { + service.notifyAccessibilityButtonVisibilityChanged(shown); + } catch (RemoteException re) { + Log.e(LOG_TAG, "Error while dispatching accessibility button visibility change", re); + } + } + + /** + * Set an IAccessibilityInteractionConnection to replace the actions of a picture-in-picture + * window. Intended for use by the System UI only. + * + * @param connection The connection to handle the actions. Set to {@code null} to avoid + * affecting the actions. + * + * @hide + */ + public void setPictureInPictureActionReplacingConnection( + @Nullable IAccessibilityInteractionConnection connection) { + final IAccessibilityManager service; + synchronized (mLock) { + service = getServiceLocked(); + if (service == null) { + return; + } + } + try { + service.setPictureInPictureActionReplacingConnection(connection); + } catch (RemoteException re) { + Log.e(LOG_TAG, "Error setting picture in picture action replacement", re); + } } + private IAccessibilityManager getServiceLocked() { + if (mService == null) { + tryConnectToServiceLocked(null); + } + return mService; + } + + private void tryConnectToServiceLocked(IAccessibilityManager service) { + if (service == null) { + IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); + if (iBinder == null) { + return; + } + service = IAccessibilityManager.Stub.asInterface(iBinder); + } + + try { + final long userStateAndRelevantEvents = service.addClient(mClient, mUserId); + setStateLocked(IntPair.first(userStateAndRelevantEvents)); + mRelevantEventTypes = IntPair.second(userStateAndRelevantEvents); + mService = service; + } catch (RemoteException re) { + Log.e(LOG_TAG, "AccessibilityManagerService is dead", re); + } + } + + /** + * Notifies the registered {@link AccessibilityStateChangeListener}s. + */ + private void notifyAccessibilityStateChanged() { + final boolean isEnabled; + final ArrayMap listeners; + synchronized (mLock) { + if (mAccessibilityStateChangeListeners.isEmpty()) { + return; + } + isEnabled = mIsEnabled; + listeners = new ArrayMap<>(mAccessibilityStateChangeListeners); + } + + int numListeners = listeners.size(); + for (int i = 0; i < numListeners; i++) { + final AccessibilityStateChangeListener listener = + mAccessibilityStateChangeListeners.keyAt(i); + mAccessibilityStateChangeListeners.valueAt(i) + .post(() -> listener.onAccessibilityStateChanged(isEnabled)); + } + } + + /** + * Notifies the registered {@link TouchExplorationStateChangeListener}s. + */ + private void notifyTouchExplorationStateChanged() { + final boolean isTouchExplorationEnabled; + final ArrayMap listeners; + synchronized (mLock) { + if (mTouchExplorationStateChangeListeners.isEmpty()) { + return; + } + isTouchExplorationEnabled = mIsTouchExplorationEnabled; + listeners = new ArrayMap<>(mTouchExplorationStateChangeListeners); + } + + int numListeners = listeners.size(); + for (int i = 0; i < numListeners; i++) { + final TouchExplorationStateChangeListener listener = + mTouchExplorationStateChangeListeners.keyAt(i); + mTouchExplorationStateChangeListeners.valueAt(i) + .post(() -> listener.onTouchExplorationStateChanged(isTouchExplorationEnabled)); + } + } + + /** + * Notifies the registered {@link HighTextContrastChangeListener}s. + */ + private void notifyHighTextContrastStateChanged() { + final boolean isHighTextContrastEnabled; + final ArrayMap listeners; + synchronized (mLock) { + if (mHighTextContrastStateChangeListeners.isEmpty()) { + return; + } + isHighTextContrastEnabled = mIsHighTextContrastEnabled; + listeners = new ArrayMap<>(mHighTextContrastStateChangeListeners); + } + + int numListeners = listeners.size(); + for (int i = 0; i < numListeners; i++) { + final HighTextContrastChangeListener listener = + mHighTextContrastStateChangeListeners.keyAt(i); + mHighTextContrastStateChangeListeners.valueAt(i) + .post(() -> listener.onHighTextContrastStateChanged(isHighTextContrastEnabled)); + } + } + + /** + * Determines if the accessibility button within the system navigation area is supported. + * + * @return {@code true} if the accessibility button is supported on this device, + * {@code false} otherwise + */ + public static boolean isAccessibilityButtonSupported() { + final Resources res = Resources.getSystem(); + return res.getBoolean(com.android.internal.R.bool.config_showNavigationBar); + } + + private final class MyCallback implements Handler.Callback { + public static final int MSG_SET_STATE = 1; + + @Override + public boolean handleMessage(Message message) { + switch (message.what) { + case MSG_SET_STATE: { + // See comment at mClient + final int state = message.arg1; + synchronized (mLock) { + setStateLocked(state); + } + } break; + } + return true; + } + } } diff --git a/android/view/autofill/AutofillManager.java b/android/view/autofill/AutofillManager.java index e564fa34..4fb2a99a 100644 --- a/android/view/autofill/AutofillManager.java +++ b/android/view/autofill/AutofillManager.java @@ -91,10 +91,10 @@ import java.util.Objects; * * *

    When the service returns datasets, the Android System displays an autofill dataset picker - * UI associated with the view, when the view is focused on and is part of a dataset. - * The application can be notified when the UI is shown by registering an + * UI affordance associated with the view, when the view is focused on and is part of a dataset. + * The application can be notified when the affordance is shown by registering an * {@link AutofillCallback} through {@link #registerCallback(AutofillCallback)}. When the user - * selects a dataset from the UI, all views present in the dataset are autofilled, through + * selects a dataset from the affordance, all views present in the dataset are autofilled, through * calls to {@link View#autofill(AutofillValue)} or {@link View#autofill(SparseArray)}. * *

    When the service returns ids of savable views, the Android System keeps track of changes @@ -108,7 +108,7 @@ import java.util.Objects; * * *

    Finally, after the autofill context is commited (i.e., not cancelled), the Android System - * shows an autofill save UI if the value of savable views have changed. If the user selects the + * shows a save UI affordance if the value of savable views have changed. If the user selects the * option to Save, the current value of the views is then sent to the autofill service. * *

    It is safe to call into its methods from any thread. @@ -150,12 +150,6 @@ public final class AutofillManager { * service authentication will contain the Bundle set by * {@link android.service.autofill.FillResponse.Builder#setClientState(Bundle)} on this extra. * - *

    On Android {@link android.os.Build.VERSION_CODES#P} and higher, the autofill service - * can also add this bundle to the {@link Intent} set as the - * {@link android.app.Activity#setResult(int, Intent) result} for an authentication request, - * so the bundle can be recovered later on - * {@link android.service.autofill.SaveRequest#getClientState()}. - * *

    * Type: {@link android.os.Bundle} */ @@ -317,14 +311,6 @@ public final class AutofillManager { @GuardedBy("mLock") @Nullable private ArraySet mFillableIds; - /** If set, session is commited when the field is clicked. */ - @GuardedBy("mLock") - @Nullable private AutofillId mSaveTriggerId; - - /** If set, session is commited when the activity is finished; otherwise session is canceled. */ - @GuardedBy("mLock") - private boolean mSaveOnFinish; - /** @hide */ public interface AutofillClient { /** @@ -848,46 +834,6 @@ public final class AutofillManager { } } - - /** - * Called when a {@link View} is clicked. Currently only used by views that should trigger save. - * - * @hide - */ - public void notifyViewClicked(View view) { - final AutofillId id = view.getAutofillId(); - - if (sVerbose) Log.v(TAG, "notifyViewClicked(): id=" + id + ", trigger=" + mSaveTriggerId); - - synchronized (mLock) { - if (mSaveTriggerId != null && mSaveTriggerId.equals(id)) { - if (sDebug) Log.d(TAG, "triggering commit by click of " + id); - commitLocked(); - mMetricsLogger.action(MetricsEvent.AUTOFILL_SAVE_EXPLICITLY_TRIGGERED, - mContext.getPackageName()); - } - } - } - - /** - * Called by {@link android.app.Activity} to commit or cancel the session on finish. - * - * @hide - */ - public void onActivityFinished() { - if (!hasAutofillFeature()) { - return; - } - synchronized (mLock) { - if (mSaveOnFinish) { - commitLocked(); - } else { - if (sDebug) Log.d(TAG, "Cancelling session on finish() as requested by service"); - cancelLocked(); - } - } - } - /** * Called to indicate the current autofill context should be commited. * @@ -904,15 +850,12 @@ public final class AutofillManager { return; } synchronized (mLock) { - commitLocked(); - } - } + if (!mEnabled && !isActiveLocked()) { + return; + } - private void commitLocked() { - if (!mEnabled && !isActiveLocked()) { - return; + finishSessionLocked(); } - finishSessionLocked(); } /** @@ -931,15 +874,12 @@ public final class AutofillManager { return; } synchronized (mLock) { - cancelLocked(); - } - } + if (!mEnabled && !isActiveLocked()) { + return; + } - private void cancelLocked() { - if (!mEnabled && !isActiveLocked()) { - return; + cancelSessionLocked(); } - cancelSessionLocked(); } /** @hide */ @@ -997,12 +937,7 @@ public final class AutofillManager { } private AutofillClient getClientLocked() { - final AutofillClient client = mContext.getAutofillClient(); - if (client == null && sDebug) { - Log.d(TAG, "No AutofillClient for " + mContext.getPackageName() + " on context " - + mContext); - } - return client; + return mContext.getAutofillClient(); } /** @hide */ @@ -1024,10 +959,6 @@ public final class AutofillManager { final Parcelable result = data.getParcelableExtra(EXTRA_AUTHENTICATION_RESULT); final Bundle responseData = new Bundle(); responseData.putParcelable(EXTRA_AUTHENTICATION_RESULT, result); - final Bundle newClientState = data.getBundleExtra(EXTRA_CLIENT_STATE); - if (newClientState != null) { - responseData.putBundle(EXTRA_CLIENT_STATE, newClientState); - } try { mService.setAuthenticationResult(responseData, mSessionId, authenticationId, mContext.getUserId()); @@ -1107,7 +1038,6 @@ public final class AutofillManager { mState = STATE_UNKNOWN; mTrackedViews = null; mFillableIds = null; - mSaveTriggerId = null; } private void updateSessionLocked(AutofillId id, Rect bounds, AutofillValue value, int action, @@ -1359,15 +1289,12 @@ public final class AutofillManager { /** * Set the tracked views. * - * @param trackedIds The views to be tracked. + * @param trackedIds The views to be tracked * @param saveOnAllViewsInvisible Finish the session once all tracked views are invisible. - * @param saveOnFinish Finish the session once the activity is finished. * @param fillableIds Views that might anchor FillUI. - * @param saveTriggerId View that when clicked triggers commit(). */ private void setTrackedViews(int sessionId, @Nullable AutofillId[] trackedIds, - boolean saveOnAllViewsInvisible, boolean saveOnFinish, - @Nullable AutofillId[] fillableIds, @Nullable AutofillId saveTriggerId) { + boolean saveOnAllViewsInvisible, @Nullable AutofillId[] fillableIds) { synchronized (mLock) { if (mEnabled && mSessionId == sessionId) { if (saveOnAllViewsInvisible) { @@ -1375,7 +1302,6 @@ public final class AutofillManager { } else { mTrackedViews = null; } - mSaveOnFinish = saveOnFinish; if (fillableIds != null) { if (mFillableIds == null) { mFillableIds = new ArraySet<>(fillableIds.length); @@ -1388,30 +1314,10 @@ public final class AutofillManager { + ", mFillableIds" + mFillableIds); } } - - if (mSaveTriggerId != null && !mSaveTriggerId.equals(saveTriggerId)) { - // Turn off trigger on previous view id. - setNotifyOnClickLocked(mSaveTriggerId, false); - } - - if (saveTriggerId != null && !saveTriggerId.equals(mSaveTriggerId)) { - // Turn on trigger on new view id. - mSaveTriggerId = saveTriggerId; - setNotifyOnClickLocked(mSaveTriggerId, true); - } } } } - private void setNotifyOnClickLocked(@NonNull AutofillId id, boolean notify) { - final View view = findView(id); - if (view == null) { - Log.w(TAG, "setNotifyOnClick(): invalid id: " + id); - return; - } - view.setNotifyAutofillManagerOnClick(notify); - } - private void setSaveUiState(int sessionId, boolean shown) { if (sDebug) Log.d(TAG, "setSaveUiState(" + sessionId + "): " + shown); synchronized (mLock) { @@ -1584,7 +1490,6 @@ public final class AutofillManager { final String pfx = outerPrefix + " "; pw.print(pfx); pw.print("sessionId: "); pw.println(mSessionId); pw.print(pfx); pw.print("state: "); pw.println(getStateAsStringLocked()); - pw.print(pfx); pw.print("context: "); pw.println(mContext); pw.print(pfx); pw.print("enabled: "); pw.println(mEnabled); pw.print(pfx); pw.print("hasService: "); pw.println(mService != null); pw.print(pfx); pw.print("hasCallback: "); pw.println(mCallback != null); @@ -1599,8 +1504,6 @@ public final class AutofillManager { pw.print(pfx2); pw.print("invisible:"); pw.println(mTrackedViews.mInvisibleTrackedIds); } pw.print(pfx); pw.print("fillable ids: "); pw.println(mFillableIds); - pw.print(pfx); pw.print("save trigger id: "); pw.println(mSaveTriggerId); - pw.print(pfx); pw.print("save on finish(): "); pw.println(mSaveOnFinish); } private String getStateAsStringLocked() { @@ -1849,7 +1752,7 @@ public final class AutofillManager { * Callback for autofill related events. * *

    Typically used for applications that display their own "auto-complete" views, so they can - * enable / disable such views when the autofill UI is shown / hidden. + * enable / disable such views when the autofill UI affordance is shown / hidden. */ public abstract static class AutofillCallback { @@ -1859,26 +1762,26 @@ public final class AutofillManager { public @interface AutofillEventType {} /** - * The autofill input UI associated with the view was shown. + * The autofill input UI affordance associated with the view was shown. * - *

    If the view provides its own auto-complete UI and its currently shown, it + *

    If the view provides its own auto-complete UI affordance and its currently shown, it * should be hidden upon receiving this event. */ public static final int EVENT_INPUT_SHOWN = 1; /** - * The autofill input UI associated with the view was hidden. + * The autofill input UI affordance associated with the view was hidden. * - *

    If the view provides its own auto-complete UI that was hidden upon a + *

    If the view provides its own auto-complete UI affordance that was hidden upon a * {@link #EVENT_INPUT_SHOWN} event, it could be shown again now. */ public static final int EVENT_INPUT_HIDDEN = 2; /** - * The autofill input UI associated with the view isn't shown because + * The autofill input UI affordance associated with the view isn't shown because * autofill is not available. * - *

    If the view provides its own auto-complete UI but was not displaying it + *

    If the view provides its own auto-complete UI affordance but was not displaying it * to avoid flickering, it could shown it upon receiving this event. */ public static final int EVENT_INPUT_UNAVAILABLE = 3; @@ -1980,12 +1883,12 @@ public final class AutofillManager { @Override public void setTrackedViews(int sessionId, AutofillId[] ids, - boolean saveOnAllViewsInvisible, boolean saveOnFinish, AutofillId[] fillableIds, - AutofillId saveTriggerId) { + boolean saveOnAllViewsInvisible, AutofillId[] fillableIds) { final AutofillManager afm = mAfm.get(); if (afm != null) { - afm.post(() -> afm.setTrackedViews(sessionId, ids, saveOnAllViewsInvisible, - saveOnFinish, fillableIds, saveTriggerId)); + afm.post(() -> + afm.setTrackedViews(sessionId, ids, saveOnAllViewsInvisible, fillableIds) + ); } } diff --git a/android/view/textclassifier/TextClassifier.java b/android/view/textclassifier/TextClassifier.java index c3601d9d..bb1e693f 100644 --- a/android/view/textclassifier/TextClassifier.java +++ b/android/view/textclassifier/TextClassifier.java @@ -152,12 +152,4 @@ public interface TextClassifier { */ @WorkerThread default void logEvent(String source, String event) {} - - /** - * Returns this TextClassifier's settings. - * @hide - */ - default TextClassifierConstants getSettings() { - return TextClassifierConstants.DEFAULT; - } } diff --git a/android/view/textclassifier/TextClassifierConstants.java b/android/view/textclassifier/TextClassifierConstants.java deleted file mode 100644 index 51e6168e..00000000 --- a/android/view/textclassifier/TextClassifierConstants.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2017 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.textclassifier; - -import android.annotation.Nullable; -import android.util.KeyValueListParser; -import android.util.Slog; - -/** - * TextClassifier specific settings. - * This is encoded as a key=value list, separated by commas. Ex: - * - *

    - * smart_selection_dark_launch              (boolean)
    - * smart_selection_enabled_for_edit_text    (boolean)
    - * 
    - * - *

    - * Type: string - * see also android.provider.Settings.Global.TEXT_CLASSIFIER_CONSTANTS - * - * Example of setting the values for testing. - * adb shell settings put global text_classifier_constants smart_selection_dark_launch=true,smart_selection_enabled_for_edit_text=true - * @hide - */ -public final class TextClassifierConstants { - - private static final String LOG_TAG = "TextClassifierConstants"; - - private static final String SMART_SELECTION_DARK_LAUNCH = - "smart_selection_dark_launch"; - private static final String SMART_SELECTION_ENABLED_FOR_EDIT_TEXT = - "smart_selection_enabled_for_edit_text"; - - private static final boolean SMART_SELECTION_DARK_LAUNCH_DEFAULT = false; - private static final boolean SMART_SELECTION_ENABLED_FOR_EDIT_TEXT_DEFAULT = true; - - /** Default settings. */ - static final TextClassifierConstants DEFAULT = new TextClassifierConstants(); - - private final boolean mDarkLaunch; - private final boolean mSuggestSelectionEnabledForEditableText; - - private TextClassifierConstants() { - mDarkLaunch = SMART_SELECTION_DARK_LAUNCH_DEFAULT; - mSuggestSelectionEnabledForEditableText = SMART_SELECTION_ENABLED_FOR_EDIT_TEXT_DEFAULT; - } - - private TextClassifierConstants(@Nullable String settings) { - final KeyValueListParser parser = new KeyValueListParser(','); - try { - parser.setString(settings); - } catch (IllegalArgumentException e) { - // Failed to parse the settings string, log this and move on with defaults. - Slog.e(LOG_TAG, "Bad TextClassifier settings: " + settings); - } - mDarkLaunch = parser.getBoolean( - SMART_SELECTION_DARK_LAUNCH, - SMART_SELECTION_DARK_LAUNCH_DEFAULT); - mSuggestSelectionEnabledForEditableText = parser.getBoolean( - SMART_SELECTION_ENABLED_FOR_EDIT_TEXT, - SMART_SELECTION_ENABLED_FOR_EDIT_TEXT_DEFAULT); - } - - static TextClassifierConstants loadFromString(String settings) { - return new TextClassifierConstants(settings); - } - - public boolean isDarkLaunch() { - return mDarkLaunch; - } - - public boolean isSuggestSelectionEnabledForEditableText() { - return mSuggestSelectionEnabledForEditableText; - } -} diff --git a/android/view/textclassifier/TextClassifierImpl.java b/android/view/textclassifier/TextClassifierImpl.java index ef087472..2aa81a2c 100644 --- a/android/view/textclassifier/TextClassifierImpl.java +++ b/android/view/textclassifier/TextClassifierImpl.java @@ -24,12 +24,12 @@ import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.Drawable; +import android.icu.text.BreakIterator; import android.net.Uri; import android.os.LocaleList; import android.os.ParcelFileDescriptor; import android.provider.Browser; import android.provider.ContactsContract; -import android.provider.Settings; import android.text.Spannable; import android.text.TextUtils; import android.text.method.WordIterator; @@ -47,7 +47,6 @@ import com.android.internal.util.Preconditions; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; -import java.text.BreakIterator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -92,8 +91,6 @@ final class TextClassifierImpl implements TextClassifier { @GuardedBy("mSmartSelectionLock") // Do not access outside this lock. private SmartSelection mSmartSelection; - private TextClassifierConstants mSettings; - TextClassifierImpl(Context context) { mContext = Preconditions.checkNotNull(context); } @@ -192,15 +189,6 @@ final class TextClassifierImpl implements TextClassifier { } } - @Override - public TextClassifierConstants getSettings() { - if (mSettings == null) { - mSettings = TextClassifierConstants.loadFromString(Settings.Global.getString( - mContext.getContentResolver(), Settings.Global.TEXT_CLASSIFIER_CONSTANTS)); - } - return mSettings; - } - private SmartSelection getSmartSelection(LocaleList localeList) throws FileNotFoundException { synchronized (mSmartSelectionLock) { localeList = localeList == null ? LocaleList.getEmptyLocaleList() : localeList; diff --git a/android/view/textservice/TextServicesManager.java b/android/view/textservice/TextServicesManager.java index 8e1f2183..f368c74a 100644 --- a/android/view/textservice/TextServicesManager.java +++ b/android/view/textservice/TextServicesManager.java @@ -1,58 +1,213 @@ /* - * Copyright (C) 2016 The Android Open Source Project + * Copyright (C) 2011 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. */ package android.view.textservice; +import android.annotation.SystemService; +import android.content.Context; import android.os.Bundle; +import android.os.RemoteException; +import android.os.ServiceManager; +import android.os.ServiceManager.ServiceNotFoundException; +import android.util.Log; import android.view.textservice.SpellCheckerSession.SpellCheckerSessionListener; +import com.android.internal.textservice.ITextServicesManager; + import java.util.Locale; /** - * A stub class of TextServicesManager for Layout-Lib. + * System API to the overall text services, which arbitrates interaction between applications + * and text services. + * + * The user can change the current text services in Settings. And also applications can specify + * the target text services. + * + *

    Architecture Overview

    + * + *

    There are three primary parties involved in the text services + * framework (TSF) architecture:

    + * + *
      + *
    • The text services manager as expressed by this class + * is the central point of the system that manages interaction between all + * other parts. It is expressed as the client-side API here which exists + * in each application context and communicates with a global system service + * that manages the interaction across all processes. + *
    • A text service implements a particular + * interaction model allowing the client application to retrieve information of text. + * The system binds to the current text service that is in use, causing it to be created and run. + *
    • Multiple client applications arbitrate with the text service + * manager for connections to text services. + *
    + * + *

    Text services sessions

    + *
      + *
    • The spell checker session is one of the text services. + * {@link android.view.textservice.SpellCheckerSession}
    • + *
    + * */ +@SystemService(Context.TEXT_SERVICES_MANAGER_SERVICE) public final class TextServicesManager { - private static final TextServicesManager sInstance = new TextServicesManager(); - private static final SpellCheckerInfo[] EMPTY_SPELL_CHECKER_INFO = new SpellCheckerInfo[0]; + private static final String TAG = TextServicesManager.class.getSimpleName(); + private static final boolean DBG = false; + + private static TextServicesManager sInstance; + + private final ITextServicesManager mService; + + private TextServicesManager() throws ServiceNotFoundException { + mService = ITextServicesManager.Stub.asInterface( + ServiceManager.getServiceOrThrow(Context.TEXT_SERVICES_MANAGER_SERVICE)); + } /** * Retrieve the global TextServicesManager instance, creating it if it doesn't already exist. * @hide */ public static TextServicesManager getInstance() { - return sInstance; + synchronized (TextServicesManager.class) { + if (sInstance == null) { + try { + sInstance = new TextServicesManager(); + } catch (ServiceNotFoundException e) { + throw new IllegalStateException(e); + } + } + return sInstance; + } + } + + /** + * Returns the language component of a given locale string. + */ + private static String parseLanguageFromLocaleString(String locale) { + final int idx = locale.indexOf('_'); + if (idx < 0) { + return locale; + } else { + return locale.substring(0, idx); + } } + /** + * Get a spell checker session for the specified spell checker + * @param locale the locale for the spell checker. If {@code locale} is null and + * referToSpellCheckerLanguageSettings is true, the locale specified in Settings will be + * returned. If {@code locale} is not null and referToSpellCheckerLanguageSettings is true, + * the locale specified in Settings will be returned only when it is same as {@code locale}. + * Exceptionally, when referToSpellCheckerLanguageSettings is true and {@code locale} is + * only language (e.g. "en"), the specified locale in Settings (e.g. "en_US") will be + * selected. + * @param listener a spell checker session lister for getting results from a spell checker. + * @param referToSpellCheckerLanguageSettings if true, the session for one of enabled + * languages in settings will be returned. + * @return the spell checker session of the spell checker + */ public SpellCheckerSession newSpellCheckerSession(Bundle bundle, Locale locale, SpellCheckerSessionListener listener, boolean referToSpellCheckerLanguageSettings) { - return null; + if (listener == null) { + throw new NullPointerException(); + } + if (!referToSpellCheckerLanguageSettings && locale == null) { + throw new IllegalArgumentException("Locale should not be null if you don't refer" + + " settings."); + } + + if (referToSpellCheckerLanguageSettings && !isSpellCheckerEnabled()) { + return null; + } + + final SpellCheckerInfo sci; + try { + sci = mService.getCurrentSpellChecker(null); + } catch (RemoteException e) { + return null; + } + if (sci == null) { + return null; + } + SpellCheckerSubtype subtypeInUse = null; + if (referToSpellCheckerLanguageSettings) { + subtypeInUse = getCurrentSpellCheckerSubtype(true); + if (subtypeInUse == null) { + return null; + } + if (locale != null) { + final String subtypeLocale = subtypeInUse.getLocale(); + final String subtypeLanguage = parseLanguageFromLocaleString(subtypeLocale); + if (subtypeLanguage.length() < 2 || !locale.getLanguage().equals(subtypeLanguage)) { + return null; + } + } + } else { + final String localeStr = locale.toString(); + for (int i = 0; i < sci.getSubtypeCount(); ++i) { + final SpellCheckerSubtype subtype = sci.getSubtypeAt(i); + final String tempSubtypeLocale = subtype.getLocale(); + final String tempSubtypeLanguage = parseLanguageFromLocaleString(tempSubtypeLocale); + if (tempSubtypeLocale.equals(localeStr)) { + subtypeInUse = subtype; + break; + } else if (tempSubtypeLanguage.length() >= 2 && + locale.getLanguage().equals(tempSubtypeLanguage)) { + subtypeInUse = subtype; + } + } + } + if (subtypeInUse == null) { + return null; + } + final SpellCheckerSession session = new SpellCheckerSession(sci, mService, listener); + try { + mService.getSpellCheckerService(sci.getId(), subtypeInUse.getLocale(), + session.getTextServicesSessionListener(), + session.getSpellCheckerSessionListener(), bundle); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + return session; } /** * @hide */ public SpellCheckerInfo[] getEnabledSpellCheckers() { - return EMPTY_SPELL_CHECKER_INFO; + try { + final SpellCheckerInfo[] retval = mService.getEnabledSpellCheckers(); + if (DBG) { + Log.d(TAG, "getEnabledSpellCheckers: " + (retval != null ? retval.length : "null")); + } + return retval; + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } } /** * @hide */ public SpellCheckerInfo getCurrentSpellChecker() { - return null; + try { + // Passing null as a locale for ICS + return mService.getCurrentSpellChecker(null); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } } /** @@ -60,13 +215,22 @@ public final class TextServicesManager { */ public SpellCheckerSubtype getCurrentSpellCheckerSubtype( boolean allowImplicitlySelectedSubtype) { - return null; + try { + // Passing null as a locale until we support multiple enabled spell checker subtypes. + return mService.getCurrentSpellCheckerSubtype(null, allowImplicitlySelectedSubtype); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } } /** * @hide */ public boolean isSpellCheckerEnabled() { - return false; + try { + return mService.isSpellCheckerEnabled(); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } } } diff --git a/android/webkit/WebView.java b/android/webkit/WebView.java index 202f2046..dfc81b2b 100644 --- a/android/webkit/WebView.java +++ b/android/webkit/WebView.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008 The Android Open Source Project + * 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. @@ -16,223 +16,3001 @@ package android.webkit; -import com.android.layoutlib.bridge.MockView; - +import android.annotation.IntDef; +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.annotation.SystemApi; +import android.annotation.Widget; import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageInfo; +import android.content.res.Configuration; import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Paint; import android.graphics.Picture; +import android.graphics.Rect; +import android.graphics.drawable.Drawable; +import android.net.Uri; +import android.net.http.SslCertificate; +import android.os.Build; import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; import android.os.Message; +import android.os.RemoteException; +import android.os.StrictMode; +import android.print.PrintDocumentAdapter; +import android.security.KeyChain; import android.util.AttributeSet; +import android.util.Log; +import android.util.SparseArray; +import android.view.DragEvent; +import android.view.KeyEvent; +import android.view.MotionEvent; import android.view.View; +import android.view.ViewDebug; +import android.view.ViewGroup; +import android.view.ViewHierarchyEncoder; +import android.view.ViewStructure; +import android.view.ViewTreeObserver; +import android.view.accessibility.AccessibilityEvent; +import android.view.accessibility.AccessibilityNodeInfo; +import android.view.accessibility.AccessibilityNodeProvider; +import android.view.autofill.AutofillValue; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputConnection; +import android.view.textclassifier.TextClassifier; +import android.widget.AbsoluteLayout; + +import java.io.BufferedWriter; +import java.io.File; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.List; +import java.util.Map; /** - * Mock version of the WebView. - * Only non override public methods from the real WebView have been added in there. - * Methods that take an unknown class as parameter or as return object, have been removed for now. - * - * TODO: generate automatically. + *

    A View that displays web pages. This class is the basis upon which you + * can roll your own web browser or simply display some online content within your Activity. + * It uses the WebKit rendering engine to display + * web pages and includes methods to navigate forward and backward + * through a history, zoom in and out, perform text searches and more. + * + *

    Note that, in order for your Activity to access the Internet and load web pages + * in a WebView, you must add the {@code INTERNET} permissions to your + * Android Manifest file: + * + *

    + * {@code }
    + * 
    + * + *

    This must be a child of the {@code } + * element. + * + *

    For more information, read + * Building Web Apps in WebView. + * + *

    Basic usage

    + * + *

    By default, a WebView provides no browser-like widgets, does not + * enable JavaScript and web page errors are ignored. If your goal is only + * to display some HTML as a part of your UI, this is probably fine; + * the user won't need to interact with the web page beyond reading + * it, and the web page won't need to interact with the user. If you + * actually want a full-blown web browser, then you probably want to + * invoke the Browser application with a URL Intent rather than show it + * with a WebView. For example: + *

    + * Uri uri = Uri.parse("https://www.example.com");
    + * Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    + * startActivity(intent);
    + * 
    + *

    See {@link android.content.Intent} for more information. + * + *

    To provide a WebView in your own Activity, include a {@code } in your layout, + * or set the entire Activity window as a WebView during {@link + * android.app.Activity#onCreate(Bundle) onCreate()}: + * + *

    + * WebView webview = new WebView(this);
    + * setContentView(webview);
    + * 
    + * + *

    Then load the desired web page: + * + *

    + * // Simplest usage: note that an exception will NOT be thrown
    + * // if there is an error loading this page (see below).
    + * webview.loadUrl("https://example.com/");
    + *
    + * // OR, you can also load from an HTML string:
    + * String summary = "<html><body>You scored <b>192</b> points.</body></html>";
    + * webview.loadData(summary, "text/html", null);
    + * // ... although note that there are restrictions on what this HTML can do.
    + * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link
    + * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info.
    + * 
    + * + *

    A WebView has several customization points where you can add your + * own behavior. These are: + * + *

      + *
    • Creating and setting a {@link android.webkit.WebChromeClient} subclass. + * This class is called when something that might impact a + * browser UI happens, for instance, progress updates and + * JavaScript alerts are sent here (see Debugging Tasks). + *
    • + *
    • Creating and setting a {@link android.webkit.WebViewClient} subclass. + * It will be called when things happen that impact the + * rendering of the content, eg, errors or form submissions. You + * can also intercept URL loading here (via {@link + * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String) + * shouldOverrideUrlLoading()}).
    • + *
    • Modifying the {@link android.webkit.WebSettings}, such as + * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean) + * setJavaScriptEnabled()}.
    • + *
    • Injecting Java objects into the WebView using the + * {@link android.webkit.WebView#addJavascriptInterface} method. This + * method allows you to inject Java objects into a page's JavaScript + * context, so that they can be accessed by JavaScript in the page.
    • + *
    + * + *

    Here's a more complicated example, showing error handling, + * settings, and progress notification: + * + *

    + * // Let's display the progress in the activity title bar, like the
    + * // browser app does.
    + * getWindow().requestFeature(Window.FEATURE_PROGRESS);
    + *
    + * webview.getSettings().setJavaScriptEnabled(true);
    + *
    + * final Activity activity = this;
    + * webview.setWebChromeClient(new WebChromeClient() {
    + *   public void onProgressChanged(WebView view, int progress) {
    + *     // Activities and WebViews measure progress with different scales.
    + *     // The progress meter will automatically disappear when we reach 100%
    + *     activity.setProgress(progress * 1000);
    + *   }
    + * });
    + * webview.setWebViewClient(new WebViewClient() {
    + *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
    + *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
    + *   }
    + * });
    + *
    + * webview.loadUrl("https://developer.android.com/");
    + * 
    + * + *

    Zoom

    + * + *

    To enable the built-in zoom, set + * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} + * (introduced in API level {@link android.os.Build.VERSION_CODES#CUPCAKE}). + * + *

    NOTE: Using zoom if either the height or width is set to + * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} may lead to undefined behavior + * and should be avoided. + * + *

    Cookie and window management

    + * + *

    For obvious security reasons, your application has its own + * cache, cookie store etc.—it does not share the Browser + * application's data. + * + *

    By default, requests by the HTML to open new windows are + * ignored. This is {@code true} whether they be opened by JavaScript or by + * the target attribute on a link. You can customize your + * {@link WebChromeClient} to provide your own behavior for opening multiple windows, + * and render them in whatever manner you want. + * + *

    The standard behavior for an Activity is to be destroyed and + * recreated when the device orientation or any other configuration changes. This will cause + * the WebView to reload the current page. If you don't want that, you + * can set your Activity to handle the {@code orientation} and {@code keyboardHidden} + * changes, and then just leave the WebView alone. It'll automatically + * re-orient itself as appropriate. Read Handling Runtime Changes for + * more information about how to handle configuration changes during runtime. + * + * + *

    Building web pages to support different screen densities

    + * + *

    The screen density of a device is based on the screen resolution. A screen with low density + * has fewer available pixels per inch, where a screen with high density + * has more — sometimes significantly more — pixels per inch. The density of a + * screen is important because, other things being equal, a UI element (such as a button) whose + * height and width are defined in terms of screen pixels will appear larger on the lower density + * screen and smaller on the higher density screen. + * For simplicity, Android collapses all actual screen densities into three generalized densities: + * high, medium, and low. + *

    By default, WebView scales a web page so that it is drawn at a size that matches the default + * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen + * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels + * are bigger). + * Starting with API level {@link android.os.Build.VERSION_CODES#ECLAIR}, WebView supports DOM, CSS, + * and meta tag features to help you (as a web developer) target screens with different screen + * densities. + *

    Here's a summary of the features you can use to handle different screen densities: + *

      + *
    • The {@code window.devicePixelRatio} DOM property. The value of this property specifies the + * default scaling factor used for the current device. For example, if the value of {@code + * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device + * and default scaling is not applied to the web page; if the value is "1.5", then the device is + * considered a high density device (hdpi) and the page content is scaled 1.5x; if the + * value is "0.75", then the device is considered a low density device (ldpi) and the content is + * scaled 0.75x.
    • + *
    • The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen + * densities for which this style sheet is to be used. The corresponding value should be either + * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium + * density, or high density screens, respectively. For example: + *
      + * <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" />
      + *

      The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5, + * which is the high density pixel ratio. + *

    • + *
    + * + *

    HTML5 Video support

    + * + *

    In order to support inline HTML5 video in your application you need to have hardware + * acceleration turned on. + * + *

    Full screen support

    + * + *

    In order to support full screen — for video or other HTML content — you need to set a + * {@link android.webkit.WebChromeClient} and implement both + * {@link WebChromeClient#onShowCustomView(View, WebChromeClient.CustomViewCallback)} + * and {@link WebChromeClient#onHideCustomView()}. If the implementation of either of these two methods is + * missing then the web contents will not be allowed to enter full screen. Optionally you can implement + * {@link WebChromeClient#getVideoLoadingProgressView()} to customize the View displayed whilst a video + * is loading. + * + *

    HTML5 Geolocation API support

    + * + *

    For applications targeting Android N and later releases + * (API level > {@link android.os.Build.VERSION_CODES#M}) the geolocation api is only supported on + * secure origins such as https. For such applications requests to geolocation api on non-secure + * origins are automatically denied without invoking the corresponding + * {@link WebChromeClient#onGeolocationPermissionsShowPrompt(String, GeolocationPermissions.Callback)} + * method. + * + *

    Layout size

    + *

    + * It is recommended to set the WebView layout height to a fixed value or to + * {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT} instead of using + * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}. + * When using {@link android.view.ViewGroup.LayoutParams#MATCH_PARENT} + * for the height none of the WebView's parents should use a + * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} layout height since that could result in + * incorrect sizing of the views. + * + *

    Setting the WebView's height to {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} + * enables the following behaviors: + *

      + *
    • The HTML body layout height is set to a fixed value. This means that elements with a height + * relative to the HTML body may not be sized correctly.
    • + *
    • For applications targeting {@link android.os.Build.VERSION_CODES#KITKAT} and earlier SDKs the + * HTML viewport meta tag will be ignored in order to preserve backwards compatibility.
    • + *
    + * + *

    + * Using a layout width of {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} is not + * supported. If such a width is used the WebView will attempt to use the width of the parent + * instead. + * + *

    Metrics

    + * + *

    + * WebView may upload anonymous diagnostic data to Google when the user has consented. This data + * helps Google improve WebView. Data is collected on a per-app basis for each app which has + * instantiated a WebView. An individual app can opt out of this feature by putting the following + * tag in its manifest: + *

    + * <meta-data android:name="android.webkit.WebView.MetricsOptOut"
    + *            android:value="true" />
    + * 
    + *

    + * Data will only be uploaded for a given app if the user has consented AND the app has not opted + * out. + * + *

    Safe Browsing

    + * + *

    + * If Safe Browsing is enabled, WebView will block malicious URLs and present a warning UI to the + * user to allow them to navigate back safely or proceed to the malicious page. + *

    + * The recommended way for apps to enable the feature is putting the following tag in the manifest: + *

    + *

    + * <meta-data android:name="android.webkit.WebView.EnableSafeBrowsing"
    + *            android:value="true" />
    + * 
    * */ -public class WebView extends MockView { +// Implementation notes. +// The WebView is a thin API class that delegates its public API to a backend WebViewProvider +// class instance. WebView extends {@link AbsoluteLayout} for backward compatibility reasons. +// Methods are delegated to the provider implementation: all public API methods introduced in this +// file are fully delegated, whereas public and protected methods from the View base classes are +// only delegated where a specific need exists for them to do so. +@Widget +public class WebView extends AbsoluteLayout + implements ViewTreeObserver.OnGlobalFocusChangeListener, + ViewGroup.OnHierarchyChangeListener, ViewDebug.HierarchyHandler { + + private static final String LOGTAG = "WebView"; + + // Throwing an exception for incorrect thread usage if the + // build target is JB MR2 or newer. Defaults to false, and is + // set in the WebView constructor. + private static volatile boolean sEnforceThreadChecking = false; + + /** + * Transportation object for returning WebView across thread boundaries. + */ + public class WebViewTransport { + private WebView mWebview; + + /** + * Sets the WebView to the transportation object. + * + * @param webview the WebView to transport + */ + public synchronized void setWebView(WebView webview) { + mWebview = webview; + } + + /** + * Gets the WebView object. + * + * @return the transported WebView object + */ + public synchronized WebView getWebView() { + return mWebview; + } + } + + /** + * URI scheme for telephone number. + */ + public static final String SCHEME_TEL = "tel:"; + /** + * URI scheme for email address. + */ + public static final String SCHEME_MAILTO = "mailto:"; + /** + * URI scheme for map address. + */ + public static final String SCHEME_GEO = "geo:0,0?q="; + + /** + * Interface to listen for find results. + */ + public interface FindListener { + /** + * Notifies the listener about progress made by a find operation. + * + * @param activeMatchOrdinal the zero-based ordinal of the currently selected match + * @param numberOfMatches how many matches have been found + * @param isDoneCounting whether the find operation has actually completed. The listener + * may be notified multiple times while the + * operation is underway, and the numberOfMatches + * value should not be considered final unless + * isDoneCounting is {@code true}. + */ + public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, + boolean isDoneCounting); + } + + /** + * Callback interface supplied to {@link #postVisualStateCallback} for receiving + * notifications about the visual state. + */ + public static abstract class VisualStateCallback { + /** + * Invoked when the visual state is ready to be drawn in the next {@link #onDraw}. + * + * @param requestId The identifier passed to {@link #postVisualStateCallback} when this + * callback was posted. + */ + public abstract void onComplete(long requestId); + } + + /** + * Interface to listen for new pictures as they change. + * + * @deprecated This interface is now obsolete. + */ + @Deprecated + public interface PictureListener { + /** + * Used to provide notification that the WebView's picture has changed. + * See {@link WebView#capturePicture} for details of the picture. + * + * @param view the WebView that owns the picture + * @param picture the new picture. Applications targeting + * {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2} or above + * will always receive a {@code null} Picture. + * @deprecated Deprecated due to internal changes. + */ + @Deprecated + void onNewPicture(WebView view, @Nullable Picture picture); + } + + public static class HitTestResult { + /** + * Default HitTestResult, where the target is unknown. + */ + public static final int UNKNOWN_TYPE = 0; + /** + * @deprecated This type is no longer used. + */ + @Deprecated + public static final int ANCHOR_TYPE = 1; + /** + * HitTestResult for hitting a phone number. + */ + public static final int PHONE_TYPE = 2; + /** + * HitTestResult for hitting a map address. + */ + public static final int GEO_TYPE = 3; + /** + * HitTestResult for hitting an email address. + */ + public static final int EMAIL_TYPE = 4; + /** + * HitTestResult for hitting an HTML::img tag. + */ + public static final int IMAGE_TYPE = 5; + /** + * @deprecated This type is no longer used. + */ + @Deprecated + public static final int IMAGE_ANCHOR_TYPE = 6; + /** + * HitTestResult for hitting a HTML::a tag with src=http. + */ + public static final int SRC_ANCHOR_TYPE = 7; + /** + * HitTestResult for hitting a HTML::a tag with src=http + HTML::img. + */ + public static final int SRC_IMAGE_ANCHOR_TYPE = 8; + /** + * HitTestResult for hitting an edit text area. + */ + public static final int EDIT_TEXT_TYPE = 9; + + private int mType; + private String mExtra; + + /** + * @hide Only for use by WebViewProvider implementations + */ + @SystemApi + public HitTestResult() { + mType = UNKNOWN_TYPE; + } + + /** + * @hide Only for use by WebViewProvider implementations + */ + @SystemApi + public void setType(int type) { + mType = type; + } + + /** + * @hide Only for use by WebViewProvider implementations + */ + @SystemApi + public void setExtra(String extra) { + mExtra = extra; + } + + /** + * Gets the type of the hit test result. See the XXX_TYPE constants + * defined in this class. + * + * @return the type of the hit test result + */ + public int getType() { + return mType; + } + + /** + * Gets additional type-dependant information about the result. See + * {@link WebView#getHitTestResult()} for details. May either be {@code null} + * or contain extra information about this result. + * + * @return additional type-dependant information about the result + */ + @Nullable + public String getExtra() { + return mExtra; + } + } /** - * Construct a new WebView with a Context object. - * @param context A Context object used to access application assets. + * Constructs a new WebView with a Context object. + * + * @param context a Context object used to access application assets */ public WebView(Context context) { this(context, null); } /** - * Construct a new WebView with layout parameters. - * @param context A Context object used to access application assets. - * @param attrs An AttributeSet passed to our parent. + * Constructs a new WebView with layout parameters. + * + * @param context a Context object used to access application assets + * @param attrs an AttributeSet passed to our parent */ public WebView(Context context, AttributeSet attrs) { this(context, attrs, com.android.internal.R.attr.webViewStyle); } /** - * Construct a new WebView with layout parameters and a default style. - * @param context A Context object used to access application assets. - * @param attrs An AttributeSet passed to our parent. - * @param defStyle The default style resource ID. + * Constructs a new WebView with layout parameters and a default style. + * + * @param context a Context object used to access application assets + * @param attrs an AttributeSet passed to our parent + * @param defStyleAttr an attribute in the current theme that contains a + * reference to a style resource that supplies default values for + * the view. Can be 0 to not look for defaults. + */ + public WebView(Context context, AttributeSet attrs, int defStyleAttr) { + this(context, attrs, defStyleAttr, 0); + } + + /** + * Constructs a new WebView with layout parameters and a default style. + * + * @param context a Context object used to access application assets + * @param attrs an AttributeSet passed to our parent + * @param defStyleAttr an attribute in the current theme that contains a + * reference to a style resource that supplies default values for + * the view. Can be 0 to not look for defaults. + * @param defStyleRes a resource identifier of a style resource that + * supplies default values for the view, used only if + * defStyleAttr is 0 or can not be found in the theme. Can be 0 + * to not look for defaults. + */ + public WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + this(context, attrs, defStyleAttr, defStyleRes, null, false); + } + + /** + * Constructs a new WebView with layout parameters and a default style. + * + * @param context a Context object used to access application assets + * @param attrs an AttributeSet passed to our parent + * @param defStyleAttr an attribute in the current theme that contains a + * reference to a style resource that supplies default values for + * the view. Can be 0 to not look for defaults. + * @param privateBrowsing whether this WebView will be initialized in + * private mode + * + * @deprecated Private browsing is no longer supported directly via + * WebView and will be removed in a future release. Prefer using + * {@link WebSettings}, {@link WebViewDatabase}, {@link CookieManager} + * and {@link WebStorage} for fine-grained control of privacy data. + */ + @Deprecated + public WebView(Context context, AttributeSet attrs, int defStyleAttr, + boolean privateBrowsing) { + this(context, attrs, defStyleAttr, 0, null, privateBrowsing); + } + + /** + * Constructs a new WebView with layout parameters, a default style and a set + * of custom JavaScript interfaces to be added to this WebView at initialization + * time. This guarantees that these interfaces will be available when the JS + * context is initialized. + * + * @param context a Context object used to access application assets + * @param attrs an AttributeSet passed to our parent + * @param defStyleAttr an attribute in the current theme that contains a + * reference to a style resource that supplies default values for + * the view. Can be 0 to not look for defaults. + * @param javaScriptInterfaces a Map of interface names, as keys, and + * object implementing those interfaces, as + * values + * @param privateBrowsing whether this WebView will be initialized in + * private mode + * @hide This is used internally by dumprendertree, as it requires the JavaScript interfaces to + * be added synchronously, before a subsequent loadUrl call takes effect. + */ + protected WebView(Context context, AttributeSet attrs, int defStyleAttr, + Map javaScriptInterfaces, boolean privateBrowsing) { + this(context, attrs, defStyleAttr, 0, javaScriptInterfaces, privateBrowsing); + } + + /** + * @hide */ - public WebView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); + @SuppressWarnings("deprecation") // for super() call into deprecated base class constructor. + protected WebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes, + Map javaScriptInterfaces, boolean privateBrowsing) { + super(context, attrs, defStyleAttr, defStyleRes); + + // WebView is important by default, unless app developer overrode attribute. + if (getImportantForAutofill() == IMPORTANT_FOR_AUTOFILL_AUTO) { + setImportantForAutofill(IMPORTANT_FOR_AUTOFILL_YES); + } + + if (context == null) { + throw new IllegalArgumentException("Invalid context argument"); + } + sEnforceThreadChecking = context.getApplicationInfo().targetSdkVersion >= + Build.VERSION_CODES.JELLY_BEAN_MR2; + checkThread(); + + ensureProviderCreated(); + mProvider.init(javaScriptInterfaces, privateBrowsing); + // Post condition of creating a webview is the CookieSyncManager.getInstance() is allowed. + CookieSyncManager.setGetInstanceIsAllowed(); } - - // START FAKE PUBLIC METHODS - + + /** + * Specifies whether the horizontal scrollbar has overlay style. + * + * @deprecated This method has no effect. + * @param overlay {@code true} if horizontal scrollbar should have overlay style + */ + @Deprecated public void setHorizontalScrollbarOverlay(boolean overlay) { } + /** + * Specifies whether the vertical scrollbar has overlay style. + * + * @deprecated This method has no effect. + * @param overlay {@code true} if vertical scrollbar should have overlay style + */ + @Deprecated public void setVerticalScrollbarOverlay(boolean overlay) { } + /** + * Gets whether horizontal scrollbar has overlay style. + * + * @deprecated This method is now obsolete. + * @return {@code true} + */ + @Deprecated public boolean overlayHorizontalScrollbar() { - return false; + // The old implementation defaulted to true, so return true for consistency + return true; } + /** + * Gets whether vertical scrollbar has overlay style. + * + * @deprecated This method is now obsolete. + * @return {@code false} + */ + @Deprecated public boolean overlayVerticalScrollbar() { + // The old implementation defaulted to false, so return false for consistency return false; } + /** + * Gets the visible height (in pixels) of the embedded title bar (if any). + * + * @deprecated This method is now obsolete. + * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} + */ + @Deprecated + public int getVisibleTitleHeight() { + checkThread(); + return mProvider.getVisibleTitleHeight(); + } + + /** + * Gets the SSL certificate for the main top-level page or {@code null} if there is + * no certificate (the site is not secure). + * + * @return the SSL certificate for the main top-level page + */ + @Nullable + public SslCertificate getCertificate() { + checkThread(); + return mProvider.getCertificate(); + } + + /** + * Sets the SSL certificate for the main top-level page. + * + * @deprecated Calling this function has no useful effect, and will be + * ignored in future releases. + */ + @Deprecated + public void setCertificate(SslCertificate certificate) { + checkThread(); + mProvider.setCertificate(certificate); + } + + //------------------------------------------------------------------------- + // Methods called by activity + //------------------------------------------------------------------------- + + /** + * Sets a username and password pair for the specified host. This data is + * used by the WebView to autocomplete username and password fields in web + * forms. Note that this is unrelated to the credentials used for HTTP + * authentication. + * + * @param host the host that required the credentials + * @param username the username for the given host + * @param password the password for the given host + * @see WebViewDatabase#clearUsernamePassword + * @see WebViewDatabase#hasUsernamePassword + * @deprecated Saving passwords in WebView will not be supported in future versions. + */ + @Deprecated public void savePassword(String host, String username, String password) { + checkThread(); + mProvider.savePassword(host, username, password); } + /** + * Stores HTTP authentication credentials for a given host and realm to the {@link WebViewDatabase} + * instance. + * + * @param host the host to which the credentials apply + * @param realm the realm to which the credentials apply + * @param username the username + * @param password the password + * @deprecated Use {@link WebViewDatabase#setHttpAuthUsernamePassword} instead + */ + @Deprecated public void setHttpAuthUsernamePassword(String host, String realm, String username, String password) { + checkThread(); + mProvider.setHttpAuthUsernamePassword(host, realm, username, password); } + /** + * Retrieves HTTP authentication credentials for a given host and realm from the {@link + * WebViewDatabase} instance. + * @param host the host to which the credentials apply + * @param realm the realm to which the credentials apply + * @return the credentials as a String array, if found. The first element + * is the username and the second element is the password. {@code null} if + * no credentials are found. + * @deprecated Use {@link WebViewDatabase#getHttpAuthUsernamePassword} instead + */ + @Deprecated + @Nullable public String[] getHttpAuthUsernamePassword(String host, String realm) { - return null; + checkThread(); + return mProvider.getHttpAuthUsernamePassword(host, realm); } + /** + * Destroys the internal state of this WebView. This method should be called + * after this WebView has been removed from the view system. No other + * methods may be called on this WebView after destroy. + */ public void destroy() { + checkThread(); + mProvider.destroy(); } + /** + * Enables platform notifications of data state and proxy changes. + * Notifications are enabled by default. + * + * @deprecated This method is now obsolete. + * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} + */ + @Deprecated public static void enablePlatformNotifications() { + // noop } + /** + * Disables platform notifications of data state and proxy changes. + * Notifications are enabled by default. + * + * @deprecated This method is now obsolete. + * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} + */ + @Deprecated public static void disablePlatformNotifications() { + // noop } - public void loadUrl(String url) { + /** + * Used only by internal tests to free up memory. + * + * @hide + */ + public static void freeMemoryForTests() { + getFactory().getStatics().freeMemoryForTests(); } - public void loadData(String data, String mimeType, String encoding) { + /** + * Informs WebView of the network state. This is used to set + * the JavaScript property window.navigator.isOnline and + * generates the online/offline event as specified in HTML5, sec. 5.7.7 + * + * @param networkUp a boolean indicating if network is available + */ + public void setNetworkAvailable(boolean networkUp) { + checkThread(); + mProvider.setNetworkAvailable(networkUp); } - public void loadDataWithBaseURL(String baseUrl, String data, - String mimeType, String encoding, String failUrl) { + /** + * Saves the state of this WebView used in + * {@link android.app.Activity#onSaveInstanceState}. Please note that this + * method no longer stores the display data for this WebView. The previous + * behavior could potentially leak files if {@link #restoreState} was never + * called. + * + * @param outState the Bundle to store this WebView's state + * @return the same copy of the back/forward list used to save the state, {@code null} if the + * method fails. + */ + @Nullable + public WebBackForwardList saveState(Bundle outState) { + checkThread(); + return mProvider.saveState(outState); } - public void stopLoading() { + /** + * Saves the current display data to the Bundle given. Used in conjunction + * with {@link #saveState}. + * @param b a Bundle to store the display data + * @param dest the file to store the serialized picture data. Will be + * overwritten with this WebView's picture data. + * @return {@code true} if the picture was successfully saved + * @deprecated This method is now obsolete. + * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} + */ + @Deprecated + public boolean savePicture(Bundle b, final File dest) { + checkThread(); + return mProvider.savePicture(b, dest); } - public void reload() { + /** + * Restores the display data that was saved in {@link #savePicture}. Used in + * conjunction with {@link #restoreState}. Note that this will not work if + * this WebView is hardware accelerated. + * + * @param b a Bundle containing the saved display data + * @param src the file where the picture data was stored + * @return {@code true} if the picture was successfully restored + * @deprecated This method is now obsolete. + * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} + */ + @Deprecated + public boolean restorePicture(Bundle b, File src) { + checkThread(); + return mProvider.restorePicture(b, src); } - public boolean canGoBack() { - return false; + /** + * Restores the state of this WebView from the given Bundle. This method is + * intended for use in {@link android.app.Activity#onRestoreInstanceState} + * and should be called to restore the state of this WebView. If + * it is called after this WebView has had a chance to build state (load + * pages, create a back/forward list, etc.) there may be undesirable + * side-effects. Please note that this method no longer restores the + * display data for this WebView. + * + * @param inState the incoming Bundle of state + * @return the restored back/forward list or {@code null} if restoreState failed + */ + @Nullable + public WebBackForwardList restoreState(Bundle inState) { + checkThread(); + return mProvider.restoreState(inState); } - public void goBack() { + /** + * Loads the given URL with the specified additional HTTP headers. + *

    + * Also see compatibility note on {@link #evaluateJavascript}. + * + * @param url the URL of the resource to load + * @param additionalHttpHeaders the additional headers to be used in the + * HTTP request for this URL, specified as a map from name to + * value. Note that if this map contains any of the headers + * that are set by default by this WebView, such as those + * controlling caching, accept types or the User-Agent, their + * values may be overridden by this WebView's defaults. + */ + public void loadUrl(String url, Map additionalHttpHeaders) { + checkThread(); + mProvider.loadUrl(url, additionalHttpHeaders); } - public boolean canGoForward() { - return false; + /** + * Loads the given URL. + *

    + * Also see compatibility note on {@link #evaluateJavascript}. + * + * @param url the URL of the resource to load + */ + public void loadUrl(String url) { + checkThread(); + mProvider.loadUrl(url); } - public void goForward() { + /** + * Loads the URL with postData using "POST" method into this WebView. If url + * is not a network URL, it will be loaded with {@link #loadUrl(String)} + * instead, ignoring the postData param. + * + * @param url the URL of the resource to load + * @param postData the data will be passed to "POST" request, which must be + * be "application/x-www-form-urlencoded" encoded. + */ + public void postUrl(String url, byte[] postData) { + checkThread(); + if (URLUtil.isNetworkUrl(url)) { + mProvider.postUrl(url, postData); + } else { + mProvider.loadUrl(url); + } } - public boolean canGoBackOrForward(int steps) { - return false; + /** + * Loads the given data into this WebView using a 'data' scheme URL. + *

    + * Note that JavaScript's same origin policy means that script running in a + * page loaded using this method will be unable to access content loaded + * using any scheme other than 'data', including 'http(s)'. To avoid this + * restriction, use {@link + * #loadDataWithBaseURL(String,String,String,String,String) + * loadDataWithBaseURL()} with an appropriate base URL. + *

    + * The encoding parameter specifies whether the data is base64 or URL + * encoded. If the data is base64 encoded, the value of the encoding + * parameter must be 'base64'. For all other values of the parameter, + * including {@code null}, it is assumed that the data uses ASCII encoding for + * octets inside the range of safe URL characters and use the standard %xx + * hex encoding of URLs for octets outside that range. For example, '#', + * '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively. + *

    + * The 'data' scheme URL formed by this method uses the default US-ASCII + * charset. If you need need to set a different charset, you should form a + * 'data' scheme URL which explicitly specifies a charset parameter in the + * mediatype portion of the URL and call {@link #loadUrl(String)} instead. + * Note that the charset obtained from the mediatype portion of a data URL + * always overrides that specified in the HTML or XML document itself. + * + * @param data a String of data in the given encoding + * @param mimeType the MIMEType of the data, e.g. 'text/html'. If {@code null}, + * defaults to 'text/html'. + * @param encoding the encoding of the data + */ + public void loadData(String data, @Nullable String mimeType, @Nullable String encoding) { + checkThread(); + mProvider.loadData(data, mimeType, encoding); } - public void goBackOrForward(int steps) { + /** + * Loads the given data into this WebView, using baseUrl as the base URL for + * the content. The base URL is used both to resolve relative URLs and when + * applying JavaScript's same origin policy. The historyUrl is used for the + * history entry. + *

    + * Note that content specified in this way can access local device files + * (via 'file' scheme URLs) only if baseUrl specifies a scheme other than + * 'http', 'https', 'ftp', 'ftps', 'about' or 'javascript'. + *

    + * If the base URL uses the data scheme, this method is equivalent to + * calling {@link #loadData(String,String,String) loadData()} and the + * historyUrl is ignored, and the data will be treated as part of a data: URL. + * If the base URL uses any other scheme, then the data will be loaded into + * the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded + * entities in the string will not be decoded. + *

    + * Note that the baseUrl is sent in the 'Referer' HTTP header when + * requesting subresources (images, etc.) of the page loaded using this method. + * + * @param baseUrl the URL to use as the page's base URL. If {@code null} defaults to + * 'about:blank'. + * @param data a String of data in the given encoding + * @param mimeType the MIMEType of the data, e.g. 'text/html'. If {@code null}, + * defaults to 'text/html'. + * @param encoding the encoding of the data + * @param historyUrl the URL to use as the history entry. If {@code null} defaults + * to 'about:blank'. If non-null, this must be a valid URL. + */ + public void loadDataWithBaseURL(@Nullable String baseUrl, String data, + @Nullable String mimeType, @Nullable String encoding, @Nullable String historyUrl) { + checkThread(); + mProvider.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); } - public boolean pageUp(boolean top) { - return false; - } - - public boolean pageDown(boolean bottom) { - return false; + /** + * Asynchronously evaluates JavaScript in the context of the currently displayed page. + * If non-null, |resultCallback| will be invoked with any result returned from that + * execution. This method must be called on the UI thread and the callback will + * be made on the UI thread. + *

    + * Compatibility note. Applications targeting {@link android.os.Build.VERSION_CODES#N} or + * later, JavaScript state from an empty WebView is no longer persisted across navigations like + * {@link #loadUrl(String)}. For example, global variables and functions defined before calling + * {@link #loadUrl(String)} will not exist in the loaded page. Applications should use + * {@link #addJavascriptInterface} instead to persist JavaScript objects across navigations. + * + * @param script the JavaScript to execute. + * @param resultCallback A callback to be invoked when the script execution + * completes with the result of the execution (if any). + * May be {@code null} if no notification of the result is required. + */ + public void evaluateJavascript(String script, @Nullable ValueCallback resultCallback) { + checkThread(); + mProvider.evaluateJavaScript(script, resultCallback); } - public void clearView() { - } - - public Picture capturePicture() { - return null; + /** + * Saves the current view as a web archive. + * + * @param filename the filename where the archive should be placed + */ + public void saveWebArchive(String filename) { + checkThread(); + mProvider.saveWebArchive(filename); } - public float getScale() { - return 0; + /** + * Saves the current view as a web archive. + * + * @param basename the filename where the archive should be placed + * @param autoname if {@code false}, takes basename to be a file. If {@code true}, basename + * is assumed to be a directory in which a filename will be + * chosen according to the URL of the current page. + * @param callback called after the web archive has been saved. The + * parameter for onReceiveValue will either be the filename + * under which the file was saved, or {@code null} if saving the + * file failed. + */ + public void saveWebArchive(String basename, boolean autoname, @Nullable ValueCallback + callback) { + checkThread(); + mProvider.saveWebArchive(basename, autoname, callback); } - public void setInitialScale(int scaleInPercent) { + /** + * Stops the current load. + */ + public void stopLoading() { + checkThread(); + mProvider.stopLoading(); } - public void invokeZoomPicker() { + /** + * Reloads the current URL. + */ + public void reload() { + checkThread(); + mProvider.reload(); } - public void requestFocusNodeHref(Message hrefMsg) { + /** + * Gets whether this WebView has a back history item. + * + * @return {@code true} iff this WebView has a back history item + */ + public boolean canGoBack() { + checkThread(); + return mProvider.canGoBack(); } - public void requestImageRef(Message msg) { + /** + * Goes back in the history of this WebView. + */ + public void goBack() { + checkThread(); + mProvider.goBack(); } - public String getUrl() { - return null; + /** + * Gets whether this WebView has a forward history item. + * + * @return {@code true} iff this WebView has a forward history item + */ + public boolean canGoForward() { + checkThread(); + return mProvider.canGoForward(); } - public String getTitle() { - return null; + /** + * Goes forward in the history of this WebView. + */ + public void goForward() { + checkThread(); + mProvider.goForward(); } - public Bitmap getFavicon() { - return null; + /** + * Gets whether the page can go back or forward the given + * number of steps. + * + * @param steps the negative or positive number of steps to move the + * history + */ + public boolean canGoBackOrForward(int steps) { + checkThread(); + return mProvider.canGoBackOrForward(steps); } - public int getProgress() { - return 0; - } - - public int getContentHeight() { - return 0; + /** + * Goes to the history item that is the number of steps away from + * the current item. Steps is negative if backward and positive + * if forward. + * + * @param steps the number of steps to take back or forward in the back + * forward list + */ + public void goBackOrForward(int steps) { + checkThread(); + mProvider.goBackOrForward(steps); } - public void pauseTimers() { + /** + * Gets whether private browsing is enabled in this WebView. + */ + public boolean isPrivateBrowsingEnabled() { + checkThread(); + return mProvider.isPrivateBrowsingEnabled(); } - public void resumeTimers() { + /** + * Scrolls the contents of this WebView up by half the view size. + * + * @param top {@code true} to jump to the top of the page + * @return {@code true} if the page was scrolled + */ + public boolean pageUp(boolean top) { + checkThread(); + return mProvider.pageUp(top); } - public void clearCache() { + /** + * Scrolls the contents of this WebView down by half the page size. + * + * @param bottom {@code true} to jump to bottom of page + * @return {@code true} if the page was scrolled + */ + public boolean pageDown(boolean bottom) { + checkThread(); + return mProvider.pageDown(bottom); } - public void clearFormData() { + /** + * Posts a {@link VisualStateCallback}, which will be called when + * the current state of the WebView is ready to be drawn. + * + *

    Because updates to the DOM are processed asynchronously, updates to the DOM may not + * immediately be reflected visually by subsequent {@link WebView#onDraw} invocations. The + * {@link VisualStateCallback} provides a mechanism to notify the caller when the contents of + * the DOM at the current time are ready to be drawn the next time the {@link WebView} + * draws. + * + *

    The next draw after the callback completes is guaranteed to reflect all the updates to the + * DOM up to the point at which the {@link VisualStateCallback} was posted, but it may also + * contain updates applied after the callback was posted. + * + *

    The state of the DOM covered by this API includes the following: + *

      + *
    • primitive HTML elements (div, img, span, etc..)
    • + *
    • images
    • + *
    • CSS animations
    • + *
    • WebGL
    • + *
    • canvas
    • + *
    + * It does not include the state of: + *
      + *
    • the video tag
    • + *
    + * + *

    To guarantee that the {@link WebView} will successfully render the first frame + * after the {@link VisualStateCallback#onComplete} method has been called a set of conditions + * must be met: + *

      + *
    • If the {@link WebView}'s visibility is set to {@link View#VISIBLE VISIBLE} then + * the {@link WebView} must be attached to the view hierarchy.
    • + *
    • If the {@link WebView}'s visibility is set to {@link View#INVISIBLE INVISIBLE} + * then the {@link WebView} must be attached to the view hierarchy and must be made + * {@link View#VISIBLE VISIBLE} from the {@link VisualStateCallback#onComplete} method.
    • + *
    • If the {@link WebView}'s visibility is set to {@link View#GONE GONE} then the + * {@link WebView} must be attached to the view hierarchy and its + * {@link AbsoluteLayout.LayoutParams LayoutParams}'s width and height need to be set to fixed + * values and must be made {@link View#VISIBLE VISIBLE} from the + * {@link VisualStateCallback#onComplete} method.
    • + *
    + * + *

    When using this API it is also recommended to enable pre-rasterization if the {@link + * WebView} is off screen to avoid flickering. See {@link WebSettings#setOffscreenPreRaster} for + * more details and do consider its caveats. + * + * @param requestId An id that will be returned in the callback to allow callers to match + * requests with callbacks. + * @param callback The callback to be invoked. + */ + public void postVisualStateCallback(long requestId, VisualStateCallback callback) { + checkThread(); + mProvider.insertVisualStateCallback(requestId, callback); } - public void clearHistory() { + /** + * Clears this WebView so that onDraw() will draw nothing but white background, + * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY. + * @deprecated Use WebView.loadUrl("about:blank") to reliably reset the view state + * and release page resources (including any running JavaScript). + */ + @Deprecated + public void clearView() { + checkThread(); + mProvider.clearView(); } - public void clearSslPreferences() { + /** + * Gets a new picture that captures the current contents of this WebView. + * The picture is of the entire document being displayed, and is not + * limited to the area currently displayed by this WebView. Also, the + * picture is a static copy and is unaffected by later changes to the + * content being displayed. + *

    + * Note that due to internal changes, for API levels between + * {@link android.os.Build.VERSION_CODES#HONEYCOMB} and + * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH} inclusive, the + * picture does not include fixed position elements or scrollable divs. + *

    + * Note that from {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} the returned picture + * should only be drawn into bitmap-backed Canvas - using any other type of Canvas will involve + * additional conversion at a cost in memory and performance. Also the + * {@link android.graphics.Picture#createFromStream} and + * {@link android.graphics.Picture#writeToStream} methods are not supported on the + * returned object. + * + * @deprecated Use {@link #onDraw} to obtain a bitmap snapshot of the WebView, or + * {@link #saveWebArchive} to save the content to a file. + * + * @return a picture that captures the current contents of this WebView + */ + @Deprecated + public Picture capturePicture() { + checkThread(); + return mProvider.capturePicture(); } - public static String findAddress(String addr) { - return null; + /** + * @deprecated Use {@link #createPrintDocumentAdapter(String)} which requires user + * to provide a print document name. + */ + @Deprecated + public PrintDocumentAdapter createPrintDocumentAdapter() { + checkThread(); + return mProvider.createPrintDocumentAdapter("default"); } - public void documentHasImages(Message response) { + /** + * Creates a PrintDocumentAdapter that provides the content of this WebView for printing. + * + * The adapter works by converting the WebView contents to a PDF stream. The WebView cannot + * be drawn during the conversion process - any such draws are undefined. It is recommended + * to use a dedicated off screen WebView for the printing. If necessary, an application may + * temporarily hide a visible WebView by using a custom PrintDocumentAdapter instance + * wrapped around the object returned and observing the onStart and onFinish methods. See + * {@link android.print.PrintDocumentAdapter} for more information. + * + * @param documentName The user-facing name of the printed document. See + * {@link android.print.PrintDocumentInfo} + */ + public PrintDocumentAdapter createPrintDocumentAdapter(String documentName) { + checkThread(); + return mProvider.createPrintDocumentAdapter(documentName); } - public void setWebViewClient(WebViewClient client) { + /** + * Gets the current scale of this WebView. + * + * @return the current scale + * + * @deprecated This method is prone to inaccuracy due to race conditions + * between the web rendering and UI threads; prefer + * {@link WebViewClient#onScaleChanged}. + */ + @Deprecated + @ViewDebug.ExportedProperty(category = "webview") + public float getScale() { + checkThread(); + return mProvider.getScale(); } - public void setDownloadListener(DownloadListener listener) { + /** + * Sets the initial scale for this WebView. 0 means default. + * The behavior for the default scale depends on the state of + * {@link WebSettings#getUseWideViewPort()} and + * {@link WebSettings#getLoadWithOverviewMode()}. + * If the content fits into the WebView control by width, then + * the zoom is set to 100%. For wide content, the behavior + * depends on the state of {@link WebSettings#getLoadWithOverviewMode()}. + * If its value is {@code true}, the content will be zoomed out to be fit + * by width into the WebView control, otherwise not. + * + * If initial scale is greater than 0, WebView starts with this value + * as initial scale. + * Please note that unlike the scale properties in the viewport meta tag, + * this method doesn't take the screen density into account. + * + * @param scaleInPercent the initial scale in percent + */ + public void setInitialScale(int scaleInPercent) { + checkThread(); + mProvider.setInitialScale(scaleInPercent); } - public void setWebChromeClient(WebChromeClient client) { + /** + * Invokes the graphical zoom picker widget for this WebView. This will + * result in the zoom widget appearing on the screen to control the zoom + * level of this WebView. + */ + public void invokeZoomPicker() { + checkThread(); + mProvider.invokeZoomPicker(); } - public void addJavascriptInterface(Object obj, String interfaceName) { + /** + * Gets a HitTestResult based on the current cursor node. If a HTML::a + * tag is found and the anchor has a non-JavaScript URL, the HitTestResult + * type is set to SRC_ANCHOR_TYPE and the URL is set in the "extra" field. + * If the anchor does not have a URL or if it is a JavaScript URL, the type + * will be UNKNOWN_TYPE and the URL has to be retrieved through + * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is + * found, the HitTestResult type is set to IMAGE_TYPE and the URL is set in + * the "extra" field. A type of + * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a URL that has an image as + * a child node. If a phone number is found, the HitTestResult type is set + * to PHONE_TYPE and the phone number is set in the "extra" field of + * HitTestResult. If a map address is found, the HitTestResult type is set + * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. + * If an email address is found, the HitTestResult type is set to EMAIL_TYPE + * and the email is set in the "extra" field of HitTestResult. Otherwise, + * HitTestResult type is set to UNKNOWN_TYPE. + */ + public HitTestResult getHitTestResult() { + checkThread(); + return mProvider.getHitTestResult(); } + /** + * Requests the anchor or image element URL at the last tapped point. + * If hrefMsg is {@code null}, this method returns immediately and does not + * dispatch hrefMsg to its target. If the tapped point hits an image, + * an anchor, or an image in an anchor, the message associates + * strings in named keys in its data. The value paired with the key + * may be an empty string. + * + * @param hrefMsg the message to be dispatched with the result of the + * request. The message data contains three keys. "url" + * returns the anchor's href attribute. "title" returns the + * anchor's text. "src" returns the image's src attribute. + */ + public void requestFocusNodeHref(@Nullable Message hrefMsg) { + checkThread(); + mProvider.requestFocusNodeHref(hrefMsg); + } + + /** + * Requests the URL of the image last touched by the user. msg will be sent + * to its target with a String representing the URL as its object. + * + * @param msg the message to be dispatched with the result of the request + * as the data member with "url" as key. The result can be {@code null}. + */ + public void requestImageRef(Message msg) { + checkThread(); + mProvider.requestImageRef(msg); + } + + /** + * Gets the URL for the current page. This is not always the same as the URL + * passed to WebViewClient.onPageStarted because although the load for + * that URL has begun, the current page may not have changed. + * + * @return the URL for the current page + */ + @ViewDebug.ExportedProperty(category = "webview") + public String getUrl() { + checkThread(); + return mProvider.getUrl(); + } + + /** + * Gets the original URL for the current page. This is not always the same + * as the URL passed to WebViewClient.onPageStarted because although the + * load for that URL has begun, the current page may not have changed. + * Also, there may have been redirects resulting in a different URL to that + * originally requested. + * + * @return the URL that was originally requested for the current page + */ + @ViewDebug.ExportedProperty(category = "webview") + public String getOriginalUrl() { + checkThread(); + return mProvider.getOriginalUrl(); + } + + /** + * Gets the title for the current page. This is the title of the current page + * until WebViewClient.onReceivedTitle is called. + * + * @return the title for the current page + */ + @ViewDebug.ExportedProperty(category = "webview") + public String getTitle() { + checkThread(); + return mProvider.getTitle(); + } + + /** + * Gets the favicon for the current page. This is the favicon of the current + * page until WebViewClient.onReceivedIcon is called. + * + * @return the favicon for the current page + */ + public Bitmap getFavicon() { + checkThread(); + return mProvider.getFavicon(); + } + + /** + * Gets the touch icon URL for the apple-touch-icon element, or + * a URL on this site's server pointing to the standard location of a + * touch icon. + * + * @hide + */ + public String getTouchIconUrl() { + return mProvider.getTouchIconUrl(); + } + + /** + * Gets the progress for the current page. + * + * @return the progress for the current page between 0 and 100 + */ + public int getProgress() { + checkThread(); + return mProvider.getProgress(); + } + + /** + * Gets the height of the HTML content. + * + * @return the height of the HTML content + */ + @ViewDebug.ExportedProperty(category = "webview") + public int getContentHeight() { + checkThread(); + return mProvider.getContentHeight(); + } + + /** + * Gets the width of the HTML content. + * + * @return the width of the HTML content + * @hide + */ + @ViewDebug.ExportedProperty(category = "webview") + public int getContentWidth() { + return mProvider.getContentWidth(); + } + + /** + * Pauses all layout, parsing, and JavaScript timers for all WebViews. This + * is a global requests, not restricted to just this WebView. This can be + * useful if the application has been paused. + */ + public void pauseTimers() { + checkThread(); + mProvider.pauseTimers(); + } + + /** + * Resumes all layout, parsing, and JavaScript timers for all WebViews. + * This will resume dispatching all timers. + */ + public void resumeTimers() { + checkThread(); + mProvider.resumeTimers(); + } + + /** + * Does a best-effort attempt to pause any processing that can be paused + * safely, such as animations and geolocation. Note that this call + * does not pause JavaScript. To pause JavaScript globally, use + * {@link #pauseTimers}. + * + * To resume WebView, call {@link #onResume}. + */ + public void onPause() { + checkThread(); + mProvider.onPause(); + } + + /** + * Resumes a WebView after a previous call to {@link #onPause}. + */ + public void onResume() { + checkThread(); + mProvider.onResume(); + } + + /** + * Gets whether this WebView is paused, meaning onPause() was called. + * Calling onResume() sets the paused state back to {@code false}. + * + * @hide + */ + public boolean isPaused() { + return mProvider.isPaused(); + } + + /** + * Informs this WebView that memory is low so that it can free any available + * memory. + * @deprecated Memory caches are automatically dropped when no longer needed, and in response + * to system memory pressure. + */ + @Deprecated + public void freeMemory() { + checkThread(); + mProvider.freeMemory(); + } + + /** + * Clears the resource cache. Note that the cache is per-application, so + * this will clear the cache for all WebViews used. + * + * @param includeDiskFiles if {@code false}, only the RAM cache is cleared + */ + public void clearCache(boolean includeDiskFiles) { + checkThread(); + mProvider.clearCache(includeDiskFiles); + } + + /** + * Removes the autocomplete popup from the currently focused form field, if + * present. Note this only affects the display of the autocomplete popup, + * it does not remove any saved form data from this WebView's store. To do + * that, use {@link WebViewDatabase#clearFormData}. + */ + public void clearFormData() { + checkThread(); + mProvider.clearFormData(); + } + + /** + * Tells this WebView to clear its internal back/forward list. + */ + public void clearHistory() { + checkThread(); + mProvider.clearHistory(); + } + + /** + * Clears the SSL preferences table stored in response to proceeding with + * SSL certificate errors. + */ + public void clearSslPreferences() { + checkThread(); + mProvider.clearSslPreferences(); + } + + /** + * Clears the client certificate preferences stored in response + * to proceeding/cancelling client cert requests. Note that WebView + * automatically clears these preferences when it receives a + * {@link KeyChain#ACTION_STORAGE_CHANGED} intent. The preferences are + * shared by all the WebViews that are created by the embedder application. + * + * @param onCleared A runnable to be invoked when client certs are cleared. + * The runnable will be called in UI thread. + */ + public static void clearClientCertPreferences(@Nullable Runnable onCleared) { + getFactory().getStatics().clearClientCertPreferences(onCleared); + } + + /** + * Starts Safe Browsing initialization. + *

    + * URL loads are not guaranteed to be protected by Safe Browsing until after {@code callback} is + * invoked with {@code true}. Safe Browsing is not fully supported on all devices. For those + * devices {@code callback} will receive {@code false}. + *

    + * This does not enable the Safe Browsing feature itself, and should only be called if Safe + * Browsing is enabled by the manifest tag or {@link WebSettings#setSafeBrowsingEnabled}. This + * prepares resources used for Safe Browsing. + *

    + * This should be called with the Application Context (and will always use the Application + * context to do its work regardless). + * + * @param context Application Context. + * @param callback will be called on the UI thread with {@code true} if initialization is + * successful, {@code false} otherwise. + */ + public static void startSafeBrowsing(Context context, + @Nullable ValueCallback callback) { + getFactory().getStatics().initSafeBrowsing(context, callback); + } + + /** + * Sets the list of domains that are exempt from SafeBrowsing checks. The list is + * global for all the WebViews. + *

    + * Each rule should take one of these: + * + * + * + * + * + * + *
    Rule Example Matches Subdomain
    HOSTNAME example.com Yes
    .HOSTNAME .example.com No
    IPV4_LITERAL 192.168.1.1 No
    IPV6_LITERAL_WITH_BRACKETS [10:20:30:40:50:60:70:80]No
    + *

    + * All other rules, including wildcards, are invalid. + * + * @param urls the list of URLs + * @param callback will be called with {@code true} if URLs are successfully added to the + * whitelist. It will be called with {@code false} if any URLs are malformed. The callback will + * be run on the UI thread + */ + public static void setSafeBrowsingWhitelist(@NonNull List urls, + @Nullable ValueCallback callback) { + getFactory().getStatics().setSafeBrowsingWhitelist(urls, callback); + } + + /** + * Returns a URL pointing to the privacy policy for Safe Browsing reporting. + * + * @return the url pointing to a privacy policy document which can be displayed to users. + */ + @NonNull + public static Uri getSafeBrowsingPrivacyPolicyUrl() { + return getFactory().getStatics().getSafeBrowsingPrivacyPolicyUrl(); + } + + /** + * Gets the WebBackForwardList for this WebView. This contains the + * back/forward list for use in querying each item in the history stack. + * This is a copy of the private WebBackForwardList so it contains only a + * snapshot of the current state. Multiple calls to this method may return + * different objects. The object returned from this method will not be + * updated to reflect any new state. + */ + public WebBackForwardList copyBackForwardList() { + checkThread(); + return mProvider.copyBackForwardList(); + + } + + /** + * Registers the listener to be notified as find-on-page operations + * progress. This will replace the current listener. + * + * @param listener an implementation of {@link FindListener} + */ + public void setFindListener(FindListener listener) { + checkThread(); + setupFindListenerIfNeeded(); + mFindListener.mUserFindListener = listener; + } + + /** + * Highlights and scrolls to the next match found by + * {@link #findAllAsync}, wrapping around page boundaries as necessary. + * Notifies any registered {@link FindListener}. If {@link #findAllAsync(String)} + * has not been called yet, or if {@link #clearMatches} has been called since the + * last find operation, this function does nothing. + * + * @param forward the direction to search + * @see #setFindListener + */ + public void findNext(boolean forward) { + checkThread(); + mProvider.findNext(forward); + } + + /** + * Finds all instances of find on the page and highlights them. + * Notifies any registered {@link FindListener}. + * + * @param find the string to find + * @return the number of occurrences of the String "find" that were found + * @deprecated {@link #findAllAsync} is preferred. + * @see #setFindListener + */ + @Deprecated + public int findAll(String find) { + checkThread(); + StrictMode.noteSlowCall("findAll blocks UI: prefer findAllAsync"); + return mProvider.findAll(find); + } + + /** + * Finds all instances of find on the page and highlights them, + * asynchronously. Notifies any registered {@link FindListener}. + * Successive calls to this will cancel any pending searches. + * + * @param find the string to find. + * @see #setFindListener + */ + public void findAllAsync(String find) { + checkThread(); + mProvider.findAllAsync(find); + } + + /** + * Starts an ActionMode for finding text in this WebView. Only works if this + * WebView is attached to the view system. + * + * @param text if non-null, will be the initial text to search for. + * Otherwise, the last String searched for in this WebView will + * be used to start. + * @param showIme if {@code true}, show the IME, assuming the user will begin typing. + * If {@code false} and text is non-null, perform a find all. + * @return {@code true} if the find dialog is shown, {@code false} otherwise + * @deprecated This method does not work reliably on all Android versions; + * implementing a custom find dialog using WebView.findAllAsync() + * provides a more robust solution. + */ + @Deprecated + public boolean showFindDialog(@Nullable String text, boolean showIme) { + checkThread(); + return mProvider.showFindDialog(text, showIme); + } + + /** + * Gets the first substring consisting of the address of a physical + * location. Currently, only addresses in the United States are detected, + * and consist of: + *

      + *
    • a house number
    • + *
    • a street name
    • + *
    • a street type (Road, Circle, etc), either spelled out or + * abbreviated
    • + *
    • a city name
    • + *
    • a state or territory, either spelled out or two-letter abbr
    • + *
    • an optional 5 digit or 9 digit zip code
    • + *
    + * All names must be correctly capitalized, and the zip code, if present, + * must be valid for the state. The street type must be a standard USPS + * spelling or abbreviation. The state or territory must also be spelled + * or abbreviated using USPS standards. The house number may not exceed + * five digits. + * + * @param addr the string to search for addresses + * @return the address, or if no address is found, {@code null} + */ + @Nullable + public static String findAddress(String addr) { + // TODO: Rewrite this in Java so it is not needed to start up chromium + // Could also be deprecated + return getFactory().getStatics().findAddress(addr); + } + + /** + * For apps targeting the L release, WebView has a new default behavior that reduces + * memory footprint and increases performance by intelligently choosing + * the portion of the HTML document that needs to be drawn. These + * optimizations are transparent to the developers. However, under certain + * circumstances, an App developer may want to disable them: + *
      + *
    1. When an app uses {@link #onDraw} to do own drawing and accesses portions + * of the page that is way outside the visible portion of the page.
    2. + *
    3. When an app uses {@link #capturePicture} to capture a very large HTML document. + * Note that capturePicture is a deprecated API.
    4. + *
    + * Enabling drawing the entire HTML document has a significant performance + * cost. This method should be called before any WebViews are created. + */ + public static void enableSlowWholeDocumentDraw() { + getFactory().getStatics().enableSlowWholeDocumentDraw(); + } + + /** + * Clears the highlighting surrounding text matches created by + * {@link #findAllAsync}. + */ + public void clearMatches() { + checkThread(); + mProvider.clearMatches(); + } + + /** + * Queries the document to see if it contains any image references. The + * message object will be dispatched with arg1 being set to 1 if images + * were found and 0 if the document does not reference any images. + * + * @param response the message that will be dispatched with the result + */ + public void documentHasImages(Message response) { + checkThread(); + mProvider.documentHasImages(response); + } + + /** + * Sets the WebViewClient that will receive various notifications and + * requests. This will replace the current handler. + * + * @param client an implementation of WebViewClient + * @see #getWebViewClient + */ + public void setWebViewClient(WebViewClient client) { + checkThread(); + mProvider.setWebViewClient(client); + } + + /** + * Gets the WebViewClient. + * + * @return the WebViewClient, or a default client if not yet set + * @see #setWebViewClient + */ + public WebViewClient getWebViewClient() { + checkThread(); + return mProvider.getWebViewClient(); + } + + /** + * Registers the interface to be used when content can not be handled by + * the rendering engine, and should be downloaded instead. This will replace + * the current handler. + * + * @param listener an implementation of DownloadListener + */ + public void setDownloadListener(DownloadListener listener) { + checkThread(); + mProvider.setDownloadListener(listener); + } + + /** + * Sets the chrome handler. This is an implementation of WebChromeClient for + * use in handling JavaScript dialogs, favicons, titles, and the progress. + * This will replace the current handler. + * + * @param client an implementation of WebChromeClient + * @see #getWebChromeClient + */ + public void setWebChromeClient(WebChromeClient client) { + checkThread(); + mProvider.setWebChromeClient(client); + } + + /** + * Gets the chrome handler. + * + * @return the WebChromeClient, or {@code null} if not yet set + * @see #setWebChromeClient + */ + @Nullable + public WebChromeClient getWebChromeClient() { + checkThread(); + return mProvider.getWebChromeClient(); + } + + /** + * Sets the Picture listener. This is an interface used to receive + * notifications of a new Picture. + * + * @param listener an implementation of WebView.PictureListener + * @deprecated This method is now obsolete. + */ + @Deprecated + public void setPictureListener(PictureListener listener) { + checkThread(); + mProvider.setPictureListener(listener); + } + + /** + * Injects the supplied Java object into this WebView. The object is + * injected into the JavaScript context of the main frame, using the + * supplied name. This allows the Java object's methods to be + * accessed from JavaScript. For applications targeted to API + * level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} + * and above, only public methods that are annotated with + * {@link android.webkit.JavascriptInterface} can be accessed from JavaScript. + * For applications targeted to API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or below, + * all public methods (including the inherited ones) can be accessed, see the + * important security note below for implications. + *

    Note that injected objects will not appear in JavaScript until the page is next + * (re)loaded. JavaScript should be enabled before injecting the object. For example: + *

    +     * class JsObject {
    +     *    {@literal @}JavascriptInterface
    +     *    public String toString() { return "injectedObject"; }
    +     * }
    +     * webview.getSettings().setJavaScriptEnabled(true);
    +     * webView.addJavascriptInterface(new JsObject(), "injectedObject");
    +     * webView.loadData("", "text/html", null);
    +     * webView.loadUrl("javascript:alert(injectedObject.toString())");
    + *

    + * IMPORTANT: + *

      + *
    • This method can be used to allow JavaScript to control the host + * application. This is a powerful feature, but also presents a security + * risk for apps targeting {@link android.os.Build.VERSION_CODES#JELLY_BEAN} or earlier. + * Apps that target a version later than {@link android.os.Build.VERSION_CODES#JELLY_BEAN} + * are still vulnerable if the app runs on a device running Android earlier than 4.2. + * The most secure way to use this method is to target {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} + * and to ensure the method is called only when running on Android 4.2 or later. + * With these older versions, JavaScript could use reflection to access an + * injected object's public fields. Use of this method in a WebView + * containing untrusted content could allow an attacker to manipulate the + * host application in unintended ways, executing Java code with the + * permissions of the host application. Use extreme care when using this + * method in a WebView which could contain untrusted content.
    • + *
    • JavaScript interacts with Java object on a private, background + * thread of this WebView. Care is therefore required to maintain thread + * safety. + *
    • + *
    • The Java object's fields are not accessible.
    • + *
    • For applications targeted to API level {@link android.os.Build.VERSION_CODES#LOLLIPOP} + * and above, methods of injected Java objects are enumerable from + * JavaScript.
    • + *
    + * + * @param object the Java object to inject into this WebView's JavaScript + * context. {@code null} values are ignored. + * @param name the name used to expose the object in JavaScript + */ + public void addJavascriptInterface(Object object, String name) { + checkThread(); + mProvider.addJavascriptInterface(object, name); + } + + /** + * Removes a previously injected Java object from this WebView. Note that + * the removal will not be reflected in JavaScript until the page is next + * (re)loaded. See {@link #addJavascriptInterface}. + * + * @param name the name used to expose the object in JavaScript + */ + public void removeJavascriptInterface(@NonNull String name) { + checkThread(); + mProvider.removeJavascriptInterface(name); + } + + /** + * Creates a message channel to communicate with JS and returns the message + * ports that represent the endpoints of this message channel. The HTML5 message + * channel functionality is described + * here + * + * + *

    The returned message channels are entangled and already in started state. + * + * @return the two message ports that form the message channel. + */ + public WebMessagePort[] createWebMessageChannel() { + checkThread(); + return mProvider.createWebMessageChannel(); + } + + /** + * Post a message to main frame. The embedded application can restrict the + * messages to a certain target origin. See + * + * HTML5 spec for how target origin can be used. + *

    + * A target origin can be set as a wildcard ("*"). However this is not recommended. + * See the page above for security issues. + * + * @param message the WebMessage + * @param targetOrigin the target origin. + */ + public void postWebMessage(WebMessage message, Uri targetOrigin) { + checkThread(); + mProvider.postMessageToMainFrame(message, targetOrigin); + } + + /** + * Gets the WebSettings object used to control the settings for this + * WebView. + * + * @return a WebSettings object that can be used to control this WebView's + * settings + */ + public WebSettings getSettings() { + checkThread(); + return mProvider.getSettings(); + } + + /** + * Enables debugging of web contents (HTML / CSS / JavaScript) + * loaded into any WebViews of this application. This flag can be enabled + * in order to facilitate debugging of web layouts and JavaScript + * code running inside WebViews. Please refer to WebView documentation + * for the debugging guide. + * + * The default is {@code false}. + * + * @param enabled whether to enable web contents debugging + */ + public static void setWebContentsDebuggingEnabled(boolean enabled) { + getFactory().getStatics().setWebContentsDebuggingEnabled(enabled); + } + + /** + * Gets the list of currently loaded plugins. + * + * @return the list of currently loaded plugins + * @deprecated This was used for Gears, which has been deprecated. + * @hide + */ + @Deprecated + public static synchronized PluginList getPluginList() { + return new PluginList(); + } + + /** + * @deprecated This was used for Gears, which has been deprecated. + * @hide + */ + @Deprecated + public void refreshPlugins(boolean reloadOpenPages) { + checkThread(); + } + + /** + * Puts this WebView into text selection mode. Do not rely on this + * functionality; it will be deprecated in the future. + * + * @deprecated This method is now obsolete. + * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} + */ + @Deprecated + public void emulateShiftHeld() { + checkThread(); + } + + /** + * @deprecated WebView no longer needs to implement + * ViewGroup.OnHierarchyChangeListener. This method does nothing now. + */ + @Override + // Cannot add @hide as this can always be accessed via the interface. + @Deprecated + public void onChildViewAdded(View parent, View child) {} + + /** + * @deprecated WebView no longer needs to implement + * ViewGroup.OnHierarchyChangeListener. This method does nothing now. + */ + @Override + // Cannot add @hide as this can always be accessed via the interface. + @Deprecated + public void onChildViewRemoved(View p, View child) {} + + /** + * @deprecated WebView should not have implemented + * ViewTreeObserver.OnGlobalFocusChangeListener. This method does nothing now. + */ + @Override + // Cannot add @hide as this can always be accessed via the interface. + @Deprecated + public void onGlobalFocusChanged(View oldFocus, View newFocus) { + } + + /** + * @deprecated Only the default case, {@code true}, will be supported in a future version. + */ + @Deprecated + public void setMapTrackballToArrowKeys(boolean setMap) { + checkThread(); + mProvider.setMapTrackballToArrowKeys(setMap); + } + + + public void flingScroll(int vx, int vy) { + checkThread(); + mProvider.flingScroll(vx, vy); + } + + /** + * Gets the zoom controls for this WebView, as a separate View. The caller + * is responsible for inserting this View into the layout hierarchy. + *

    + * API level {@link android.os.Build.VERSION_CODES#CUPCAKE} introduced + * built-in zoom mechanisms for the WebView, as opposed to these separate + * zoom controls. The built-in mechanisms are preferred and can be enabled + * using {@link WebSettings#setBuiltInZoomControls}. + * + * @deprecated the built-in zoom mechanisms are preferred + * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN} + */ + @Deprecated public View getZoomControls() { - return null; + checkThread(); + return mProvider.getZoomControls(); + } + + /** + * Gets whether this WebView can be zoomed in. + * + * @return {@code true} if this WebView can be zoomed in + * + * @deprecated This method is prone to inaccuracy due to race conditions + * between the web rendering and UI threads; prefer + * {@link WebViewClient#onScaleChanged}. + */ + @Deprecated + public boolean canZoomIn() { + checkThread(); + return mProvider.canZoomIn(); + } + + /** + * Gets whether this WebView can be zoomed out. + * + * @return {@code true} if this WebView can be zoomed out + * + * @deprecated This method is prone to inaccuracy due to race conditions + * between the web rendering and UI threads; prefer + * {@link WebViewClient#onScaleChanged}. + */ + @Deprecated + public boolean canZoomOut() { + checkThread(); + return mProvider.canZoomOut(); + } + + /** + * Performs a zoom operation in this WebView. + * + * @param zoomFactor the zoom factor to apply. The zoom factor will be clamped to the WebView's + * zoom limits. This value must be in the range 0.01 to 100.0 inclusive. + */ + public void zoomBy(float zoomFactor) { + checkThread(); + if (zoomFactor < 0.01) + throw new IllegalArgumentException("zoomFactor must be greater than 0.01."); + if (zoomFactor > 100.0) + throw new IllegalArgumentException("zoomFactor must be less than 100."); + mProvider.zoomBy(zoomFactor); } + /** + * Performs zoom in in this WebView. + * + * @return {@code true} if zoom in succeeds, {@code false} if no zoom changes + */ public boolean zoomIn() { - return false; + checkThread(); + return mProvider.zoomIn(); } + /** + * Performs zoom out in this WebView. + * + * @return {@code true} if zoom out succeeds, {@code false} if no zoom changes + */ public boolean zoomOut() { - return false; + checkThread(); + return mProvider.zoomOut(); + } + + /** + * @deprecated This method is now obsolete. + * @hide Since API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1} + */ + @Deprecated + public void debugDump() { + checkThread(); + } + + /** + * See {@link ViewDebug.HierarchyHandler#dumpViewHierarchyWithProperties(BufferedWriter, int)} + * @hide + */ + @Override + public void dumpViewHierarchyWithProperties(BufferedWriter out, int level) { + mProvider.dumpViewHierarchyWithProperties(out, level); + } + + /** + * See {@link ViewDebug.HierarchyHandler#findHierarchyView(String, int)} + * @hide + */ + @Override + public View findHierarchyView(String className, int hashCode) { + return mProvider.findHierarchyView(className, hashCode); + } + + /** @hide */ + @IntDef({ + RENDERER_PRIORITY_WAIVED, + RENDERER_PRIORITY_BOUND, + RENDERER_PRIORITY_IMPORTANT + }) + @Retention(RetentionPolicy.SOURCE) + public @interface RendererPriority {} + + /** + * The renderer associated with this WebView is bound with + * {@link Context#BIND_WAIVE_PRIORITY}. At this priority level + * {@link WebView} renderers will be strong targets for out of memory + * killing. + * + * Use with {@link #setRendererPriorityPolicy}. + */ + public static final int RENDERER_PRIORITY_WAIVED = 0; + /** + * The renderer associated with this WebView is bound with + * the default priority for services. + * + * Use with {@link #setRendererPriorityPolicy}. + */ + public static final int RENDERER_PRIORITY_BOUND = 1; + /** + * The renderer associated with this WebView is bound with + * {@link Context#BIND_IMPORTANT}. + * + * Use with {@link #setRendererPriorityPolicy}. + */ + public static final int RENDERER_PRIORITY_IMPORTANT = 2; + + /** + * Set the renderer priority policy for this {@link WebView}. The + * priority policy will be used to determine whether an out of + * process renderer should be considered to be a target for OOM + * killing. + * + * Because a renderer can be associated with more than one + * WebView, the final priority it is computed as the maximum of + * any attached WebViews. When a WebView is destroyed it will + * cease to be considerered when calculating the renderer + * priority. Once no WebViews remain associated with the renderer, + * the priority of the renderer will be reduced to + * {@link #RENDERER_PRIORITY_WAIVED}. + * + * The default policy is to set the priority to + * {@link #RENDERER_PRIORITY_IMPORTANT} regardless of visibility, + * and this should not be changed unless the caller also handles + * renderer crashes with + * {@link WebViewClient#onRenderProcessGone}. Any other setting + * will result in WebView renderers being killed by the system + * more aggressively than the application. + * + * @param rendererRequestedPriority the minimum priority at which + * this WebView desires the renderer process to be bound. + * @param waivedWhenNotVisible if {@code true}, this flag specifies that + * when this WebView is not visible, it will be treated as + * if it had requested a priority of + * {@link #RENDERER_PRIORITY_WAIVED}. + */ + public void setRendererPriorityPolicy( + @RendererPriority int rendererRequestedPriority, + boolean waivedWhenNotVisible) { + mProvider.setRendererPriorityPolicy(rendererRequestedPriority, waivedWhenNotVisible); + } + + /** + * Get the requested renderer priority for this WebView. + * + * @return the requested renderer priority policy. + */ + @RendererPriority + public int getRendererRequestedPriority() { + return mProvider.getRendererRequestedPriority(); + } + + /** + * Return whether this WebView requests a priority of + * {@link #RENDERER_PRIORITY_WAIVED} when not visible. + * + * @return whether this WebView requests a priority of + * {@link #RENDERER_PRIORITY_WAIVED} when not visible. + */ + public boolean getRendererPriorityWaivedWhenNotVisible() { + return mProvider.getRendererPriorityWaivedWhenNotVisible(); + } + + /** + * Sets the {@link TextClassifier} for this WebView. + */ + public void setTextClassifier(@Nullable TextClassifier textClassifier) { + mProvider.setTextClassifier(textClassifier); + } + + /** + * Returns the {@link TextClassifier} used by this WebView. + * If no TextClassifier has been set, this WebView uses the default set by the system. + */ + @NonNull + public TextClassifier getTextClassifier() { + return mProvider.getTextClassifier(); + } + + //------------------------------------------------------------------------- + // Interface for WebView providers + //------------------------------------------------------------------------- + + /** + * Gets the WebViewProvider. Used by providers to obtain the underlying + * implementation, e.g. when the application responds to + * WebViewClient.onCreateWindow() request. + * + * @hide WebViewProvider is not public API. + */ + @SystemApi + public WebViewProvider getWebViewProvider() { + return mProvider; + } + + /** + * Callback interface, allows the provider implementation to access non-public methods + * and fields, and make super-class calls in this WebView instance. + * @hide Only for use by WebViewProvider implementations + */ + @SystemApi + public class PrivateAccess { + // ---- Access to super-class methods ---- + public int super_getScrollBarStyle() { + return WebView.super.getScrollBarStyle(); + } + + public void super_scrollTo(int scrollX, int scrollY) { + WebView.super.scrollTo(scrollX, scrollY); + } + + public void super_computeScroll() { + WebView.super.computeScroll(); + } + + public boolean super_onHoverEvent(MotionEvent event) { + return WebView.super.onHoverEvent(event); + } + + public boolean super_performAccessibilityAction(int action, Bundle arguments) { + return WebView.super.performAccessibilityActionInternal(action, arguments); + } + + public boolean super_performLongClick() { + return WebView.super.performLongClick(); + } + + public boolean super_setFrame(int left, int top, int right, int bottom) { + return WebView.super.setFrame(left, top, right, bottom); + } + + public boolean super_dispatchKeyEvent(KeyEvent event) { + return WebView.super.dispatchKeyEvent(event); + } + + public boolean super_onGenericMotionEvent(MotionEvent event) { + return WebView.super.onGenericMotionEvent(event); + } + + public boolean super_requestFocus(int direction, Rect previouslyFocusedRect) { + return WebView.super.requestFocus(direction, previouslyFocusedRect); + } + + public void super_setLayoutParams(ViewGroup.LayoutParams params) { + WebView.super.setLayoutParams(params); + } + + public void super_startActivityForResult(Intent intent, int requestCode) { + WebView.super.startActivityForResult(intent, requestCode); + } + + // ---- Access to non-public methods ---- + public void overScrollBy(int deltaX, int deltaY, + int scrollX, int scrollY, + int scrollRangeX, int scrollRangeY, + int maxOverScrollX, int maxOverScrollY, + boolean isTouchEvent) { + WebView.this.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, + maxOverScrollX, maxOverScrollY, isTouchEvent); + } + + public void awakenScrollBars(int duration) { + WebView.this.awakenScrollBars(duration); + } + + public void awakenScrollBars(int duration, boolean invalidate) { + WebView.this.awakenScrollBars(duration, invalidate); + } + + public float getVerticalScrollFactor() { + return WebView.this.getVerticalScrollFactor(); + } + + public float getHorizontalScrollFactor() { + return WebView.this.getHorizontalScrollFactor(); + } + + public void setMeasuredDimension(int measuredWidth, int measuredHeight) { + WebView.this.setMeasuredDimension(measuredWidth, measuredHeight); + } + + public void onScrollChanged(int l, int t, int oldl, int oldt) { + WebView.this.onScrollChanged(l, t, oldl, oldt); + } + + public int getHorizontalScrollbarHeight() { + return WebView.this.getHorizontalScrollbarHeight(); + } + + public void super_onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, + int l, int t, int r, int b) { + WebView.super.onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b); + } + + // ---- Access to (non-public) fields ---- + /** Raw setter for the scroll X value, without invoking onScrollChanged handlers etc. */ + public void setScrollXRaw(int scrollX) { + WebView.this.mScrollX = scrollX; + } + + /** Raw setter for the scroll Y value, without invoking onScrollChanged handlers etc. */ + public void setScrollYRaw(int scrollY) { + WebView.this.mScrollY = scrollY; + } + + } + + //------------------------------------------------------------------------- + // Package-private internal stuff + //------------------------------------------------------------------------- + + // Only used by android.webkit.FindActionModeCallback. + void setFindDialogFindListener(FindListener listener) { + checkThread(); + setupFindListenerIfNeeded(); + mFindListener.mFindDialogFindListener = listener; + } + + // Only used by android.webkit.FindActionModeCallback. + void notifyFindDialogDismissed() { + checkThread(); + mProvider.notifyFindDialogDismissed(); + } + + //------------------------------------------------------------------------- + // Private internal stuff + //------------------------------------------------------------------------- + + private WebViewProvider mProvider; + + /** + * In addition to the FindListener that the user may set via the WebView.setFindListener + * API, FindActionModeCallback will register it's own FindListener. We keep them separate + * via this class so that the two FindListeners can potentially exist at once. + */ + private class FindListenerDistributor implements FindListener { + private FindListener mFindDialogFindListener; + private FindListener mUserFindListener; + + @Override + public void onFindResultReceived(int activeMatchOrdinal, int numberOfMatches, + boolean isDoneCounting) { + if (mFindDialogFindListener != null) { + mFindDialogFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches, + isDoneCounting); + } + + if (mUserFindListener != null) { + mUserFindListener.onFindResultReceived(activeMatchOrdinal, numberOfMatches, + isDoneCounting); + } + } + } + private FindListenerDistributor mFindListener; + + private void setupFindListenerIfNeeded() { + if (mFindListener == null) { + mFindListener = new FindListenerDistributor(); + mProvider.setFindListener(mFindListener); + } + } + + private void ensureProviderCreated() { + checkThread(); + if (mProvider == null) { + // As this can get called during the base class constructor chain, pass the minimum + // number of dependencies here; the rest are deferred to init(). + mProvider = getFactory().createWebView(this, new PrivateAccess()); + } + } + + private static WebViewFactoryProvider getFactory() { + return WebViewFactory.getProvider(); + } + + private final Looper mWebViewThread = Looper.myLooper(); + + private void checkThread() { + // Ignore mWebViewThread == null because this can be called during in the super class + // constructor, before this class's own constructor has even started. + if (mWebViewThread != null && Looper.myLooper() != mWebViewThread) { + Throwable throwable = new Throwable( + "A WebView method was called on thread '" + + Thread.currentThread().getName() + "'. " + + "All WebView methods must be called on the same thread. " + + "(Expected Looper " + mWebViewThread + " called on " + Looper.myLooper() + + ", FYI main Looper is " + Looper.getMainLooper() + ")"); + Log.w(LOGTAG, Log.getStackTraceString(throwable)); + StrictMode.onWebViewMethodCalledOnWrongThread(throwable); + + if (sEnforceThreadChecking) { + throw new RuntimeException(throwable); + } + } + } + + //------------------------------------------------------------------------- + // Override View methods + //------------------------------------------------------------------------- + + // TODO: Add a test that enumerates all methods in ViewDelegte & ScrollDelegate, and ensures + // there's a corresponding override (or better, caller) for each of them in here. + + @Override + protected void onAttachedToWindow() { + super.onAttachedToWindow(); + mProvider.getViewDelegate().onAttachedToWindow(); + } + + /** @hide */ + @Override + protected void onDetachedFromWindowInternal() { + mProvider.getViewDelegate().onDetachedFromWindow(); + super.onDetachedFromWindowInternal(); + } + + /** @hide */ + @Override + public void onMovedToDisplay(int displayId, Configuration config) { + mProvider.getViewDelegate().onMovedToDisplay(displayId, config); + } + + @Override + public void setLayoutParams(ViewGroup.LayoutParams params) { + mProvider.getViewDelegate().setLayoutParams(params); + } + + @Override + public void setOverScrollMode(int mode) { + super.setOverScrollMode(mode); + // This method may be called in the constructor chain, before the WebView provider is + // created. + ensureProviderCreated(); + mProvider.getViewDelegate().setOverScrollMode(mode); + } + + @Override + public void setScrollBarStyle(int style) { + mProvider.getViewDelegate().setScrollBarStyle(style); + super.setScrollBarStyle(style); + } + + @Override + protected int computeHorizontalScrollRange() { + return mProvider.getScrollDelegate().computeHorizontalScrollRange(); + } + + @Override + protected int computeHorizontalScrollOffset() { + return mProvider.getScrollDelegate().computeHorizontalScrollOffset(); + } + + @Override + protected int computeVerticalScrollRange() { + return mProvider.getScrollDelegate().computeVerticalScrollRange(); + } + + @Override + protected int computeVerticalScrollOffset() { + return mProvider.getScrollDelegate().computeVerticalScrollOffset(); + } + + @Override + protected int computeVerticalScrollExtent() { + return mProvider.getScrollDelegate().computeVerticalScrollExtent(); + } + + @Override + public void computeScroll() { + mProvider.getScrollDelegate().computeScroll(); + } + + @Override + public boolean onHoverEvent(MotionEvent event) { + return mProvider.getViewDelegate().onHoverEvent(event); + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + return mProvider.getViewDelegate().onTouchEvent(event); + } + + @Override + public boolean onGenericMotionEvent(MotionEvent event) { + return mProvider.getViewDelegate().onGenericMotionEvent(event); + } + + @Override + public boolean onTrackballEvent(MotionEvent event) { + return mProvider.getViewDelegate().onTrackballEvent(event); + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + return mProvider.getViewDelegate().onKeyDown(keyCode, event); + } + + @Override + public boolean onKeyUp(int keyCode, KeyEvent event) { + return mProvider.getViewDelegate().onKeyUp(keyCode, event); + } + + @Override + public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { + return mProvider.getViewDelegate().onKeyMultiple(keyCode, repeatCount, event); + } + + /* + TODO: These are not currently implemented in WebViewClassic, but it seems inconsistent not + to be delegating them too. + + @Override + public boolean onKeyPreIme(int keyCode, KeyEvent event) { + return mProvider.getViewDelegate().onKeyPreIme(keyCode, event); + } + @Override + public boolean onKeyLongPress(int keyCode, KeyEvent event) { + return mProvider.getViewDelegate().onKeyLongPress(keyCode, event); + } + @Override + public boolean onKeyShortcut(int keyCode, KeyEvent event) { + return mProvider.getViewDelegate().onKeyShortcut(keyCode, event); + } + */ + + @Override + public AccessibilityNodeProvider getAccessibilityNodeProvider() { + AccessibilityNodeProvider provider = + mProvider.getViewDelegate().getAccessibilityNodeProvider(); + return provider == null ? super.getAccessibilityNodeProvider() : provider; + } + + @Deprecated + @Override + public boolean shouldDelayChildPressedState() { + return mProvider.getViewDelegate().shouldDelayChildPressedState(); + } + + @Override + public CharSequence getAccessibilityClassName() { + return WebView.class.getName(); + } + + @Override + public void onProvideVirtualStructure(ViewStructure structure) { + mProvider.getViewDelegate().onProvideVirtualStructure(structure); + } + + /** + * {@inheritDoc} + * + *

    The {@link ViewStructure} traditionally represents a {@link View}, while for web pages + * it represent HTML nodes. Hence, it's necessary to "map" the HTML properties in a way that is + * understood by the {@link android.service.autofill.AutofillService} implementations: + * + *

      + *
    1. Only the HTML nodes inside a {@code FORM} are generated. + *
    2. The source of the HTML is set using {@link ViewStructure#setWebDomain(String)} in the + * node representing the WebView. + *
    3. If a web page has multiple {@code FORM}s, only the data for the current form is + * represented—if the user taps a field from another form, then the current autofill + * context is canceled (by calling {@link android.view.autofill.AutofillManager#cancel()} and + * a new context is created for that {@code FORM}. + *
    4. Similarly, if the page has {@code IFRAME} nodes, they are not initially represented in + * the view structure until the user taps a field from a {@code FORM} inside the + * {@code IFRAME}, in which case it would be treated the same way as multiple forms described + * above, except that the {@link ViewStructure#setWebDomain(String) web domain} of the + * {@code FORM} contains the {@code src} attribute from the {@code IFRAME} node. + *
    5. The W3C autofill field ({@code autocomplete} tag attribute) maps to + * {@link ViewStructure#setAutofillHints(String[])}. + *
    6. If the view is editable, the {@link ViewStructure#setAutofillType(int)} and + * {@link ViewStructure#setAutofillValue(AutofillValue)} must be set. + *
    7. The {@code placeholder} attribute maps to {@link ViewStructure#setHint(CharSequence)}. + *
    8. Other HTML attributes can be represented through + * {@link ViewStructure#setHtmlInfo(android.view.ViewStructure.HtmlInfo)}. + *
    + * + *

    If the WebView implementation can determine that the value of a field was set statically + * (for example, not through Javascript), it should also call + * {@code structure.setDataIsSensitive(false)}. + * + *

    For example, an HTML form with 2 fields for username and password: + * + *

    +     *    <input type="text" name="username" id="user" value="Type your username" autocomplete="username" placeholder="Email or username">
    +     *    <input type="password" name="password" id="pass" autocomplete="current-password" placeholder="Password">
    +     * 
    + * + *

    Would map to: + * + *

    +     *     int index = structure.addChildCount(2);
    +     *     ViewStructure username = structure.newChild(index);
    +     *     username.setAutofillId(structure.getAutofillId(), 1); // id 1 - first child
    +     *     username.setAutofillHints("username");
    +     *     username.setHtmlInfo(username.newHtmlInfoBuilder("input")
    +     *         .addAttribute("type", "text")
    +     *         .addAttribute("name", "username")
    +     *         .build());
    +     *     username.setHint("Email or username");
    +     *     username.setAutofillType(View.AUTOFILL_TYPE_TEXT);
    +     *     username.setAutofillValue(AutofillValue.forText("Type your username"));
    +     *     // Value of the field is not sensitive because it was created statically and not changed.
    +     *     username.setDataIsSensitive(false);
    +     *
    +     *     ViewStructure password = structure.newChild(index + 1);
    +     *     username.setAutofillId(structure, 2); // id 2 - second child
    +     *     password.setAutofillHints("current-password");
    +     *     password.setHtmlInfo(password.newHtmlInfoBuilder("input")
    +     *         .addAttribute("type", "password")
    +     *         .addAttribute("name", "password")
    +     *         .build());
    +     *     password.setHint("Password");
    +     *     password.setAutofillType(View.AUTOFILL_TYPE_TEXT);
    +     * 
    + */ + @Override + public void onProvideAutofillVirtualStructure(ViewStructure structure, int flags) { + mProvider.getViewDelegate().onProvideAutofillVirtualStructure(structure, flags); + } + + @Override + public void autofill(SparseArrayvalues) { + mProvider.getViewDelegate().autofill(values); + } + + /** @hide */ + @Override + public void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { + super.onInitializeAccessibilityNodeInfoInternal(info); + mProvider.getViewDelegate().onInitializeAccessibilityNodeInfo(info); + } + + /** @hide */ + @Override + public void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { + super.onInitializeAccessibilityEventInternal(event); + mProvider.getViewDelegate().onInitializeAccessibilityEvent(event); + } + + /** @hide */ + @Override + public boolean performAccessibilityActionInternal(int action, Bundle arguments) { + return mProvider.getViewDelegate().performAccessibilityAction(action, arguments); + } + + /** @hide */ + @Override + protected void onDrawVerticalScrollBar(Canvas canvas, Drawable scrollBar, + int l, int t, int r, int b) { + mProvider.getViewDelegate().onDrawVerticalScrollBar(canvas, scrollBar, l, t, r, b); + } + + @Override + protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) { + mProvider.getViewDelegate().onOverScrolled(scrollX, scrollY, clampedX, clampedY); + } + + @Override + protected void onWindowVisibilityChanged(int visibility) { + super.onWindowVisibilityChanged(visibility); + mProvider.getViewDelegate().onWindowVisibilityChanged(visibility); + } + + @Override + protected void onDraw(Canvas canvas) { + mProvider.getViewDelegate().onDraw(canvas); + } + + @Override + public boolean performLongClick() { + return mProvider.getViewDelegate().performLongClick(); + } + + @Override + protected void onConfigurationChanged(Configuration newConfig) { + mProvider.getViewDelegate().onConfigurationChanged(newConfig); + } + + /** + * Creates a new InputConnection for an InputMethod to interact with the WebView. + * This is similar to {@link View#onCreateInputConnection} but note that WebView + * calls InputConnection methods on a thread other than the UI thread. + * If these methods are overridden, then the overriding methods should respect + * thread restrictions when calling View methods or accessing data. + */ + @Override + public InputConnection onCreateInputConnection(EditorInfo outAttrs) { + return mProvider.getViewDelegate().onCreateInputConnection(outAttrs); + } + + @Override + public boolean onDragEvent(DragEvent event) { + return mProvider.getViewDelegate().onDragEvent(event); + } + + @Override + protected void onVisibilityChanged(View changedView, int visibility) { + super.onVisibilityChanged(changedView, visibility); + // This method may be called in the constructor chain, before the WebView provider is + // created. + ensureProviderCreated(); + mProvider.getViewDelegate().onVisibilityChanged(changedView, visibility); + } + + @Override + public void onWindowFocusChanged(boolean hasWindowFocus) { + mProvider.getViewDelegate().onWindowFocusChanged(hasWindowFocus); + super.onWindowFocusChanged(hasWindowFocus); + } + + @Override + protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { + mProvider.getViewDelegate().onFocusChanged(focused, direction, previouslyFocusedRect); + super.onFocusChanged(focused, direction, previouslyFocusedRect); + } + + /** @hide */ + @Override + protected boolean setFrame(int left, int top, int right, int bottom) { + return mProvider.getViewDelegate().setFrame(left, top, right, bottom); + } + + @Override + protected void onSizeChanged(int w, int h, int ow, int oh) { + super.onSizeChanged(w, h, ow, oh); + mProvider.getViewDelegate().onSizeChanged(w, h, ow, oh); + } + + @Override + protected void onScrollChanged(int l, int t, int oldl, int oldt) { + super.onScrollChanged(l, t, oldl, oldt); + mProvider.getViewDelegate().onScrollChanged(l, t, oldl, oldt); + } + + @Override + public boolean dispatchKeyEvent(KeyEvent event) { + return mProvider.getViewDelegate().dispatchKeyEvent(event); + } + + @Override + public boolean requestFocus(int direction, Rect previouslyFocusedRect) { + return mProvider.getViewDelegate().requestFocus(direction, previouslyFocusedRect); + } + + @Override + protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { + super.onMeasure(widthMeasureSpec, heightMeasureSpec); + mProvider.getViewDelegate().onMeasure(widthMeasureSpec, heightMeasureSpec); + } + + @Override + public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) { + return mProvider.getViewDelegate().requestChildRectangleOnScreen(child, rect, immediate); + } + + @Override + public void setBackgroundColor(int color) { + mProvider.getViewDelegate().setBackgroundColor(color); + } + + @Override + public void setLayerType(int layerType, Paint paint) { + super.setLayerType(layerType, paint); + mProvider.getViewDelegate().setLayerType(layerType, paint); + } + + @Override + protected void dispatchDraw(Canvas canvas) { + mProvider.getViewDelegate().preDispatchDraw(canvas); + super.dispatchDraw(canvas); + } + + @Override + public void onStartTemporaryDetach() { + super.onStartTemporaryDetach(); + mProvider.getViewDelegate().onStartTemporaryDetach(); + } + + @Override + public void onFinishTemporaryDetach() { + super.onFinishTemporaryDetach(); + mProvider.getViewDelegate().onFinishTemporaryDetach(); + } + + @Override + public Handler getHandler() { + return mProvider.getViewDelegate().getHandler(super.getHandler()); + } + + @Override + public View findFocus() { + return mProvider.getViewDelegate().findFocus(super.findFocus()); + } + + /** + * If WebView has already been loaded into the current process this method will return the + * package that was used to load it. Otherwise, the package that would be used if the WebView + * was loaded right now will be returned; this does not cause WebView to be loaded, so this + * information may become outdated at any time. + * The WebView package changes either when the current WebView package is updated, disabled, or + * uninstalled. It can also be changed through a Developer Setting. + * If the WebView package changes, any app process that has loaded WebView will be killed. The + * next time the app starts and loads WebView it will use the new WebView package instead. + * @return the current WebView package, or {@code null} if there is none. + */ + @Nullable + public static PackageInfo getCurrentWebViewPackage() { + PackageInfo webviewPackage = WebViewFactory.getLoadedPackageInfo(); + if (webviewPackage != null) { + return webviewPackage; + } + + IWebViewUpdateService service = WebViewFactory.getUpdateService(); + if (service == null) { + return null; + } + try { + return service.getCurrentWebViewPackage(); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } + + /** + * Receive the result from a previous call to {@link #startActivityForResult(Intent, int)}. + * + * @param requestCode The integer request code originally supplied to + * startActivityForResult(), allowing you to identify who this + * result came from. + * @param resultCode The integer result code returned by the child activity + * through its setResult(). + * @param data An Intent, which can return result data to the caller + * (various data can be attached to Intent "extras"). + * @hide + */ + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + mProvider.getViewDelegate().onActivityResult(requestCode, resultCode, data); + } + + /** @hide */ + @Override + protected void encodeProperties(@NonNull ViewHierarchyEncoder encoder) { + super.encodeProperties(encoder); + + checkThread(); + encoder.addProperty("webview:contentHeight", mProvider.getContentHeight()); + encoder.addProperty("webview:contentWidth", mProvider.getContentWidth()); + encoder.addProperty("webview:scale", mProvider.getScale()); + encoder.addProperty("webview:title", mProvider.getTitle()); + encoder.addProperty("webview:url", mProvider.getUrl()); + encoder.addProperty("webview:originalUrl", mProvider.getOriginalUrl()); } } diff --git a/android/widget/Editor.java b/android/widget/Editor.java index d4be7e57..afd11881 100644 --- a/android/widget/Editor.java +++ b/android/widget/Editor.java @@ -165,7 +165,7 @@ public class Editor { private static final int MENU_ITEM_ORDER_PASTE_AS_PLAIN_TEXT = 11; private static final int MENU_ITEM_ORDER_PROCESS_TEXT_INTENT_ACTIONS_START = 100; - private static final float MAGNIFIER_ZOOM = 1.25f; + private static final float MAGNIFIER_ZOOM = 1.5f; @IntDef({MagnifierHandleTrigger.SELECTION_START, MagnifierHandleTrigger.SELECTION_END, MagnifierHandleTrigger.INSERTION}) @@ -476,17 +476,6 @@ public class Editor { stopTextActionModeWithPreservingSelection(); } - void invalidateMagnifier() { - final DisplayMetrics dm = mTextView.getResources().getDisplayMetrics(); - invalidateMagnifier(0, 0, dm.widthPixels, dm.heightPixels); - } - - void invalidateMagnifier(final float l, final float t, final float r, final float b) { - if (mMagnifier != null) { - mTextView.post(() -> mMagnifier.invalidate(new RectF(l, t, r, b))); - } - } - private void discardTextDisplayLists() { if (mTextRenderNodes != null) { for (int i = 0; i < mTextRenderNodes.length; i++) { @@ -4556,17 +4545,17 @@ public class Editor { + mTextView.getLayout().getLineBottom(lineNumber)) / 2.0f; final int[] coordinatesOnScreen = new int[2]; mTextView.getLocationOnScreen(coordinatesOnScreen); - final float centerXOnScreen = mTextView.convertViewToScreenCoord(xPosInView, true); - final float centerYOnScreen = mTextView.convertViewToScreenCoord(yPosInView, false); + final float centerXOnScreen = xPosInView + mTextView.getTotalPaddingLeft() + - mTextView.getScrollX() + coordinatesOnScreen[0]; + final float centerYOnScreen = yPosInView + mTextView.getTotalPaddingTop() + - mTextView.getScrollY() + coordinatesOnScreen[1]; - suspendBlink(); mMagnifier.show(centerXOnScreen, centerYOnScreen, MAGNIFIER_ZOOM); } protected final void dismissMagnifier() { if (mMagnifier != null) { mMagnifier.dismiss(); - resumeBlink(); } } diff --git a/android/widget/RemoteViews.java b/android/widget/RemoteViews.java index 199b596a..1b26f8e2 100644 --- a/android/widget/RemoteViews.java +++ b/android/widget/RemoteViews.java @@ -2653,11 +2653,7 @@ public class RemoteViews implements Parcelable, Filter { /** * Equivalent to calling * {@link android.view.View#setOnClickListener(android.view.View.OnClickListener)} - * to launch the provided {@link PendingIntent}. The source bounds - * ({@link Intent#getSourceBounds()}) of the intent will be set to the bounds of the clicked - * view in screen space. - * Note that any activity options associated with the pendingIntent may get overridden - * before starting the intent. + * to launch the provided {@link PendingIntent}. * * When setting the on-click action of items within collections (eg. {@link ListView}, * {@link StackView} etc.), this method will not work. Instead, use {@link diff --git a/android/widget/SelectionActionModeHelper.java b/android/widget/SelectionActionModeHelper.java index 5e22650a..3be42a5b 100644 --- a/android/widget/SelectionActionModeHelper.java +++ b/android/widget/SelectionActionModeHelper.java @@ -95,15 +95,11 @@ public final class SelectionActionModeHelper { } public void startActionModeAsync(boolean adjustSelection) { - // Check if the smart selection should run for editable text. - adjustSelection &= !mTextView.isTextEditable() - || mTextView.getTextClassifier().getSettings() - .isSuggestSelectionEnabledForEditableText(); - mSelectionTracker.onOriginalSelection( getText(mTextView), mTextView.getSelectionStart(), - mTextView.getSelectionEnd()); + mTextView.getSelectionEnd(), + mTextView.isTextEditable()); cancelAsyncTask(); if (skipTextClassification()) { startActionMode(null); @@ -200,10 +196,7 @@ public final class SelectionActionModeHelper { private void startActionMode(@Nullable SelectionResult result) { final CharSequence text = getText(mTextView); if (result != null && text instanceof Spannable) { - // Do not change the selection if TextClassifier should be dark launched. - if (!mTextView.getTextClassifier().getSettings().isDarkLaunch()) { - Selection.setSelection((Spannable) text, result.mStart, result.mEnd); - } + Selection.setSelection((Spannable) text, result.mStart, result.mEnd); mTextClassification = result.mClassification; } else { mTextClassification = null; @@ -384,7 +377,7 @@ public final class SelectionActionModeHelper { } private void resetTextClassificationHelper() { - mTextClassificationHelper.init( + mTextClassificationHelper.reset( mTextView.getTextClassifier(), getText(mTextView), mTextView.getSelectionStart(), mTextView.getSelectionEnd(), @@ -422,7 +415,8 @@ public final class SelectionActionModeHelper { /** * Called when the original selection happens, before smart selection is triggered. */ - public void onOriginalSelection(CharSequence text, int selectionStart, int selectionEnd) { + public void onOriginalSelection( + CharSequence text, int selectionStart, int selectionEnd, boolean editableText) { // If we abandoned a selection and created a new one very shortly after, we may still // have a pending request to log ABANDON, which we flush here. mDelayedLogAbandon.flush(); @@ -818,11 +812,11 @@ public final class SelectionActionModeHelper { TextClassificationHelper(TextClassifier textClassifier, CharSequence text, int selectionStart, int selectionEnd, LocaleList locales) { - init(textClassifier, text, selectionStart, selectionEnd, locales); + reset(textClassifier, text, selectionStart, selectionEnd, locales); } @UiThread - public void init(TextClassifier textClassifier, + public void reset(TextClassifier textClassifier, CharSequence text, int selectionStart, int selectionEnd, LocaleList locales) { mTextClassifier = Preconditions.checkNotNull(textClassifier); mText = Preconditions.checkNotNull(text).toString(); @@ -845,12 +839,8 @@ public final class SelectionActionModeHelper { trimText(); final TextSelection selection = mTextClassifier.suggestSelection( mTrimmedText, mRelativeStart, mRelativeEnd, mLocales); - // Do not classify new selection boundaries if TextClassifier should be dark launched. - if (!mTextClassifier.getSettings().isDarkLaunch()) { - mSelectionStart = Math.max(0, selection.getSelectionStartIndex() + mTrimStart); - mSelectionEnd = Math.min( - mText.length(), selection.getSelectionEndIndex() + mTrimStart); - } + mSelectionStart = Math.max(0, selection.getSelectionStartIndex() + mTrimStart); + mSelectionEnd = Math.min(mText.length(), selection.getSelectionEndIndex() + mTrimStart); return performClassification(selection); } diff --git a/android/widget/TextView.java b/android/widget/TextView.java index ce805526..24ae03c3 100644 --- a/android/widget/TextView.java +++ b/android/widget/TextView.java @@ -9219,36 +9219,6 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener } } - @Override - public void invalidate() { - super.invalidate(); - - if (mEditor != null) { - mEditor.invalidateMagnifier(); - } - } - - @Override - public void invalidate(int l, int t, int r, int b) { - super.invalidate(l, t, r, b); - - if (mEditor != null) { - mEditor.invalidateMagnifier( - convertViewToScreenCoord(l, true /* isHorizontal */), - convertViewToScreenCoord(t, false /* isHorizontal */), - convertViewToScreenCoord(r, true /* isHorizontal */), - convertViewToScreenCoord(b, false /* isHorizontal */)); - } - } - - float convertViewToScreenCoord(float viewCoord, boolean isHorizontal) { - final int[] coordinatesOnScreen = new int[2]; - getLocationOnScreen(coordinatesOnScreen); - return isHorizontal - ? viewCoord + getTotalPaddingLeft() - getScrollX() + coordinatesOnScreen[0] - : viewCoord + getTotalPaddingTop() - getScrollY() + coordinatesOnScreen[1]; - } - /** * @return whether or not the cursor is visible (assuming this TextView is editable) * @@ -10368,17 +10338,6 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener // of the View (and can be any drawable) or a BackgroundColorSpan inside the text. structure.setTextStyle(getTextSize(), getCurrentTextColor(), AssistStructure.ViewNode.TEXT_COLOR_UNDEFINED /* bgColor */, style); - } else { - structure.setMinTextEms(getMinEms()); - structure.setMaxTextEms(getMaxEms()); - int maxLength = -1; - for (InputFilter filter: getFilters()) { - if (filter instanceof InputFilter.LengthFilter) { - maxLength = ((InputFilter.LengthFilter) filter).getMax(); - break; - } - } - structure.setMaxTextLength(maxLength); } } structure.setHint(getHint()); -- cgit v1.2.3