summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--PREUPLOAD.cfg2
-rw-r--r--cmds/uinput/src/com/android/commands/uinput/EvemuParser.java14
-rw-r--r--cmds/uinput/tests/src/com/android/commands/uinput/tests/EvemuParserTest.java5
-rw-r--r--core/api/current.txt6
-rw-r--r--core/java/android/app/Activity.java15
-rw-r--r--core/java/android/app/Notification.java73
-rw-r--r--core/java/android/app/jank/JankTracker.java7
-rw-r--r--core/java/android/app/usage/IStorageStatsManager.aidl1
-rw-r--r--core/java/android/app/usage/StorageStats.java64
-rw-r--r--core/java/android/app/usage/flags.aconfig10
-rw-r--r--core/java/android/appwidget/AppWidgetHostView.java139
-rw-r--r--core/java/android/appwidget/AppWidgetManager.java18
-rw-r--r--core/java/android/companion/AssociationRequest.java8
-rw-r--r--core/java/android/companion/virtual/flags/flags.aconfig2
-rw-r--r--core/java/android/content/pm/multiuser.aconfig10
-rw-r--r--core/java/android/content/theming/FieldColor.java80
-rw-r--r--core/java/android/content/theming/FieldColorBoth.java70
-rw-r--r--core/java/android/content/theming/FieldColorIndex.java64
-rw-r--r--core/java/android/content/theming/FieldColorSource.java76
-rw-r--r--core/java/android/content/theming/FieldThemeStyle.java76
-rw-r--r--core/java/android/content/theming/ThemeSettings.java200
-rw-r--r--core/java/android/content/theming/ThemeSettingsField.java287
-rw-r--r--core/java/android/content/theming/ThemeSettingsUpdater.java244
-rw-r--r--core/java/android/content/theming/ThemeStyle.java180
-rw-r--r--core/java/android/hardware/display/DisplayManagerGlobal.java4
-rw-r--r--core/java/android/os/BatteryStats.java103
-rw-r--r--core/java/android/os/BatteryUsageStats.java33
-rw-r--r--core/java/android/security/advancedprotection/AdvancedProtectionManager.java2
-rw-r--r--core/java/android/security/flags.aconfig7
-rw-r--r--core/java/android/text/Layout.java6
-rw-r--r--core/java/android/view/InsetsAnimationControlImpl.java5
-rw-r--r--core/java/android/view/InsetsAnimationControlRunner.java6
-rw-r--r--core/java/android/view/InsetsAnimationThreadControlRunner.java13
-rw-r--r--core/java/android/view/InsetsController.java60
-rw-r--r--core/java/android/view/InsetsResizeAnimationRunner.java5
-rw-r--r--core/java/android/view/InsetsSourceConsumer.java6
-rw-r--r--core/java/android/view/View.java67
-rw-r--r--core/java/android/view/ViewRootImpl.java21
-rw-r--r--core/java/android/view/autofill/AutofillFeatureFlags.java2
-rw-r--r--core/java/android/view/inputmethod/ImeTracker.java6
-rw-r--r--core/java/android/widget/RemoteViews.java58
-rw-r--r--core/java/android/window/DesktopModeFlags.java8
-rw-r--r--core/java/com/android/internal/content/FileSystemProvider.java11
-rw-r--r--core/java/com/android/internal/inputmethod/InputMethodDebug.java2
-rw-r--r--core/java/com/android/internal/inputmethod/SoftInputShowHideReason.java7
-rw-r--r--core/java/com/android/internal/protolog/LogcatOnlyProtoLogImpl.java8
-rw-r--r--core/java/com/android/internal/protolog/ProtoLog.java21
-rw-r--r--core/java/com/android/internal/protolog/common/LogLevel.java3
-rw-r--r--core/java/com/android/internal/util/ContrastColorUtil.java9
-rw-r--r--core/jni/fd_utils.cpp3
-rw-r--r--core/res/AndroidManifest.xml8
-rw-r--r--core/res/res/drawable/ic_standby.xml10
-rw-r--r--core/res/res/values/config.xml4
-rw-r--r--core/res/res/values/public-staging.xml2
-rw-r--r--core/res/res/values/strings.xml3
-rw-r--r--core/res/res/values/symbols.xml4
-rw-r--r--core/tests/coretests/src/android/app/NotificationTest.java61
-rw-r--r--core/tests/coretests/src/android/appwidget/AppWidgetEventsTest.kt138
-rw-r--r--core/tests/coretests/src/android/text/LayoutTest.java102
-rw-r--r--core/tests/coretests/src/android/view/ViewRootImplTest.java141
-rw-r--r--core/tests/coretests/src/com/android/internal/logging/ProtoLogTest.java53
-rw-r--r--core/tests/coretests/src/com/android/internal/logging/ProtoLogTestGroup.java85
-rw-r--r--data/etc/privapp-permissions-platform.xml4
-rw-r--r--libs/WindowManager/Shell/res/values/styles.xml1
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/animation/SizeChangeAnimation.java6
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarAnimationHelper.java2
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java3
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java24
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip2Module.java23
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopDisplayModeController.kt35
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeVisualIndicator.java76
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopPipTransitionController.kt115
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopPipTransitionObserver.kt81
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt73
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksTransitionObserver.kt3
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/multidesks/DesksOrganizer.kt3
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/multidesks/RootTaskDesksOrganizer.kt11
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java62
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java11
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java8
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CarWindowDecoration.java19
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java16
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenu.kt27
-rw-r--r--libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/common/ButtonBackgroundDrawableUtils.kt12
-rw-r--r--libs/WindowManager/Shell/tests/e2e/splitscreen/flicker-legacy/src/com/android/wm/shell/flicker/splitscreen/benchmark/SwitchAppByDoubleTapDividerBenchmark.kt2
-rw-r--r--libs/WindowManager/Shell/tests/e2e/splitscreen/scenarios/src/com/android/wm/shell/scenarios/SwitchAppByDoubleTapDivider.kt2
-rw-r--r--libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/utils/SplitScreenUtils.kt40
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopDisplayModeControllerTest.kt442
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopModeVisualIndicatorTest.kt60
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopPipTransitionControllerTest.kt165
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopPipTransitionObserverTest.kt98
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksControllerTest.kt96
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksTransitionObserverTest.kt3
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/multidesks/RootTaskDesksOrganizerTest.kt37
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/splitscreen/StageCoordinatorTests.java3
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/DefaultTransitionHandlerTest.java3
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/HomeTransitionObserverTest.java3
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/ShellTransitionTests.java10
-rw-r--r--libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModelTestsBase.kt3
-rw-r--r--location/java/android/location/flags/location.aconfig10
-rw-r--r--media/java/android/media/flags/media_better_together.aconfig10
-rw-r--r--media/java/android/media/tv/extension/scan/IScanInterface.aidl2
-rw-r--r--packages/CompanionDeviceManager/res/values/strings.xml13
-rw-r--r--packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionAssociationActivity.java6
-rw-r--r--packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceResources.java12
-rw-r--r--packages/ExternalStorageProvider/src/com/android/externalstorage/ExternalStorageProvider.java5
-rw-r--r--packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_button_background_normal.xml4
-rw-r--r--packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_high.xml22
-rw-r--r--packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_low.xml22
-rw-r--r--packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_medium.xml22
-rw-r--r--packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_normal.xml22
-rw-r--r--packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_outline_button_content.xml22
-rw-r--r--packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_outline_button_stroke_normal.xml22
-rw-r--r--packages/SettingsLib/BannerMessagePreference/res/values-v36/styles_expressive.xml1
-rw-r--r--packages/SettingsLib/BannerMessagePreference/src/com/android/settingslib/widget/BannerMessagePreference.java74
-rw-r--r--packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/dialog/SettingsAlterDialogContent.kt8
-rw-r--r--packages/SettingsLib/StatusBannerPreference/src/com/android/settingslib/widget/StatusBannerPreference.kt13
-rw-r--r--packages/SettingsLib/res/xml/timezones.xml1
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/RestrictedLockUtilsInternal.java42
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/display/OWNERS5
-rw-r--r--packages/SettingsLib/src/com/android/settingslib/wifi/WifiUtils.kt6
-rw-r--r--packages/SettingsLib/tests/robotests/src/com/android/settingslib/RestrictedLockUtilsTest.java10
-rw-r--r--packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BannerMessagePreferenceTest.java240
-rw-r--r--packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/WifiUtilsTest.java3
-rw-r--r--packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java39
-rw-r--r--packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java15
-rw-r--r--packages/Shell/AndroidManifest.xml3
-rw-r--r--packages/SystemUI/OWNERS1
-rw-r--r--packages/SystemUI/aconfig/systemui.aconfig21
-rw-r--r--packages/SystemUI/animation/src/com/android/systemui/animation/ActivityTransitionAnimator.kt3
-rw-r--r--packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt43
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/clipboardoverlay/ActionIntentCreatorTest.kt81
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalAutoOpenInteractorTest.kt4
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractorTest.kt62
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalSettingsInteractorTest.kt4
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/communal/posturing/domain/interactor/PosturingInteractorTest.kt2
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryFaceAuthInteractorTest.kt29
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/ui/viewmodel/UdfpsAccessibilityOverlayViewModelTest.kt81
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/keyboard/shortcut/data/source/TestShortcuts.kt2
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerTransitionViewModelTest.kt63
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModelTest.kt229
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt93
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModelTest.kt74
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt77
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/shade/ShadeControllerSceneImplTest.kt16
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/NotificationShadeDepthControllerTest.kt3
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryTest.java18
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java54
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/headsup/HeadsUpManagerImplTest.kt14
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationContentExtractorImplTest.kt708
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationsInteractorTest.kt147
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java29
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/row/NotificationRowContentBinderImplTest.kt26
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainerTest.java14
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorKairosAdapterTest.kt2
-rw-r--r--packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModelTest.kt43
-rw-r--r--packages/SystemUI/res/drawable/ic_qs_category_accessibility.xml26
-rw-r--r--packages/SystemUI/res/drawable/ic_qs_category_connectivty.xml26
-rw-r--r--packages/SystemUI/res/drawable/ic_qs_category_display.xml26
-rw-r--r--packages/SystemUI/res/drawable/ic_qs_category_privacy.xml26
-rw-r--r--packages/SystemUI/res/drawable/ic_qs_category_provided_by_apps.xml26
-rw-r--r--packages/SystemUI/res/drawable/ic_qs_category_unknown.xml26
-rw-r--r--packages/SystemUI/res/drawable/ic_qs_category_utilities.xml26
-rw-r--r--packages/SystemUI/res/layout/battery_percentage_view.xml2
-rw-r--r--packages/SystemUI/res/layout/biometric_prompt_one_pane_layout.xml2
-rw-r--r--packages/SystemUI/res/layout/biometric_prompt_two_pane_layout.xml2
-rw-r--r--packages/SystemUI/res/layout/combined_qs_header.xml2
-rw-r--r--packages/SystemUI/res/layout/keyguard_status_bar.xml2
-rw-r--r--packages/SystemUI/res/layout/notification_conversation_info.xml10
-rw-r--r--packages/SystemUI/res/layout/status_bar.xml2
-rw-r--r--packages/SystemUI/res/layout/system_icons.xml2
-rw-r--r--packages/SystemUI/res/values/colors.xml1
-rw-r--r--packages/SystemUI/res/values/strings.xml4
-rw-r--r--packages/SystemUI/res/values/styles.xml19
-rw-r--r--packages/SystemUI/src/com/android/systemui/backup/BackupHelper.kt5
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/UdfpsOverlayInteractor.kt24
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt60
-rw-r--r--packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt17
-rw-r--r--packages/SystemUI/src/com/android/systemui/brightness/ui/compose/BrightnessSlider.kt16
-rw-r--r--packages/SystemUI/src/com/android/systemui/clipboardoverlay/ActionIntentCreator.kt51
-rw-r--r--packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalSceneRepository.kt16
-rw-r--r--packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalSettingsRepository.kt9
-rw-r--r--packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractor.kt27
-rw-r--r--packages/SystemUI/src/com/android/systemui/communal/posturing/domain/interactor/PosturingInteractor.kt12
-rw-r--r--packages/SystemUI/src/com/android/systemui/communal/shared/model/CommunalTransitionKeys.kt2
-rw-r--r--packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt5
-rw-r--r--packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/SystemUIDeviceEntryFaceAuthInteractor.kt19
-rw-r--r--packages/SystemUI/src/com/android/systemui/deviceentry/ui/binder/UdfpsAccessibilityOverlayBinder.kt43
-rw-r--r--packages/SystemUI/src/com/android/systemui/deviceentry/ui/view/UdfpsAccessibilityOverlay.kt2
-rw-r--r--packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/AlternateBouncerUdfpsAccessibilityOverlayViewModel.kt13
-rw-r--r--packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/DeviceEntryUdfpsAccessibilityOverlayViewModel.kt3
-rw-r--r--packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/UdfpsAccessibilityOverlayViewModel.kt21
-rw-r--r--packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialogLite.java45
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/dagger/PrimaryBouncerTransitionModule.kt10
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDreamingTransitionInteractor.kt1
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromGlanceableHubTransitionInteractor.kt2
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractor.kt1
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/AccessibilityActionsViewBinder.kt27
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/AlternateBouncerViewBinder.kt22
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AccessibilityActionsViewModel.kt14
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerTransitionViewModel.kt49
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModel.kt66
-rw-r--r--packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModel.kt59
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/controls/ui/binder/SeekBarObserver.kt1
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaControlPanel.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaViewController.kt10
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt1
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/EditTile.kt72
-rw-r--r--packages/SystemUI/src/com/android/systemui/qs/shared/model/TileCategory.kt37
-rw-r--r--packages/SystemUI/src/com/android/systemui/scene/domain/startable/SceneContainerStartable.kt27
-rw-r--r--packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt15
-rw-r--r--packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt27
-rw-r--r--packages/SystemUI/src/com/android/systemui/shade/OWNERS13
-rw-r--r--packages/SystemUI/src/com/android/systemui/shade/ShadeControllerSceneImpl.kt1
-rw-r--r--packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt20
-rw-r--r--packages/SystemUI/src/com/android/systemui/shade/ShadeStateTraceLogger.kt15
-rw-r--r--packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractor.kt29
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt32
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/chips/notification/shared/StatusBarNotifChips.kt9
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/compose/ChipContent.kt6
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/model/OngoingActivityChipModel.kt9
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/viewmodel/TimeRemainingState.kt5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java1
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationUiAod.kt9
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationUiForceExpanded.kt9
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationInteractor.kt28
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java13
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfo.java7
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java4
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationTemplateViewWrapper.java5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java2
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt25
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/StackedMobileIconBinder.kt7
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt14
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/ui/view/SingleBindableStatusBarComposeIconView.kt5
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyStateInflater.kt76
-rw-r--r--packages/SystemUI/src/com/android/systemui/statusbar/policy/domain/interactor/SensitiveNotificationProtectionInteractor.kt48
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt8
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/globalactions/GlobalActionsDialogLiteTest.java100
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfoTest.java31
-rw-r--r--packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java12
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/communal/data/repository/FakeCommunalSceneRepository.kt11
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractorKosmos.kt2
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/data/ui/viewmodel/UdfpsAccessibilityOverlayViewModelKosmos.kt12
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/AccessibilityActionsViewModelKosmos.kt2
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerViewModelKosmos.kt29
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModelKosmos.kt6
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModelKosmos.kt29
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractorKosmos.kt2
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationContentExtractorKosmos.kt4
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationInteractorKosmos.kt4
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt3
-rw-r--r--packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/policy/domain/interactor/SensitiveNotificationProtectionInteractorKosmos.kt25
-rw-r--r--ravenwood/README.md23
-rw-r--r--ravenwood/api-maintainers.md94
-rw-r--r--ravenwood/test-authors.md193
-rw-r--r--ravenwood/texts/ravenwood-annotation-allowed-classes.txt4
-rw-r--r--services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java31
-rw-r--r--services/accessibility/java/com/android/server/accessibility/autoclick/AutoclickController.java68
-rw-r--r--services/accessibility/java/com/android/server/accessibility/autoclick/AutoclickScrollPanel.java2
-rw-r--r--services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java27
-rw-r--r--services/companion/java/com/android/server/companion/utils/MetricUtils.java8
-rw-r--r--services/companion/java/com/android/server/companion/utils/PermissionsUtils.java6
-rw-r--r--services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java2
-rw-r--r--services/core/java/com/android/server/BinaryTransparencyService.java29
-rw-r--r--services/core/java/com/android/server/am/BatteryStatsService.java8
-rw-r--r--services/core/java/com/android/server/am/BroadcastHistory.java11
-rw-r--r--services/core/java/com/android/server/inputmethod/IInputMethodClientInvoker.java2
-rw-r--r--services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java4
-rw-r--r--services/core/java/com/android/server/inputmethod/InputMethodManagerService.java4
-rw-r--r--services/core/java/com/android/server/location/injector/SystemEmergencyHelper.java81
-rw-r--r--services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java5
-rw-r--r--services/core/java/com/android/server/media/LegacyDeviceRouteController.java5
-rw-r--r--services/core/java/com/android/server/media/MediaSessionService.java10
-rw-r--r--services/core/java/com/android/server/notification/NotificationManagerService.java4
-rw-r--r--services/core/java/com/android/server/pm/permission/PermissionManagerService.java15
-rw-r--r--services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionService.java48
-rw-r--r--services/core/java/com/android/server/theming/ThemeSettingsManager.java166
-rw-r--r--services/core/java/com/android/server/updates/CertPinInstallReceiver.java20
-rw-r--r--services/core/java/com/android/server/wallpaper/WallpaperManagerService.java11
-rw-r--r--services/core/java/com/android/server/wm/ActivityClientController.java11
-rw-r--r--services/core/java/com/android/server/wm/DisplayAreaPolicy.java3
-rw-r--r--services/core/java/com/android/server/wm/ImeInsetsSourceProvider.java17
-rw-r--r--services/core/java/com/android/server/wm/TaskChangeNotificationController.java25
-rw-r--r--services/core/java/com/android/server/wm/TrustedPresentationListenerController.java6
-rw-r--r--services/core/java/com/android/server/wm/WindowManagerInternal.java2
-rw-r--r--services/credentials/java/com/android/server/credentials/CreateRequestSession.java4
-rw-r--r--services/credentials/java/com/android/server/credentials/GetRequestSession.java7
-rw-r--r--services/credentials/java/com/android/server/credentials/MetricUtilities.java6
-rw-r--r--services/credentials/java/com/android/server/credentials/metrics/ChosenProviderFinalPhaseMetric.java12
-rw-r--r--services/credentials/java/com/android/server/credentials/metrics/RequestSessionMetric.java15
-rw-r--r--services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java7
-rw-r--r--services/java/com/android/server/flags.aconfig7
-rw-r--r--services/permission/java/com/android/server/permission/access/AccessPolicy.kt2
-rw-r--r--services/permission/java/com/android/server/permission/access/permission/AppIdPermissionPolicy.kt176
-rw-r--r--services/permission/java/com/android/server/permission/access/permission/AppIdPermissionUpgrade.kt222
-rw-r--r--services/tests/PermissionServiceMockingTests/src/com/android/server/permission/test/AppIdPermissionPolicyPermissionStatesTest.kt605
-rw-r--r--services/tests/PermissionServiceMockingTests/src/com/android/server/permission/test/BasePermissionPolicyTest.kt301
-rw-r--r--services/tests/mockingservicestests/src/com/android/server/wallpaper/WallpaperManagerServiceTests.java77
-rw-r--r--services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java39
-rw-r--r--services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsRule.java2
-rw-r--r--services/tests/servicestests/Android.bp11
-rw-r--r--services/tests/servicestests/src/com/android/server/accessibility/autoclick/AutoclickControllerTest.java121
-rw-r--r--services/tests/servicestests/src/com/android/server/media/LegacyDeviceRouteControllerTest.java28
-rw-r--r--services/tests/servicestests/src/com/android/server/security/advancedprotection/AdvancedProtectionServiceTest.java254
-rw-r--r--services/tests/servicestests/src/com/android/server/theming/FieldColorBothTests.java99
-rw-r--r--services/tests/servicestests/src/com/android/server/theming/FieldColorIndexTests.java103
-rw-r--r--services/tests/servicestests/src/com/android/server/theming/FieldColorSourceTests.java94
-rw-r--r--services/tests/servicestests/src/com/android/server/theming/FieldColorTests.java107
-rw-r--r--services/tests/servicestests/src/com/android/server/theming/FieldThemeStyleTests.java86
-rw-r--r--services/tests/servicestests/src/com/android/server/theming/TEST_MAPPING7
-rw-r--r--services/tests/servicestests/src/com/android/server/theming/ThemeSettingsFieldTests.java169
-rw-r--r--services/tests/servicestests/src/com/android/server/theming/ThemeSettingsManagerTests.java114
-rw-r--r--services/tests/servicestests/src/com/android/server/theming/ThemeSettingsTests.java108
-rw-r--r--services/tests/servicestests/src/com/android/server/theming/ThemeSettingsUpdaterTests.java154
-rw-r--r--services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java52
-rw-r--r--services/usage/java/com/android/server/usage/StorageStatsService.java73
-rw-r--r--tests/AppJankTest/src/android/app/jank/tests/IntegrationTests.java42
-rw-r--r--tests/AppJankTest/src/android/app/jank/tests/JankUtils.java12
-rw-r--r--tests/Input/src/android/hardware/input/InputDeviceBatteryListenerTest.kt101
-rw-r--r--tests/Input/src/android/hardware/input/InputManagerTest.kt15
-rw-r--r--tests/Input/src/android/hardware/input/KeyGestureEventHandlerTest.kt126
-rw-r--r--tests/Input/src/android/hardware/input/KeyGestureEventListenerTest.kt66
-rw-r--r--tests/Input/src/android/hardware/input/KeyboardBacklightListenerTest.kt67
-rw-r--r--tests/Input/src/android/hardware/input/KeyboardLayoutPreviewTests.kt5
-rw-r--r--tests/Input/src/android/hardware/input/StickyModifierStateListenerTest.kt62
-rw-r--r--tests/Input/src/com/android/server/input/AmbientKeyboardBacklightControllerTests.kt138
-rw-r--r--tests/Input/src/com/android/server/input/BatteryControllerTests.kt321
-rw-r--r--tests/Input/src/com/android/server/input/InputDataStoreTests.kt504
-rw-r--r--tests/Input/src/com/android/server/input/InputGestureManagerTests.kt150
-rw-r--r--tests/Input/src/com/android/server/input/InputManagerServiceTests.kt296
-rw-r--r--tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt694
-rw-r--r--tests/Input/src/com/android/server/input/KeyRemapperTests.kt76
-rw-r--r--tests/Input/src/com/android/server/input/KeyboardBacklightControllerTests.kt237
-rw-r--r--tests/Input/src/com/android/server/input/KeyboardGlyphManagerTests.kt50
-rw-r--r--tests/Input/src/com/android/server/input/KeyboardLayoutManagerTests.kt603
-rw-r--r--tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt148
-rw-r--r--tests/Input/src/com/android/server/input/PointerIconCacheTest.kt20
-rw-r--r--tests/Input/src/com/android/test/input/InputEventAssignerTest.kt70
-rw-r--r--tests/Input/src/com/android/test/input/InputEventSenderAndReceiverTest.kt27
-rw-r--r--tests/Input/src/com/android/test/input/KeyCharacterMapTest.kt31
-rw-r--r--tests/Input/src/com/android/test/input/MockInputManagerRule.kt4
-rw-r--r--tests/Input/src/com/android/test/input/MotionPredictorTest.kt72
-rw-r--r--tests/Input/src/com/android/test/input/PointerEventDispatcherTest.kt15
-rw-r--r--tests/Input/src/com/android/test/input/PointerIconLoadingTest.kt86
-rw-r--r--tests/Input/src/com/android/test/input/SpyInputEventSenderAndReceiver.kt6
-rw-r--r--tests/Input/src/com/android/test/input/UinputRecordingIntegrationTests.kt81
-rw-r--r--tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt14
-rw-r--r--tests/Input/src/com/android/test/input/ViewFrameInfoTest.kt7
-rw-r--r--tests/Tracing/src/com/android/internal/protolog/ProcessedPerfettoProtoLogImplTest.java2
351 files changed, 11911 insertions, 4903 deletions
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
index e862cd9e0a95..843fde7baf2b 100644
--- a/PREUPLOAD.cfg
+++ b/PREUPLOAD.cfg
@@ -19,7 +19,7 @@ clang_format = --commit ${PREUPLOAD_COMMIT} --style file --extensions c,h,cc,cpp
tests/
tools/
bpfmt = -d
-ktfmt = --kotlinlang-style --include-dirs=services/permission,packages/SystemUI,libs/WindowManager/Shell/src/com/android/wm/shell/freeform,libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode,libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode,apct-tests
+ktfmt = --kotlinlang-style --include-dirs=services/permission,packages/SystemUI,libs/WindowManager/Shell/src/com/android/wm/shell/freeform,libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode,libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode,apct-tests,tests/Input
[Hook Scripts]
checkstyle_hook = ${REPO_ROOT}/prebuilts/checkstyle/checkstyle.py --sha ${PREUPLOAD_COMMIT}
diff --git a/cmds/uinput/src/com/android/commands/uinput/EvemuParser.java b/cmds/uinput/src/com/android/commands/uinput/EvemuParser.java
index d3e62d5351f0..017d9563b9a8 100644
--- a/cmds/uinput/src/com/android/commands/uinput/EvemuParser.java
+++ b/cmds/uinput/src/com/android/commands/uinput/EvemuParser.java
@@ -61,17 +61,18 @@ public class EvemuParser implements EventParser {
mReader = in;
}
- private @Nullable String findNextLine() throws IOException {
+ private void findNextLine() throws IOException {
String line = "";
while (line != null && line.length() == 0) {
String unstrippedLine = mReader.readLine();
if (unstrippedLine == null) {
mAtEndOfFile = true;
- return null;
+ mNextLine = null;
+ return;
}
line = stripComments(unstrippedLine);
}
- return line;
+ mNextLine = line;
}
private static String stripComments(String line) {
@@ -92,7 +93,7 @@ public class EvemuParser implements EventParser {
*/
public @Nullable String peekLine() throws IOException {
if (mNextLine == null && !mAtEndOfFile) {
- mNextLine = findNextLine();
+ findNextLine();
}
return mNextLine;
}
@@ -103,7 +104,10 @@ public class EvemuParser implements EventParser {
mNextLine = null;
}
- public boolean isAtEndOfFile() {
+ public boolean isAtEndOfFile() throws IOException {
+ if (mNextLine == null && !mAtEndOfFile) {
+ findNextLine();
+ }
return mAtEndOfFile;
}
diff --git a/cmds/uinput/tests/src/com/android/commands/uinput/tests/EvemuParserTest.java b/cmds/uinput/tests/src/com/android/commands/uinput/tests/EvemuParserTest.java
index 5239fbc7e0a8..f18cab51fb4d 100644
--- a/cmds/uinput/tests/src/com/android/commands/uinput/tests/EvemuParserTest.java
+++ b/cmds/uinput/tests/src/com/android/commands/uinput/tests/EvemuParserTest.java
@@ -216,6 +216,9 @@ public class EvemuParserTest {
assertInjectEvent(parser.getNextEvent(), 0x2, 0x0, 1, -1);
assertInjectEvent(parser.getNextEvent(), 0x2, 0x1, -2);
assertInjectEvent(parser.getNextEvent(), 0x0, 0x0, 0);
+
+ // Now we should be at the end of the file.
+ assertThat(parser.getNextEvent()).isNull();
}
@Test
@@ -246,6 +249,8 @@ public class EvemuParserTest {
assertInjectEvent(parser.getNextEvent(), 0x1, 0x15, 1, 1_000_000);
assertInjectEvent(parser.getNextEvent(), 0x0, 0x0, 0);
+
+ assertThat(parser.getNextEvent()).isNull();
}
@Test
diff --git a/core/api/current.txt b/core/api/current.txt
index bba21f418e41..151a6738505c 100644
--- a/core/api/current.txt
+++ b/core/api/current.txt
@@ -286,7 +286,7 @@ package android {
field public static final String REQUEST_COMPANION_PROFILE_COMPUTER = "android.permission.REQUEST_COMPANION_PROFILE_COMPUTER";
field public static final String REQUEST_COMPANION_PROFILE_GLASSES = "android.permission.REQUEST_COMPANION_PROFILE_GLASSES";
field public static final String REQUEST_COMPANION_PROFILE_NEARBY_DEVICE_STREAMING = "android.permission.REQUEST_COMPANION_PROFILE_NEARBY_DEVICE_STREAMING";
- field @FlaggedApi("android.companion.virtualdevice.flags.enable_limited_vdm_role") public static final String REQUEST_COMPANION_PROFILE_SENSOR_DEVICE_STREAMING = "android.permission.REQUEST_COMPANION_PROFILE_SENSOR_DEVICE_STREAMING";
+ field @FlaggedApi("android.companion.virtualdevice.flags.enable_limited_vdm_role") public static final String REQUEST_COMPANION_PROFILE_VIRTUAL_DEVICE = "android.permission.REQUEST_COMPANION_PROFILE_VIRTUAL_DEVICE";
field public static final String REQUEST_COMPANION_PROFILE_WATCH = "android.permission.REQUEST_COMPANION_PROFILE_WATCH";
field public static final String REQUEST_COMPANION_RUN_IN_BACKGROUND = "android.permission.REQUEST_COMPANION_RUN_IN_BACKGROUND";
field public static final String REQUEST_COMPANION_SELF_MANAGED = "android.permission.REQUEST_COMPANION_SELF_MANAGED";
@@ -2483,7 +2483,6 @@ package android {
field public static final int primary = 16908300; // 0x102000c
field public static final int progress = 16908301; // 0x102000d
field public static final int redo = 16908339; // 0x1020033
- field @FlaggedApi("android.appwidget.flags.engagement_metrics") public static final int remoteViewsMetricsId;
field public static final int replaceText = 16908340; // 0x1020034
field public static final int secondaryProgress = 16908303; // 0x102000f
field public static final int selectAll = 16908319; // 0x102001f
@@ -10086,7 +10085,7 @@ package android.companion {
field @RequiresPermission(android.Manifest.permission.REQUEST_COMPANION_PROFILE_COMPUTER) public static final String DEVICE_PROFILE_COMPUTER = "android.app.role.COMPANION_DEVICE_COMPUTER";
field @RequiresPermission(android.Manifest.permission.REQUEST_COMPANION_PROFILE_GLASSES) public static final String DEVICE_PROFILE_GLASSES = "android.app.role.COMPANION_DEVICE_GLASSES";
field @RequiresPermission(android.Manifest.permission.REQUEST_COMPANION_PROFILE_NEARBY_DEVICE_STREAMING) public static final String DEVICE_PROFILE_NEARBY_DEVICE_STREAMING = "android.app.role.COMPANION_DEVICE_NEARBY_DEVICE_STREAMING";
- field @FlaggedApi("android.companion.virtualdevice.flags.enable_limited_vdm_role") @RequiresPermission(android.Manifest.permission.REQUEST_COMPANION_PROFILE_SENSOR_DEVICE_STREAMING) public static final String DEVICE_PROFILE_SENSOR_DEVICE_STREAMING = "android.app.role.COMPANION_DEVICE_SENSOR_DEVICE_STREAMING";
+ field @FlaggedApi("android.companion.virtualdevice.flags.enable_limited_vdm_role") @RequiresPermission(android.Manifest.permission.REQUEST_COMPANION_PROFILE_VIRTUAL_DEVICE) public static final String DEVICE_PROFILE_VIRTUAL_DEVICE = "android.app.role.COMPANION_DEVICE_VIRTUAL_DEVICE";
field public static final String DEVICE_PROFILE_WATCH = "android.app.role.COMPANION_DEVICE_WATCH";
}
@@ -61755,6 +61754,7 @@ package android.widget {
method public void setTextViewText(@IdRes int, CharSequence);
method public void setTextViewTextSize(@IdRes int, int, float);
method public void setUri(@IdRes int, String, android.net.Uri);
+ method @FlaggedApi("android.appwidget.flags.engagement_metrics") public void setUsageEventTag(@IdRes int, int);
method public void setViewLayoutHeight(@IdRes int, float, int);
method public void setViewLayoutHeightAttr(@IdRes int, @AttrRes int);
method public void setViewLayoutHeightDimen(@IdRes int, @DimenRes int);
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index d5df48a2ea22..c129fde3f819 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -3174,6 +3174,15 @@ public class Activity extends ContextThemeWrapper
throw new IllegalArgumentException("Expected non-null picture-in-picture params");
}
if (!mCanEnterPictureInPicture) {
+ if (isTvImplicitEnterPipProhibited()) {
+ // Don't throw exception on TV so that apps don't crash when not adapted to new
+ // restrictions.
+ Log.e(TAG,
+ "Activity must be resumed to enter picture-in-picture and not about to be"
+ + " paused. Implicit app entry is only permitted on TV if android"
+ + ".permission.TV_IMPLICIT_ENTER_PIP is held by the app.");
+ return false;
+ }
throw new IllegalStateException("Activity must be resumed to enter"
+ " picture-in-picture");
}
@@ -3212,7 +3221,7 @@ public class Activity extends ContextThemeWrapper
return ActivityTaskManager.getMaxNumPictureInPictureActions(this);
}
- private boolean isImplicitEnterPipProhibited() {
+ private boolean isTvImplicitEnterPipProhibited() {
PackageManager pm = getPackageManager();
if (android.app.Flags.enableTvImplicitEnterPipRestriction()) {
return pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK)
@@ -9346,7 +9355,7 @@ public class Activity extends ContextThemeWrapper
+ mComponent.getClassName());
}
- if (isImplicitEnterPipProhibited()) {
+ if (isTvImplicitEnterPipProhibited()) {
mCanEnterPictureInPicture = false;
}
@@ -9376,7 +9385,7 @@ public class Activity extends ContextThemeWrapper
final void performUserLeaving() {
onUserInteraction();
- if (isImplicitEnterPipProhibited()) {
+ if (isTvImplicitEnterPipProhibited()) {
mCanEnterPictureInPicture = false;
}
onUserLeaveHint();
diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java
index f5277fd86a57..521b70b599f6 100644
--- a/core/java/android/app/Notification.java
+++ b/core/java/android/app/Notification.java
@@ -3253,9 +3253,24 @@ public class Notification implements Parcelable
* @hide
*/
public boolean hasTitle() {
- return extras != null
- && (!TextUtils.isEmpty(extras.getCharSequence(EXTRA_TITLE))
- || !TextUtils.isEmpty(extras.getCharSequence(EXTRA_TITLE_BIG)));
+ if (extras == null) {
+ return false;
+ }
+ // CallStyle notifications only use the other person's name as the title.
+ if (isStyle(CallStyle.class)) {
+ Person person = extras.getParcelable(EXTRA_CALL_PERSON, Person.class);
+ return person != null && !TextUtils.isEmpty(person.getName());
+ }
+ // non-CallStyle notifications can use EXTRA_TITLE
+ if (!TextUtils.isEmpty(extras.getCharSequence(EXTRA_TITLE))) {
+ return true;
+ }
+ // BigTextStyle notifications first use EXTRA_TITLE_BIG
+ if (isStyle(BigTextStyle.class)) {
+ return !TextUtils.isEmpty(extras.getCharSequence(EXTRA_TITLE_BIG));
+ } else {
+ return false;
+ }
}
/**
@@ -3280,12 +3295,23 @@ public class Notification implements Parcelable
*/
@FlaggedApi(Flags.FLAG_API_RICH_ONGOING)
public boolean hasPromotableCharacteristics() {
- return isColorizedRequested()
- && isOngoingEvent()
- && hasTitle()
- && !isGroupSummary()
- && !containsCustomViews()
- && hasPromotableStyle();
+ if (!isOngoingEvent() || isGroupSummary() || containsCustomViews() || !hasTitle()) {
+ return false;
+ }
+ // Only "Ongoing CallStyle" notifications are promotable without EXTRA_COLORIZED
+ if (isOngoingCallStyle()) {
+ return true;
+ }
+ return isColorizedRequested() && hasPromotableStyle();
+ }
+
+ /** Returns whether the notification is CallStyle.forOngoingCall(). */
+ private boolean isOngoingCallStyle() {
+ if (!isStyle(CallStyle.class)) {
+ return false;
+ }
+ int callType = extras.getInt(EXTRA_CALL_TYPE, CallStyle.CALL_TYPE_UNKNOWN);
+ return callType == CallStyle.CALL_TYPE_ONGOING;
}
/**
@@ -6096,6 +6122,21 @@ public class Notification implements Parcelable
return mColors;
}
+ private void updateHeaderBackgroundColor(RemoteViews contentView,
+ StandardTemplateParams p) {
+ if (!Flags.uiRichOngoing()) {
+ return;
+ }
+ if (isBackgroundColorized(p)) {
+ contentView.setInt(R.id.notification_header, "setBackgroundColor",
+ getBackgroundColor(p));
+ } else {
+ // Clear it!
+ contentView.setInt(R.id.notification_header, "setBackgroundResource",
+ 0);
+ }
+ }
+
private void updateBackgroundColor(RemoteViews contentView,
StandardTemplateParams p) {
if (isBackgroundColorized(p)) {
@@ -6900,7 +6941,7 @@ public class Notification implements Parcelable
* @hide
*/
public RemoteViews makeNotificationGroupHeader() {
- return makeNotificationHeader(mParams.reset()
+ return makeNotificationHeader(mParams.reset().disallowColorization()
.viewType(StandardTemplateParams.VIEW_TYPE_GROUP_HEADER)
.fillTextsFrom(this));
}
@@ -6912,12 +6953,11 @@ public class Notification implements Parcelable
* @param p the template params to inflate this with
*/
private RemoteViews makeNotificationHeader(StandardTemplateParams p) {
- // Headers on their own are never colorized
- p.disallowColorization();
RemoteViews header = new BuilderRemoteViews(mContext.getApplicationInfo(),
getHeaderLayoutResource());
resetNotificationHeader(header);
bindNotificationHeader(header, p);
+ updateHeaderBackgroundColor(header, p);
if (Flags.notificationsRedesignTemplates()
&& (p.mViewType == StandardTemplateParams.VIEW_TYPE_MINIMIZED
|| p.mViewType == StandardTemplateParams.VIEW_TYPE_PUBLIC)) {
@@ -7041,6 +7081,10 @@ public class Notification implements Parcelable
savedBundle.getBoolean(EXTRA_SHOW_CHRONOMETER));
publicExtras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN,
savedBundle.getBoolean(EXTRA_CHRONOMETER_COUNT_DOWN));
+ if (mN.isPromotedOngoing()) {
+ publicExtras.putBoolean(EXTRA_COLORIZED,
+ savedBundle.getBoolean(EXTRA_COLORIZED));
+ }
String appName = savedBundle.getString(EXTRA_SUBSTITUTE_APP_NAME);
if (appName != null) {
publicExtras.putString(EXTRA_SUBSTITUTE_APP_NAME, appName);
@@ -7053,6 +7097,9 @@ public class Notification implements Parcelable
if (isLowPriority) {
params.highlightExpander(false);
}
+ if (!mN.isPromotedOngoing()) {
+ params.disallowColorization();
+ }
view = makeNotificationHeader(params);
view.setBoolean(R.id.notification_header, "setExpandOnlyOnButton", true);
mN.extras = savedBundle;
@@ -7072,7 +7119,7 @@ public class Notification implements Parcelable
* @hide
*/
public RemoteViews makeLowPriorityContentView(boolean useRegularSubtext) {
- StandardTemplateParams p = mParams.reset()
+ StandardTemplateParams p = mParams.reset().disallowColorization()
.viewType(StandardTemplateParams.VIEW_TYPE_MINIMIZED)
.highlightExpander(false)
.fillTextsFrom(this);
diff --git a/core/java/android/app/jank/JankTracker.java b/core/java/android/app/jank/JankTracker.java
index e3f67811757c..a085701b006a 100644
--- a/core/java/android/app/jank/JankTracker.java
+++ b/core/java/android/app/jank/JankTracker.java
@@ -143,6 +143,13 @@ public class JankTracker {
* stats
*/
public void mergeAppJankStats(AppJankStats appJankStats) {
+ if (appJankStats.getUid() != mAppUid) {
+ if (DEBUG) {
+ Log.d(DEBUG_KEY, "Reported JankStats AppUID does not match AppUID of "
+ + "enclosing activity.");
+ }
+ return;
+ }
getHandler().post(new Runnable() {
@Override
public void run() {
diff --git a/core/java/android/app/usage/IStorageStatsManager.aidl b/core/java/android/app/usage/IStorageStatsManager.aidl
index b5036da33a95..390300360c8f 100644
--- a/core/java/android/app/usage/IStorageStatsManager.aidl
+++ b/core/java/android/app/usage/IStorageStatsManager.aidl
@@ -30,6 +30,7 @@ interface IStorageStatsManager {
long getCacheBytes(String volumeUuid, String callingPackage);
long getCacheQuotaBytes(String volumeUuid, int uid, String callingPackage);
StorageStats queryStatsForPackage(String volumeUuid, String packageName, int userId, String callingPackage);
+ StorageStats queryArtManagedStats(String packageName, int userId, int uid);
StorageStats queryStatsForUid(String volumeUuid, int uid, String callingPackage);
StorageStats queryStatsForUser(String volumeUuid, int userId, String callingPackage);
ExternalStorageStats queryExternalStatsForUser(String volumeUuid, int userId, String callingPackage);
diff --git a/core/java/android/app/usage/StorageStats.java b/core/java/android/app/usage/StorageStats.java
index 7bfaef4e9857..d01b423d67f2 100644
--- a/core/java/android/app/usage/StorageStats.java
+++ b/core/java/android/app/usage/StorageStats.java
@@ -22,7 +22,10 @@ import android.annotation.IntDef;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
+import android.os.RemoteException;
+import android.os.ServiceManager;
import android.os.UserHandle;
+import android.util.Log;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -34,6 +37,9 @@ import java.lang.annotation.RetentionPolicy;
* @see StorageStatsManager
*/
public final class StorageStats implements Parcelable {
+ /** @hide */ public String packageName;
+ /** @hide */ public int userHandle;
+ /** @hide */ public int uid;
/** @hide */ public long codeBytes;
/** @hide */ public long dataBytes;
/** @hide */ public long cacheBytes;
@@ -130,6 +136,14 @@ public final class StorageStats implements Parcelable {
@Retention(RetentionPolicy.SOURCE)
public @interface AppDataType {}
+ private static final String TAG = "StorageStats";
+
+ /**
+ * artStatsFetched is only applicable when
+ * Flags.getAppArtManagedBytes() is true;
+ */
+ private boolean artStatsFetched;
+
/**
* Return the size of app. This includes {@code APK} files, optimized
* compiler output, and unpacked native libraries.
@@ -157,9 +171,9 @@ public final class StorageStats implements Parcelable {
@FlaggedApi(Flags.FLAG_GET_APP_BYTES_BY_DATA_TYPE_API)
public long getAppBytesByDataType(@AppDataType int dataType) {
switch (dataType) {
- case APP_DATA_TYPE_FILE_TYPE_DEXOPT_ARTIFACT: return dexoptBytes;
- case APP_DATA_TYPE_FILE_TYPE_REFERENCE_PROFILE: return refProfBytes;
- case APP_DATA_TYPE_FILE_TYPE_CURRENT_PROFILE: return curProfBytes;
+ case APP_DATA_TYPE_FILE_TYPE_DEXOPT_ARTIFACT: return getDexoptBytes();
+ case APP_DATA_TYPE_FILE_TYPE_REFERENCE_PROFILE: return getRefProfBytes();
+ case APP_DATA_TYPE_FILE_TYPE_CURRENT_PROFILE: return getCurProfBytes();
case APP_DATA_TYPE_FILE_TYPE_APK: return apkBytes;
case APP_DATA_TYPE_LIB: return libBytes;
case APP_DATA_TYPE_FILE_TYPE_DM: return dmBytes;
@@ -215,6 +229,9 @@ public final class StorageStats implements Parcelable {
/** {@hide} */
public StorageStats(Parcel in) {
+ this.packageName = in.readString8();
+ this.userHandle = in.readInt();
+ this.uid = in.readInt();
this.codeBytes = in.readLong();
this.dataBytes = in.readLong();
this.cacheBytes = in.readLong();
@@ -234,6 +251,9 @@ public final class StorageStats implements Parcelable {
@Override
public void writeToParcel(Parcel dest, int flags) {
+ dest.writeString8(packageName);
+ dest.writeInt(userHandle);
+ dest.writeInt(uid);
dest.writeLong(codeBytes);
dest.writeLong(dataBytes);
dest.writeLong(cacheBytes);
@@ -257,4 +277,42 @@ public final class StorageStats implements Parcelable {
return new StorageStats[size];
}
};
+
+ private void getArtManagedStats() {
+ try {
+ IStorageStatsManager storageStatsManagerService;
+ // Fetch art stats only if it is not already fetched.
+ if (Flags.getAppArtManagedBytes() && !artStatsFetched) {
+ android.os.IBinder binder = ServiceManager.getService("storagestats");
+ storageStatsManagerService = IStorageStatsManager.Stub.asInterface(binder);
+
+ StorageStats newStats =
+ storageStatsManagerService.queryArtManagedStats(packageName, userHandle, uid);
+
+ dexoptBytes = newStats.dexoptBytes;
+ curProfBytes = newStats.curProfBytes;
+ refProfBytes = newStats.refProfBytes;
+
+ artStatsFetched = true;
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to get art stats", e);
+ e.rethrowFromSystemServer();
+ }
+ }
+
+ private long getDexoptBytes() {
+ getArtManagedStats();
+ return dexoptBytes;
+ }
+
+ private long getCurProfBytes() {
+ getArtManagedStats();
+ return curProfBytes;
+ }
+
+ private long getRefProfBytes() {
+ getArtManagedStats();
+ return refProfBytes;
+ }
}
diff --git a/core/java/android/app/usage/flags.aconfig b/core/java/android/app/usage/flags.aconfig
index 04c36867271c..520284993841 100644
--- a/core/java/android/app/usage/flags.aconfig
+++ b/core/java/android/app/usage/flags.aconfig
@@ -49,6 +49,16 @@ flag {
}
flag {
+ name: "get_app_art_managed_bytes"
+ namespace: "system_performance"
+ description: "Bug fixing flag for optional collection of app ART managed file stats"
+ bug: "395548922"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
+flag {
name: "disable_idle_check"
namespace: "backstage_power"
description: "disable idle check for USER_SYSTEM during boot up"
diff --git a/core/java/android/appwidget/AppWidgetHostView.java b/core/java/android/appwidget/AppWidgetHostView.java
index b9b5c6a8bbc3..33326347fda0 100644
--- a/core/java/android/appwidget/AppWidgetHostView.java
+++ b/core/java/android/appwidget/AppWidgetHostView.java
@@ -16,10 +16,15 @@
package android.appwidget;
+import static android.appwidget.flags.Flags.FLAG_ENGAGEMENT_METRICS;
+import static android.appwidget.flags.Flags.engagementMetrics;
+
+import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.Activity;
import android.app.ActivityOptions;
+import android.app.PendingIntent;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.ComponentName;
import android.content.Context;
@@ -38,6 +43,7 @@ import android.os.Build;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.Parcelable;
+import android.util.ArraySet;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Pair;
@@ -48,6 +54,7 @@ import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo;
+import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
@@ -57,8 +64,11 @@ import android.widget.RemoteViews.InteractionHandler;
import android.widget.RemoteViewsAdapter.RemoteAdapterConnectionCallback;
import android.widget.TextView;
+import com.android.internal.annotations.VisibleForTesting;
+
import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.Executor;
/**
@@ -99,7 +109,8 @@ public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppW
int mViewMode = VIEW_MODE_NOINIT;
// If true, we should not try to re-apply the RemoteViews on the next inflation.
boolean mColorMappingChanged = false;
- private InteractionHandler mInteractionHandler;
+ @NonNull
+ private InteractionLogger mInteractionLogger = new InteractionLogger();
private boolean mOnLightBackground;
private SizeF mCurrentSize = null;
private RemoteViews.ColorResources mColorResources = null;
@@ -124,7 +135,7 @@ public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppW
*/
public AppWidgetHostView(Context context, InteractionHandler handler) {
this(context, android.R.anim.fade_in, android.R.anim.fade_out);
- mInteractionHandler = getHandler(handler);
+ setInteractionHandler(handler);
}
/**
@@ -145,13 +156,29 @@ public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppW
/**
* Pass the given handler to RemoteViews when updating this widget. Unless this
- * is done immediatly after construction, a call to {@link #updateAppWidget(RemoteViews)}
+ * is done immediately after construction, a call to {@link #updateAppWidget(RemoteViews)}
* should be made.
*
* @hide
*/
public void setInteractionHandler(InteractionHandler handler) {
- mInteractionHandler = getHandler(handler);
+ if (handler instanceof InteractionLogger logger) {
+ // Nested AppWidgetHostViews should reuse the parent logger instead of wrapping it.
+ mInteractionLogger = logger;
+ } else {
+ mInteractionLogger = new InteractionLogger(handler);
+ }
+ }
+
+ /**
+ * Return the InteractionLogger used by this class.
+ *
+ * @hide
+ */
+ @VisibleForTesting
+ @NonNull
+ public InteractionLogger getInteractionLogger() {
+ return mInteractionLogger;
}
/**
@@ -588,7 +615,7 @@ public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppW
if (!mColorMappingChanged && rvToApply.canRecycleView(mView)) {
try {
- rvToApply.reapply(mContext, mView, mInteractionHandler, mCurrentSize,
+ rvToApply.reapply(mContext, mView, mInteractionLogger, mCurrentSize,
mColorResources);
content = mView;
mLastInflatedRemoteViewsId = rvToApply.computeUniqueId(remoteViews);
@@ -602,7 +629,7 @@ public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppW
// Try normal RemoteView inflation
if (content == null) {
try {
- content = rvToApply.apply(mContext, this, mInteractionHandler,
+ content = rvToApply.apply(mContext, this, mInteractionLogger,
mCurrentSize, mColorResources);
mLastInflatedRemoteViewsId = rvToApply.computeUniqueId(remoteViews);
if (LOGD) Log.d(TAG, "had to inflate new layout");
@@ -660,7 +687,7 @@ public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppW
mView,
mAsyncExecutor,
new ViewApplyListener(remoteViews, layoutId, true),
- mInteractionHandler,
+ mInteractionLogger,
mCurrentSize,
mColorResources);
} catch (Exception e) {
@@ -672,7 +699,7 @@ public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppW
this,
mAsyncExecutor,
new ViewApplyListener(remoteViews, layoutId, false),
- mInteractionHandler,
+ mInteractionLogger,
mCurrentSize,
mColorResources);
}
@@ -711,7 +738,7 @@ public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppW
AppWidgetHostView.this,
mAsyncExecutor,
new ViewApplyListener(mViews, mLayoutId, false),
- mInteractionHandler,
+ mInteractionLogger,
mCurrentSize);
} else {
applyContent(null, false, e);
@@ -916,21 +943,6 @@ public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppW
return null;
}
- private InteractionHandler getHandler(InteractionHandler handler) {
- return (view, pendingIntent, response) -> {
- AppWidgetManager manager = AppWidgetManager.getInstance(mContext);
- if (manager != null) {
- manager.noteAppWidgetTapped(mAppWidgetId);
- }
- if (handler != null) {
- return handler.onInteraction(view, pendingIntent, response);
- } else {
- return RemoteViews.startPendingIntent(view, pendingIntent,
- response.getLaunchOptions(view));
- }
- };
- }
-
/**
* Set the dynamically overloaded color resources.
*
@@ -1016,4 +1028,83 @@ public class AppWidgetHostView extends FrameLayout implements AppWidgetHost.AppW
post(this::handleViewError);
}
}
+
+ /**
+ * This class is used to track user interactions with this widget.
+ * @hide
+ */
+ public class InteractionLogger implements RemoteViews.InteractionHandler {
+ // Max number of clicked and scrolled IDs stored per impression.
+ public static final int MAX_NUM_ITEMS = 10;
+ // Clicked views
+ @NonNull
+ private final Set<Integer> mClickedIds = new ArraySet<>(MAX_NUM_ITEMS);
+ // Scrolled views
+ @NonNull
+ private final Set<Integer> mScrolledIds = new ArraySet<>(MAX_NUM_ITEMS);
+ @Nullable
+ private RemoteViews.InteractionHandler mInteractionHandler = null;
+
+ InteractionLogger() {
+ }
+
+ InteractionLogger(@Nullable InteractionHandler handler) {
+ mInteractionHandler = handler;
+ }
+
+ @VisibleForTesting
+ @NonNull
+ public Set<Integer> getClickedIds() {
+ return mClickedIds;
+ }
+
+ @VisibleForTesting
+ @NonNull
+ public Set<Integer> getScrolledIds() {
+ return mScrolledIds;
+ }
+
+ @Override
+ public boolean onInteraction(View view, PendingIntent pendingIntent,
+ RemoteViews.RemoteResponse response) {
+ if (engagementMetrics() && mClickedIds.size() < MAX_NUM_ITEMS) {
+ mClickedIds.add(getMetricsId(view));
+ }
+ AppWidgetManager manager = AppWidgetManager.getInstance(mContext);
+ if (manager != null) {
+ manager.noteAppWidgetTapped(mAppWidgetId);
+ }
+
+ if (mInteractionHandler != null) {
+ return mInteractionHandler.onInteraction(view, pendingIntent, response);
+ } else {
+ return RemoteViews.startPendingIntent(view, pendingIntent,
+ response.getLaunchOptions(view));
+ }
+ }
+
+ @Override
+ public void onScroll(@NonNull AbsListView view) {
+ if (!engagementMetrics()) return;
+
+ if (mScrolledIds.size() < MAX_NUM_ITEMS) {
+ mScrolledIds.add(getMetricsId(view));
+ }
+
+ if (mInteractionHandler != null) {
+ mInteractionHandler.onScroll(view);
+ }
+ }
+
+ @FlaggedApi(FLAG_ENGAGEMENT_METRICS)
+ private int getMetricsId(@NonNull View view) {
+ int viewId = view.getId();
+ Object metricsTag = view.getTag(com.android.internal.R.id.remoteViewsMetricsId);
+ if (metricsTag instanceof Integer tag) {
+ viewId = tag;
+ }
+ return viewId;
+ }
+ }
}
+
diff --git a/core/java/android/appwidget/AppWidgetManager.java b/core/java/android/appwidget/AppWidgetManager.java
index b54e17beb100..52315d68afda 100644
--- a/core/java/android/appwidget/AppWidgetManager.java
+++ b/core/java/android/appwidget/AppWidgetManager.java
@@ -515,12 +515,13 @@ public class AppWidgetManager {
/**
* This bundle extra describes which views have been clicked during a single impression of the
- * widget. It is an integer array of view IDs of the clicked views.
+ * widget. It is an integer array of view IDs of the clicked views. The array may contain up to
+ * 10 distinct IDs per event.
*
- * Widget providers may set a different ID for event purposes by setting the
- * {@link android.R.id.remoteViewsMetricsId} int tag on the view.
+ * Widget providers may set a different ID for event logging by setting the usage event tag on
+ * the view with {@link RemoteViews#setUsageEventTag}.
*
- * @see android.views.RemoteViews.setIntTag
+ * @see android.widget.RemoteViews#setUsageEventTag
*/
@FlaggedApi(Flags.FLAG_ENGAGEMENT_METRICS)
public static final String EXTRA_EVENT_CLICKED_VIEWS =
@@ -528,12 +529,13 @@ public class AppWidgetManager {
/**
* This bundle extra describes which views have been scrolled during a single impression of the
- * widget. It is an integer array of view IDs of the scrolled views.
+ * widget. It is an integer array of view IDs of the scrolled views. The array may contain up to
+ * 10 distinct IDs per event.
*
- * Widget providers may set a different ID for event purposes by setting the
- * {@link android.R.id.remoteViewsMetricsId} int tag on the view.
+ * Widget providers may set a different ID for event logging by setting the usage event tag on
+ * the view with {@link RemoteViews#setUsageEventTag}.
*
- * @see android.views.RemoteViews.setIntTag
+ * @see android.widget.RemoteViews#setUsageEventTag
*/
@FlaggedApi(Flags.FLAG_ENGAGEMENT_METRICS)
public static final String EXTRA_EVENT_SCROLLED_VIEWS =
diff --git a/core/java/android/companion/AssociationRequest.java b/core/java/android/companion/AssociationRequest.java
index 11e20e65d355..9641d7e69d4a 100644
--- a/core/java/android/companion/AssociationRequest.java
+++ b/core/java/android/companion/AssociationRequest.java
@@ -140,15 +140,15 @@ public final class AssociationRequest implements Parcelable {
* IMU between an Android host and a nearby device.
* <p>
* Only applications that have been granted
- * {@link android.Manifest.permission#REQUEST_COMPANION_PROFILE_SENSOR_DEVICE_STREAMING}
+ * {@link android.Manifest.permission#REQUEST_COMPANION_PROFILE_VIRTUAL_DEVICE}
* are allowed to request to be associated with such devices.
*
* @see AssociationRequest.Builder#setDeviceProfile
*/
@FlaggedApi(android.companion.virtualdevice.flags.Flags.FLAG_ENABLE_LIMITED_VDM_ROLE)
- @RequiresPermission(Manifest.permission.REQUEST_COMPANION_PROFILE_SENSOR_DEVICE_STREAMING)
- public static final String DEVICE_PROFILE_SENSOR_DEVICE_STREAMING =
- "android.app.role.COMPANION_DEVICE_SENSOR_DEVICE_STREAMING";
+ @RequiresPermission(Manifest.permission.REQUEST_COMPANION_PROFILE_VIRTUAL_DEVICE)
+ public static final String DEVICE_PROFILE_VIRTUAL_DEVICE =
+ "android.app.role.COMPANION_DEVICE_VIRTUAL_DEVICE";
/**
* Device profile: Android Automotive Projection
diff --git a/core/java/android/companion/virtual/flags/flags.aconfig b/core/java/android/companion/virtual/flags/flags.aconfig
index 161f05bc5139..c29f1528be89 100644
--- a/core/java/android/companion/virtual/flags/flags.aconfig
+++ b/core/java/android/companion/virtual/flags/flags.aconfig
@@ -154,7 +154,7 @@ flag {
flag {
namespace: "virtual_devices"
name: "viewconfiguration_apis"
- description: "APIs for settings ViewConfiguration attributes on virtual devices"
+ description: "APIs for setting ViewConfiguration attributes on virtual devices"
bug: "370720522"
is_exported: true
}
diff --git a/core/java/android/content/pm/multiuser.aconfig b/core/java/android/content/pm/multiuser.aconfig
index 3dbd5b239ae5..fefa8ab8f000 100644
--- a/core/java/android/content/pm/multiuser.aconfig
+++ b/core/java/android/content/pm/multiuser.aconfig
@@ -384,6 +384,16 @@ flag {
is_fixed_read_only: true
}
+flag {
+ name: "require_pin_before_user_deletion"
+ namespace: "multiuser"
+ description: "Require credential authentication when a user tries to delete themselves or another user"
+ bug: "342395399"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
# This flag guards the private space feature and all its implementations excluding the APIs. APIs are guarded by android.os.Flags.allow_private_profile.
flag {
name: "enable_private_space_features"
diff --git a/core/java/android/content/theming/FieldColor.java b/core/java/android/content/theming/FieldColor.java
new file mode 100644
index 000000000000..a06a54f362b5
--- /dev/null
+++ b/core/java/android/content/theming/FieldColor.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2025 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.content.theming;
+
+import android.annotation.ColorInt;
+import android.annotation.FlaggedApi;
+import android.graphics.Color;
+
+import androidx.annotation.Nullable;
+
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+
+/** @hide */
+@FlaggedApi(android.server.Flags.FLAG_ENABLE_THEME_SERVICE)
+public class FieldColor extends ThemeSettingsField<Integer, String> {
+ private static final Pattern COLOR_PATTERN = Pattern.compile("[0-9a-fA-F]{6,8}");
+
+ public FieldColor(
+ String key,
+ BiConsumer<ThemeSettingsUpdater, Integer> setter,
+ Function<ThemeSettings, Integer> getter,
+ ThemeSettings defaults
+ ) {
+ super(key, setter, getter, defaults);
+ }
+
+ @Override
+ @ColorInt
+ @Nullable
+ public Integer parse(String primitive) {
+ if (primitive == null) {
+ return null;
+ }
+ if (!COLOR_PATTERN.matcher(primitive).matches()) {
+ return null;
+ }
+
+ try {
+ return Color.valueOf(Color.parseColor("#" + primitive)).toArgb();
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public String serialize(@ColorInt Integer value) {
+ return Integer.toHexString(value);
+ }
+
+ @Override
+ public boolean validate(Integer value) {
+ return !value.equals(Color.TRANSPARENT);
+ }
+
+ @Override
+ public Class<Integer> getFieldType() {
+ return Integer.class;
+ }
+
+ @Override
+ public Class<String> getJsonType() {
+ return String.class;
+ }
+}
diff --git a/core/java/android/content/theming/FieldColorBoth.java b/core/java/android/content/theming/FieldColorBoth.java
new file mode 100644
index 000000000000..e4a9f7f716d8
--- /dev/null
+++ b/core/java/android/content/theming/FieldColorBoth.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2025 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.content.theming;
+
+import android.annotation.FlaggedApi;
+
+import androidx.annotation.Nullable;
+
+import java.util.Objects;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+
+/** @hide */
+@FlaggedApi(android.server.Flags.FLAG_ENABLE_THEME_SERVICE)
+public class FieldColorBoth extends ThemeSettingsField<Boolean, String> {
+ public FieldColorBoth(
+ String key,
+ BiConsumer<ThemeSettingsUpdater, Boolean> setter,
+ Function<ThemeSettings, Boolean> getter,
+ ThemeSettings defaults
+ ) {
+ super(key, setter, getter, defaults);
+ }
+
+ @Override
+ @Nullable
+ public Boolean parse(String primitive) {
+ return switch (primitive) {
+ case "1" -> true;
+ case "0" -> false;
+ default -> null;
+ };
+ }
+
+ @Override
+ public String serialize(Boolean typedValue) {
+ if (typedValue) return "1";
+ return "0";
+ }
+
+ @Override
+ public boolean validate(Boolean value) {
+ Objects.requireNonNull(value);
+ return true;
+ }
+
+ @Override
+ public Class<Boolean> getFieldType() {
+ return Boolean.class;
+ }
+
+ @Override
+ public Class<String> getJsonType() {
+ return String.class;
+ }
+}
diff --git a/core/java/android/content/theming/FieldColorIndex.java b/core/java/android/content/theming/FieldColorIndex.java
new file mode 100644
index 000000000000..683568a42318
--- /dev/null
+++ b/core/java/android/content/theming/FieldColorIndex.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2025 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.content.theming;
+
+import android.annotation.FlaggedApi;
+
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+
+/** @hide */
+@FlaggedApi(android.server.Flags.FLAG_ENABLE_THEME_SERVICE)
+public class FieldColorIndex extends ThemeSettingsField<Integer, String> {
+ public FieldColorIndex(
+ String key,
+ BiConsumer<ThemeSettingsUpdater, Integer> setter,
+ Function<ThemeSettings, Integer> getter,
+ ThemeSettings defaults
+ ) {
+ super(key, setter, getter, defaults);
+ }
+
+ @Override
+ public Integer parse(String primitive) {
+ try {
+ return Integer.parseInt(primitive);
+ } catch (NumberFormatException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public String serialize(Integer typedValue) {
+ return typedValue.toString();
+ }
+
+ @Override
+ public boolean validate(Integer value) {
+ return value >= -1;
+ }
+
+ @Override
+ public Class<Integer> getFieldType() {
+ return Integer.class;
+ }
+
+ @Override
+ public Class<String> getJsonType() {
+ return String.class;
+ }
+}
diff --git a/core/java/android/content/theming/FieldColorSource.java b/core/java/android/content/theming/FieldColorSource.java
new file mode 100644
index 000000000000..1ff3aa64fda5
--- /dev/null
+++ b/core/java/android/content/theming/FieldColorSource.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2025 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.content.theming;
+
+import android.annotation.FlaggedApi;
+import android.annotation.StringDef;
+
+import androidx.annotation.Nullable;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+
+/** @hide */
+@FlaggedApi(android.server.Flags.FLAG_ENABLE_THEME_SERVICE)
+public class FieldColorSource extends ThemeSettingsField<String, String> {
+ public FieldColorSource(
+ String key,
+ BiConsumer<ThemeSettingsUpdater, String> setter,
+ Function<ThemeSettings, String> getter,
+ ThemeSettings defaults
+ ) {
+ super(key, setter, getter, defaults);
+ }
+
+ @Override
+ @Nullable
+ @Type
+ public String parse(String primitive) {
+ return primitive;
+ }
+
+ @Override
+ public String serialize(@Type String typedValue) {
+ return typedValue;
+ }
+
+ @Override
+ public boolean validate(String value) {
+ return switch (value) {
+ case "preset", "home_wallpaper", "lock_wallpaper" -> true;
+ default -> false;
+ };
+ }
+
+ @Override
+ public Class<String> getFieldType() {
+ return String.class;
+ }
+
+ @Override
+ public Class<String> getJsonType() {
+ return String.class;
+ }
+
+
+ @StringDef({"preset", "home_wallpaper", "lock_wallpaper"})
+ @Retention(RetentionPolicy.SOURCE)
+ @interface Type {
+ }
+}
diff --git a/core/java/android/content/theming/FieldThemeStyle.java b/core/java/android/content/theming/FieldThemeStyle.java
new file mode 100644
index 000000000000..b433e5b96ec3
--- /dev/null
+++ b/core/java/android/content/theming/FieldThemeStyle.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2025 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.content.theming;
+
+import android.annotation.FlaggedApi;
+import android.annotation.Nullable;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+
+/** @hide */
+@FlaggedApi(android.server.Flags.FLAG_ENABLE_THEME_SERVICE)
+public class FieldThemeStyle extends ThemeSettingsField<Integer, String> {
+ public FieldThemeStyle(
+ String key,
+ BiConsumer<ThemeSettingsUpdater, Integer> setter,
+ Function<ThemeSettings, Integer> getter,
+ ThemeSettings defaults
+ ) {
+ super(key, setter, getter, defaults);
+ }
+
+ private static final @ThemeStyle.Type List<Integer> sValidStyles = Arrays.asList(
+ ThemeStyle.EXPRESSIVE,
+ ThemeStyle.SPRITZ,
+ ThemeStyle.TONAL_SPOT, ThemeStyle.FRUIT_SALAD, ThemeStyle.RAINBOW,
+ ThemeStyle.VIBRANT,
+ ThemeStyle.MONOCHROMATIC);
+
+ @Override
+ public String serialize(@ThemeStyle.Type Integer typedValue) {
+ return ThemeStyle.toString(typedValue);
+ }
+
+ @Override
+ public boolean validate(Integer value) {
+ return sValidStyles.contains(value);
+ }
+
+ @Override
+ @Nullable
+ @ThemeStyle.Type
+ public Integer parse(String primitive) {
+ try {
+ return ThemeStyle.valueOf(primitive);
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ @Override
+ public Class<Integer> getFieldType() {
+ return Integer.class;
+ }
+
+ @Override
+ public Class<String> getJsonType() {
+ return String.class;
+ }
+}
diff --git a/core/java/android/content/theming/ThemeSettings.java b/core/java/android/content/theming/ThemeSettings.java
new file mode 100644
index 000000000000..e94c1fef5382
--- /dev/null
+++ b/core/java/android/content/theming/ThemeSettings.java
@@ -0,0 +1,200 @@
+/*
+ * Copyright (C) 2025 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.content.theming;
+
+import android.annotation.ColorInt;
+import android.annotation.FlaggedApi;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import androidx.annotation.NonNull;
+
+import java.util.Objects;
+
+/**
+ * Represents the theme settings for the system.
+ * This class holds various properties related to theming, such as color indices, palettes,
+ * accent colors, color sources, theme styles, and color combinations.
+ *
+ * @hide
+ */
+@FlaggedApi(android.server.Flags.FLAG_ENABLE_THEME_SERVICE)
+public final class ThemeSettings implements Parcelable {
+ private final int mColorIndex;
+ private final int mSystemPalette;
+ private final int mAccentColor;
+ @NonNull
+ private final String mColorSource;
+ private final int mThemeStyle;
+ private final boolean mColorBoth;
+
+ /**
+ * Constructs a new ThemeSettings object.
+ *
+ * @param colorIndex The color index.
+ * @param systemPalette The system palette color.
+ * @param accentColor The accent color.
+ * @param colorSource The color source.
+ * @param themeStyle The theme style.
+ * @param colorBoth The color combination.
+ */
+
+ public ThemeSettings(int colorIndex, @ColorInt int systemPalette,
+ @ColorInt int accentColor, @NonNull String colorSource, int themeStyle,
+ boolean colorBoth) {
+
+ this.mAccentColor = accentColor;
+ this.mColorBoth = colorBoth;
+ this.mColorIndex = colorIndex;
+ this.mColorSource = colorSource;
+ this.mSystemPalette = systemPalette;
+ this.mThemeStyle = themeStyle;
+ }
+
+ /**
+ * Constructs a ThemeSettings object from a Parcel.
+ *
+ * @param in The Parcel to read from.
+ */
+ ThemeSettings(Parcel in) {
+ this.mAccentColor = in.readInt();
+ this.mColorBoth = in.readBoolean();
+ this.mColorIndex = in.readInt();
+ this.mColorSource = Objects.requireNonNullElse(in.readString8(), "s");
+ this.mSystemPalette = in.readInt();
+ this.mThemeStyle = in.readInt();
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(mAccentColor);
+ dest.writeBoolean(mColorBoth);
+ dest.writeInt(mColorIndex);
+ dest.writeString8(mColorSource);
+ dest.writeInt(mSystemPalette);
+ dest.writeInt(mThemeStyle);
+ }
+
+ /**
+ * Gets the color index.
+ *
+ * @return The color index.
+ */
+ public Integer colorIndex() {
+ return mColorIndex;
+ }
+
+ /**
+ * Gets the system palette color.
+ *
+ * @return The system palette color.
+ */
+ @ColorInt
+ public Integer systemPalette() {
+ return mSystemPalette;
+ }
+
+ /**
+ * Gets the accent color.
+ *
+ * @return The accent color.
+ */
+ @ColorInt
+ public Integer accentColor() {
+ return mAccentColor;
+ }
+
+ /**
+ * Gets the color source.
+ *
+ * @return The color source.
+ */
+ @FieldColorSource.Type
+ public String colorSource() {
+ return mColorSource;
+ }
+
+ /**
+ * Gets the theme style.
+ *
+ * @return The theme style.
+ */
+ @ThemeStyle.Type
+ public Integer themeStyle() {
+ return mThemeStyle;
+ }
+
+ /**
+ * Gets the color combination.
+ *
+ * @return The color combination.
+ */
+ public Boolean colorBoth() {
+ return mColorBoth;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+
+ return obj instanceof ThemeSettings other
+ && mColorIndex == other.mColorIndex
+ && mSystemPalette == other.mSystemPalette
+ && mAccentColor == other.mAccentColor
+ && mColorSource.equals(other.mColorSource)
+ && mThemeStyle == other.mThemeStyle
+ && mColorBoth == other.mColorBoth;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(mColorIndex, mSystemPalette, mAccentColor, mColorSource, mThemeStyle,
+ mColorBoth);
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ /**
+ * Creator for Parcelable interface.
+ */
+ public static final Creator<ThemeSettings> CREATOR = new Creator<>() {
+ @Override
+ public ThemeSettings createFromParcel(Parcel in) {
+ return new ThemeSettings(in);
+ }
+
+ @Override
+ public ThemeSettings[] newArray(int size) {
+ return new ThemeSettings[size];
+ }
+ };
+
+ /**
+ * Creates a new {@link ThemeSettingsUpdater} instance for updating the {@link ThemeSettings}
+ * through the API.
+ *
+ * @return A new {@link ThemeSettingsUpdater} instance.
+ */
+ public static ThemeSettingsUpdater updater() {
+ return new ThemeSettingsUpdater();
+ }
+}
diff --git a/core/java/android/content/theming/ThemeSettingsField.java b/core/java/android/content/theming/ThemeSettingsField.java
new file mode 100644
index 000000000000..1696df4ad0f6
--- /dev/null
+++ b/core/java/android/content/theming/ThemeSettingsField.java
@@ -0,0 +1,287 @@
+/*
+ * Copyright (C) 2025 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.content.theming;
+
+
+import android.annotation.FlaggedApi;
+import android.util.Log;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.annotation.VisibleForTesting;
+
+import com.android.internal.util.Preconditions;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+
+/**
+ * Represents a field within {@link ThemeSettings}, providing methods for parsing, serializing,
+ * managing default values, and validating the field's value.
+ * <p>
+ * This class is designed to be extended by concrete classes that represent specific fields within
+ * {@link ThemeSettings}. Each subclass should define the following methods, where T is the type of
+ * the field's value and J is the type of the field's value stored in JSON:
+ * <ul>
+ * <li>{@link #parse(Object)} to parse a JSON representation into the field's value type.</li>
+ * <li>{@link #serialize(Object)} to serialize the field's value into a JSON representation.</li>
+ * <li>{@link #validate(Object)} to validate the field's value.</li>
+ * <li>{@link #getFieldType()} to return the type of the field's value.</li>
+ * <li>{@link #getJsonType()} to return the type of the field's value stored in JSON.</li>
+ * </ul>
+ * <p>
+ * The {@link #fromJSON(JSONObject, ThemeSettingsUpdater)} and
+ * {@link #toJSON(ThemeSettings, JSONObject)}
+ * methods handle the extraction and serialization of the field's value to and from JSON objects
+ * respectively. The {@link #fallbackParse(Object, Object)} method is used to parse a string
+ * representation of the field's value, falling back to a default value if parsing fails.
+ *
+ * @param <T> The type of the field's value.
+ * @param <J> The type of the JSON property.
+ * @hide
+ */
+@FlaggedApi(android.server.Flags.FLAG_ENABLE_THEME_SERVICE)
+public abstract class ThemeSettingsField<T, J> {
+ private static final String TAG = ThemeSettingsField.class.getSimpleName();
+
+ private static final String KEY_PREFIX = "android.theme.customization.";
+ public static final String OVERLAY_CATEGORY_ACCENT_COLOR = KEY_PREFIX + "accent_color";
+ public static final String OVERLAY_CATEGORY_SYSTEM_PALETTE = KEY_PREFIX + "system_palette";
+ public static final String OVERLAY_CATEGORY_THEME_STYLE = KEY_PREFIX + "theme_style";
+ public static final String OVERLAY_COLOR_SOURCE = KEY_PREFIX + "color_source";
+ public static final String OVERLAY_COLOR_INDEX = KEY_PREFIX + "color_index";
+ public static final String OVERLAY_COLOR_BOTH = KEY_PREFIX + "color_both";
+
+
+ /**
+ * Returns an array of all available {@link ThemeSettingsField} instances.
+ *
+ * @param defaults The default {@link ThemeSettings} object to use for default values.
+ * @return An array of {@link ThemeSettingsField} instances.
+ */
+ public static ThemeSettingsField<?, ?>[] getFields(ThemeSettings defaults) {
+ return new ThemeSettingsField[]{
+ new FieldColorIndex(
+ OVERLAY_COLOR_INDEX,
+ ThemeSettingsUpdater::colorIndex,
+ ThemeSettings::colorIndex,
+ defaults),
+ new FieldColor(
+ OVERLAY_CATEGORY_SYSTEM_PALETTE,
+ ThemeSettingsUpdater::systemPalette,
+ ThemeSettings::systemPalette,
+ defaults),
+ new FieldColor(
+ OVERLAY_CATEGORY_ACCENT_COLOR,
+ ThemeSettingsUpdater::accentColor,
+ ThemeSettings::accentColor,
+ defaults),
+ new FieldColorSource(
+ OVERLAY_COLOR_SOURCE,
+ ThemeSettingsUpdater::colorSource,
+ ThemeSettings::colorSource,
+ defaults),
+ new FieldThemeStyle(
+ OVERLAY_CATEGORY_THEME_STYLE,
+ ThemeSettingsUpdater::themeStyle,
+ ThemeSettings::themeStyle,
+ defaults),
+ new FieldColorBoth(
+ OVERLAY_COLOR_BOTH,
+ ThemeSettingsUpdater::colorBoth,
+ ThemeSettings::colorBoth,
+ defaults)
+ };
+ }
+
+ public final String key;
+ private final BiConsumer<ThemeSettingsUpdater, T> mSetter;
+ private final Function<ThemeSettings, T> mGetter;
+ private final ThemeSettings mDefaults;
+
+ /**
+ * Creates a new {@link ThemeSettingsField}.
+ *
+ * @param key The key to identify the field in JSON objects.
+ * @param setter The setter to update the field's value in a {@link ThemeSettingsUpdater}.
+ * @param getter The getter to retrieve the field's value from a {@link ThemeSettings}
+ * object.
+ * @param defaults The default {@link ThemeSettings} object to provide default values.
+ */
+
+ public ThemeSettingsField(
+ String key,
+ BiConsumer<ThemeSettingsUpdater, T> setter,
+ Function<ThemeSettings, T> getter,
+ ThemeSettings defaults
+ ) {
+ this.key = key;
+ mSetter = setter;
+ mGetter = getter;
+ mDefaults = defaults;
+ }
+
+ /**
+ * Attempts to parse a JSON primitive representation of the field's value. If parsing fails, it
+ * defaults to the field's default value.
+ *
+ * @param primitive The string representation to parse.
+ */
+ private T fallbackParse(Object primitive, T fallbackValue) {
+ if (primitive == null) {
+ Log.w(TAG, "Error, field `" + key + "` was not found, defaulting to " + fallbackValue);
+ return fallbackValue;
+ }
+
+ if (!getJsonType().isInstance(primitive)) {
+ Log.w(TAG, "Error, field `" + key + "` expected to be of type `"
+ + getJsonType().getSimpleName()
+ + "`, got `" + primitive.getClass().getSimpleName() + "`, defaulting to "
+ + fallbackValue);
+ return fallbackValue;
+ }
+
+ // skips parsing if destination json type is already the same as field type
+ T parsedValue = getFieldType() == getJsonType() ? (T) primitive : parse((J) primitive);
+
+ if (parsedValue == null) {
+ Log.w(TAG, "Error parsing JSON field `" + key + "` , defaulting to " + fallbackValue);
+ return fallbackValue;
+ }
+
+ if (!validate(parsedValue)) {
+ Log.w(TAG,
+ "Error validating JSON field `" + key + "` , defaulting to " + fallbackValue);
+ return fallbackValue;
+ }
+
+ if (parsedValue.getClass() != getFieldType()) {
+ Log.w(TAG, "Error: JSON field `" + key + "` expected to be of type `"
+ + getFieldType().getSimpleName()
+ + "`, defaulting to " + fallbackValue);
+ return fallbackValue;
+ }
+
+ return parsedValue;
+ }
+
+
+ /**
+ * Extracts the field's value from a JSON object and sets it in a
+ * {@link ThemeSettingsUpdater}.
+ *
+ * @param source The JSON object containing the field's value.
+ */
+ public void fromJSON(JSONObject source, ThemeSettingsUpdater updater) {
+ Object primitiveStr = source.opt(key);
+ T typedValue = fallbackParse(primitiveStr, getDefaultValue());
+ mSetter.accept(updater, typedValue);
+ }
+
+ /**
+ * Serializes the field's value from a {@link ThemeSettings} object into a JSON object.
+ *
+ * @param source The {@link ThemeSettings} object from which to retrieve the field's
+ * value.
+ * @param destination The JSON object to which the field's value will be added.
+ */
+ public void toJSON(ThemeSettings source, JSONObject destination) {
+ T value = mGetter.apply(source);
+ Preconditions.checkState(value.getClass() == getFieldType());
+
+ J serialized;
+ if (validate(value)) {
+ serialized = serialize(value);
+ } else {
+ T fallbackValue = getDefaultValue();
+ serialized = serialize(fallbackValue);
+ Log.w(TAG, "Invalid value `" + value + "` for key `" + key + "`, defaulting to '"
+ + fallbackValue);
+ }
+
+ try {
+ destination.put(key, serialized);
+ } catch (JSONException e) {
+ Log.d(TAG,
+ "Error writing JSON primitive, skipping field " + key + ", " + e.getMessage());
+ }
+ }
+
+
+ /**
+ * Returns the default value of the field.
+ *
+ * @return The default value.
+ */
+ @VisibleForTesting
+ @NonNull
+ public T getDefaultValue() {
+ return mGetter.apply(mDefaults);
+ }
+
+ /**
+ * Parses a string representation into the field's value type.
+ *
+ * @param primitive The string representation to parse.
+ * @return The parsed value, or null if parsing fails.
+ */
+ @VisibleForTesting
+ @Nullable
+ public abstract T parse(J primitive);
+
+ /**
+ * Serializes the field's value into a primitive type suitable for JSON.
+ *
+ * @param value The value to serialize.
+ * @return The serialized value.
+ */
+ @VisibleForTesting
+ public abstract J serialize(T value);
+
+ /**
+ * Validates the field's value.
+ * This method can be overridden to perform custom validation logic and MUST NOT validate for
+ * nullity.
+ *
+ * @param value The value to validate.
+ * @return {@code true} if the value is valid, {@code false} otherwise.
+ */
+ @VisibleForTesting
+ public abstract boolean validate(T value);
+
+ /**
+ * Returns the type of the field's value.
+ *
+ * @return The type of the field's value.
+ */
+ @VisibleForTesting
+ public abstract Class<T> getFieldType();
+
+ /**
+ * Returns the type of the field's value stored in JSON.
+ *
+ * <p>This method is used to determine the expected type of the field's value when it is
+ * stored in a JSON object.
+ *
+ * @return The type of the field's value stored in JSON.
+ */
+ @VisibleForTesting
+ public abstract Class<J> getJsonType();
+}
diff --git a/core/java/android/content/theming/ThemeSettingsUpdater.java b/core/java/android/content/theming/ThemeSettingsUpdater.java
new file mode 100644
index 000000000000..acd7d356db69
--- /dev/null
+++ b/core/java/android/content/theming/ThemeSettingsUpdater.java
@@ -0,0 +1,244 @@
+/*
+ * Copyright (C) 2025 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.content.theming;
+
+
+import android.annotation.ColorInt;
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.SuppressLint;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import androidx.annotation.VisibleForTesting;
+
+import java.util.Objects;
+
+/**
+ * Updater class for constructing {@link ThemeSettings} objects.
+ * This class provides a fluent interface for setting the various properties of the theme
+ * settings.
+ *
+ * @hide
+ */
+@FlaggedApi(android.server.Flags.FLAG_ENABLE_THEME_SERVICE)
+public class ThemeSettingsUpdater implements Parcelable {
+ @ColorInt
+ private Integer mAccentColor;
+ private Boolean mColorBoth;
+ private Integer mColorIndex;
+ private String mColorSource;
+ @ColorInt
+ private Integer mSystemPalette;
+ private Integer mThemeStyle;
+
+ ThemeSettingsUpdater(Integer colorIndex, @ColorInt Integer systemPalette,
+ @ColorInt Integer accentColor, @FieldColorSource.Type String colorSource,
+ @ThemeStyle.Type Integer themeStyle, Boolean colorBoth) {
+ this.mAccentColor = accentColor;
+ this.mColorBoth = colorBoth;
+ this.mColorIndex = colorIndex;
+ this.mColorSource = colorSource;
+ this.mSystemPalette = systemPalette;
+ this.mThemeStyle = themeStyle;
+ }
+
+ ThemeSettingsUpdater() {
+ }
+
+ // only reading basic JVM types for nullability
+ @SuppressLint("ParcelClassLoader")
+ protected ThemeSettingsUpdater(Parcel in) {
+ mAccentColor = (Integer) in.readValue(null);
+ mColorBoth = (Boolean) in.readValue(null);
+ mColorIndex = (Integer) in.readValue(null);
+ mColorSource = (String) in.readValue(null);
+ mSystemPalette = (Integer) in.readValue(null);
+ mThemeStyle = (Integer) in.readValue(null);
+ }
+
+ // using read/writeValue for nullability support
+ @SuppressWarnings("AndroidFrameworkEfficientParcelable")
+ @Override
+ public void writeToParcel(Parcel dest, int flags) {
+ dest.writeValue(mAccentColor);
+ dest.writeValue(mColorBoth);
+ dest.writeValue(mColorIndex);
+ dest.writeValue(mColorSource);
+ dest.writeValue(mSystemPalette);
+ dest.writeValue(mThemeStyle);
+ }
+
+ /**
+ * Sets the color index.
+ *
+ * @param colorIndex The color index to set.
+ * @return This {@link ThemeSettingsUpdater} instance.
+ */
+ public ThemeSettingsUpdater colorIndex(int colorIndex) {
+ this.mColorIndex = colorIndex;
+ return this;
+ }
+
+ /**
+ * Returns the color index.
+ *
+ * @return The color index.
+ */
+ @VisibleForTesting
+ public Integer getColorIndex() {
+ return mColorIndex;
+ }
+
+ /**
+ * Sets the system palette color.
+ *
+ * @param systemPalette The system palette color to set.
+ * @return This {@link ThemeSettingsUpdater} instance.
+ */
+ public ThemeSettingsUpdater systemPalette(@ColorInt int systemPalette) {
+ this.mSystemPalette = systemPalette;
+ return this;
+ }
+
+ /**
+ * Returns the system palette color.
+ *
+ * @return The system palette color.
+ */
+ @VisibleForTesting
+ public Integer getSystemPalette() {
+ return mSystemPalette;
+ }
+
+ /**
+ * Sets the accent color.
+ *
+ * @param accentColor The accent color to set.
+ * @return This {@link ThemeSettingsUpdater} instance.
+ */
+ public ThemeSettingsUpdater accentColor(@ColorInt int accentColor) {
+ this.mAccentColor = accentColor;
+ return this;
+ }
+
+ /**
+ * Returns the accent color.
+ *
+ * @return The accent color.
+ */
+ @VisibleForTesting
+ public Integer getAccentColor() {
+ return mAccentColor;
+ }
+
+ /**
+ * Sets the color source.
+ *
+ * @param colorSource The color source to set.
+ * @return This {@link ThemeSettingsUpdater} instance.
+ */
+ public ThemeSettingsUpdater colorSource(@NonNull @FieldColorSource.Type String colorSource) {
+ this.mColorSource = colorSource;
+ return this;
+ }
+
+ /**
+ * Returns the theme style.
+ *
+ * @return The theme style.
+ */
+ @VisibleForTesting
+ public Integer getThemeStyle() {
+ return mThemeStyle;
+ }
+
+ /**
+ * Sets the theme style.
+ *
+ * @param themeStyle The theme style to set.
+ * @return This {@link ThemeSettingsUpdater} instance.
+ */
+ public ThemeSettingsUpdater themeStyle(@ThemeStyle.Type int themeStyle) {
+ this.mThemeStyle = themeStyle;
+ return this;
+ }
+
+ /**
+ * Returns the color source.
+ *
+ * @return The color source.
+ */
+ @VisibleForTesting
+ public String getColorSource() {
+ return mColorSource;
+ }
+
+ /**
+ * Sets the color combination.
+ *
+ * @param colorBoth The color combination to set.
+ * @return This {@link ThemeSettingsUpdater} instance.
+ */
+ public ThemeSettingsUpdater colorBoth(boolean colorBoth) {
+ this.mColorBoth = colorBoth;
+ return this;
+ }
+
+ /**
+ * Returns the color combination.
+ *
+ * @return The color combination.
+ */
+ @VisibleForTesting
+ public Boolean getColorBoth() {
+ return mColorBoth;
+ }
+
+ /**
+ * Constructs a new {@link ThemeSettings} object with the current builder settings.
+ *
+ * @return A new {@link ThemeSettings} object.
+ */
+ public ThemeSettings toThemeSettings(@NonNull ThemeSettings defaults) {
+ return new ThemeSettings(
+ Objects.requireNonNullElse(mColorIndex, defaults.colorIndex()),
+ Objects.requireNonNullElse(mSystemPalette, defaults.systemPalette()),
+ Objects.requireNonNullElse(mAccentColor, defaults.accentColor()),
+ Objects.requireNonNullElse(mColorSource, defaults.colorSource()),
+ Objects.requireNonNullElse(mThemeStyle, defaults.themeStyle()),
+ Objects.requireNonNullElse(mColorBoth, defaults.colorBoth()));
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ public static final Creator<ThemeSettingsUpdater> CREATOR =
+ new Creator<>() {
+ @Override
+ public ThemeSettingsUpdater createFromParcel(Parcel in) {
+ return new ThemeSettingsUpdater(in);
+ }
+
+ @Override
+ public ThemeSettingsUpdater[] newArray(int size) {
+ return new ThemeSettingsUpdater[size];
+ }
+ };
+}
diff --git a/core/java/android/content/theming/ThemeStyle.java b/core/java/android/content/theming/ThemeStyle.java
new file mode 100644
index 000000000000..607896405020
--- /dev/null
+++ b/core/java/android/content/theming/ThemeStyle.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright (C) 2025 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.content.theming;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * A class defining the different styles available for theming.
+ * This class replaces the previous enum implementation for improved performance and compatibility.
+ *
+ * @hide
+ */
+public final class ThemeStyle {
+
+ private ThemeStyle() {
+ }
+
+ /**
+ * @hide
+ */
+ @IntDef({
+ SPRITZ,
+ TONAL_SPOT,
+ VIBRANT,
+ EXPRESSIVE,
+ RAINBOW,
+ FRUIT_SALAD,
+ CONTENT,
+ MONOCHROMATIC,
+ CLOCK,
+ CLOCK_VIBRANT
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface Type {
+ }
+
+ /**
+ * Represents the SPRITZ style.
+ */
+ public static final int SPRITZ = 0;
+ /**
+ * Represents the TONAL_SPOT style.
+ */
+ public static final int TONAL_SPOT = 1;
+ /**
+ * Represents the VIBRANT style.
+ */
+ public static final int VIBRANT = 2;
+ /**
+ * Represents the EXPRESSIVE style.
+ */
+ public static final int EXPRESSIVE = 3;
+ /**
+ * Represents the RAINBOW style.
+ */
+ public static final int RAINBOW = 4;
+ /**
+ * Represents the FRUIT_SALAD style.
+ */
+ public static final int FRUIT_SALAD = 5;
+ /**
+ * Represents the CONTENT style.
+ */
+ public static final int CONTENT = 6;
+ /**
+ * Represents the MONOCHROMATIC style.
+ */
+ public static final int MONOCHROMATIC = 7;
+ /**
+ * Represents the CLOCK style.
+ */
+ public static final int CLOCK = 8;
+ /**
+ * Represents the CLOCK_VIBRANT style.
+ */
+ public static final int CLOCK_VIBRANT = 9;
+
+
+ /**
+ * Returns the string representation of the given style.
+ *
+ * @param style The style value.
+ * @return The string representation of the style.
+ * @throws IllegalArgumentException if the style value is invalid.
+ */
+ @NonNull
+ public static String toString(@Nullable @Type Integer style) {
+ // Throw an exception if style is null
+ if (style == null) {
+ throw new IllegalArgumentException("Invalid style value: null");
+ }
+
+ return switch (style) {
+ case SPRITZ -> "SPRITZ";
+ case TONAL_SPOT -> "TONAL_SPOT";
+ case VIBRANT -> "VIBRANT";
+ case EXPRESSIVE -> "EXPRESSIVE";
+ case RAINBOW -> "RAINBOW";
+ case FRUIT_SALAD -> "FRUIT_SALAD";
+ case CONTENT -> "CONTENT";
+ case MONOCHROMATIC -> "MONOCHROMATIC";
+ case CLOCK -> "CLOCK";
+ case CLOCK_VIBRANT -> "CLOCK_VIBRANT";
+ default -> throw new IllegalArgumentException("Invalid style value: " + style);
+ };
+ }
+
+ /**
+ * Returns the style value corresponding to the given style name.
+ *
+ * @param styleName The name of the style.
+ * @return The style value.
+ * @throws IllegalArgumentException if the style name is invalid.
+ */
+ public static @Type int valueOf(@Nullable String styleName) {
+ return switch (styleName) {
+ case "SPRITZ" -> SPRITZ;
+ case "TONAL_SPOT" -> TONAL_SPOT;
+ case "VIBRANT" -> VIBRANT;
+ case "EXPRESSIVE" -> EXPRESSIVE;
+ case "RAINBOW" -> RAINBOW;
+ case "FRUIT_SALAD" -> FRUIT_SALAD;
+ case "CONTENT" -> CONTENT;
+ case "MONOCHROMATIC" -> MONOCHROMATIC;
+ case "CLOCK" -> CLOCK;
+ case "CLOCK_VIBRANT" -> CLOCK_VIBRANT;
+ default -> throw new IllegalArgumentException("Invalid style name: " + styleName);
+ };
+ }
+
+ /**
+ * Returns the name of the given style. This method is equivalent to {@link #toString(int)}.
+ *
+ * @param style The style value.
+ * @return The name of the style.
+ */
+ @NonNull
+ public static String name(@Type int style) {
+ return toString(style);
+ }
+
+ /**
+ * Returns an array containing all the style values.
+ *
+ * @return An array of all style values.
+ */
+ public static int[] values() {
+ return new int[]{
+ SPRITZ,
+ TONAL_SPOT,
+ VIBRANT,
+ EXPRESSIVE,
+ RAINBOW,
+ FRUIT_SALAD,
+ CONTENT,
+ MONOCHROMATIC,
+ CLOCK,
+ CLOCK_VIBRANT
+ };
+ }
+}
diff --git a/core/java/android/hardware/display/DisplayManagerGlobal.java b/core/java/android/hardware/display/DisplayManagerGlobal.java
index bebca57125b6..42df43e4d436 100644
--- a/core/java/android/hardware/display/DisplayManagerGlobal.java
+++ b/core/java/android/hardware/display/DisplayManagerGlobal.java
@@ -475,6 +475,7 @@ public final class DisplayManagerGlobal {
synchronized (mLock) {
if (!mShouldImplicitlyRegisterRrChanges) {
mShouldImplicitlyRegisterRrChanges = true;
+ Slog.i(TAG, "Implicitly registering for refresh rate");
updateCallbackIfNeededLocked();
}
}
@@ -1759,6 +1760,9 @@ public final class DisplayManagerGlobal {
synchronized (mLock) {
mDispatchNativeCallbacks = true;
if (Flags.delayImplicitRrRegistrationUntilRrAccessed()) {
+ if (!mShouldImplicitlyRegisterRrChanges) {
+ Slog.i(TAG, "Choreographer implicitly registered for the refresh rate.");
+ }
mShouldImplicitlyRegisterRrChanges = true;
}
registerCallbackIfNeededLocked();
diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java
index cc1dee7a5747..b2f25212729e 100644
--- a/core/java/android/os/BatteryStats.java
+++ b/core/java/android/os/BatteryStats.java
@@ -6948,8 +6948,9 @@ public abstract class BatteryStats {
// This constant MUST be incremented whenever the history dump format changes.
private static final int FORMAT_VERSION = 2;
- private final SimpleDateFormat mHistoryItemTimestampFormat =
- new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US);
+ private final boolean mPerformanceBaseline;
+ private final HistoryLogTimeFormatter mHistoryLogTimeFormatter;
+ private final SimpleDateFormat mHistoryItemTimestampFormat;
private final SimpleDateFormat mCurrentTimeEventTimeFormat =
new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);
@@ -6960,6 +6961,7 @@ public abstract class BatteryStats {
private final int mFormatVersion;
+ private final StringBuilder mStringBuilder = new StringBuilder();
int oldState = 0;
int oldState2 = 0;
int oldLevel = -1;
@@ -6974,18 +6976,30 @@ public abstract class BatteryStats {
long lastTime = -1;
public HistoryPrinter() {
- this(TimeZone.getDefault());
+ this(0);
}
- public HistoryPrinter(TimeZone timeZone) {
+ public HistoryPrinter(int flags) {
+ this(TimeZone.getDefault(), flags);
+ }
+
+ public HistoryPrinter(TimeZone timeZone, int flags) {
this(com.android.server.power.optimization.Flags
.extendedBatteryHistoryContinuousCollectionEnabled()
- ? FORMAT_VERSION : FORMAT_LEGACY, timeZone);
+ ? FORMAT_VERSION : FORMAT_LEGACY, timeZone, flags);
}
- private HistoryPrinter(int formatVersion, TimeZone timeZone) {
+ private HistoryPrinter(int formatVersion, TimeZone timeZone, int flags) {
mFormatVersion = formatVersion;
- mHistoryItemTimestampFormat.getCalendar().setTimeZone(timeZone);
+ mPerformanceBaseline = (flags & DUMP_DEBUG_PERF_BASELINE) != 0;
+ if (mPerformanceBaseline) {
+ mHistoryItemTimestampFormat = new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US);
+ mHistoryItemTimestampFormat.getCalendar().setTimeZone(timeZone);
+ mHistoryLogTimeFormatter = null;
+ } else {
+ mHistoryItemTimestampFormat = null;
+ mHistoryLogTimeFormatter = new HistoryLogTimeFormatter(timeZone);
+ }
mCurrentTimeEventTimeFormat.getCalendar().setTimeZone(timeZone);
}
@@ -7019,7 +7033,8 @@ public abstract class BatteryStats {
@SuppressWarnings("JavaUtilDate")
private String printNextItem(HistoryItem rec, long baseTime, boolean checkin,
boolean verbose) {
- StringBuilder item = new StringBuilder();
+ StringBuilder item = mStringBuilder;
+ item.setLength(0);
if (!checkin) {
item.append(" ");
if (mFormatVersion == FORMAT_LEGACY) {
@@ -7029,8 +7044,13 @@ public abstract class BatteryStats {
item.append(rec.numReadInts);
item.append(") ");
} else {
- mDate.setTime(rec.currentTime);
- item.append(mHistoryItemTimestampFormat.format(mDate)).append(' ');
+ if (mPerformanceBaseline) {
+ mDate.setTime(rec.currentTime);
+ item.append(mHistoryItemTimestampFormat.format(mDate)).append(' ');
+ } else {
+ mHistoryLogTimeFormatter.append(item, rec.currentTime);
+ item.append(' ');
+ }
}
} else {
item.append(BATTERY_STATS_CHECKIN_VERSION); item.append(',');
@@ -7399,6 +7419,64 @@ public abstract class BatteryStats {
sb.append(":");
sb.append(stime);
}
+
+ /**
+ * In essence, this is a wrapper over SimpleDateFormat that takes advantage
+ * of the fact that events in battery history are closely spaced, which allows it
+ * to reuse the results of the most expensive formatting work.
+ */
+ private static class HistoryLogTimeFormatter {
+ private static final long HOUR_MILLIS = 3600000L;
+ private static final long MINUTE_MILLIS = 60000L;
+ private final SimpleDateFormat mDateFormat =
+ new SimpleDateFormat("MM-dd HH:", Locale.US);
+ private final Date mDate = new Date();
+
+ private final long mTimeZoneOffset;
+ private long mCachedHour;
+ private String mCachedHourFormatted;
+
+ private HistoryLogTimeFormatter(TimeZone timeZone) {
+ mTimeZoneOffset = timeZone.getRawOffset();
+ mDateFormat.getCalendar().setTimeZone(timeZone);
+ }
+
+ /* Appends timestampMs formatted as "MM-dd HH:mm:ss.SSS" */
+ void append(StringBuilder sb, long timestampMs) {
+ long localTime = timestampMs + mTimeZoneOffset;
+ long hour = localTime / HOUR_MILLIS;
+ if (hour != mCachedHour) {
+ mDate.setTime(timestampMs);
+ mCachedHourFormatted = mDateFormat.format(mDate);
+ mCachedHour = hour;
+ }
+ sb.append(mCachedHourFormatted);
+
+ long remainder = localTime % HOUR_MILLIS;
+
+ long minutes = remainder / MINUTE_MILLIS;
+ if (minutes < 10) {
+ sb.append('0');
+ }
+ sb.append(minutes).append(':');
+
+ remainder = remainder % MINUTE_MILLIS;
+ long seconds = remainder / 1000;
+ if (seconds < 10) {
+ sb.append('0');
+ }
+ sb.append(seconds).append('.');
+
+ long millis = remainder % 1000;
+ if (millis < 100) {
+ sb.append('0');
+ if (millis < 10) {
+ sb.append('0');
+ }
+ }
+ sb.append(millis);
+ }
+ }
}
private void printSizeValue(PrintWriter pw, long size) {
@@ -7584,9 +7662,10 @@ public abstract class BatteryStats {
public static final int DUMP_INCLUDE_HISTORY = 1<<4;
public static final int DUMP_VERBOSE = 1<<5;
public static final int DUMP_DEVICE_WIFI_ONLY = 1<<6;
+ public static final int DUMP_DEBUG_PERF_BASELINE = 1 << 7;
private void dumpHistory(PrintWriter pw, int flags, long histStart, boolean checkin) {
- final HistoryPrinter hprinter = new HistoryPrinter();
+ final HistoryPrinter hprinter = new HistoryPrinter(flags);
synchronized (this) {
if (!checkin) {
final long historyTotalSize = getHistoryTotalSize();
@@ -8522,7 +8601,7 @@ public abstract class BatteryStats {
}
// History data (HISTORY_DATA)
- final HistoryPrinter hprinter = new HistoryPrinter();
+ final HistoryPrinter hprinter = new HistoryPrinter(flags);
long lastTime = -1;
long baseTime = -1;
boolean printed = false;
diff --git a/core/java/android/os/BatteryUsageStats.java b/core/java/android/os/BatteryUsageStats.java
index 739908ef0dfc..b4ca217539a3 100644
--- a/core/java/android/os/BatteryUsageStats.java
+++ b/core/java/android/os/BatteryUsageStats.java
@@ -129,12 +129,6 @@ public final class BatteryUsageStats implements Parcelable, Closeable {
// Max window size. CursorWindow uses only as much memory as needed.
private static final long BATTERY_CONSUMER_CURSOR_WINDOW_SIZE = 20_000_000; // bytes
- /**
- * Used by tests to ensure all BatteryUsageStats instances are closed.
- */
- @VisibleForTesting
- public static boolean DEBUG_INSTANCE_COUNT;
-
private static final int STATSD_PULL_ATOM_MAX_BYTES = 45000;
private static final int[] UID_USAGE_TIME_PROCESS_STATES = {
@@ -1267,11 +1261,16 @@ public final class BatteryUsageStats implements Parcelable, Closeable {
}
}
+ /*
+ * Used by tests to ensure all BatteryUsageStats instances are closed.
+ */
+ private static volatile boolean sInstanceLeakDetectionEnabled;
+
@GuardedBy("BatteryUsageStats.class")
private static Map<CursorWindow, Exception> sInstances;
private static void onCursorWindowAllocated(CursorWindow window) {
- if (!DEBUG_INSTANCE_COUNT) {
+ if (!sInstanceLeakDetectionEnabled) {
return;
}
@@ -1284,7 +1283,7 @@ public final class BatteryUsageStats implements Parcelable, Closeable {
}
private static void onCursorWindowReleased(CursorWindow window) {
- if (!DEBUG_INSTANCE_COUNT) {
+ if (!sInstanceLeakDetectionEnabled) {
return;
}
@@ -1294,12 +1293,26 @@ public final class BatteryUsageStats implements Parcelable, Closeable {
}
/**
+ * Enables detection of leaked BatteryUsageStats instances, meaning instances that are created
+ * but not closed during the test execution.
+ */
+ @VisibleForTesting
+ public static void enableInstanceLeakDetection() {
+ sInstanceLeakDetectionEnabled = true;
+ synchronized (BatteryUsageStats.class) {
+ if (sInstances != null) {
+ sInstances.clear();
+ }
+ }
+ }
+
+ /**
* Used by tests to ensure all BatteryUsageStats instances are closed.
*/
@VisibleForTesting
public static void assertAllInstancesClosed() {
- if (!DEBUG_INSTANCE_COUNT) {
- throw new IllegalStateException("DEBUG_INSTANCE_COUNT is false");
+ if (!sInstanceLeakDetectionEnabled) {
+ throw new IllegalStateException("Instance leak detection is not enabled");
}
synchronized (BatteryUsageStats.class) {
diff --git a/core/java/android/security/advancedprotection/AdvancedProtectionManager.java b/core/java/android/security/advancedprotection/AdvancedProtectionManager.java
index cb2b13d1e120..ecc5fd468ee8 100644
--- a/core/java/android/security/advancedprotection/AdvancedProtectionManager.java
+++ b/core/java/android/security/advancedprotection/AdvancedProtectionManager.java
@@ -308,7 +308,7 @@ public final class AdvancedProtectionManager {
}
/**
- * Enables or disables advanced protection on the device.
+ * Enables or disables advanced protection on the device. Can only be called by an admin user.
*
* @param enabled {@code true} to enable advanced protection, {@code false} to disable it.
* @hide
diff --git a/core/java/android/security/flags.aconfig b/core/java/android/security/flags.aconfig
index 09137c3a7b65..edfb78e59fe3 100644
--- a/core/java/android/security/flags.aconfig
+++ b/core/java/android/security/flags.aconfig
@@ -52,13 +52,6 @@ flag {
}
flag {
- name: "binary_transparency_sepolicy_hash"
- namespace: "hardware_backed_security"
- description: "Collect sepolicy hash from sysfs"
- bug: "308471499"
-}
-
-flag {
name: "frp_enforcement"
is_exported: true
namespace: "hardware_backed_security"
diff --git a/core/java/android/text/Layout.java b/core/java/android/text/Layout.java
index 0152c52a6753..ebd6efac3d96 100644
--- a/core/java/android/text/Layout.java
+++ b/core/java/android/text/Layout.java
@@ -1074,15 +1074,15 @@ public abstract class Layout {
public void onCharacterBounds(int index, int lineNum, float left, float top,
float right, float bottom) {
- var newBackground = determineContrastingBackgroundColor(index);
- var hasBgColorChanged = newBackground != bgPaint.getColor();
-
// Skip processing if the character is a space or a tap to avoid
// rendering an abrupt, empty rectangle.
if (TextLine.isLineEndSpace(mText.charAt(index))) {
return;
}
+ var newBackground = determineContrastingBackgroundColor(index);
+ var hasBgColorChanged = newBackground != bgPaint.getColor();
+
// To avoid highlighting emoji sequences, we use Extended_Pictgraphs as a
// heuristic. Highlighting is skipped based on code points, not glyph type
// (text vs. color), so emojis with default text presentation are
diff --git a/core/java/android/view/InsetsAnimationControlImpl.java b/core/java/android/view/InsetsAnimationControlImpl.java
index 6decd6d3a603..0558858895b8 100644
--- a/core/java/android/view/InsetsAnimationControlImpl.java
+++ b/core/java/android/view/InsetsAnimationControlImpl.java
@@ -257,6 +257,11 @@ public class InsetsAnimationControlImpl implements InternalInsetsAnimationContro
}
@Override
+ public boolean willUpdateSurface() {
+ return !mFinished && !mCancelled;
+ }
+
+ @Override
public @AnimationType int getAnimationType() {
return mAnimationType;
}
diff --git a/core/java/android/view/InsetsAnimationControlRunner.java b/core/java/android/view/InsetsAnimationControlRunner.java
index 4f102da4692a..968181b1723d 100644
--- a/core/java/android/view/InsetsAnimationControlRunner.java
+++ b/core/java/android/view/InsetsAnimationControlRunner.java
@@ -55,6 +55,12 @@ public interface InsetsAnimationControlRunner {
void updateSurfacePosition(SparseArray<InsetsSourceControl> controls);
/**
+ * Returns {@code true} if this runner will keep playing the animation and updating the surface.
+ * {@code false} otherwise.
+ */
+ boolean willUpdateSurface();
+
+ /**
* Cancels the animation.
*/
void cancel();
diff --git a/core/java/android/view/InsetsAnimationThreadControlRunner.java b/core/java/android/view/InsetsAnimationThreadControlRunner.java
index 8c2c4951a9f7..8acb46dcc0a4 100644
--- a/core/java/android/view/InsetsAnimationThreadControlRunner.java
+++ b/core/java/android/view/InsetsAnimationThreadControlRunner.java
@@ -89,7 +89,7 @@ public class InsetsAnimationThreadControlRunner implements InsetsAnimationContro
}
};
- private SurfaceParamsApplier mSurfaceParamsApplier = new SurfaceParamsApplier() {
+ private final SurfaceParamsApplier mSurfaceParamsApplier = new SurfaceParamsApplier() {
private final float[] mTmpFloat9 = new float[9];
@@ -170,6 +170,17 @@ public class InsetsAnimationThreadControlRunner implements InsetsAnimationContro
@Override
@UiThread
+ public boolean willUpdateSurface() {
+ synchronized (mControl) {
+ // This is called from the UI thread, however, applyChangeInsets would be called on the
+ // animation thread, so we need this critical section to ensure this is not called
+ // during applyChangeInsets. See: scheduleApplyChangeInsets.
+ return mControl.willUpdateSurface();
+ }
+ }
+
+ @Override
+ @UiThread
public void cancel() {
InsetsAnimationThread.getHandler().post(mControl::cancel);
}
diff --git a/core/java/android/view/InsetsController.java b/core/java/android/view/InsetsController.java
index 4c578fb93600..f7ffc1e1a103 100644
--- a/core/java/android/view/InsetsController.java
+++ b/core/java/android/view/InsetsController.java
@@ -1747,9 +1747,9 @@ public class InsetsController implements WindowInsetsController, InsetsAnimation
mTypesBeingCancelled |= types;
try {
for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
- InsetsAnimationControlRunner control = mRunningAnimations.get(i).runner;
- if ((control.getTypes() & types) != 0) {
- cancelAnimation(control, true /* invokeCallback */);
+ final InsetsAnimationControlRunner runner = mRunningAnimations.get(i).runner;
+ if ((runner.getTypes() & types) != 0) {
+ cancelAnimation(runner, true /* invokeCallback */);
}
}
if ((types & ime()) != 0) {
@@ -1788,11 +1788,11 @@ public class InsetsController implements WindowInsetsController, InsetsAnimation
ImeTracker.PHASE_CLIENT_ANIMATION_FINISHED_SHOW);
ImeTracker.forLogging().onShown(statsToken);
} else {
- ImeTracker.forLogging().onProgress(statsToken,
- ImeTracker.PHASE_CLIENT_ANIMATION_FINISHED_HIDE);
// The requestedVisibleTypes are only send at the end of the hide animation.
// Therefore, the requested is not finished at this point.
if (!Flags.refactorInsetsController()) {
+ ImeTracker.forLogging().onProgress(statsToken,
+ ImeTracker.PHASE_CLIENT_ANIMATION_FINISHED_HIDE);
ImeTracker.forLogging().onHidden(statsToken);
}
}
@@ -1807,10 +1807,10 @@ public class InsetsController implements WindowInsetsController, InsetsAnimation
void notifyControlRevoked(InsetsSourceConsumer consumer) {
final @InsetsType int type = consumer.getType();
for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
- InsetsAnimationControlRunner control = mRunningAnimations.get(i).runner;
- control.notifyControlRevoked(type);
- if (control.getControllingTypes() == 0) {
- cancelAnimation(control, true /* invokeCallback */);
+ final InsetsAnimationControlRunner runner = mRunningAnimations.get(i).runner;
+ runner.notifyControlRevoked(type);
+ if (runner.getControllingTypes() == 0) {
+ cancelAnimation(runner, true /* invokeCallback */);
}
}
if (type == ime()) {
@@ -1823,38 +1823,38 @@ public class InsetsController implements WindowInsetsController, InsetsAnimation
}
}
- private void cancelAnimation(InsetsAnimationControlRunner control, boolean invokeCallback) {
+ private void cancelAnimation(InsetsAnimationControlRunner runner, boolean invokeCallback) {
if (invokeCallback) {
- ImeTracker.forLogging().onCancelled(control.getStatsToken(),
+ ImeTracker.forLogging().onCancelled(runner.getStatsToken(),
ImeTracker.PHASE_CLIENT_ANIMATION_CANCEL);
- control.cancel();
+ runner.cancel();
} else {
// Succeeds if invokeCallback is false (i.e. when called from notifyFinished).
- ImeTracker.forLogging().onProgress(control.getStatsToken(),
+ ImeTracker.forLogging().onProgress(runner.getStatsToken(),
ImeTracker.PHASE_CLIENT_ANIMATION_CANCEL);
}
if (DEBUG) {
Log.d(TAG, TextUtils.formatSimple(
"cancelAnimation of types: %d, animType: %d, host: %s",
- control.getTypes(), control.getAnimationType(), mHost.getRootViewTitle()));
+ runner.getTypes(), runner.getAnimationType(), mHost.getRootViewTitle()));
}
@InsetsType int removedTypes = 0;
for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
RunningAnimation runningAnimation = mRunningAnimations.get(i);
- if (runningAnimation.runner == control) {
+ if (runningAnimation.runner == runner) {
mRunningAnimations.remove(i);
- removedTypes = control.getTypes();
+ removedTypes = runner.getTypes();
if (invokeCallback) {
dispatchAnimationEnd(runningAnimation.runner.getAnimation());
} else {
if (Flags.refactorInsetsController()) {
if ((removedTypes & ime()) != 0
- && control.getAnimationType() == ANIMATION_TYPE_HIDE) {
+ && runner.getAnimationType() == ANIMATION_TYPE_HIDE) {
if (mHost != null) {
// if the (hide) animation is cancelled, the
// requestedVisibleTypes should be reported at this point.
reportRequestedVisibleTypes(!Flags.reportAnimatingInsetsTypes()
- ? control.getStatsToken() : null);
+ ? runner.getStatsToken() : null);
mHost.getInputMethodManager().removeImeSurface(
mHost.getWindowToken());
}
@@ -1869,9 +1869,9 @@ public class InsetsController implements WindowInsetsController, InsetsAnimation
if (mHost != null) {
final boolean dispatchStatsToken =
Flags.reportAnimatingInsetsTypes() && (removedTypes & ime()) != 0
- && control.getAnimationType() == ANIMATION_TYPE_HIDE;
+ && runner.getAnimationType() == ANIMATION_TYPE_HIDE;
mHost.updateAnimatingTypes(mAnimatingTypes,
- dispatchStatsToken ? control.getStatsToken() : null);
+ dispatchStatsToken ? runner.getStatsToken() : null);
}
}
@@ -1959,14 +1959,30 @@ public class InsetsController implements WindowInsetsController, InsetsAnimation
@VisibleForTesting(visibility = PACKAGE)
public @AnimationType int getAnimationType(@InsetsType int type) {
for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
- InsetsAnimationControlRunner control = mRunningAnimations.get(i).runner;
- if (control.controlsType(type)) {
+ final InsetsAnimationControlRunner runner = mRunningAnimations.get(i).runner;
+ if (runner.controlsType(type)) {
return mRunningAnimations.get(i).type;
}
}
return ANIMATION_TYPE_NONE;
}
+ /**
+ * Returns {@code true} if there is an animation which controls the given {@link InsetsType} and
+ * the runner is still playing the surface animation.
+ *
+ * @see InsetsAnimationControlRunner#willUpdateSurface()
+ */
+ boolean hasSurfaceAnimation(@InsetsType int type) {
+ for (int i = mRunningAnimations.size() - 1; i >= 0; i--) {
+ final InsetsAnimationControlRunner runner = mRunningAnimations.get(i).runner;
+ if (runner.controlsType(type) && runner.willUpdateSurface()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
@VisibleForTesting(visibility = PACKAGE)
public void setRequestedVisibleTypes(@InsetsType int visibleTypes, @InsetsType int mask) {
final @InsetsType int requestedVisibleTypes =
diff --git a/core/java/android/view/InsetsResizeAnimationRunner.java b/core/java/android/view/InsetsResizeAnimationRunner.java
index 5262751cc6ed..6356be262cc4 100644
--- a/core/java/android/view/InsetsResizeAnimationRunner.java
+++ b/core/java/android/view/InsetsResizeAnimationRunner.java
@@ -233,6 +233,11 @@ public class InsetsResizeAnimationRunner implements InsetsAnimationControlRunner
}
@Override
+ public boolean willUpdateSurface() {
+ return false;
+ }
+
+ @Override
public boolean hasZeroInsetsIme() {
return false;
}
diff --git a/core/java/android/view/InsetsSourceConsumer.java b/core/java/android/view/InsetsSourceConsumer.java
index 945975a88cd5..1a750a3f89c4 100644
--- a/core/java/android/view/InsetsSourceConsumer.java
+++ b/core/java/android/view/InsetsSourceConsumer.java
@@ -17,7 +17,6 @@
package android.view;
import static android.view.InsetsController.ANIMATION_TYPE_NONE;
-import static android.view.InsetsController.ANIMATION_TYPE_RESIZE;
import static android.view.InsetsController.AnimationType;
import static android.view.InsetsController.DEBUG;
import static android.view.InsetsSourceConsumerProto.ANIMATION_STATE;
@@ -201,9 +200,8 @@ public class InsetsSourceConsumer {
}
// If there is no animation controlling the leash, make sure the visibility and the
- // position is up-to-date. Note: ANIMATION_TYPE_RESIZE doesn't control the leash.
- final int animType = mController.getAnimationType(mType);
- if (animType == ANIMATION_TYPE_NONE || animType == ANIMATION_TYPE_RESIZE) {
+ // position is up-to-date.
+ if (!mController.hasSurfaceAnimation(mType)) {
applyRequestedVisibilityAndPositionToControl();
}
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index f32ce6f1d6e4..1213d173ab3b 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -5179,9 +5179,9 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
* This lives here since it's only valid for interactive views. This list is null
* until its first use.
*/
- private List<Rect> mSystemGestureExclusionRects = null;
- private List<Rect> mKeepClearRects = null;
- private List<Rect> mUnrestrictedKeepClearRects = null;
+ private ArrayList<Rect> mSystemGestureExclusionRects = null;
+ private ArrayList<Rect> mKeepClearRects = null;
+ private ArrayList<Rect> mUnrestrictedKeepClearRects = null;
private boolean mPreferKeepClear = false;
private Rect mHandwritingArea = null;
@@ -12891,21 +12891,34 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
final ListenerInfo info = getListenerInfo();
final boolean rectsChanged = !reduceChangedExclusionRectsMsgs()
- || !Objects.equals(info.mSystemGestureExclusionRects, rects);
- if (info.mSystemGestureExclusionRects != null) {
- if (rectsChanged) {
- info.mSystemGestureExclusionRects.clear();
- info.mSystemGestureExclusionRects.addAll(rects);
- }
- } else {
- info.mSystemGestureExclusionRects = new ArrayList<>(rects);
+ || !Objects.deepEquals(info.mSystemGestureExclusionRects, rects);
+ if (info.mSystemGestureExclusionRects == null) {
+ info.mSystemGestureExclusionRects = new ArrayList<>();
}
if (rectsChanged) {
+ deepCopyRectsObjectRecycling(info.mSystemGestureExclusionRects, rects);
updatePositionUpdateListener();
postUpdate(this::updateSystemGestureExclusionRects);
}
}
+ private void deepCopyRectsObjectRecycling(@NonNull ArrayList<Rect> dest, List<Rect> src) {
+ dest.ensureCapacity(src.size());
+ for (int i = 0; i < src.size(); i++) {
+ if (i < dest.size()) {
+ // Replace if there is an old rect to refresh
+ dest.get(i).set(src.get(i));
+ } else {
+ // Add a rect if the list enlarged
+ dest.add(Rect.copyOrNull(src.get(i)));
+ }
+ }
+ while (dest.size() > src.size()) {
+ // Remove elements if the list shrank
+ dest.removeLast();
+ }
+ }
+
private void updatePositionUpdateListener() {
final ListenerInfo info = getListenerInfo();
if (getSystemGestureExclusionRects().isEmpty()
@@ -13031,14 +13044,16 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
*/
public final void setPreferKeepClearRects(@NonNull List<Rect> rects) {
final ListenerInfo info = getListenerInfo();
- if (info.mKeepClearRects != null) {
- info.mKeepClearRects.clear();
- info.mKeepClearRects.addAll(rects);
- } else {
- info.mKeepClearRects = new ArrayList<>(rects);
+ final boolean rectsChanged = !reduceChangedExclusionRectsMsgs()
+ || !Objects.deepEquals(info.mKeepClearRects, rects);
+ if (info.mKeepClearRects == null) {
+ info.mKeepClearRects = new ArrayList<>();
+ }
+ if (rectsChanged) {
+ deepCopyRectsObjectRecycling(info.mKeepClearRects, rects);
+ updatePositionUpdateListener();
+ postUpdate(this::updateKeepClearRects);
}
- updatePositionUpdateListener();
- postUpdate(this::updateKeepClearRects);
}
/**
@@ -13076,14 +13091,16 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
@RequiresPermission(android.Manifest.permission.SET_UNRESTRICTED_KEEP_CLEAR_AREAS)
public final void setUnrestrictedPreferKeepClearRects(@NonNull List<Rect> rects) {
final ListenerInfo info = getListenerInfo();
- if (info.mUnrestrictedKeepClearRects != null) {
- info.mUnrestrictedKeepClearRects.clear();
- info.mUnrestrictedKeepClearRects.addAll(rects);
- } else {
- info.mUnrestrictedKeepClearRects = new ArrayList<>(rects);
+ final boolean rectsChanged = !reduceChangedExclusionRectsMsgs()
+ || !Objects.deepEquals(info.mUnrestrictedKeepClearRects, rects);
+ if (info.mUnrestrictedKeepClearRects == null) {
+ info.mUnrestrictedKeepClearRects = new ArrayList<>();
+ }
+ if (rectsChanged) {
+ deepCopyRectsObjectRecycling(info.mUnrestrictedKeepClearRects, rects);
+ updatePositionUpdateListener();
+ postUpdate(this::updateKeepClearRects);
}
- updatePositionUpdateListener();
- postUpdate(this::updateKeepClearRects);
}
/**
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 4e3ff9063179..9a62045f3435 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -189,6 +189,7 @@ import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.RenderNode;
+import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.hardware.SyncFence;
@@ -292,6 +293,7 @@ import com.android.internal.os.SomeArgs;
import com.android.internal.policy.DecorView;
import com.android.internal.policy.PhoneFallbackEventHandler;
import com.android.internal.protolog.ProtoLog;
+import com.android.internal.util.ContrastColorUtil;
import com.android.internal.util.FastPrintWriter;
import com.android.internal.view.BaseSurfaceHolder;
import com.android.internal.view.RootViewSurfaceTaker;
@@ -2078,12 +2080,21 @@ public final class ViewRootImpl implements ViewParent,
// preference for dark mode in configuration.uiMode. Instead, we assume that both
// force invert and the system's dark theme are enabled.
if (shouldApplyForceInvertDark()) {
- final boolean isLightTheme =
- a.getBoolean(R.styleable.Theme_isLightTheme, false);
- // TODO: b/372558459 - Also check the background ColorDrawable color lightness
// TODO: b/368725782 - Use hwui color area detection instead of / in
// addition to these heuristics.
- if (isLightTheme) {
+ final boolean isLightTheme =
+ a.getBoolean(R.styleable.Theme_isLightTheme, false);
+ final boolean isBackgroundColorLight;
+ if (mView != null && mView.getBackground()
+ instanceof ColorDrawable colorDrawable) {
+ isBackgroundColorLight =
+ !ContrastColorUtil.isColorDarkLab(colorDrawable.getColor());
+ } else {
+ // Treat unknown as light, so that only isLightTheme is used to determine
+ // force dark treatment.
+ isBackgroundColorLight = true;
+ }
+ if (isLightTheme && isBackgroundColorLight) {
return ForceDarkType.FORCE_INVERT_COLOR_DARK;
} else {
return ForceDarkType.NONE;
@@ -10270,6 +10281,8 @@ public final class ViewRootImpl implements ViewParent,
try {
mWindowSession.notifyImeWindowVisibilityChangedFromClient(mWindow, visible, statsToken);
} catch (RemoteException e) {
+ ImeTracker.forLogging().onFailed(statsToken,
+ ImeTracker.PHASE_CLIENT_NOTIFY_IME_VISIBILITY_CHANGED);
e.rethrowFromSystemServer();
}
}
diff --git a/core/java/android/view/autofill/AutofillFeatureFlags.java b/core/java/android/view/autofill/AutofillFeatureFlags.java
index 0814e23eea87..816d2debf87e 100644
--- a/core/java/android/view/autofill/AutofillFeatureFlags.java
+++ b/core/java/android/view/autofill/AutofillFeatureFlags.java
@@ -422,7 +422,7 @@ public class AutofillFeatureFlags {
*
* @hide
*/
- public static final boolean DEFAULT_SESSION_FILL_EVENT_HISTORY_ENABLED = false;
+ public static final boolean DEFAULT_SESSION_FILL_EVENT_HISTORY_ENABLED = true;
/**
* @hide
diff --git a/core/java/android/view/inputmethod/ImeTracker.java b/core/java/android/view/inputmethod/ImeTracker.java
index b1ba8b32d2f4..64f41c7a2987 100644
--- a/core/java/android/view/inputmethod/ImeTracker.java
+++ b/core/java/android/view/inputmethod/ImeTracker.java
@@ -232,6 +232,8 @@ public interface ImeTracker {
PHASE_WM_NOTIFY_HIDE_ANIMATION_FINISHED,
PHASE_WM_UPDATE_DISPLAY_WINDOW_ANIMATING_TYPES,
PHASE_CLIENT_ON_CONTROLS_CHANGED,
+ PHASE_SERVER_IME_INVOKER,
+ PHASE_SERVER_CLIENT_INVOKER,
})
@Retention(RetentionPolicy.SOURCE)
@interface Phase {}
@@ -473,6 +475,10 @@ public interface ImeTracker {
/** InsetsController received a control for the IME. */
int PHASE_CLIENT_ON_CONTROLS_CHANGED =
ImeProtoEnums.PHASE_CLIENT_ON_CONTROLS_CHANGED;
+ /** Reached the IME invoker on the server. */
+ int PHASE_SERVER_IME_INVOKER = ImeProtoEnums.PHASE_SERVER_IME_INVOKER;
+ /** Reached the IME client invoker on the server. */
+ int PHASE_SERVER_CLIENT_INVOKER = ImeProtoEnums.PHASE_SERVER_CLIENT_INVOKER;
/**
* Called when an IME request is started.
diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java
index 3dfbc2517986..1e0c4906e6ed 100644
--- a/core/java/android/widget/RemoteViews.java
+++ b/core/java/android/widget/RemoteViews.java
@@ -548,6 +548,25 @@ public class RemoteViews implements Parcelable, Filter {
}
/**
+ * Set a view tag associating a View with an ID to be used for widget interaction usage events
+ * ({@link android.app.usage.UsageEvents.Event}). When this RemoteViews is applied to a bound
+ * widget, any clicks or scrolls on the tagged view will be reported to
+ * {@link android.app.usage.UsageStatsManager} using this tag.
+ *
+ * @param viewId ID of the View whose tag will be set
+ * @param tag The integer tag to use for the event
+ *
+ * @see android.appwidget.AppWidgetManager#EVENT_TYPE_WIDGET_INTERACTION
+ * @see android.appwidget.AppWidgetManager#EXTRA_EVENT_CLICKED_VIEWS
+ * @see android.appwidget.AppWidgetManager#EXTRA_EVENT_SCROLLED_VIEWS
+ * @see android.app.usage.UsageStatsManager#queryEventsForSelf
+ */
+ @FlaggedApi(Flags.FLAG_ENGAGEMENT_METRICS)
+ public void setUsageEventTag(@IdRes int viewId, int tag) {
+ addAction(new SetIntTagAction(viewId, com.android.internal.R.id.remoteViewsMetricsId, tag));
+ }
+
+ /**
* Set that it is disallowed to reapply another remoteview with the same layout as this view.
* This should be done if an action is destroying the view tree of the base layout.
*
@@ -666,6 +685,14 @@ public class RemoteViews implements Parcelable, Filter {
View view,
PendingIntent pendingIntent,
RemoteResponse response);
+
+ /**
+ * Invoked when an AbsListView is scrolled.
+ * @param view view that was scrolled
+ *
+ * @hide
+ */
+ default void onScroll(@NonNull AbsListView view) {}
}
/**
@@ -1313,6 +1340,21 @@ public class RemoteViews implements Parcelable, Filter {
// a type error.
throw new ActionException(throwable);
}
+ if (adapterView instanceof AbsListView listView) {
+ listView.setOnScrollListener(new AbsListView.OnScrollListener() {
+ @Override
+ public void onScrollStateChanged(AbsListView view, int scrollState) {
+ if (scrollState != SCROLL_STATE_IDLE) {
+ params.handler.onScroll(view);
+ }
+ }
+
+ @Override
+ public void onScroll(AbsListView view, int firstVisibleItem,
+ int visibleItemCount, int totalItemCount) {
+ }
+ });
+ }
}
@Override
@@ -1804,6 +1846,19 @@ public class RemoteViews implements Parcelable, Filter {
AbsListView v = (AbsListView) target;
v.setRemoteViewsAdapter(mIntent, mIsAsync);
v.setRemoteViewsInteractionHandler(params.handler);
+ v.setOnScrollListener(new AbsListView.OnScrollListener() {
+ @Override
+ public void onScrollStateChanged(AbsListView view, int scrollState) {
+ if (scrollState != SCROLL_STATE_IDLE) {
+ params.handler.onScroll(view);
+ }
+ }
+
+ @Override
+ public void onScroll(AbsListView view, int firstVisibleItem,
+ int visibleItemCount, int totalItemCount) {
+ }
+ });
} else if (target instanceof AdapterViewAnimator) {
AdapterViewAnimator v = (AdapterViewAnimator) target;
v.setRemoteViewsAdapter(mIntent, mIsAsync);
@@ -1894,7 +1949,8 @@ public class RemoteViews implements Parcelable, Filter {
target.setTagInternal(com.android.internal.R.id.fillInIntent, null);
return;
}
- target.setOnClickListener(v -> mResponse.handleViewInteraction(v, params.handler));
+ target.setOnClickListener(v ->
+ mResponse.handleViewInteraction(v, params.handler));
}
@Override
diff --git a/core/java/android/window/DesktopModeFlags.java b/core/java/android/window/DesktopModeFlags.java
index 28a922d56019..983be682b8aa 100644
--- a/core/java/android/window/DesktopModeFlags.java
+++ b/core/java/android/window/DesktopModeFlags.java
@@ -55,14 +55,14 @@ public enum DesktopModeFlags {
ENABLE_CAPTION_COMPAT_INSET_FORCE_CONSUMPTION_ALWAYS(
Flags::enableCaptionCompatInsetForceConsumptionAlways, true),
ENABLE_CASCADING_WINDOWS(Flags::enableCascadingWindows, true),
- ENABLE_DESKTOP_APP_HANDLE_ANIMATION(Flags::enableDesktopAppHandleAnimation, false),
+ ENABLE_DESKTOP_APP_HANDLE_ANIMATION(Flags::enableDesktopAppHandleAnimation, true),
ENABLE_DESKTOP_APP_LAUNCH_ALTTAB_TRANSITIONS_BUGFIX(
Flags::enableDesktopAppLaunchAlttabTransitionsBugfix, true),
ENABLE_DESKTOP_APP_LAUNCH_TRANSITIONS_BUGFIX(Flags::enableDesktopAppLaunchTransitionsBugfix,
true),
ENABLE_DESKTOP_CLOSE_SHORTCUT_BUGFIX(Flags::enableDesktopCloseShortcutBugfix, false),
ENABLE_DESKTOP_COMPAT_UI_VISIBILITY_STATUS(Flags::enableCompatUiVisibilityStatus, true),
- ENABLE_DESKTOP_IMMERSIVE_DRAG_BUGFIX(Flags::enableDesktopImmersiveDragBugfix, false),
+ ENABLE_DESKTOP_IMMERSIVE_DRAG_BUGFIX(Flags::enableDesktopImmersiveDragBugfix, true),
ENABLE_DESKTOP_INDICATOR_IN_SEPARATE_THREAD_BUGFIX(
Flags::enableDesktopIndicatorInSeparateThreadBugfix, false),
ENABLE_DESKTOP_OPENING_DEEPLINK_MINIMIZE_ANIMATION_BUGFIX(
@@ -111,7 +111,7 @@ public enum DesktopModeFlags {
ENABLE_FULLY_IMMERSIVE_IN_DESKTOP(Flags::enableFullyImmersiveInDesktop, true),
ENABLE_HANDLE_INPUT_FIX(Flags::enableHandleInputFix, true),
ENABLE_HOLD_TO_DRAG_APP_HANDLE(Flags::enableHoldToDragAppHandle, true),
- ENABLE_INPUT_LAYER_TRANSITION_FIX(Flags::enableInputLayerTransitionFix, false),
+ ENABLE_INPUT_LAYER_TRANSITION_FIX(Flags::enableInputLayerTransitionFix, true),
ENABLE_MINIMIZE_BUTTON(Flags::enableMinimizeButton, true),
ENABLE_MODALS_FULLSCREEN_WITH_PERMISSIONS(Flags::enableModalsFullscreenWithPermission, true),
ENABLE_OPAQUE_BACKGROUND_FOR_TRANSPARENT_WINDOWS(
@@ -150,7 +150,7 @@ public enum DesktopModeFlags {
INHERIT_TASK_BOUNDS_FOR_TRAMPOLINE_TASK_LAUNCHES(
Flags::inheritTaskBoundsForTrampolineTaskLaunches, true),
SKIP_DECOR_VIEW_RELAYOUT_WHEN_CLOSING_BUGFIX(
- Flags::skipDecorViewRelayoutWhenClosingBugfix, false),
+ Flags::skipDecorViewRelayoutWhenClosingBugfix, true),
// go/keep-sorted end
;
diff --git a/core/java/com/android/internal/content/FileSystemProvider.java b/core/java/com/android/internal/content/FileSystemProvider.java
index 0801dd8c0bd8..fc74a179f66e 100644
--- a/core/java/com/android/internal/content/FileSystemProvider.java
+++ b/core/java/com/android/internal/content/FileSystemProvider.java
@@ -119,7 +119,7 @@ public abstract class FileSystemProvider extends DocumentsProvider {
* Callback indicating that the given document has been deleted or moved. This gives
* the provider a hook to revoke the uri permissions.
*/
- protected void onDocIdDeleted(String docId) {
+ protected void onDocIdDeleted(String docId, boolean shouldRevokeUriPermission) {
// Default is no-op
}
@@ -292,7 +292,6 @@ public abstract class FileSystemProvider extends DocumentsProvider {
final String afterDocId = getDocIdForFile(after);
onDocIdChanged(docId);
- onDocIdDeleted(docId);
onDocIdChanged(afterDocId);
final File afterVisibleFile = getFileForDocId(afterDocId, true);
@@ -301,6 +300,10 @@ public abstract class FileSystemProvider extends DocumentsProvider {
updateMediaStore(getContext(), afterVisibleFile);
if (!TextUtils.equals(docId, afterDocId)) {
+ // DocumentsProvider handles the revoking / granting uri permission for the docId and
+ // the afterDocId in the renameDocument case. Don't need to call revokeUriPermission
+ // for the docId here.
+ onDocIdDeleted(docId, /* shouldRevokeUriPermission */ false);
return afterDocId;
} else {
return null;
@@ -324,7 +327,7 @@ public abstract class FileSystemProvider extends DocumentsProvider {
final String docId = getDocIdForFile(after);
onDocIdChanged(sourceDocumentId);
- onDocIdDeleted(sourceDocumentId);
+ onDocIdDeleted(sourceDocumentId, /* shouldRevokeUriPermission */ true);
onDocIdChanged(docId);
// update the database
updateMediaStore(getContext(), visibleFileBefore);
@@ -362,7 +365,7 @@ public abstract class FileSystemProvider extends DocumentsProvider {
}
onDocIdChanged(docId);
- onDocIdDeleted(docId);
+ onDocIdDeleted(docId, /* shouldRevokeUriPermission */ true);
updateMediaStore(getContext(), visibleFile);
}
diff --git a/core/java/com/android/internal/inputmethod/InputMethodDebug.java b/core/java/com/android/internal/inputmethod/InputMethodDebug.java
index 4d5e67ab8fde..9cdfc02e2e28 100644
--- a/core/java/com/android/internal/inputmethod/InputMethodDebug.java
+++ b/core/java/com/android/internal/inputmethod/InputMethodDebug.java
@@ -305,6 +305,8 @@ public final class InputMethodDebug {
return "HIDE_INPUT_TARGET_CHANGED";
case SoftInputShowHideReason.HIDE_WINDOW_LOST_FOCUS:
return "HIDE_WINDOW_LOST_FOCUS";
+ case SoftInputShowHideReason.IME_REQUESTED_CHANGED_LISTENER:
+ return "IME_REQUESTED_CHANGED_LISTENER";
default:
return "Unknown=" + reason;
}
diff --git a/core/java/com/android/internal/inputmethod/SoftInputShowHideReason.java b/core/java/com/android/internal/inputmethod/SoftInputShowHideReason.java
index cf0580c2f021..8b4371ea8478 100644
--- a/core/java/com/android/internal/inputmethod/SoftInputShowHideReason.java
+++ b/core/java/com/android/internal/inputmethod/SoftInputShowHideReason.java
@@ -92,6 +92,7 @@ import java.lang.annotation.Retention;
SoftInputShowHideReason.SHOW_INPUT_TARGET_CHANGED,
SoftInputShowHideReason.HIDE_INPUT_TARGET_CHANGED,
SoftInputShowHideReason.HIDE_WINDOW_LOST_FOCUS,
+ SoftInputShowHideReason.IME_REQUESTED_CHANGED_LISTENER,
})
public @interface SoftInputShowHideReason {
/** Default, undefined reason. */
@@ -422,4 +423,10 @@ public @interface SoftInputShowHideReason {
/** Hide soft input when the window lost focus. */
int HIDE_WINDOW_LOST_FOCUS = ImeProtoEnums.REASON_HIDE_WINDOW_LOST_FOCUS;
+
+ /**
+ * Show / Hide soft input by
+ * {@link com.android.server.wm.WindowManagerInternal.OnImeRequestedChangedListener}
+ */
+ int IME_REQUESTED_CHANGED_LISTENER = ImeProtoEnums.REASON_IME_REQUESTED_CHANGED_LISTENER;
}
diff --git a/core/java/com/android/internal/protolog/LogcatOnlyProtoLogImpl.java b/core/java/com/android/internal/protolog/LogcatOnlyProtoLogImpl.java
index 34e04181388d..256a3ffd6456 100644
--- a/core/java/com/android/internal/protolog/LogcatOnlyProtoLogImpl.java
+++ b/core/java/com/android/internal/protolog/LogcatOnlyProtoLogImpl.java
@@ -19,6 +19,7 @@ package com.android.internal.protolog;
import static com.android.internal.protolog.ProtoLog.REQUIRE_PROTOLOGTOOL;
import android.annotation.NonNull;
+import android.ravenwood.annotation.RavenwoodKeepWholeClass;
import android.text.TextUtils;
import android.util.Log;
@@ -31,14 +32,15 @@ import java.util.Collections;
import java.util.List;
/**
- * Class only create and used to server temporarily for when there is source code pre-processing by
+ * Class only created and used to serve temporarily for when there is source code pre-processing by
* the ProtoLog tool, when the tracing to Perfetto flag is off, and the static REQUIRE_PROTOLOGTOOL
* boolean is false. In which case we simply want to log protolog message to logcat. Note, that this
* means that in such cases there is no real advantage of using protolog over logcat.
*
- * @deprecated Should not be used. This is just a temporary class to support a legacy behavior.
+ * NOTE: Should not be used in real products as this mostly removes the benefits of protolog. This
+ * is just a temporary class to support a legacy behavior and tests running on the host-side.
*/
-@Deprecated
+@RavenwoodKeepWholeClass
public class LogcatOnlyProtoLogImpl implements IProtoLog {
private static final String LOG_TAG = LogcatOnlyProtoLogImpl.class.getName();
diff --git a/core/java/com/android/internal/protolog/ProtoLog.java b/core/java/com/android/internal/protolog/ProtoLog.java
index c81af959f36c..915b981a7e7a 100644
--- a/core/java/com/android/internal/protolog/ProtoLog.java
+++ b/core/java/com/android/internal/protolog/ProtoLog.java
@@ -17,6 +17,8 @@
package com.android.internal.protolog;
import android.os.ServiceManager;
+import android.ravenwood.annotation.RavenwoodKeepWholeClass;
+import android.ravenwood.annotation.RavenwoodReplace;
import android.tracing.perfetto.DataSourceParams;
import android.tracing.perfetto.InitArguments;
import android.tracing.perfetto.Producer;
@@ -47,6 +49,7 @@ import java.util.HashSet;
* Methods in this class are stubs, that are replaced by optimised versions by the ProtoLogTool
* during build.
*/
+@RavenwoodKeepWholeClass
// LINT.IfChange
public class ProtoLog {
// LINT.ThenChange(frameworks/base/tools/protologtool/src/com/android/protolog/tool/ProtoLogTool.kt)
@@ -73,13 +76,25 @@ public class ProtoLog {
// These tracing instances are only used when we cannot or do not preprocess the source
// files to extract out the log strings. Otherwise, the trace calls are replaced with calls
// directly to the generated tracing implementations.
- if (android.tracing.Flags.perfettoProtologTracing()) {
- initializePerfettoProtoLog(groups);
- } else {
+ if (logOnlyToLogcat()) {
sProtoLogInstance = new LogcatOnlyProtoLogImpl();
+ } else {
+ initializePerfettoProtoLog(groups);
}
}
+ @RavenwoodReplace(reason = "Always use the Log backend on ravenwood, not Perfetto")
+ private static boolean logOnlyToLogcat() {
+ return !android.tracing.Flags.perfettoProtologTracing();
+ }
+
+ private static boolean logOnlyToLogcat$ravenwood() {
+ // We don't want to initialize Perfetto data sources and have to deal with Perfetto
+ // when running tests on the host side, instead just log everything to logcat which has
+ // already been made compatible with ravenwood.
+ return true;
+ }
+
private static void initializePerfettoProtoLog(IProtoLogGroup... groups) {
var datasource = getSharedSingleInstanceDataSource();
diff --git a/core/java/com/android/internal/protolog/common/LogLevel.java b/core/java/com/android/internal/protolog/common/LogLevel.java
index b5541ae81c2d..ea62a665c980 100644
--- a/core/java/com/android/internal/protolog/common/LogLevel.java
+++ b/core/java/com/android/internal/protolog/common/LogLevel.java
@@ -16,6 +16,9 @@
package com.android.internal.protolog.common;
+import android.ravenwood.annotation.RavenwoodKeepWholeClass;
+
+@RavenwoodKeepWholeClass
public enum LogLevel {
DEBUG("d", 1),
VERBOSE("v", 2),
diff --git a/core/java/com/android/internal/util/ContrastColorUtil.java b/core/java/com/android/internal/util/ContrastColorUtil.java
index 0fd139188665..c68f107951ac 100644
--- a/core/java/com/android/internal/util/ContrastColorUtil.java
+++ b/core/java/com/android/internal/util/ContrastColorUtil.java
@@ -41,8 +41,6 @@ import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.util.Pair;
-import com.android.internal.annotations.VisibleForTesting;
-
import java.util.Arrays;
import java.util.WeakHashMap;
@@ -381,6 +379,13 @@ public class ContrastColorUtil {
return calculateLuminance(color) <= 0.17912878474;
}
+ /** Like {@link #isColorDark(int)} but converts to LAB before checking the L component. */
+ public static boolean isColorDarkLab(int color) {
+ final double[] result = ColorUtilsFromCompat.getTempDouble3Array();
+ ColorUtilsFromCompat.colorToLAB(color, result);
+ return result[0] < 50;
+ }
+
private int processColor(int color) {
return Color.argb(Color.alpha(color),
255 - Color.red(color),
diff --git a/core/jni/fd_utils.cpp b/core/jni/fd_utils.cpp
index 5225ce878310..0eb7c4aee287 100644
--- a/core/jni/fd_utils.cpp
+++ b/core/jni/fd_utils.cpp
@@ -51,8 +51,7 @@ static const char* kPathAllowlist[] = {
"/dev/blkio/tasks",
"/metadata/aconfig/maps/system.package.map",
"/metadata/aconfig/maps/system.flag.map",
- "/metadata/aconfig/boot/system.val",
- "/metadata/libprocessgroup/memcg_v2_max_activation_depth" // TODO Revert after go/android-memcgv2-exp b/386797433
+ "/metadata/aconfig/boot/system.val"
};
static const char kFdPath[] = "/proc/self/fd";
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 9e0200481421..f62ce278f28a 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -4554,12 +4554,12 @@
android:protectionLevel="signature|privileged" />
<!-- Allows application to request to stream content from an Android host to a nearby device
- ({@link android.companion.AssociationRequest#DEVICE_PROFILE_SENSOR_DEVICE_STREAMING})
+ ({@link android.companion.AssociationRequest#DEVICE_PROFILE_VIRTUAL_DEVICE})
by {@link android.companion.CompanionDeviceManager}.
<p>Not for use by third-party applications.
@FlaggedApi(android.companion.virtualdevice.flags.Flags.FLAG_ENABLE_LIMITED_VDM_ROLE)
-->
- <permission android:name="android.permission.REQUEST_COMPANION_PROFILE_SENSOR_DEVICE_STREAMING"
+ <permission android:name="android.permission.REQUEST_COMPANION_PROFILE_VIRTUAL_DEVICE"
android:protectionLevel="signature|privileged"
android:featureFlag="android.companion.virtualdevice.flags.enable_limited_vdm_role" />
@@ -9287,11 +9287,15 @@
<receiver android:name="com.android.server.updates.CertPinInstallReceiver"
android:exported="true"
+ android:systemUserOnly="true"
android:permission="android.permission.UPDATE_CONFIG">
<intent-filter>
<action android:name="android.intent.action.UPDATE_PINS" />
<data android:scheme="content" android:host="*" android:mimeType="*/*" />
</intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
+ </intent-filter>
</receiver>
<receiver android:name="com.android.server.updates.IntentFirewallInstallReceiver"
diff --git a/core/res/res/drawable/ic_standby.xml b/core/res/res/drawable/ic_standby.xml
new file mode 100644
index 000000000000..6736f14f1377
--- /dev/null
+++ b/core/res/res/drawable/ic_standby.xml
@@ -0,0 +1,10 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:viewportWidth="960"
+ android:viewportHeight="960"
+ android:tint="?attr/colorControlNormal">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M480,600Q530,600 565,565Q600,530 600,480Q600,430 565,395Q530,360 480,360Q430,360 395,395Q360,430 360,480Q360,530 395,565Q430,600 480,600ZM480,880Q397,880 324,848.5Q251,817 197,763Q143,709 111.5,636Q80,563 80,480Q80,397 111.5,324Q143,251 197,197Q251,143 324,111.5Q397,80 480,80Q563,80 636,111.5Q709,143 763,197Q817,251 848.5,324Q880,397 880,480Q880,563 848.5,636Q817,709 763,763Q709,817 636,848.5Q563,880 480,880ZM480,800Q614,800 707,707Q800,614 800,480Q800,346 707,253Q614,160 480,160Q346,160 253,253Q160,346 160,480Q160,614 253,707Q346,800 480,800ZM480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Z"/>
+</vector>
diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml
index 828461c66a1f..cb4dd46e70fe 100644
--- a/core/res/res/values/config.xml
+++ b/core/res/res/values/config.xml
@@ -2029,6 +2029,9 @@
<!-- Class name of WallpaperManagerService. -->
<string name="config_wallpaperManagerServiceName" translatable="false">com.android.server.wallpaper.WallpaperManagerService</string>
+ <!-- True if live wallpapers can be supported in the deskop experience -->
+ <bool name="config_isLiveWallpaperSupportedInDesktopExperience">false</bool>
+
<!-- Specifies priority of automatic time sources. Suggestions from higher entries in the list
take precedence over lower ones.
See com.android.server.timedetector.TimeDetectorStrategy for available sources. -->
@@ -3836,6 +3839,7 @@
"lockdown" = Lock down device until the user authenticates
"logout" = Logout the current user
"system_update" = Launch System Update screen
+ "standby" = Bring the device to standby
-->
<string-array translatable="false" name="config_globalActionsList">
<item>emergency</item>
diff --git a/core/res/res/values/public-staging.xml b/core/res/res/values/public-staging.xml
index ac1e841d3143..ed524054a5d4 100644
--- a/core/res/res/values/public-staging.xml
+++ b/core/res/res/values/public-staging.xml
@@ -128,7 +128,7 @@
<staging-public-group type="id" first-id="0x01b20000">
<!-- @FlaggedApi(android.appwidget.flags.Flags.FLAG_ENGAGEMENT_METRICS) -->
- <public name="remoteViewsMetricsId"/>
+ <public name="removed_remoteViewsMetricsId"/>
<!-- @FlaggedApi("android.view.accessibility.a11y_selection_api") -->
<public name="accessibilityActionSetExtendedSelection"/>
</staging-public-group>
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index d94d659446ac..da6ebe9e7ac0 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -739,6 +739,9 @@
<!-- label for screenshot item in power menu [CHAR LIMIT=24]-->
<string name="global_action_screenshot">Screenshot</string>
+ <!-- label for standby item in power menu [CHAR LIMIT=24]-->
+ <string name="global_action_standby">Standby</string>
+
<!-- Take bug report menu title [CHAR LIMIT=30] -->
<string name="bugreport_title">Bug report</string>
<!-- Message in bugreport dialog describing what it does [CHAR LIMIT=NONE] -->
diff --git a/core/res/res/values/symbols.xml b/core/res/res/values/symbols.xml
index 219ac3f89997..ab219a595b09 100644
--- a/core/res/res/values/symbols.xml
+++ b/core/res/res/values/symbols.xml
@@ -1958,6 +1958,7 @@
<java-symbol type="string" name="global_action_voice_assist" />
<java-symbol type="string" name="global_action_assist" />
<java-symbol type="string" name="global_action_screenshot" />
+ <java-symbol type="string" name="global_action_standby" />
<java-symbol type="string" name="invalidPuk" />
<java-symbol type="string" name="lockscreen_carrier_default" />
<java-symbol type="style" name="Animation.LockScreen" />
@@ -2281,6 +2282,7 @@
<java-symbol type="string" name="heavy_weight_notification_detail" />
<java-symbol type="string" name="image_wallpaper_component" />
<java-symbol type="string" name="fallback_wallpaper_component" />
+ <java-symbol type="bool" name="config_isLiveWallpaperSupportedInDesktopExperience" />
<java-symbol type="string" name="input_method_binding_label" />
<java-symbol type="string" name="input_method_ime_switch_long_click_action_desc" />
<java-symbol type="string" name="launch_warning_original" />
@@ -3721,6 +3723,7 @@
<java-symbol type="drawable" name="ic_screenshot" />
<java-symbol type="drawable" name="ic_faster_emergency" />
<java-symbol type="drawable" name="ic_media_seamless" />
+ <java-symbol type="drawable" name="ic_standby" />
<java-symbol type="drawable" name="emergency_icon" />
<java-symbol type="array" name="config_convert_to_emergency_number_map" />
@@ -5224,6 +5227,7 @@
<java-symbol type="id" name="remote_views_next_child" />
<java-symbol type="id" name="remote_views_stable_id" />
<java-symbol type="id" name="remote_views_override_id" />
+ <java-symbol type="id" name="remoteViewsMetricsId" />
<!-- View and control prompt -->
<java-symbol type="drawable" name="ic_accessibility_24dp" />
diff --git a/core/tests/coretests/src/android/app/NotificationTest.java b/core/tests/coretests/src/android/app/NotificationTest.java
index 157c74abc5de..0287956bd07f 100644
--- a/core/tests/coretests/src/android/app/NotificationTest.java
+++ b/core/tests/coretests/src/android/app/NotificationTest.java
@@ -462,7 +462,7 @@ public class NotificationTest {
@Test
@EnableFlags(Flags.FLAG_UI_RICH_ONGOING)
- public void testHasPromotableCharacteristics() {
+ public void testHasPromotableCharacteristics_bigText_bigTitle() {
Notification n = new Notification.Builder(mContext, "test")
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setStyle(new Notification.BigTextStyle().setBigContentTitle("BIG"))
@@ -475,6 +475,20 @@ public class NotificationTest {
@Test
@EnableFlags(Flags.FLAG_UI_RICH_ONGOING)
+ public void testHasPromotableCharacteristics_bigText_normalTitle() {
+ Notification n = new Notification.Builder(mContext, "test")
+ .setSmallIcon(android.R.drawable.sym_def_app_icon)
+ .setStyle(new Notification.BigTextStyle())
+ .setContentTitle("TITLE")
+ .setColor(Color.WHITE)
+ .setColorized(true)
+ .setOngoing(true)
+ .build();
+ assertThat(n.hasPromotableCharacteristics()).isTrue();
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_UI_RICH_ONGOING)
public void testHasPromotableCharacteristics_notOngoing() {
Notification n = new Notification.Builder(mContext, "test")
.setSmallIcon(android.R.drawable.sym_def_app_icon)
@@ -526,6 +540,51 @@ public class NotificationTest {
@Test
@EnableFlags(Flags.FLAG_UI_RICH_ONGOING)
+ public void testHasPromotableCharacteristics_noStyle_onlyBigTitle() {
+ Bundle extras = new Bundle();
+ extras.putString(Notification.EXTRA_TITLE_BIG, "BIG");
+ Notification n = new Notification.Builder(mContext, "test")
+ .setSmallIcon(android.R.drawable.sym_def_app_icon)
+ .setColor(Color.WHITE)
+ .setColorized(true)
+ .setOngoing(true)
+ .addExtras(extras)
+ .build();
+ assertThat(n.hasPromotableCharacteristics()).isFalse();
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_UI_RICH_ONGOING)
+ public void testHasPromotableCharacteristics_ongoingCallStyle_notColorized() {
+ PendingIntent intent = PendingIntent.getActivity(
+ mContext, 0, new Intent("test1"), PendingIntent.FLAG_IMMUTABLE);
+ Person person = new Person.Builder().setName("Caller").build();
+ Notification n = new Notification.Builder(mContext, "test")
+ .setSmallIcon(android.R.drawable.sym_def_app_icon)
+ .setStyle(Notification.CallStyle.forOngoingCall(person, intent))
+ .setColor(Color.WHITE)
+ .setOngoing(true)
+ .build();
+ assertThat(n.hasPromotableCharacteristics()).isTrue();
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_UI_RICH_ONGOING)
+ public void testHasPromotableCharacteristics_incomingCallStyle_notColorized() {
+ PendingIntent intent = PendingIntent.getActivity(
+ mContext, 0, new Intent("test1"), PendingIntent.FLAG_IMMUTABLE);
+ Person person = new Person.Builder().setName("Caller").build();
+ Notification n = new Notification.Builder(mContext, "test")
+ .setSmallIcon(android.R.drawable.sym_def_app_icon)
+ .setStyle(Notification.CallStyle.forIncomingCall(person, intent, intent))
+ .setColor(Color.WHITE)
+ .setOngoing(true)
+ .build();
+ assertThat(n.hasPromotableCharacteristics()).isFalse();
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_UI_RICH_ONGOING)
public void testHasPromotableCharacteristics_groupSummary() {
Notification n = new Notification.Builder(mContext, "test")
.setSmallIcon(android.R.drawable.sym_def_app_icon)
diff --git a/core/tests/coretests/src/android/appwidget/AppWidgetEventsTest.kt b/core/tests/coretests/src/android/appwidget/AppWidgetEventsTest.kt
index ea1158c88055..0135378ba681 100644
--- a/core/tests/coretests/src/android/appwidget/AppWidgetEventsTest.kt
+++ b/core/tests/coretests/src/android/appwidget/AppWidgetEventsTest.kt
@@ -16,14 +16,33 @@
package android.appwidget
+import android.app.PendingIntent
+import android.appwidget.AppWidgetHostView.InteractionLogger.MAX_NUM_ITEMS
+import android.content.Intent
import android.graphics.Rect
+import android.view.View
+import android.widget.ListView
+import android.widget.RemoteViews
import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import com.android.frameworks.coretests.R
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AppWidgetEventsTest {
+ private val context = InstrumentationRegistry.getInstrumentation().targetContext!!
+ private val hostView = AppWidgetHostView(context).apply {
+ setAppWidget(0, AppWidgetManager.getInstance(context).installedProviders.first())
+ }
+ private val pendingIntent = PendingIntent.getActivity(
+ context,
+ 0,
+ Intent(),
+ PendingIntent.FLAG_IMMUTABLE,
+ )
+
@Test
fun createWidgetInteractionEvent() {
val appWidgetId = 1
@@ -48,4 +67,123 @@ class AppWidgetEventsTest {
assertThat(bundle.getIntArray(AppWidgetManager.EXTRA_EVENT_SCROLLED_VIEWS))
.asList().containsExactly(scrolled[0], scrolled[1], scrolled[2])
}
+
+ @Test
+ fun interactionLogger_click() {
+ val itemCount = MAX_NUM_ITEMS + 1
+ // Set a different value for the viewId to test that the logger always uses the
+ // metrics tag if available.
+ fun viewId(i: Int) = i + Int.MIN_VALUE
+ val remoteViews = RemoteViews(context.packageName, R.layout.remote_views_test).apply {
+ for (i in 0 until itemCount) {
+ val metricsTag = i
+ val item =
+ RemoteViews(context.packageName, R.layout.remote_views_text, viewId(i)).apply {
+ setUsageEventTag(viewId(i), metricsTag)
+ setOnClickPendingIntent(viewId(i), pendingIntent)
+ }
+ addView(R.id.layout, item)
+ }
+ }
+ hostView.updateAppWidget(remoteViews)
+ assertThat(hostView.interactionLogger.clickedIds).isEmpty()
+
+
+ for (i in 0 until itemCount.minus(1)) {
+ val item = hostView.findViewById<View>(viewId(i))
+ assertThat(item).isNotNull()
+ assertThat(item.performClick()).isTrue()
+ assertThat(hostView.interactionLogger.clickedIds)
+ .containsExactlyElementsIn(0..i)
+ }
+ assertThat(hostView.interactionLogger.clickedIds).hasSize(MAX_NUM_ITEMS)
+
+ // Last item click should not be recorded because we've reached MAX_VIEW_IDS
+ val lastItem = hostView.findViewById<View>(viewId(itemCount - 1))
+ assertThat(lastItem).isNotNull()
+ assertThat(lastItem.performClick()).isTrue()
+ assertThat(hostView.interactionLogger.clickedIds).hasSize(MAX_NUM_ITEMS)
+ assertThat(hostView.interactionLogger.clickedIds)
+ .containsExactlyElementsIn(0..itemCount.minus(2))
+ }
+
+ @Test
+ fun interactionLogger_click_listItem() {
+ val itemCount = 5
+ val remoteViews = RemoteViews(context.packageName, R.layout.remote_views_list).apply {
+ setPendingIntentTemplate(R.id.list, pendingIntent)
+ setRemoteAdapter(
+ R.id.list,
+ RemoteViews.RemoteCollectionItems.Builder().run {
+ for (i in 0 until itemCount) {
+ val item = RemoteViews(context.packageName, R.layout.remote_views_test)
+ item.setOnClickFillInIntent(R.id.text, Intent())
+ item.setUsageEventTag(R.id.text, i)
+ addItem(i.toLong(), item)
+ }
+ build()
+ }
+ )
+ setUsageEventTag(R.id.list, -1)
+ }
+ hostView.updateAppWidget(remoteViews)
+ assertThat(hostView.interactionLogger.clickedIds).isEmpty()
+
+ val list = hostView.findViewById<ListView>(R.id.list)
+ assertThat(list).isNotNull()
+ list.layout(0, 0, 500, 500)
+ for (i in 0 until itemCount) {
+ val item = list.getChildAt(i).findViewById<View>(R.id.text)
+ assertThat(item.performClick()).isTrue()
+ assertThat(hostView.interactionLogger.clickedIds)
+ .containsExactlyElementsIn(0..i)
+ }
+ }
+
+ @Test
+ fun interactionLogger_scroll() {
+ val itemCount = MAX_NUM_ITEMS + 1
+ // Set a different value for the viewId to test that the logger always uses the
+ // metrics tag if available.
+ fun viewId(i: Int) = i + Int.MIN_VALUE
+ val remoteViews = RemoteViews(context.packageName, R.layout.remote_views_test).apply {
+ for (i in 0 until itemCount) {
+ val metricsTag = i
+ val item =
+ RemoteViews(context.packageName, R.layout.remote_views_list, viewId(i)).apply {
+ setUsageEventTag(viewId(i), metricsTag)
+ setRemoteAdapter(
+ viewId(i),
+ RemoteViews.RemoteCollectionItems.Builder().run {
+ addItem(
+ 0L,
+ RemoteViews(context.packageName, R.layout.remote_views_test)
+ )
+ build()
+ }
+ )
+ }
+ addView(R.id.layout, item)
+ }
+ }
+ hostView.updateAppWidget(remoteViews)
+ assertThat(hostView.interactionLogger.scrolledIds).isEmpty()
+
+ for (i in 0 until itemCount.minus(1)) {
+ val item = hostView.findViewById<ListView>(viewId(i))
+ assertThat(item).isNotNull()
+ item.fling(/* velocityY= */ 100)
+ assertThat(hostView.interactionLogger.scrolledIds)
+ .containsExactlyElementsIn(0..i)
+ }
+ assertThat(hostView.interactionLogger.scrolledIds).hasSize(MAX_NUM_ITEMS)
+
+ // Last item scroll should not be recorded because we've reached MAX_VIEW_IDS
+ val lastItem = hostView.findViewById<ListView>(viewId(itemCount - 1))
+ assertThat(lastItem).isNotNull()
+ lastItem.fling(/* velocityY= */ 100)
+ assertThat(hostView.interactionLogger.scrolledIds).hasSize(MAX_NUM_ITEMS)
+ assertThat(hostView.interactionLogger.scrolledIds)
+ .containsExactlyElementsIn(0..itemCount.minus(2))
+ }
}
diff --git a/core/tests/coretests/src/android/text/LayoutTest.java b/core/tests/coretests/src/android/text/LayoutTest.java
index 11ec9f8e1912..7d8afcabad7b 100644
--- a/core/tests/coretests/src/android/text/LayoutTest.java
+++ b/core/tests/coretests/src/android/text/LayoutTest.java
@@ -1029,51 +1029,16 @@ public class LayoutTest {
@Test
@RequiresFlagsEnabled(FLAG_HIGH_CONTRAST_TEXT_SMALL_TEXT_RECT)
- public void highContrastTextEnabled_testWhitespaceText_DrawsBackgroundsWithAdjacentLetters() {
- mTextPaint.setColor(Color.BLACK);
- SpannableString spannedText = new SpannableString("Test\tTap and Space");
-
- // Set the entire text to white initially
- spannedText.setSpan(
- new ForegroundColorSpan(Color.WHITE),
- /* start= */ 0,
- /* end= */ spannedText.length(),
- Spanned.SPAN_INCLUSIVE_EXCLUSIVE
- );
-
- // Find the whitespace character and set its color to black
- for (int i = 0; i < spannedText.length(); i++) {
- if (Character.isWhitespace(spannedText.charAt(i))) {
- spannedText.setSpan(
- new ForegroundColorSpan(Color.BLACK),
- i,
- i + 1,
- Spanned.SPAN_INCLUSIVE_EXCLUSIVE
- );
- }
- }
-
- Layout layout = new StaticLayout(spannedText, mTextPaint, mWidth,
- mAlign, mSpacingMult, mSpacingAdd, /* includePad= */ false);
-
- MockCanvas c = new MockCanvas(/* width= */ 256, /* height= */ 256);
- c.setHighContrastTextEnabled(true);
- layout.draw(
- c,
- /* highlightPaths= */ null,
- /* highlightPaints= */ null,
- /* selectionPath= */ null,
- /* selectionPaint= */ null,
- /* cursorOffsetVertical= */ 0
- );
+ public void highContrastTextEnabled_testWhiteSpaceWithinText_drawsSameBackgroundswithText() {
+ SpannableString spannedText = new SpannableString("Hello\tWorld !");
+ testSpannableStringAppliesAllColorsCorrectly(spannedText);
+ }
- List<MockCanvas.DrawCommand> drawCommands = c.getDrawCommands();
- for (int i = 0; i < drawCommands.size(); i++) {
- MockCanvas.DrawCommand drawCommand = drawCommands.get(i);
- if (drawCommand.rect != null) {
- expect.that(removeAlpha(drawCommand.paint.getColor())).isEqualTo(Color.BLACK);
- }
- }
+ @Test
+ @RequiresFlagsEnabled(FLAG_HIGH_CONTRAST_TEXT_SMALL_TEXT_RECT)
+ public void highContrastTextEnabled_testWhiteSpaceAtStart_drawsCorrectBackgroundsOnText() {
+ SpannableString spannedText = new SpannableString(" HelloWorld!");
+ testSpannableStringAppliesAllColorsCorrectly(spannedText);
}
@Test
@@ -1331,5 +1296,54 @@ public class LayoutTest {
"",
new boolean[]{false});
}
+
+ private void testSpannableStringAppliesAllColorsCorrectly(SpannableString spannedText) {
+ for (int textColor : new int[] {Color.WHITE, Color.BLACK}) {
+ final int contrastingColor = textColor == Color.WHITE ? Color.BLACK : Color.WHITE;
+ // Set the paint color to the contrasting color to verify the high contrast text
+ // background rect color is correct.
+ mTextPaint.setColor(contrastingColor);
+
+ // Set the entire text to test color initially
+ spannedText.setSpan(
+ new ForegroundColorSpan(textColor),
+ /* start= */ 0,
+ /* end= */ spannedText.length(),
+ Spanned.SPAN_INCLUSIVE_EXCLUSIVE
+ );
+
+ Layout layout = new StaticLayout(spannedText, mTextPaint, mWidth,
+ mAlign, mSpacingMult, mSpacingAdd, /* includePad= */ false);
+
+ MockCanvas c = new MockCanvas(/* width= */ 256, /* height= */ 256);
+ c.setHighContrastTextEnabled(true);
+ layout.draw(
+ c,
+ /* highlightPaths= */ null,
+ /* highlightPaints= */ null,
+ /* selectionPath= */ null,
+ /* selectionPaint= */ null,
+ /* cursorOffsetVertical= */ 0
+ );
+
+ int numBackgroundsFound = 0;
+ List<MockCanvas.DrawCommand> drawCommands = c.getDrawCommands();
+ for (int i = 0; i < drawCommands.size(); i++) {
+ MockCanvas.DrawCommand drawCommand = drawCommands.get(i);
+
+ if (drawCommand.rect != null) {
+ numBackgroundsFound++;
+ // Verifies the background color of the high-contrast rectangle drawn behind
+ // the text. In high-contrast mode, the background color should contrast with
+ // the text color. 'contrastingColor' represents the expected background color,
+ // which is the inverse of the text color (e.g., if text is white, background
+ // is black, and vice versa).
+ expect.that(removeAlpha(drawCommand.paint.getColor()))
+ .isEqualTo(contrastingColor);
+ }
+ }
+ expect.that(numBackgroundsFound).isLessThan(spannedText.length());
+ }
+ }
}
diff --git a/core/tests/coretests/src/android/view/ViewRootImplTest.java b/core/tests/coretests/src/android/view/ViewRootImplTest.java
index 5774109e1451..1b7805c351db 100644
--- a/core/tests/coretests/src/android/view/ViewRootImplTest.java
+++ b/core/tests/coretests/src/android/view/ViewRootImplTest.java
@@ -16,8 +16,6 @@
package android.view;
-import static android.app.UiModeManager.MODE_NIGHT_NO;
-import static android.app.UiModeManager.MODE_NIGHT_YES;
import static android.util.SequenceUtils.getInitSeq;
import static android.view.HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING;
import static android.view.InputDevice.SOURCE_ROTARY_ENCODER;
@@ -69,10 +67,9 @@ import static org.junit.Assume.assumeTrue;
import android.annotation.NonNull;
import android.app.Instrumentation;
import android.app.UiModeManager;
-import android.app.UiModeManager.ForceInvertType;
import android.content.Context;
+import android.graphics.Color;
import android.graphics.ForceDarkType;
-import android.graphics.ForceDarkType.ForceDarkTypeDef;
import android.graphics.Rect;
import android.hardware.display.DisplayManagerGlobal;
import android.os.Binder;
@@ -101,8 +98,6 @@ import com.android.compatibility.common.util.TestUtils;
import com.android.cts.input.BlockingQueueEventVerifier;
import com.android.window.flags.Flags;
-import com.google.common.truth.Expect;
-
import org.hamcrest.Matcher;
import org.junit.After;
import org.junit.AfterClass;
@@ -131,8 +126,6 @@ public class ViewRootImplTest {
@Rule
public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
- @Rule
- public final Expect mExpect = Expect.create();
private ViewRootImpl mViewRootImpl;
private View mView;
@@ -1516,29 +1509,83 @@ public class ViewRootImplTest {
}
@Test
- @RequiresFlagsEnabled(FLAG_FORCE_INVERT_COLOR)
- public void updateConfiguration_returnsExpectedForceDarkMode() {
+ @EnableFlags(FLAG_FORCE_INVERT_COLOR)
+ public void determineForceDarkType_systemLightMode_returnsNone() throws Exception {
+ waitForSystemNightModeActivated(false);
+
+ TestUtils.waitUntil("Waiting for ForceDarkType to be ready",
+ () -> (mViewRootImpl.determineForceDarkType() == ForceDarkType.NONE));
+
+ }
+
+ @Test
+ @EnableFlags(FLAG_FORCE_INVERT_COLOR)
+ public void determineForceDarkType_systemNightModeAndDisableForceInvertColor_returnsNone()
+ throws Exception {
waitForSystemNightModeActivated(true);
- verifyForceDarkType(/* isAppInNightMode= */ true, /* isForceInvertEnabled= */ true,
- UiModeManager.FORCE_INVERT_TYPE_DARK, ForceDarkType.FORCE_INVERT_COLOR_DARK);
- verifyForceDarkType(/* isAppInNightMode= */ true, /* isForceInvertEnabled= */ false,
- UiModeManager.FORCE_INVERT_TYPE_OFF, ForceDarkType.NONE);
- verifyForceDarkType(/* isAppInNightMode= */ false, /* isForceInvertEnabled= */ true,
- UiModeManager.FORCE_INVERT_TYPE_DARK, ForceDarkType.FORCE_INVERT_COLOR_DARK);
- verifyForceDarkType(/* isAppInNightMode= */ false, /* isForceInvertEnabled= */ false,
- UiModeManager.FORCE_INVERT_TYPE_OFF, ForceDarkType.NONE);
+ enableForceInvertColor(false);
- waitForSystemNightModeActivated(false);
+ TestUtils.waitUntil("Waiting for ForceDarkType to be ready",
+ () -> (mViewRootImpl.determineForceDarkType() == ForceDarkType.NONE));
+ }
+
+ @Test
+ @EnableFlags(FLAG_FORCE_INVERT_COLOR)
+ public void
+ determineForceDarkType_isLightThemeAndIsLightBackground_returnsForceInvertColorDark()
+ throws Exception {
+ // Set up configurations for force invert color
+ waitForSystemNightModeActivated(true);
+ enableForceInvertColor(true);
+
+ setUpViewAttributes(/* isLightTheme= */ true, /* isLightBackground = */ true);
- verifyForceDarkType(/* isAppInNightMode= */ true, /* isForceInvertEnabled= */ true,
- UiModeManager.FORCE_INVERT_TYPE_OFF, ForceDarkType.NONE);
- verifyForceDarkType(/* isAppInNightMode= */ true, /* isForceInvertEnabled= */ false,
- UiModeManager.FORCE_INVERT_TYPE_OFF, ForceDarkType.NONE);
- verifyForceDarkType(/* isAppInNightMode= */ false, /* isForceInvertEnabled= */ true,
- UiModeManager.FORCE_INVERT_TYPE_OFF, ForceDarkType.NONE);
- verifyForceDarkType(/* isAppInNightMode= */ false, /* isForceInvertEnabled= */ false,
- UiModeManager.FORCE_INVERT_TYPE_OFF, ForceDarkType.NONE);
+ TestUtils.waitUntil("Waiting for ForceDarkType to be ready",
+ () -> (mViewRootImpl.determineForceDarkType()
+ == ForceDarkType.FORCE_INVERT_COLOR_DARK));
+ }
+
+ @Test
+ @EnableFlags(FLAG_FORCE_INVERT_COLOR)
+ public void determineForceDarkType_isLightThemeAndNotLightBackground_returnsNone()
+ throws Exception {
+ // Set up configurations for force invert color
+ waitForSystemNightModeActivated(true);
+ enableForceInvertColor(true);
+
+ setUpViewAttributes(/* isLightTheme= */ true, /* isLightBackground = */ false);
+
+ TestUtils.waitUntil("Waiting for ForceDarkType to be ready",
+ () -> (mViewRootImpl.determineForceDarkType() == ForceDarkType.NONE));
+ }
+
+ @Test
+ @EnableFlags(FLAG_FORCE_INVERT_COLOR)
+ public void determineForceDarkType_notLightThemeAndIsLightBackground_returnsNone()
+ throws Exception {
+ // Set up configurations for force invert color
+ waitForSystemNightModeActivated(true);
+ enableForceInvertColor(true);
+
+ setUpViewAttributes(/* isLightTheme= */ false, /* isLightBackground = */ true);
+
+ TestUtils.waitUntil("Waiting for ForceDarkType to be ready",
+ () -> (mViewRootImpl.determineForceDarkType() == ForceDarkType.NONE));
+ }
+
+ @Test
+ @EnableFlags(FLAG_FORCE_INVERT_COLOR)
+ public void determineForceDarkType_notLightThemeAndNotLightBackground_returnsNone()
+ throws Exception {
+ // Set up configurations for force invert color
+ waitForSystemNightModeActivated(true);
+ enableForceInvertColor(true);
+
+ setUpViewAttributes(/* isLightTheme= */ false, /* isLightBackground = */ false);
+
+ TestUtils.waitUntil("Waiting for ForceDarkType to be ready",
+ () -> (mViewRootImpl.determineForceDarkType() == ForceDarkType.NONE));
}
@Test
@@ -1792,29 +1839,35 @@ public class ViewRootImplTest {
sInstrumentation.waitForIdleSync();
}
- private void verifyForceDarkType(boolean isAppInNightMode, boolean isForceInvertEnabled,
- @ForceInvertType int expectedForceInvertType,
- @ForceDarkTypeDef int expectedForceDarkType) {
- var uiModeManager = sContext.getSystemService(UiModeManager.class);
+ private void enableForceInvertColor(boolean enabled) {
ShellIdentityUtils.invokeWithShellPermissions(() -> {
- uiModeManager.setApplicationNightMode(
- isAppInNightMode ? MODE_NIGHT_YES : MODE_NIGHT_NO);
Settings.Secure.putInt(
sContext.getContentResolver(),
Settings.Secure.ACCESSIBILITY_FORCE_INVERT_COLOR_ENABLED,
- isForceInvertEnabled ? 1 : 0);
+ enabled ? 1 : 0
+ );
});
+ }
- sInstrumentation.runOnMainSync(() ->
- mViewRootImpl.updateConfiguration(sContext.getDisplayNoVerify().getDisplayId()));
- try {
- TestUtils.waitUntil("Waiting for force invert state changed",
- () -> (uiModeManager.getForceInvertState() == expectedForceInvertType));
- } catch (Exception e) {
- Log.e(TAG, "Unexpected error trying to apply force invert state. " + e);
- e.printStackTrace();
- }
+ private void setUpViewAttributes(boolean isLightTheme, boolean isLightBackground) {
+ ShellIdentityUtils.invokeWithShellPermissions(() -> {
+ sContext.setTheme(isLightTheme ? android.R.style.Theme_DeviceDefault_Light
+ : android.R.style.Theme_DeviceDefault);
+ });
- mExpect.that(mViewRootImpl.determineForceDarkType()).isEqualTo(expectedForceDarkType);
+ sInstrumentation.runOnMainSync(() -> {
+ View view = new View(sContext);
+ WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
+ TYPE_APPLICATION_OVERLAY);
+ layoutParams.token = new Binder();
+ view.setLayoutParams(layoutParams);
+ if (isLightBackground) {
+ view.setBackgroundColor(Color.WHITE);
+ } else {
+ view.setBackgroundColor(Color.BLACK);
+ }
+ mViewRootImpl.setView(view, layoutParams, /* panelParentView= */ null);
+ mViewRootImpl.updateConfiguration(sContext.getDisplayNoVerify().getDisplayId());
+ });
}
}
diff --git a/core/tests/coretests/src/com/android/internal/logging/ProtoLogTest.java b/core/tests/coretests/src/com/android/internal/logging/ProtoLogTest.java
new file mode 100644
index 000000000000..90b6902629e6
--- /dev/null
+++ b/core/tests/coretests/src/com/android/internal/logging/ProtoLogTest.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.logging;
+
+import androidx.test.ext.junit.runners.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
+
+import com.android.internal.protolog.ProtoLog;
+import com.android.internal.protolog.common.IProtoLogGroup;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class ProtoLogTest {
+ @Test
+ public void canTrace() {
+ ProtoLog.init(TEST_GROUP_1, TEST_GROUP_2);
+
+ ProtoLog.v(TEST_GROUP_1, "Verbose message");
+ ProtoLog.d(TEST_GROUP_1, "Debug message");
+ ProtoLog.i(TEST_GROUP_1, "Info message");
+ ProtoLog.w(TEST_GROUP_1, "Warning message");
+ ProtoLog.e(TEST_GROUP_1, "Error message");
+ ProtoLog.wtf(TEST_GROUP_1, "Wtf message");
+
+ ProtoLog.v(TEST_GROUP_2, "Verbose message");
+ ProtoLog.d(TEST_GROUP_2, "Debug message");
+ ProtoLog.i(TEST_GROUP_2, "Info message");
+ ProtoLog.w(TEST_GROUP_2, "Warning message");
+ ProtoLog.e(TEST_GROUP_2, "Error message");
+ ProtoLog.wtf(TEST_GROUP_2, "Wtf message");
+ }
+
+ private static final IProtoLogGroup TEST_GROUP_1 = new ProtoLogTestGroup("TEST_TAG_1", 1);
+ private static final IProtoLogGroup TEST_GROUP_2 = new ProtoLogTestGroup("TEST_TAG_2", 2);
+
+}
diff --git a/core/tests/coretests/src/com/android/internal/logging/ProtoLogTestGroup.java b/core/tests/coretests/src/com/android/internal/logging/ProtoLogTestGroup.java
new file mode 100644
index 000000000000..ecfaae5ea0c5
--- /dev/null
+++ b/core/tests/coretests/src/com/android/internal/logging/ProtoLogTestGroup.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.logging;
+
+import com.android.internal.protolog.common.IProtoLogGroup;
+
+class ProtoLogTestGroup implements IProtoLogGroup {
+ private final boolean mEnabled;
+ private volatile boolean mLogToProto;
+ private volatile boolean mLogToLogcat;
+ private final String mTag;
+ private final int mId;
+
+ ProtoLogTestGroup(String tag, int id) {
+ this(true, true, false, tag, id);
+ }
+
+ ProtoLogTestGroup(
+ boolean enabled, boolean logToProto, boolean logToLogcat, String tag, int id) {
+ this.mEnabled = enabled;
+ this.mLogToProto = logToProto;
+ this.mLogToLogcat = logToLogcat;
+ this.mTag = tag;
+ this.mId = id;
+ }
+
+ @Override
+ public String name() {
+ return mTag;
+ }
+
+ @Override
+ public boolean isEnabled() {
+ return mEnabled;
+ }
+
+ @Override
+ public boolean isLogToProto() {
+ return mLogToProto;
+ }
+
+ @Override
+ public boolean isLogToLogcat() {
+ return mLogToLogcat;
+ }
+
+ @Override
+ public boolean isLogToAny() {
+ return mLogToLogcat || mLogToProto;
+ }
+
+ @Override
+ public String getTag() {
+ return mTag;
+ }
+
+ @Override
+ public void setLogToProto(boolean logToProto) {
+ this.mLogToProto = logToProto;
+ }
+
+ @Override
+ public void setLogToLogcat(boolean logToLogcat) {
+ this.mLogToLogcat = logToLogcat;
+ }
+
+ @Override
+ public int getId() {
+ return mId;
+ }
+}
diff --git a/data/etc/privapp-permissions-platform.xml b/data/etc/privapp-permissions-platform.xml
index 1dd0465f691e..62e14d368a1c 100644
--- a/data/etc/privapp-permissions-platform.xml
+++ b/data/etc/privapp-permissions-platform.xml
@@ -424,7 +424,7 @@ applications that come with the platform
<permission name="android.permission.REQUEST_COMPANION_PROFILE_APP_STREAMING" />
<permission name="android.permission.REQUEST_COMPANION_PROFILE_WATCH" />
<permission name="android.permission.REQUEST_COMPANION_PROFILE_NEARBY_DEVICE_STREAMING" />
- <permission name="android.permission.REQUEST_COMPANION_PROFILE_SENSOR_DEVICE_STREAMING" />
+ <permission name="android.permission.REQUEST_COMPANION_PROFILE_VIRTUAL_DEVICE" />
<permission name="android.permission.REQUEST_COMPANION_PROFILE_COMPUTER" />
<permission name="android.permission.REQUEST_COMPANION_SELF_MANAGED" />
<permission name="android.permission.REQUEST_OBSERVE_DEVICE_UUID_PRESENCE" />
@@ -621,6 +621,8 @@ applications that come with the platform
<permission name="android.permission.READ_COLOR_ZONES"/>
<!-- Permission required for CTS test - CtsTextClassifierTestCases -->
<permission name="android.permission.ACCESS_TEXT_CLASSIFIER_BY_TYPE"/>
+ <!-- Permission required for CTS test - CtsSecurityTestCases -->
+ <permission name="android.permission.MANAGE_DEVICE_POLICY_MTE"/>
</privapp-permissions>
<privapp-permissions package="com.android.soundpicker">
diff --git a/libs/WindowManager/Shell/res/values/styles.xml b/libs/WindowManager/Shell/res/values/styles.xml
index 08cda7b94a78..086c8a5651c3 100644
--- a/libs/WindowManager/Shell/res/values/styles.xml
+++ b/libs/WindowManager/Shell/res/values/styles.xml
@@ -51,7 +51,6 @@
<item name="android:clickable">true</item>
<item name="android:focusable">true</item>
<item name="android:orientation">horizontal</item>
- <item name="android:background">?android:attr/selectableItemBackground</item>
</style>
<style name="DesktopModeHandleMenuActionButtonImage">
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/animation/SizeChangeAnimation.java b/libs/WindowManager/Shell/src/com/android/wm/shell/animation/SizeChangeAnimation.java
index 8e3dc4c36c1d..711667760314 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/animation/SizeChangeAnimation.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/animation/SizeChangeAnimation.java
@@ -34,6 +34,8 @@ import android.view.animation.ScaleAnimation;
import android.view.animation.Transformation;
import android.view.animation.TranslateAnimation;
+import com.android.wm.shell.shared.animation.Interpolators;
+
import java.util.function.Consumer;
/**
@@ -196,6 +198,8 @@ public class SizeChangeAnimation {
float startScaleY = scaleFactor * ((float) startBounds.height()) / endBounds.height()
+ (1.f - scaleFactor);
final AnimationSet animSet = new AnimationSet(true);
+ // Use a linear interpolator so the driving ValueAnimator sets the interpolation
+ animSet.setInterpolator(Interpolators.LINEAR);
final Animation scaleAnim = new ScaleAnimation(startScaleX, 1, startScaleY, 1);
scaleAnim.setDuration(scalePeriod);
@@ -244,6 +248,8 @@ public class SizeChangeAnimation {
+ (1.f - scaleFactor));
AnimationSet snapAnimSet = new AnimationSet(true);
+ // Use a linear interpolator so the driving ValueAnimator sets the interpolation
+ snapAnimSet.setInterpolator(Interpolators.LINEAR);
// Animation for the "old-state" snapshot that is atop the task.
final Animation snapAlphaAnim = new AlphaAnimation(1.f, 0.f);
snapAlphaAnim.setDuration(scalePeriod);
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarAnimationHelper.java b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarAnimationHelper.java
index b89bfd5c969e..ea365efcb400 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarAnimationHelper.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/bubbles/bar/BubbleBarAnimationHelper.java
@@ -615,7 +615,7 @@ public class BubbleBarAnimationHelper {
bbev.setSurfaceZOrderedOnTop(true);
a.setDuration(EXPANDED_VIEW_ANIMATE_TO_REST_DURATION);
- a.setInterpolator(Interpolators.EMPHASIZED);
+ a.setInterpolator(EMPHASIZED);
a.start();
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
index b3c25d495002..ad509bcc1ceb 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellBaseModule.java
@@ -766,6 +766,7 @@ public abstract class WMShellBaseModule {
@ShellMainThread ShellExecutor mainExecutor,
@ShellMainThread Handler mainHandler,
@ShellAnimationThread ShellExecutor animExecutor,
+ @ShellAnimationThread Handler animHandler,
RootTaskDisplayAreaOrganizer rootTaskDisplayAreaOrganizer,
HomeTransitionObserver homeTransitionObserver,
FocusTransitionObserver focusTransitionObserver) {
@@ -775,7 +776,7 @@ public abstract class WMShellBaseModule {
}
return new Transitions(context, shellInit, shellCommandHandler, shellController, organizer,
pool, displayController, displayInsetsController, mainExecutor, mainHandler,
- animExecutor, rootTaskDisplayAreaOrganizer, homeTransitionObserver,
+ animExecutor, animHandler, rootTaskDisplayAreaOrganizer, homeTransitionObserver,
focusTransitionObserver);
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
index 07745d487f64..46c9b07fb802 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/WMShellModule.java
@@ -101,7 +101,6 @@ import com.android.wm.shell.desktopmode.DesktopModeKeyGestureHandler;
import com.android.wm.shell.desktopmode.DesktopModeLoggerTransitionObserver;
import com.android.wm.shell.desktopmode.DesktopModeMoveToDisplayTransitionHandler;
import com.android.wm.shell.desktopmode.DesktopModeUiEventLogger;
-import com.android.wm.shell.desktopmode.DesktopPipTransitionObserver;
import com.android.wm.shell.desktopmode.DesktopTaskChangeListener;
import com.android.wm.shell.desktopmode.DesktopTasksController;
import com.android.wm.shell.desktopmode.DesktopTasksLimiter;
@@ -793,7 +792,6 @@ public abstract class WMShellModule {
OverviewToDesktopTransitionObserver overviewToDesktopTransitionObserver,
DesksOrganizer desksOrganizer,
Optional<DesksTransitionObserver> desksTransitionObserver,
- Optional<DesktopPipTransitionObserver> desktopPipTransitionObserver,
UserProfileContexts userProfileContexts,
DesktopModeCompatPolicy desktopModeCompatPolicy,
DragToDisplayTransitionHandler dragToDisplayTransitionHandler,
@@ -837,7 +835,6 @@ public abstract class WMShellModule {
overviewToDesktopTransitionObserver,
desksOrganizer,
desksTransitionObserver.get(),
- desktopPipTransitionObserver,
userProfileContexts,
desktopModeCompatPolicy,
dragToDisplayTransitionHandler,
@@ -1057,7 +1054,8 @@ public abstract class WMShellModule {
DesktopModeCompatPolicy desktopModeCompatPolicy,
DesktopTilingDecorViewModel desktopTilingDecorViewModel,
MultiDisplayDragMoveIndicatorController multiDisplayDragMoveIndicatorController,
- Optional<CompatUIHandler> compatUI
+ Optional<CompatUIHandler> compatUI,
+ DesksOrganizer desksOrganizer
) {
if (!DesktopModeStatus.canEnterDesktopModeOrShowAppHandle(context)) {
return Optional.empty();
@@ -1075,7 +1073,8 @@ public abstract class WMShellModule {
activityOrientationChangeHandler, focusTransitionObserver, desktopModeEventLogger,
desktopModeUiEventLogger, taskResourceLoader, recentsTransitionHandler,
desktopModeCompatPolicy, desktopTilingDecorViewModel,
- multiDisplayDragMoveIndicatorController, compatUI.orElse(null)));
+ multiDisplayDragMoveIndicatorController, compatUI.orElse(null),
+ desksOrganizer));
}
@WMSingleton
@@ -1250,7 +1249,6 @@ public abstract class WMShellModule {
Transitions transitions,
ShellTaskOrganizer shellTaskOrganizer,
Optional<DesktopMixedTransitionHandler> desktopMixedTransitionHandler,
- Optional<DesktopPipTransitionObserver> desktopPipTransitionObserver,
Optional<BackAnimationController> backAnimationController,
DesktopWallpaperActivityTokenProvider desktopWallpaperActivityTokenProvider,
ShellInit shellInit) {
@@ -1263,7 +1261,6 @@ public abstract class WMShellModule {
transitions,
shellTaskOrganizer,
desktopMixedTransitionHandler.get(),
- desktopPipTransitionObserver,
backAnimationController.get(),
desktopWallpaperActivityTokenProvider,
shellInit)));
@@ -1285,19 +1282,6 @@ public abstract class WMShellModule {
@WMSingleton
@Provides
- static Optional<DesktopPipTransitionObserver> provideDesktopPipTransitionObserver(
- Context context
- ) {
- if (DesktopModeStatus.canEnterDesktopMode(context)
- && DesktopModeFlags.ENABLE_DESKTOP_WINDOWING_PIP.isTrue()) {
- return Optional.of(
- new DesktopPipTransitionObserver());
- }
- return Optional.empty();
- }
-
- @WMSingleton
- @Provides
static Optional<DesktopMixedTransitionHandler> provideDesktopMixedTransitionHandler(
Context context,
Transitions transitions,
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip2Module.java b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip2Module.java
index 6f0919e1d045..c5f956a80702 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip2Module.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/dagger/pip/Pip2Module.java
@@ -19,6 +19,7 @@ package com.android.wm.shell.dagger.pip;
import android.annotation.NonNull;
import android.content.Context;
import android.os.Handler;
+import android.window.DesktopModeFlags;
import com.android.internal.jank.InteractionJankMonitor;
import com.android.wm.shell.RootTaskDisplayAreaOrganizer;
@@ -42,6 +43,8 @@ import com.android.wm.shell.common.pip.PipUtils;
import com.android.wm.shell.common.pip.SizeSpecSource;
import com.android.wm.shell.dagger.WMShellBaseModule;
import com.android.wm.shell.dagger.WMSingleton;
+import com.android.wm.shell.desktopmode.DesktopPipTransitionController;
+import com.android.wm.shell.desktopmode.DesktopTasksController;
import com.android.wm.shell.desktopmode.DesktopUserRepositories;
import com.android.wm.shell.desktopmode.DragToDesktopTransitionHandler;
import com.android.wm.shell.pip2.phone.PhonePipMenuController;
@@ -55,6 +58,7 @@ import com.android.wm.shell.pip2.phone.PipTransition;
import com.android.wm.shell.pip2.phone.PipTransitionState;
import com.android.wm.shell.pip2.phone.PipUiStateChangeController;
import com.android.wm.shell.shared.annotations.ShellMainThread;
+import com.android.wm.shell.shared.desktopmode.DesktopModeStatus;
import com.android.wm.shell.splitscreen.SplitScreenController;
import com.android.wm.shell.sysui.ShellCommandHandler;
import com.android.wm.shell.sysui.ShellController;
@@ -91,12 +95,13 @@ public abstract class Pip2Module {
DisplayController displayController,
Optional<SplitScreenController> splitScreenControllerOptional,
PipDesktopState pipDesktopState,
+ Optional<DesktopPipTransitionController> desktopPipTransitionController,
PipInteractionHandler pipInteractionHandler) {
return new PipTransition(context, shellInit, shellTaskOrganizer, transitions,
pipBoundsState, null, pipBoundsAlgorithm, pipTaskListener,
pipScheduler, pipStackListenerController, pipDisplayLayoutState,
pipUiStateChangeController, displayController, splitScreenControllerOptional,
- pipDesktopState, pipInteractionHandler);
+ pipDesktopState, desktopPipTransitionController, pipInteractionHandler);
}
@WMSingleton
@@ -250,6 +255,22 @@ public abstract class Pip2Module {
dragToDesktopTransitionHandlerOptional, rootTaskDisplayAreaOrganizer);
}
+ @WMSingleton
+ @Provides
+ static Optional<DesktopPipTransitionController> provideDesktopPipTransitionController(
+ Context context, Optional<DesktopTasksController> desktopTasksControllerOptional,
+ Optional<DesktopUserRepositories> desktopUserRepositoriesOptional,
+ PipDesktopState pipDesktopState
+ ) {
+ if (DesktopModeStatus.canEnterDesktopMode(context)
+ && DesktopModeFlags.ENABLE_DESKTOP_WINDOWING_PIP.isTrue()) {
+ return Optional.of(
+ new DesktopPipTransitionController(desktopTasksControllerOptional.get(),
+ desktopUserRepositoriesOptional.get(), pipDesktopState));
+ }
+ return Optional.empty();
+ }
+
@BindsOptionalOf
abstract DragToDesktopTransitionHandler optionalDragToDesktopTransitionHandler();
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopDisplayModeController.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopDisplayModeController.kt
index ea2fdc0ee8ed..0a3e2cc3b434 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopDisplayModeController.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopDisplayModeController.kt
@@ -56,13 +56,6 @@ class DesktopDisplayModeController(
@ShellMainThread private val mainHandler: Handler,
) {
- private val onTabletModeChangedListener =
- object : InputManager.OnTabletModeChangedListener {
- override fun onTabletModeChanged(whenNanos: Long, inTabletMode: Boolean) {
- refreshDisplayWindowingMode()
- }
- }
-
private val inputDeviceListener =
object : InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) {
@@ -80,10 +73,6 @@ class DesktopDisplayModeController(
init {
if (DesktopExperienceFlags.FORM_FACTOR_BASED_DESKTOP_FIRST_SWITCH.isTrue) {
- inputManager.registerOnTabletModeChangedListener(
- onTabletModeChangedListener,
- mainHandler,
- )
inputManager.registerInputDeviceListener(inputDeviceListener, mainHandler)
}
}
@@ -139,7 +128,7 @@ class DesktopDisplayModeController(
return true
}
if (DesktopExperienceFlags.FORM_FACTOR_BASED_DESKTOP_FIRST_SWITCH.isTrue) {
- if (isInClamshellMode() || hasAnyMouseDevice()) {
+ if (hasAnyTouchpadDevice() && hasAnyPhysicalKeyboardDevice()) {
return true
}
}
@@ -186,17 +175,25 @@ class DesktopDisplayModeController(
private fun hasExternalDisplay() =
rootTaskDisplayAreaOrganizer.getDisplayIds().any { it != DEFAULT_DISPLAY }
- private fun hasAnyMouseDevice() =
- inputManager.inputDeviceIds.any {
- inputManager.getInputDevice(it)?.supportsSource(InputDevice.SOURCE_MOUSE) == true
+ private fun hasAnyTouchpadDevice() =
+ inputManager.inputDeviceIds.any { deviceId ->
+ inputManager.getInputDevice(deviceId)?.let { device ->
+ device.supportsSource(InputDevice.SOURCE_TOUCHPAD) && device.isEnabled()
+ } ?: false
}
- private fun isInClamshellMode() = inputManager.isInTabletMode() == InputManager.SWITCH_STATE_OFF
+ private fun hasAnyPhysicalKeyboardDevice() =
+ inputManager.inputDeviceIds.any { deviceId ->
+ inputManager.getInputDevice(deviceId)?.let { device ->
+ !device.isVirtual() && device.isFullKeyboard() && device.isEnabled()
+ } ?: false
+ }
private fun isDefaultDisplayDesktopEligible(): Boolean {
- val display = requireNotNull(displayController.getDisplay(DEFAULT_DISPLAY)) {
- "Display object of DEFAULT_DISPLAY must be non-null."
- }
+ val display =
+ requireNotNull(displayController.getDisplay(DEFAULT_DISPLAY)) {
+ "Display object of DEFAULT_DISPLAY must be non-null."
+ }
return DesktopModeStatus.isDesktopModeSupportedOnDisplay(context, display)
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeVisualIndicator.java b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeVisualIndicator.java
index 1c5138f486e4..8bbe36dd6644 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeVisualIndicator.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopModeVisualIndicator.java
@@ -57,7 +57,7 @@ import com.android.wm.shell.shared.bubbles.BubbleAnythingFlagHelper;
import com.android.wm.shell.shared.bubbles.BubbleDropTargetBoundsProvider;
import com.android.wm.shell.windowdecor.tiling.SnapEventHandler;
-import java.util.Arrays;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -307,7 +307,8 @@ public class DesktopModeVisualIndicator {
if (splitRightRegion.contains(x, y)) {
result = IndicatorType.TO_SPLIT_RIGHT_INDICATOR;
}
- if (BubbleAnythingFlagHelper.enableBubbleToFullscreen()) {
+ if (BubbleAnythingFlagHelper.enableBubbleToFullscreen()
+ && mDragStartState == DragStartState.FROM_FULLSCREEN) {
if (calculateBubbleLeftRegion(layout).contains(x, y)) {
result = IndicatorType.TO_BUBBLE_LEFT_INDICATOR;
} else if (calculateBubbleRightRegion(layout).contains(x, y)) {
@@ -415,30 +416,59 @@ public class DesktopModeVisualIndicator {
private List<Pair<Rect, IndicatorType>> initSmallTabletRegions(DisplayLayout layout,
boolean isLeftRightSplit) {
- boolean dragFromFullscreen = mDragStartState == DragStartState.FROM_FULLSCREEN;
- boolean dragFromSplit = mDragStartState == DragStartState.FROM_SPLIT;
- if (isLeftRightSplit && (dragFromFullscreen || dragFromSplit)) {
+ return switch (mDragStartState) {
+ case DragStartState.FROM_FULLSCREEN -> initSmallTabletRegionsFromFullscreen(layout,
+ isLeftRightSplit);
+ case DragStartState.FROM_SPLIT -> initSmallTabletRegionsFromSplit(layout,
+ isLeftRightSplit);
+ default -> Collections.emptyList();
+ };
+ }
+
+ private List<Pair<Rect, IndicatorType>> initSmallTabletRegionsFromFullscreen(
+ DisplayLayout layout, boolean isLeftRightSplit) {
+
+ List<Pair<Rect, IndicatorType>> result = new ArrayList<>();
+ if (BubbleAnythingFlagHelper.enableBubbleToFullscreen()) {
+ result.add(new Pair<>(calculateBubbleLeftRegion(layout), TO_BUBBLE_LEFT_INDICATOR));
+ result.add(new Pair<>(calculateBubbleRightRegion(layout), TO_BUBBLE_RIGHT_INDICATOR));
+ }
+
+ if (isLeftRightSplit) {
int splitRegionWidth = mContext.getResources().getDimensionPixelSize(
com.android.wm.shell.shared.R.dimen.drag_zone_h_split_from_app_width_fold);
- return Arrays.asList(
- new Pair<>(calculateBubbleLeftRegion(layout), TO_BUBBLE_LEFT_INDICATOR),
- new Pair<>(calculateBubbleRightRegion(layout), TO_BUBBLE_RIGHT_INDICATOR),
- new Pair<>(calculateSplitLeftRegion(layout, splitRegionWidth,
- /* captionHeight= */ 0), TO_SPLIT_LEFT_INDICATOR),
- new Pair<>(calculateSplitRightRegion(layout, splitRegionWidth,
- /* captionHeight= */ 0), TO_SPLIT_RIGHT_INDICATOR),
- new Pair<>(new Rect(), TO_FULLSCREEN_INDICATOR) // default to fullscreen
- );
+ result.add(new Pair<>(calculateSplitLeftRegion(layout, splitRegionWidth,
+ /* captionHeight= */ 0), TO_SPLIT_LEFT_INDICATOR));
+ result.add(new Pair<>(calculateSplitRightRegion(layout, splitRegionWidth,
+ /* captionHeight= */ 0), TO_SPLIT_RIGHT_INDICATOR));
}
- if (dragFromFullscreen) {
- // If left/right split is not available, we can only drag fullscreen tasks
- // TODO(b/401352409): add support for top/bottom split zones
- return Arrays.asList(
- new Pair<>(calculateBubbleLeftRegion(layout), TO_BUBBLE_LEFT_INDICATOR),
- new Pair<>(calculateBubbleRightRegion(layout), TO_BUBBLE_RIGHT_INDICATOR),
- new Pair<>(new Rect(), TO_FULLSCREEN_INDICATOR) // default to fullscreen
- );
+ // TODO(b/401352409): add support for top/bottom split zones
+ // default to fullscreen
+ result.add(new Pair<>(new Rect(), TO_FULLSCREEN_INDICATOR));
+ return result;
+ }
+
+ private List<Pair<Rect, IndicatorType>> initSmallTabletRegionsFromSplit(DisplayLayout layout,
+ boolean isLeftRightSplit) {
+ if (!isLeftRightSplit) {
+ // Dragging a top/bottom split is not supported on small tablets
+ return Collections.emptyList();
}
- return Collections.emptyList();
+
+ List<Pair<Rect, IndicatorType>> result = new ArrayList<>();
+ if (BubbleAnythingFlagHelper.enableBubbleAnything()) {
+ result.add(new Pair<>(calculateBubbleLeftRegion(layout), TO_BUBBLE_LEFT_INDICATOR));
+ result.add(new Pair<>(calculateBubbleRightRegion(layout), TO_BUBBLE_RIGHT_INDICATOR));
+ }
+
+ int splitRegionWidth = mContext.getResources().getDimensionPixelSize(
+ com.android.wm.shell.shared.R.dimen.drag_zone_h_split_from_app_width_fold);
+ result.add(new Pair<>(calculateSplitLeftRegion(layout, splitRegionWidth,
+ /* captionHeight= */ 0), TO_SPLIT_LEFT_INDICATOR));
+ result.add(new Pair<>(calculateSplitRightRegion(layout, splitRegionWidth,
+ /* captionHeight= */ 0), TO_SPLIT_RIGHT_INDICATOR));
+ // default to fullscreen
+ result.add(new Pair<>(new Rect(), TO_FULLSCREEN_INDICATOR));
+ return result;
}
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopPipTransitionController.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopPipTransitionController.kt
new file mode 100644
index 000000000000..88468531cc47
--- /dev/null
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopPipTransitionController.kt
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.desktopmode
+
+import android.app.ActivityManager
+import android.os.IBinder
+import android.window.DesktopExperienceFlags
+import android.window.WindowContainerTransaction
+import com.android.internal.protolog.ProtoLog
+import com.android.wm.shell.common.pip.PipDesktopState
+import com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_DESKTOP_MODE
+
+/**
+ * Controller to perform extra handling to PiP transitions that are entering while in Desktop mode.
+ */
+class DesktopPipTransitionController(
+ private val desktopTasksController: DesktopTasksController,
+ private val desktopUserRepositories: DesktopUserRepositories,
+ private val pipDesktopState: PipDesktopState,
+) {
+
+ /**
+ * This is called by [PipTransition#handleRequest] when a request for entering PiP is received.
+ *
+ * @param wct WindowContainerTransaction that will apply these changes
+ * @param transition that will apply this transaction
+ * @param taskInfo of the task that is entering PiP
+ */
+ fun handlePipTransition(
+ wct: WindowContainerTransaction,
+ transition: IBinder,
+ taskInfo: ActivityManager.RunningTaskInfo,
+ ) {
+ if (!pipDesktopState.isDesktopWindowingPipEnabled()) {
+ return
+ }
+
+ // Early return if the transition is a synthetic transition that is not backed by a true
+ // system transition.
+ if (transition == DesktopTasksController.SYNTHETIC_TRANSITION) {
+ logD("handlePipTransitionIfInDesktop: SYNTHETIC_TRANSITION, not a true transition")
+ return
+ }
+
+ val taskId = taskInfo.taskId
+ val displayId = taskInfo.displayId
+ val desktopRepository = desktopUserRepositories.getProfile(taskInfo.userId)
+ if (!desktopRepository.isAnyDeskActive(displayId)) {
+ logD("handlePipTransitionIfInDesktop: PiP transition is not in Desktop session")
+ return
+ }
+
+ val deskId =
+ desktopRepository.getActiveDeskId(displayId)
+ ?: if (DesktopExperienceFlags.ENABLE_MULTIPLE_DESKTOPS_BACKEND.isTrue) {
+ logW(
+ "handlePipTransitionIfInDesktop: " +
+ "Active desk not found for display id %d",
+ displayId,
+ )
+ return
+ } else {
+ checkNotNull(desktopRepository.getDefaultDeskId(displayId)) {
+ "$TAG: handlePipTransitionIfInDesktop: " +
+ "Expected a default desk to exist in display with id $displayId"
+ }
+ }
+
+ val isLastTask =
+ desktopRepository.isOnlyVisibleNonClosingTaskInDesk(
+ taskId = taskId,
+ deskId = deskId,
+ displayId = displayId,
+ )
+ if (!isLastTask) {
+ logD("handlePipTransitionIfInDesktop: PiP task is not last visible task in Desk")
+ return
+ }
+
+ val desktopExitRunnable =
+ desktopTasksController.performDesktopExitCleanUp(
+ wct = wct,
+ deskId = deskId,
+ displayId = displayId,
+ willExitDesktop = true,
+ )
+ desktopExitRunnable?.invoke(transition)
+ }
+
+ private fun logW(msg: String, vararg arguments: Any?) {
+ ProtoLog.w(WM_SHELL_DESKTOP_MODE, "%s: $msg", TAG, *arguments)
+ }
+
+ private fun logD(msg: String, vararg arguments: Any?) {
+ ProtoLog.d(WM_SHELL_DESKTOP_MODE, "%s: $msg", TAG, *arguments)
+ }
+
+ private companion object {
+ private const val TAG = "DesktopPipTransitionController"
+ }
+}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopPipTransitionObserver.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopPipTransitionObserver.kt
deleted file mode 100644
index efd3866e1bc4..000000000000
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopPipTransitionObserver.kt
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2025 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.wm.shell.desktopmode
-
-import android.app.WindowConfiguration.WINDOWING_MODE_PINNED
-import android.os.IBinder
-import android.window.DesktopModeFlags
-import android.window.TransitionInfo
-import com.android.internal.protolog.ProtoLog
-import com.android.wm.shell.protolog.ShellProtoLogGroup.WM_SHELL_DESKTOP_MODE
-
-/**
- * Observer of PiP in Desktop Mode transitions. At the moment, this is specifically tracking a PiP
- * transition for a task that is entering PiP via the minimize button on the caption bar.
- */
-class DesktopPipTransitionObserver {
- private val pendingPipTransitions = mutableMapOf<IBinder, PendingPipTransition>()
-
- /** Adds a pending PiP transition to be tracked. */
- fun addPendingPipTransition(transition: PendingPipTransition) {
- if (!DesktopModeFlags.ENABLE_DESKTOP_WINDOWING_PIP.isTrue) return
- pendingPipTransitions[transition.token] = transition
- }
-
- /**
- * Called when any transition is ready, which may include transitions not tracked by this
- * observer.
- */
- fun onTransitionReady(transition: IBinder, info: TransitionInfo) {
- if (!DesktopModeFlags.ENABLE_DESKTOP_WINDOWING_PIP.isTrue) return
- val pipTransition = pendingPipTransitions.remove(transition) ?: return
-
- logD("Desktop PiP transition ready: %s", transition)
- for (change in info.changes) {
- val taskInfo = change.taskInfo
- if (taskInfo == null || taskInfo.taskId == -1) {
- continue
- }
-
- if (
- taskInfo.taskId == pipTransition.taskId &&
- taskInfo.windowingMode == WINDOWING_MODE_PINNED
- ) {
- logD("Desktop PiP transition was successful")
- pipTransition.onSuccess()
- return
- }
- }
- logD("Change with PiP task not found in Desktop PiP transition; likely failed")
- }
-
- /**
- * Data tracked for a pending PiP transition.
- *
- * @property token the PiP transition that is started.
- * @property taskId task id of the task entering PiP.
- * @property onSuccess callback to be invoked if the PiP transition is successful.
- */
- data class PendingPipTransition(val token: IBinder, val taskId: Int, val onSuccess: () -> Unit)
-
- private fun logD(msg: String, vararg arguments: Any?) {
- ProtoLog.d(WM_SHELL_DESKTOP_MODE, "%s: $msg", TAG, *arguments)
- }
-
- private companion object {
- private const val TAG = "DesktopPipTransitionObserver"
- }
-}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
index b60fd5bb6c73..6214f329e0fd 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksController.kt
@@ -214,7 +214,6 @@ class DesktopTasksController(
private val overviewToDesktopTransitionObserver: OverviewToDesktopTransitionObserver,
private val desksOrganizer: DesksOrganizer,
private val desksTransitionObserver: DesksTransitionObserver,
- private val desktopPipTransitionObserver: Optional<DesktopPipTransitionObserver>,
private val userProfileContexts: UserProfileContexts,
private val desktopModeCompatPolicy: DesktopModeCompatPolicy,
private val dragToDisplayTransitionHandler: DragToDisplayTransitionHandler,
@@ -847,7 +846,6 @@ class DesktopTasksController(
}
val isMinimizingToPip =
DesktopModeFlags.ENABLE_DESKTOP_WINDOWING_PIP.isTrue &&
- desktopPipTransitionObserver.isPresent &&
(taskInfo.pictureInPictureParams?.isAutoEnterEnabled ?: false)
// If task is going to PiP, start a PiP transition instead of a minimize transition
@@ -861,25 +859,23 @@ class DesktopTasksController(
/* displayChange= */ null,
/* flags= */ 0,
)
- val requestRes = transitions.dispatchRequest(Binder(), requestInfo, /* skip= */ null)
+ val requestRes =
+ transitions.dispatchRequest(SYNTHETIC_TRANSITION, requestInfo, /* skip= */ null)
wct.merge(requestRes.second, true)
- desktopPipTransitionObserver
- .get()
- .addPendingPipTransition(
- DesktopPipTransitionObserver.PendingPipTransition(
- token = freeformTaskTransitionStarter.startPipTransition(wct),
- taskId = taskInfo.taskId,
- onSuccess = {
- onDesktopTaskEnteredPip(
- taskId = taskId,
- deskId = deskId,
- displayId = taskInfo.displayId,
- taskIsLastVisibleTaskBeforePip = isLastTask,
- )
- },
+ // If the task minimizing to PiP is the last task, modify wct to perform Desktop cleanup
+ var desktopExitRunnable: RunOnTransitStart? = null
+ if (isLastTask) {
+ desktopExitRunnable =
+ performDesktopExitCleanUp(
+ wct = wct,
+ deskId = deskId,
+ displayId = displayId,
+ willExitDesktop = true,
)
- )
+ }
+ val transition = freeformTaskTransitionStarter.startPipTransition(wct)
+ desktopExitRunnable?.invoke(transition)
} else {
snapEventHandler.removeTaskIfTiled(displayId, taskId)
val willExitDesktop = willExitDesktop(taskId, displayId, forceExitDesktop = false)
@@ -1893,11 +1889,7 @@ class DesktopTasksController(
displayId: Int,
forceExitDesktop: Boolean,
): Boolean {
- if (
- forceExitDesktop &&
- (DesktopExperienceFlags.ENABLE_MULTIPLE_DESKTOPS_BACKEND.isTrue ||
- DesktopModeFlags.ENABLE_DESKTOP_WINDOWING_PIP.isTrue)
- ) {
+ if (forceExitDesktop && DesktopExperienceFlags.ENABLE_MULTIPLE_DESKTOPS_BACKEND.isTrue) {
// |forceExitDesktop| is true when the callers knows we'll exit desktop, such as when
// explicitly going fullscreen, so there's no point in checking the desktop state.
return true
@@ -1914,33 +1906,6 @@ class DesktopTasksController(
return true
}
- /** Potentially perform Desktop cleanup after a task successfully enters PiP. */
- @VisibleForTesting
- fun onDesktopTaskEnteredPip(
- taskId: Int,
- deskId: Int,
- displayId: Int,
- taskIsLastVisibleTaskBeforePip: Boolean,
- ) {
- if (
- !willExitDesktop(taskId, displayId, forceExitDesktop = taskIsLastVisibleTaskBeforePip)
- ) {
- return
- }
-
- val wct = WindowContainerTransaction()
- val desktopExitRunnable =
- performDesktopExitCleanUp(
- wct = wct,
- deskId = deskId,
- displayId = displayId,
- willExitDesktop = true,
- )
-
- val transition = transitions.startTransition(TRANSIT_CHANGE, wct, /* handler= */ null)
- desktopExitRunnable?.invoke(transition)
- }
-
private fun performDesktopExitCleanupIfNeeded(
taskId: Int,
deskId: Int? = null,
@@ -1964,7 +1929,7 @@ class DesktopTasksController(
}
/** TODO: b/394268248 - update [deskId] to be non-null. */
- private fun performDesktopExitCleanUp(
+ fun performDesktopExitCleanUp(
wct: WindowContainerTransaction,
deskId: Int?,
displayId: Int,
@@ -3967,6 +3932,12 @@ class DesktopTasksController(
DesktopTaskToFrontReason.TASKBAR_MANAGE_WINDOW ->
UnminimizeReason.TASKBAR_MANAGE_WINDOW
}
+
+ @JvmField
+ /**
+ * A placeholder for a synthetic transition that isn't backed by a true system transition.
+ */
+ val SYNTHETIC_TRANSITION: IBinder = Binder()
}
/** Defines interface for classes that can listen to changes for task resize. */
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksTransitionObserver.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksTransitionObserver.kt
index df4d18f8c803..3fd955d112f0 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksTransitionObserver.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/DesktopTasksTransitionObserver.kt
@@ -42,7 +42,6 @@ import com.android.wm.shell.shared.TransitionUtil.isOpeningMode
import com.android.wm.shell.shared.desktopmode.DesktopModeStatus
import com.android.wm.shell.sysui.ShellInit
import com.android.wm.shell.transition.Transitions
-import java.util.Optional
/**
* A [Transitions.TransitionObserver] that observes shell transitions and updates the
@@ -55,7 +54,6 @@ class DesktopTasksTransitionObserver(
private val transitions: Transitions,
private val shellTaskOrganizer: ShellTaskOrganizer,
private val desktopMixedTransitionHandler: DesktopMixedTransitionHandler,
- private val desktopPipTransitionObserver: Optional<DesktopPipTransitionObserver>,
private val backAnimationController: BackAnimationController,
private val desktopWallpaperActivityTokenProvider: DesktopWallpaperActivityTokenProvider,
shellInit: ShellInit,
@@ -97,7 +95,6 @@ class DesktopTasksTransitionObserver(
removeTaskIfNeeded(info)
}
removeWallpaperOnLastTaskClosingIfNeeded(transition, info)
- desktopPipTransitionObserver.ifPresent { it.onTransitionReady(transition, info) }
}
private fun removeTaskIfNeeded(info: TransitionInfo) {
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/multidesks/DesksOrganizer.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/multidesks/DesksOrganizer.kt
index 5a988fcd1b77..1effcdb20505 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/multidesks/DesksOrganizer.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/multidesks/DesksOrganizer.kt
@@ -78,6 +78,9 @@ interface DesksOrganizer {
/** Whether the desk is activate according to the given change at the end of a transition. */
fun isDeskActiveAtEnd(change: TransitionInfo.Change, deskId: Int): Boolean
+ /** Allows for other classes to respond to task changes this organizer receives. */
+ fun setOnDesktopTaskInfoChangedListener(listener: (ActivityManager.RunningTaskInfo) -> Unit)
+
/** A callback that is invoked when the desk container is created. */
fun interface OnCreateCallback {
/** Calls back when the [deskId] has been created. */
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/multidesks/RootTaskDesksOrganizer.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/multidesks/RootTaskDesksOrganizer.kt
index 49ca58e7b32a..c30987ac7640 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/multidesks/RootTaskDesksOrganizer.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/desktopmode/multidesks/RootTaskDesksOrganizer.kt
@@ -54,6 +54,7 @@ class RootTaskDesksOrganizer(
mutableListOf<CreateDeskMinimizationRootRequest>()
@VisibleForTesting
val deskMinimizationRootsByDeskId: MutableMap<Int, DeskMinimizationRoot> = mutableMapOf()
+ private var onTaskInfoChangedListener: ((RunningTaskInfo) -> Unit)? = null
init {
if (DesktopExperienceFlags.ENABLE_MULTIPLE_DESKTOPS_BACKEND.isTrue) {
@@ -213,6 +214,10 @@ class RootTaskDesksOrganizer(
change.taskInfo?.isVisibleRequested == true &&
change.mode == TRANSIT_TO_FRONT
+ override fun setOnDesktopTaskInfoChangedListener(listener: (RunningTaskInfo) -> Unit) {
+ onTaskInfoChangedListener = listener
+ }
+
override fun onTaskAppeared(taskInfo: RunningTaskInfo, leash: SurfaceControl) {
handleTaskAppeared(taskInfo, leash)
updateLaunchAdjacentController()
@@ -220,6 +225,12 @@ class RootTaskDesksOrganizer(
override fun onTaskInfoChanged(taskInfo: RunningTaskInfo) {
handleTaskInfoChanged(taskInfo)
+ if (
+ taskInfo.taskId !in deskRootsByDeskId &&
+ deskMinimizationRootsByDeskId.values.none { it.rootId == taskInfo.taskId }
+ ) {
+ onTaskInfoChangedListener?.invoke(taskInfo)
+ }
updateLaunchAdjacentController()
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java
index 5d8d8b685a23..9ec1c7d65a6e 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip2/phone/PipTransition.java
@@ -50,7 +50,9 @@ import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Bundle;
+import android.os.Debug;
import android.os.IBinder;
+import android.util.Log;
import android.view.SurfaceControl;
import android.view.WindowManager;
import android.window.TransitionInfo;
@@ -71,6 +73,7 @@ import com.android.wm.shell.common.pip.PipDesktopState;
import com.android.wm.shell.common.pip.PipDisplayLayoutState;
import com.android.wm.shell.common.pip.PipMenuController;
import com.android.wm.shell.common.pip.PipUtils;
+import com.android.wm.shell.desktopmode.DesktopPipTransitionController;
import com.android.wm.shell.pip.PipTransitionController;
import com.android.wm.shell.pip2.PipSurfaceTransactionHelper;
import com.android.wm.shell.pip2.animation.PipAlphaAnimator;
@@ -115,6 +118,7 @@ public class PipTransition extends PipTransitionController implements
private final DisplayController mDisplayController;
private final PipSurfaceTransactionHelper mPipSurfaceTransactionHelper;
private final PipDesktopState mPipDesktopState;
+ private final Optional<DesktopPipTransitionController> mDesktopPipTransitionController;
private final PipInteractionHandler mPipInteractionHandler;
//
@@ -158,6 +162,7 @@ public class PipTransition extends PipTransitionController implements
DisplayController displayController,
Optional<SplitScreenController> splitScreenControllerOptional,
PipDesktopState pipDesktopState,
+ Optional<DesktopPipTransitionController> desktopPipTransitionController,
PipInteractionHandler pipInteractionHandler) {
super(shellInit, shellTaskOrganizer, transitions, pipBoundsState, pipMenuController,
pipBoundsAlgorithm);
@@ -172,6 +177,7 @@ public class PipTransition extends PipTransitionController implements
mDisplayController = displayController;
mPipSurfaceTransactionHelper = new PipSurfaceTransactionHelper(mContext);
mPipDesktopState = pipDesktopState;
+ mDesktopPipTransitionController = desktopPipTransitionController;
mPipInteractionHandler = pipInteractionHandler;
mExpandHandler = new PipExpandHandler(mContext, pipBoundsState, pipBoundsAlgorithm,
@@ -227,7 +233,18 @@ public class PipTransition extends PipTransitionController implements
@NonNull TransitionRequestInfo request) {
if (isAutoEnterInButtonNavigation(request) || isEnterPictureInPictureModeRequest(request)) {
mEnterTransition = transition;
- return getEnterPipTransaction(transition, request.getPipChange());
+ final WindowContainerTransaction wct = getEnterPipTransaction(transition,
+ request.getPipChange());
+
+ mDesktopPipTransitionController.ifPresent(
+ desktopPipTransitionController ->
+ desktopPipTransitionController.handlePipTransition(
+ wct,
+ transition,
+ request.getPipChange().getTaskInfo()
+ )
+ );
+ return wct;
}
return null;
}
@@ -300,6 +317,20 @@ public class PipTransition extends PipTransitionController implements
return startAlphaTypeEnterAnimation(info, startTransaction, finishTransaction,
finishCallback);
}
+
+ TransitionInfo.Change pipActivityChange = PipTransitionUtils
+ .getDeferConfigActivityChange(info, pipChange.getTaskInfo().getToken());
+ if (pipActivityChange == null) {
+ // Legacy-enter and swipe-pip-to-home filters did not resolve a scheduled PiP entry.
+ // Bounds-type enter animation is the last resort, and it requires a config-at-end
+ // activity amongst the list of changes. If no such change, something went wrong.
+ Log.wtf(TAG, String.format("""
+ PipTransition.startAnimation didn't handle a scheduled PiP entry
+ transitionInfo=%s,
+ callers=%s""", info, Debug.getCallers(4)));
+ return false;
+ }
+
return startBoundsTypeEnterAnimation(info, startTransaction, finishTransaction,
finishCallback);
} else if (transition == mExitViaExpandTransition) {
@@ -824,26 +855,15 @@ public class PipTransition extends PipTransitionController implements
return true;
}
- // Sometimes root PiP task can have TF children. These child containers can be collected
- // even if they can promote to their parents: e.g. if they are marked as "organized".
- // So we count the chain of containers under PiP task as one "real" changing target;
- // iterate through changes bottom-to-top to properly identify parents.
- int expectedTargetCount = 1;
- WindowContainerToken lastPipChildToken = pipChange.getContainer();
- for (int i = info.getChanges().size() - 1; i >= 0; --i) {
- TransitionInfo.Change change = info.getChanges().get(i);
- if (change == pipChange || change.getContainer() == null) continue;
- if (change.getParent() != null && change.getParent().equals(lastPipChildToken)) {
- // Allow an extra change since our pinned root task has a child.
- ++expectedTargetCount;
- lastPipChildToken = change.getContainer();
- }
- }
-
- // If the only root task change in the changes list is a opening type PiP task,
- // then this is legacy-enter PiP.
- return info.getChanges().size() == expectedTargetCount
- && TransitionUtil.isOpeningMode(pipChange.getMode());
+ // #getEnterPipTransaction() always attempts to mark PiP activity as config-at-end one.
+ // However, the activity will only actually be marked config-at-end by Core if it is
+ // both isVisible and isVisibleRequested, which is when we can't run bounds animation.
+ //
+ // So we can use the absence of a config-at-end activity as a signal that we should run
+ // a legacy-enter PiP animation instead.
+ return TransitionUtil.isOpeningMode(pipChange.getMode())
+ && PipTransitionUtils.getDeferConfigActivityChange(
+ info, pipChange.getContainer()) == null;
}
return false;
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
index e9200834c5dd..5b6993863c5d 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/DefaultTransitionHandler.java
@@ -133,6 +133,7 @@ public class DefaultTransitionHandler implements Transitions.TransitionHandler {
private final DisplayController mDisplayController;
private final Context mContext;
private final Handler mMainHandler;
+ private final Handler mAnimHandler;
private final ShellExecutor mMainExecutor;
private final ShellExecutor mAnimExecutor;
private final TransitionAnimation mTransitionAnimation;
@@ -171,6 +172,7 @@ public class DefaultTransitionHandler implements Transitions.TransitionHandler {
@NonNull TransactionPool transactionPool,
@NonNull ShellExecutor mainExecutor, @NonNull Handler mainHandler,
@NonNull ShellExecutor animExecutor,
+ @NonNull Handler animHandler,
@NonNull RootTaskDisplayAreaOrganizer rootTDAOrganizer,
@NonNull InteractionJankMonitor interactionJankMonitor) {
mDisplayController = displayController;
@@ -179,6 +181,7 @@ public class DefaultTransitionHandler implements Transitions.TransitionHandler {
mMainHandler = mainHandler;
mMainExecutor = mainExecutor;
mAnimExecutor = animExecutor;
+ mAnimHandler = animHandler;
mTransitionAnimation = new TransitionAnimation(context, false /* debug */, Transitions.TAG);
mCurrentUserId = UserHandle.myUserId();
mDevicePolicyManager = mContext.getSystemService(DevicePolicyManager.class);
@@ -349,10 +352,6 @@ public class DefaultTransitionHandler implements Transitions.TransitionHandler {
mAnimations.put(transition, animations);
final boolean isTaskTransition = isTaskTransition(info);
- if (isTaskTransition) {
- mInteractionJankMonitor.begin(info.getRoot(0).getLeash(), mContext,
- mMainHandler, CUJ_DEFAULT_TASK_TO_TASK_ANIMATION);
- }
final Runnable onAnimFinish = () -> {
if (!animations.isEmpty()) return;
@@ -642,6 +641,10 @@ public class DefaultTransitionHandler implements Transitions.TransitionHandler {
// now start animations. they are started on another thread, so we have to post them
// *after* applying the startTransaction
mAnimExecutor.execute(() -> {
+ if (isTaskTransition) {
+ mInteractionJankMonitor.begin(info.getRoot(0).getLeash(), mContext,
+ mAnimHandler, CUJ_DEFAULT_TASK_TO_TASK_ANIMATION);
+ }
for (int i = 0; i < animations.size(); ++i) {
animations.get(i).start();
}
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java
index 3dc8733c879d..84724268cfc2 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/transition/Transitions.java
@@ -215,6 +215,7 @@ public class Transitions implements RemoteCallable<Transitions>,
private final Context mContext;
private final ShellExecutor mMainExecutor;
private final ShellExecutor mAnimExecutor;
+ private final Handler mAnimHandler;
private final TransitionPlayerImpl mPlayerImpl;
private final DefaultTransitionHandler mDefaultTransitionHandler;
private final RemoteTransitionHandler mRemoteTransitionHandler;
@@ -319,11 +320,12 @@ public class Transitions implements RemoteCallable<Transitions>,
@NonNull ShellExecutor mainExecutor,
@NonNull Handler mainHandler,
@NonNull ShellExecutor animExecutor,
+ @NonNull Handler animHandler,
@NonNull HomeTransitionObserver homeTransitionObserver,
@NonNull FocusTransitionObserver focusTransitionObserver) {
this(context, shellInit, new ShellCommandHandler(), shellController, organizer, pool,
displayController, displayInsetsController, mainExecutor, mainHandler, animExecutor,
- new RootTaskDisplayAreaOrganizer(mainExecutor, context, shellInit),
+ animHandler, new RootTaskDisplayAreaOrganizer(mainExecutor, context, shellInit),
homeTransitionObserver, focusTransitionObserver);
}
@@ -338,6 +340,7 @@ public class Transitions implements RemoteCallable<Transitions>,
@NonNull ShellExecutor mainExecutor,
@NonNull Handler mainHandler,
@NonNull ShellExecutor animExecutor,
+ @NonNull Handler animHandler,
@NonNull RootTaskDisplayAreaOrganizer rootTDAOrganizer,
@NonNull HomeTransitionObserver homeTransitionObserver,
@NonNull FocusTransitionObserver focusTransitionObserver) {
@@ -345,11 +348,12 @@ public class Transitions implements RemoteCallable<Transitions>,
mContext = context;
mMainExecutor = mainExecutor;
mAnimExecutor = animExecutor;
+ mAnimHandler = animHandler;
mDisplayController = displayController;
mPlayerImpl = new TransitionPlayerImpl();
mDefaultTransitionHandler = new DefaultTransitionHandler(context, shellInit,
displayController, displayInsetsController, pool, mainExecutor, mainHandler,
- animExecutor, rootTDAOrganizer, InteractionJankMonitor.getInstance());
+ animExecutor, mAnimHandler, rootTDAOrganizer, InteractionJankMonitor.getInstance());
mRemoteTransitionHandler = new RemoteTransitionHandler(mMainExecutor);
mShellCommandHandler = shellCommandHandler;
mShellController = shellController;
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CarWindowDecoration.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CarWindowDecoration.java
index f6acca95916f..dc1b94e80ed7 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CarWindowDecoration.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/CarWindowDecoration.java
@@ -89,9 +89,6 @@ public class CarWindowDecoration extends WindowDecoration<WindowDecorLinearLayou
updateRelayoutParams(mRelayoutParams, taskInfo, isCaptionVisible);
relayout(mRelayoutParams, startT, finishT, wct, mRootView, mResult);
- if (DesktopModeFlags.ENABLE_DESKTOP_APP_HANDLE_ANIMATION.isTrue()) {
- setCaptionVisibility(isCaptionVisible);
- }
// After this line, mTaskInfo is up-to-date and should be used instead of taskInfo
mBgExecutor.execute(() -> mTaskOrganizer.applyTransaction(wct));
@@ -100,19 +97,23 @@ public class CarWindowDecoration extends WindowDecoration<WindowDecorLinearLayou
// Nothing is set up in this case including the decoration surface.
return;
}
+
if (mRootView != mResult.mRootView) {
mRootView = mResult.mRootView;
setupRootView(mResult.mRootView, mClickListener);
}
- }
- private void setCaptionVisibility(boolean visible) {
- if (mRootView == null) {
- return;
+ if (DesktopModeFlags.ENABLE_DESKTOP_APP_HANDLE_ANIMATION.isTrue()) {
+ setCaptionVisibility(mRootView, mRelayoutParams.mIsCaptionVisible);
}
+ }
+
+ private void setCaptionVisibility(@NonNull View rootView, boolean visible) {
final int v = visible ? View.VISIBLE : View.GONE;
- final View captionView = mRootView.findViewById(getCaptionViewId());
- captionView.setVisibility(v);
+ final View captionView = rootView.findViewById(getCaptionViewId());
+ if (captionView != null) {
+ captionView.setVisibility(v);
+ }
}
@Override
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
index 0082d7971ad2..16fa5120d64b 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModel.java
@@ -125,6 +125,7 @@ import com.android.wm.shell.desktopmode.common.ToggleTaskSizeInteraction;
import com.android.wm.shell.desktopmode.common.ToggleTaskSizeUtilsKt;
import com.android.wm.shell.desktopmode.education.AppHandleEducationController;
import com.android.wm.shell.desktopmode.education.AppToWebEducationController;
+import com.android.wm.shell.desktopmode.multidesks.DesksOrganizer;
import com.android.wm.shell.freeform.FreeformTaskTransitionStarter;
import com.android.wm.shell.recents.RecentsTransitionHandler;
import com.android.wm.shell.recents.RecentsTransitionStateListener;
@@ -210,6 +211,7 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
private final AppHandleAndHeaderVisibilityHelper mAppHandleAndHeaderVisibilityHelper;
private final AppHeaderViewHolder.Factory mAppHeaderViewHolderFactory;
private final AppHandleViewHolder.Factory mAppHandleViewHolderFactory;
+ private final DesksOrganizer mDesksOrganizer;
private boolean mTransitionDragActive;
private SparseArray<EventReceiver> mEventReceiversByDisplay = new SparseArray<>();
@@ -308,7 +310,8 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
DesktopModeCompatPolicy desktopModeCompatPolicy,
DesktopTilingDecorViewModel desktopTilingDecorViewModel,
MultiDisplayDragMoveIndicatorController multiDisplayDragMoveIndicatorController,
- CompatUIHandler compatUI) {
+ CompatUIHandler compatUI,
+ DesksOrganizer desksOrganizer) {
this(
context,
shellExecutor,
@@ -356,7 +359,8 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
desktopModeCompatPolicy,
desktopTilingDecorViewModel,
multiDisplayDragMoveIndicatorController,
- compatUI);
+ compatUI,
+ desksOrganizer);
}
@VisibleForTesting
@@ -407,7 +411,8 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
DesktopModeCompatPolicy desktopModeCompatPolicy,
DesktopTilingDecorViewModel desktopTilingDecorViewModel,
MultiDisplayDragMoveIndicatorController multiDisplayDragMoveIndicatorController,
- CompatUIHandler compatUI) {
+ CompatUIHandler compatUI,
+ DesksOrganizer desksOrganizer) {
mContext = context;
mMainExecutor = shellExecutor;
mMainHandler = mainHandler;
@@ -485,6 +490,7 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
mDesktopTasksController.setSnapEventHandler(this);
mMultiDisplayDragMoveIndicatorController = multiDisplayDragMoveIndicatorController;
mLatencyTracker = LatencyTracker.getInstance(mContext);
+ mDesksOrganizer = desksOrganizer;
shellInit.addInitCallback(this::onInit, this);
}
@@ -523,6 +529,10 @@ public class DesktopModeWindowDecorViewModel implements WindowDecorViewModel,
});
}
mFocusTransitionObserver.setLocalFocusTransitionListener(this, mMainExecutor);
+ mDesksOrganizer.setOnDesktopTaskInfoChangedListener((taskInfo) -> {
+ onTaskInfoChanged(taskInfo);
+ return Unit.INSTANCE;
+ });
}
@Override
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenu.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenu.kt
index cdadce57d610..71bb153e4b1e 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenu.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/HandleMenu.kt
@@ -508,6 +508,9 @@ class HandleMenu(
private val iconButtonRippleRadius = context.resources.getDimensionPixelSize(
R.dimen.desktop_mode_handle_menu_icon_button_ripple_radius
)
+ private val handleMenuCornerRadius = context.resources.getDimensionPixelSize(
+ R.dimen.desktop_mode_handle_menu_corner_radius
+ )
private val iconButtonDrawableInsetsBase = DrawableInsets(
t = iconButtondrawableBaseInset,
b = iconButtondrawableBaseInset, l = iconButtondrawableBaseInset,
@@ -866,14 +869,21 @@ class HandleMenu(
private fun bindMoreActionsPill(style: MenuStyle) {
moreActionsPill.background.setTint(style.backgroundColor)
-
- arrayOf(
+ val buttons = arrayOf(
screenshotBtn to SHOULD_SHOW_SCREENSHOT_BUTTON,
newWindowBtn to shouldShowNewWindowButton,
manageWindowBtn to shouldShowManageWindowsButton,
changeAspectRatioBtn to shouldShowChangeAspectRatioButton,
restartBtn to shouldShowRestartButton,
- ).forEach { (button, shouldShow) ->
+ )
+ val firstVisible = buttons.find { it.second }?.first
+ val lastVisible = buttons.findLast { it.second }?.first
+
+ buttons.forEach { (button, shouldShow) ->
+ val topRadius =
+ if (button == firstVisible) handleMenuCornerRadius.toFloat() else 0f
+ val bottomRadius =
+ if (button == lastVisible) handleMenuCornerRadius.toFloat() else 0f
button.apply {
isGone = !shouldShow
textView.apply {
@@ -881,6 +891,13 @@ class HandleMenu(
startMarquee()
}
iconView.imageTintList = ColorStateList.valueOf(style.textColor)
+ background = createBackgroundDrawable(
+ color = style.textColor,
+ cornerRadius = floatArrayOf(
+ topRadius, topRadius, topRadius, topRadius,
+ bottomRadius, bottomRadius, bottomRadius, bottomRadius
+ ),
+ drawableInsets = DrawableInsets())
}
}
}
@@ -899,6 +916,10 @@ class HandleMenu(
openInAppOrBrowserBtn.apply {
contentDescription = btnText
+ background = createBackgroundDrawable(
+ color = style.textColor,
+ cornerRadius = handleMenuCornerRadius,
+ drawableInsets = DrawableInsets())
textView.apply {
text = btnText
setTextColor(style.textColor)
diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/common/ButtonBackgroundDrawableUtils.kt b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/common/ButtonBackgroundDrawableUtils.kt
index f08cfa987cc7..33e743016d0d 100644
--- a/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/common/ButtonBackgroundDrawableUtils.kt
+++ b/libs/WindowManager/Shell/src/com/android/wm/shell/windowdecor/common/ButtonBackgroundDrawableUtils.kt
@@ -51,10 +51,20 @@ fun replaceColorAlpha(@ColorInt color: Int, alpha: Int): Int {
*/
fun createBackgroundDrawable(
@ColorInt color: Int, cornerRadius: Int, drawableInsets: DrawableInsets
+): Drawable = createBackgroundDrawable(
+ color,
+ FloatArray(8) { cornerRadius.toFloat() },
+ drawableInsets)
+
+/**
+ * Creates a background drawable with specified color, corner radius, and insets.
+ */
+fun createBackgroundDrawable(
+ @ColorInt color: Int, cornerRadius: FloatArray, drawableInsets: DrawableInsets
): Drawable = LayerDrawable(arrayOf(
ShapeDrawable().apply {
shape = RoundRectShape(
- FloatArray(8) { cornerRadius.toFloat() },
+ cornerRadius,
/* inset= */ null,
/* innerRadii= */ null
)
diff --git a/libs/WindowManager/Shell/tests/e2e/splitscreen/flicker-legacy/src/com/android/wm/shell/flicker/splitscreen/benchmark/SwitchAppByDoubleTapDividerBenchmark.kt b/libs/WindowManager/Shell/tests/e2e/splitscreen/flicker-legacy/src/com/android/wm/shell/flicker/splitscreen/benchmark/SwitchAppByDoubleTapDividerBenchmark.kt
index fa9864b539ee..7cd2bcc8efd4 100644
--- a/libs/WindowManager/Shell/tests/e2e/splitscreen/flicker-legacy/src/com/android/wm/shell/flicker/splitscreen/benchmark/SwitchAppByDoubleTapDividerBenchmark.kt
+++ b/libs/WindowManager/Shell/tests/e2e/splitscreen/flicker-legacy/src/com/android/wm/shell/flicker/splitscreen/benchmark/SwitchAppByDoubleTapDividerBenchmark.kt
@@ -52,7 +52,7 @@ abstract class SwitchAppByDoubleTapDividerBenchmark(override val flicker: Legacy
)
}
transitions {
- SplitScreenUtils.doubleTapDividerToSwitch(device)
+ SplitScreenUtils.doubleTapDividerToSwitch(device, instrumentation.uiAutomation)
wmHelper.StateSyncBuilder().withAppTransitionIdle().waitForAndVerify()
waitForLayersToSwitch(wmHelper)
diff --git a/libs/WindowManager/Shell/tests/e2e/splitscreen/scenarios/src/com/android/wm/shell/scenarios/SwitchAppByDoubleTapDivider.kt b/libs/WindowManager/Shell/tests/e2e/splitscreen/scenarios/src/com/android/wm/shell/scenarios/SwitchAppByDoubleTapDivider.kt
index 3fd93d3eaf59..dfc737174a4f 100644
--- a/libs/WindowManager/Shell/tests/e2e/splitscreen/scenarios/src/com/android/wm/shell/scenarios/SwitchAppByDoubleTapDivider.kt
+++ b/libs/WindowManager/Shell/tests/e2e/splitscreen/scenarios/src/com/android/wm/shell/scenarios/SwitchAppByDoubleTapDivider.kt
@@ -61,7 +61,7 @@ constructor(val rotation: Rotation = Rotation.ROTATION_0) {
@Test
open fun switchAppByDoubleTapDivider() {
- SplitScreenUtils.doubleTapDividerToSwitch(device)
+ SplitScreenUtils.doubleTapDividerToSwitch(device, instrumentation.uiAutomation)
wmHelper.StateSyncBuilder().withAppTransitionIdle().waitForAndVerify()
waitForLayersToSwitch(wmHelper)
diff --git a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/utils/SplitScreenUtils.kt b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/utils/SplitScreenUtils.kt
index e4183f16ba14..e54930d730f3 100644
--- a/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/utils/SplitScreenUtils.kt
+++ b/libs/WindowManager/Shell/tests/flicker/src/com/android/wm/shell/flicker/utils/SplitScreenUtils.kt
@@ -17,6 +17,7 @@
package com.android.wm.shell.flicker.utils
import android.app.Instrumentation
+import android.app.UiAutomation
import android.content.Context
import android.graphics.Point
import android.os.SystemClock
@@ -355,13 +356,40 @@ object SplitScreenUtils {
)
}
- fun doubleTapDividerToSwitch(device: UiDevice) {
+ fun doubleTapDividerToSwitch(device: UiDevice, uiAutomation: UiAutomation) {
val dividerBar = device.wait(Until.findObject(dividerBarSelector), TIMEOUT_MS)
- val interval =
- (ViewConfiguration.getDoubleTapTimeout() + ViewConfiguration.getDoubleTapMinTime()) / 2
- dividerBar.click()
- SystemClock.sleep(interval.toLong())
- dividerBar.click()
+ val x = dividerBar.visibleCenter.x.toFloat()
+ val y = dividerBar.visibleCenter.y.toFloat()
+
+ // To send a double-tap action, we set a DOWN event, then UP, then DOWN, then, UP.
+ val startTime = SystemClock.uptimeMillis()
+ val timeOfFirstUp = startTime + ViewConfiguration.getTapTimeout()
+ // Between the two taps, we wait an arbitrary amount of time between the min and max times
+ // for a double-tap.
+ val timeOfSecondDown = timeOfFirstUp + ViewConfiguration.getDoubleTapMinTime() +
+ ((ViewConfiguration.getDoubleTapTimeout() -
+ ViewConfiguration.getDoubleTapMinTime()) / 4)
+ val timeOfSecondUp = timeOfSecondDown + ViewConfiguration.getTapTimeout()
+
+ val downEvent = MotionEvent.obtain(startTime, startTime, MotionEvent.ACTION_DOWN, x, y,
+ 0 /* metaState */)
+ downEvent.setSource(InputDevice.SOURCE_TOUCHSCREEN)
+ uiAutomation.injectInputEvent(downEvent, true)
+
+ val upEvent = MotionEvent.obtain(startTime, timeOfFirstUp, MotionEvent.ACTION_UP, x, y,
+ 0 /* metaState */)
+ upEvent.setSource(InputDevice.SOURCE_TOUCHSCREEN)
+ uiAutomation.injectInputEvent(upEvent, true)
+
+ val downEvent2 = MotionEvent.obtain(timeOfSecondDown, timeOfSecondDown,
+ MotionEvent.ACTION_DOWN, x, y, 0 /* metaState */)
+ downEvent2.setSource(InputDevice.SOURCE_TOUCHSCREEN)
+ uiAutomation.injectInputEvent(downEvent2, true)
+
+ val upEvent2 = MotionEvent.obtain(timeOfSecondDown, timeOfSecondUp, MotionEvent.ACTION_UP,
+ x, y, 0 /* metaState */)
+ upEvent2.setSource(InputDevice.SOURCE_TOUCHSCREEN)
+ uiAutomation.injectInputEvent(upEvent2, true)
}
fun copyContentInSplit(
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopDisplayModeControllerTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopDisplayModeControllerTest.kt
index 96b826f93aae..488025a3d754 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopDisplayModeControllerTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopDisplayModeControllerTest.kt
@@ -104,7 +104,9 @@ class DesktopDisplayModeControllerTest(
private val wallpaperToken = MockToken().token()
private val defaultDisplay = mock<Display>()
private val externalDisplay = mock<Display>()
- private val mouseDevice = mock<InputDevice>()
+ private val touchpadDevice = mock<InputDevice>()
+ private val keyboardDevice = mock<InputDevice>()
+ private val connectedDeviceIds = mutableListOf<Int>()
private lateinit var extendedDisplaySettingsRestoreSession:
ExtendedDisplaySettingsRestoreSession
@@ -145,16 +147,18 @@ class DesktopDisplayModeControllerTest(
whenever(desktopWallpaperActivityTokenProvider.getToken()).thenReturn(wallpaperToken)
whenever(displayController.getDisplay(DEFAULT_DISPLAY)).thenReturn(defaultDisplay)
whenever(displayController.getDisplay(EXTERNAL_DISPLAY_ID)).thenReturn(externalDisplay)
- setTabletModeStatus(SwitchState.UNKNOWN)
- whenever(
- DesktopModeStatus.isDesktopModeSupportedOnDisplay(
- context,
- defaultDisplay
- )
- ).thenReturn(true)
- whenever(mouseDevice.supportsSource(InputDevice.SOURCE_MOUSE)).thenReturn(true)
- whenever(inputManager.getInputDevice(EXTERNAL_DEVICE_ID)).thenReturn(mouseDevice)
- setMouseConnected(false)
+ whenever(DesktopModeStatus.isDesktopModeSupportedOnDisplay(context, defaultDisplay))
+ .thenReturn(true)
+ whenever(touchpadDevice.supportsSource(InputDevice.SOURCE_TOUCHPAD)).thenReturn(true)
+ whenever(touchpadDevice.isEnabled()).thenReturn(true)
+ whenever(inputManager.getInputDevice(TOUCHPAD_DEVICE_ID)).thenReturn(touchpadDevice)
+ whenever(keyboardDevice.isFullKeyboard()).thenReturn(true)
+ whenever(keyboardDevice.isVirtual()).thenReturn(false)
+ whenever(keyboardDevice.isEnabled()).thenReturn(true)
+ whenever(inputManager.getInputDevice(KEYBOARD_DEVICE_ID)).thenReturn(keyboardDevice)
+ whenever(inputManager.inputDeviceIds).thenAnswer { connectedDeviceIds.toIntArray() }
+ setTouchpadConnected(false)
+ setKeyboardConnected(false)
}
@After
@@ -211,8 +215,8 @@ class DesktopDisplayModeControllerTest(
@DisableFlags(Flags.FLAG_FORM_FACTOR_BASED_DESKTOP_FIRST_SWITCH)
fun testTargetWindowingMode_formfactorDisabled(
@TestParameter param: ExternalDisplayBasedTargetModeTestCase,
- @TestParameter tabletModeStatus: SwitchState,
- @TestParameter hasAnyMouseDevice: Boolean,
+ @TestParameter hasAnyTouchpadDevice: Boolean,
+ @TestParameter hasAnyKeyboardDevice: Boolean,
) {
whenever(mockWindowManager.getWindowingMode(anyInt()))
.thenReturn(param.defaultWindowingMode)
@@ -221,15 +225,11 @@ class DesktopDisplayModeControllerTest(
} else {
disconnectExternalDisplay()
}
- setTabletModeStatus(tabletModeStatus)
- setMouseConnected(hasAnyMouseDevice)
+ setTouchpadConnected(hasAnyTouchpadDevice)
+ setKeyboardConnected(hasAnyKeyboardDevice)
setExtendedMode(param.extendedDisplayEnabled)
- whenever(
- DesktopModeStatus.isDesktopModeSupportedOnDisplay(
- context,
- defaultDisplay
- )
- ).thenReturn(param.isDefaultDisplayDesktopEligible)
+ whenever(DesktopModeStatus.isDesktopModeSupportedOnDisplay(context, defaultDisplay))
+ .thenReturn(param.isDefaultDisplayDesktopEligible)
assertThat(controller.getTargetWindowingModeForDefaultDisplay())
.isEqualTo(param.expectedWindowingMode)
@@ -246,15 +246,11 @@ class DesktopDisplayModeControllerTest(
} else {
disconnectExternalDisplay()
}
- setTabletModeStatus(param.tabletModeStatus)
setExtendedMode(param.extendedDisplayEnabled)
- whenever(
- DesktopModeStatus.isDesktopModeSupportedOnDisplay(
- context,
- defaultDisplay
- )
- ).thenReturn(param.isDefaultDisplayDesktopEligible)
- setMouseConnected(param.hasAnyMouseDevice)
+ whenever(DesktopModeStatus.isDesktopModeSupportedOnDisplay(context, defaultDisplay))
+ .thenReturn(param.isDefaultDisplayDesktopEligible)
+ setTouchpadConnected(param.hasAnyTouchpadDevice)
+ setKeyboardConnected(param.hasAnyKeyboardDevice)
assertThat(controller.getTargetWindowingModeForDefaultDisplay())
.isEqualTo(param.expectedWindowingMode)
@@ -308,18 +304,10 @@ class DesktopDisplayModeControllerTest(
controller.refreshDisplayWindowingMode()
}
- private fun setTabletModeStatus(status: SwitchState) {
- whenever(inputManager.isInTabletMode()).thenReturn(status.value)
- }
-
private fun setExtendedMode(enabled: Boolean) {
if (DisplayFlags.enableDisplayContentModeManagement()) {
- whenever(
- DesktopModeStatus.isDesktopModeSupportedOnDisplay(
- context,
- externalDisplay
- )
- ).thenReturn(enabled)
+ whenever(DesktopModeStatus.isDesktopModeSupportedOnDisplay(context, externalDisplay))
+ .thenReturn(enabled)
} else {
Settings.Global.putInt(
context.contentResolver,
@@ -329,9 +317,20 @@ class DesktopDisplayModeControllerTest(
}
}
- private fun setMouseConnected(connected: Boolean) {
- whenever(inputManager.inputDeviceIds)
- .thenReturn(if (connected) intArrayOf(EXTERNAL_DEVICE_ID) else intArrayOf())
+ private fun setTouchpadConnected(connected: Boolean) {
+ if (connected) {
+ connectedDeviceIds.add(TOUCHPAD_DEVICE_ID)
+ } else {
+ connectedDeviceIds.remove(TOUCHPAD_DEVICE_ID)
+ }
+ }
+
+ private fun setKeyboardConnected(connected: Boolean) {
+ if (connected) {
+ connectedDeviceIds.add(KEYBOARD_DEVICE_ID)
+ } else {
+ connectedDeviceIds.remove(KEYBOARD_DEVICE_ID)
+ }
}
private class ExtendedDisplaySettingsRestoreSession(
@@ -358,13 +357,8 @@ class DesktopDisplayModeControllerTest(
companion object {
const val EXTERNAL_DISPLAY_ID = 100
- const val EXTERNAL_DEVICE_ID = 10
-
- enum class SwitchState(val value: Int) {
- UNKNOWN(InputManager.SWITCH_STATE_UNKNOWN),
- ON(InputManager.SWITCH_STATE_ON),
- OFF(InputManager.SWITCH_STATE_OFF),
- }
+ const val TOUCHPAD_DEVICE_ID = 10
+ const val KEYBOARD_DEVICE_ID = 11
enum class ExternalDisplayBasedTargetModeTestCase(
val defaultWindowingMode: Int,
@@ -490,393 +484,265 @@ class DesktopDisplayModeControllerTest(
enum class FormFactorBasedTargetModeTestCase(
val hasExternalDisplay: Boolean,
val extendedDisplayEnabled: Boolean,
- val tabletModeStatus: SwitchState,
val isDefaultDisplayDesktopEligible: Boolean,
- val hasAnyMouseDevice: Boolean,
+ val hasAnyTouchpadDevice: Boolean,
+ val hasAnyKeyboardDevice: Boolean,
val expectedWindowingMode: Int,
) {
- EXTERNAL_EXTENDED_TABLET_NO_PROJECTED_NO_MOUSE(
+ EXTERNAL_EXTENDED_NO_PROJECTED_TOUCHPAD_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FREEFORM,
),
- NO_EXTERNAL_EXTENDED_TABLET_NO_PROJECTED_NO_MOUSE(
+ NO_EXTERNAL_EXTENDED_NO_PROJECTED_TOUCHPAD_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.ON,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
- expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
- ),
- EXTERNAL_MIRROR_TABLET_NO_PROJECTED_NO_MOUSE(
- hasExternalDisplay = true,
- extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.ON,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
- expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
- ),
- NO_EXTERNAL_MIRROR_TABLET_NO_PROJECTED_NO_MOUSE(
- hasExternalDisplay = false,
- extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.ON,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
- expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
- ),
- EXTERNAL_EXTENDED_CLAMSHELL_NO_PROJECTED_NO_MOUSE(
- hasExternalDisplay = true,
- extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.OFF,
isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FREEFORM,
),
- NO_EXTERNAL_EXTENDED_CLAMSHELL_NO_PROJECTED_NO_MOUSE(
- hasExternalDisplay = false,
- extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
- ),
- EXTERNAL_MIRROR_CLAMSHELL_NO_PROJECTED_NO_MOUSE(
+ EXTERNAL_MIRROR_NO_PROJECTED_TOUCHPAD_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.OFF,
isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FREEFORM,
),
- NO_EXTERNAL_MIRROR_CLAMSHELL_NO_PROJECTED_NO_MOUSE(
+ NO_EXTERNAL_MIRROR_NO_PROJECTED_TOUCHPAD_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.OFF,
isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FREEFORM,
),
- EXTERNAL_EXTENDED_UNKNOWN_NO_PROJECTED_NO_MOUSE(
- hasExternalDisplay = true,
- extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.UNKNOWN,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
- ),
- NO_EXTERNAL_EXTENDED_UNKNOWN_NO_PROJECTED_NO_MOUSE(
- hasExternalDisplay = false,
- extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.UNKNOWN,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
- expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
- ),
- EXTERNAL_MIRROR_UNKNOWN_NO_PROJECTED_NO_MOUSE(
- hasExternalDisplay = true,
- extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.UNKNOWN,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
- expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
- ),
- NO_EXTERNAL_MIRROR_UNKNOWN_NO_PROJECTED_NO_MOUSE(
- hasExternalDisplay = false,
- extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.UNKNOWN,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = false,
- expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
- ),
- EXTERNAL_EXTENDED_TABLET_PROJECTED_NO_MOUSE(
+ EXTERNAL_EXTENDED_PROJECTED_TOUCHPAD_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_EXTENDED_TABLET_PROJECTED_NO_MOUSE(
+ NO_EXTERNAL_EXTENDED_PROJECTED_TOUCHPAD_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_MIRROR_TABLET_PROJECTED_NO_MOUSE(
+ EXTERNAL_MIRROR_PROJECTED_TOUCHPAD_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_MIRROR_TABLET_PROJECTED_NO_MOUSE(
+ NO_EXTERNAL_MIRROR_PROJECTED_TOUCHPAD_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_EXTENDED_CLAMSHELL_PROJECTED_NO_MOUSE(
+ EXTERNAL_EXTENDED_NO_PROJECTED_NO_TOUCHPAD_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
- expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
+ isDefaultDisplayDesktopEligible = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = true,
+ expectedWindowingMode = WINDOWING_MODE_FREEFORM,
),
- NO_EXTERNAL_EXTENDED_CLAMSHELL_PROJECTED_NO_MOUSE(
+ NO_EXTERNAL_EXTENDED_NO_PROJECTED_NO_TOUCHPAD_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ isDefaultDisplayDesktopEligible = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_MIRROR_CLAMSHELL_PROJECTED_NO_MOUSE(
+ EXTERNAL_MIRROR_NO_PROJECTED_NO_TOUCHPAD_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ isDefaultDisplayDesktopEligible = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_MIRROR_CLAMSHELL_PROJECTED_NO_MOUSE(
+ NO_EXTERNAL_MIRROR_NO_PROJECTED_NO_TOUCHPAD_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ isDefaultDisplayDesktopEligible = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_EXTENDED_UNKNOWN_PROJECTED_NO_MOUSE(
+ EXTERNAL_EXTENDED_PROJECTED_NO_TOUCHPAD_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.UNKNOWN,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_EXTENDED_UNKNOWN_PROJECTED_NO_MOUSE(
+ NO_EXTERNAL_EXTENDED_PROJECTED_NO_TOUCHPAD_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.UNKNOWN,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_MIRROR_UNKNOWN_PROJECTED_NO_MOUSE(
+ EXTERNAL_MIRROR_PROJECTED_NO_TOUCHPAD_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.UNKNOWN,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_MIRROR_UNKNOWN_PROJECTED_NO_MOUSE(
+ NO_EXTERNAL_MIRROR_PROJECTED_NO_TOUCHPAD_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.UNKNOWN,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = false,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = true,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_EXTENDED_TABLET_NO_PROJECTED_MOUSE(
+ EXTERNAL_EXTENDED_NO_PROJECTED_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FREEFORM,
),
- NO_EXTERNAL_EXTENDED_TABLET_NO_PROJECTED_MOUSE(
+ NO_EXTERNAL_EXTENDED_NO_PROJECTED_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.ON,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
- ),
- EXTERNAL_MIRROR_TABLET_NO_PROJECTED_MOUSE(
- hasExternalDisplay = true,
- extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.ON,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
- ),
- NO_EXTERNAL_MIRROR_TABLET_NO_PROJECTED_MOUSE(
- hasExternalDisplay = false,
- extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
- ),
- EXTERNAL_EXTENDED_CLAMSHELL_NO_PROJECTED_MOUSE(
- hasExternalDisplay = true,
- extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
- ),
- NO_EXTERNAL_EXTENDED_CLAMSHELL_NO_PROJECTED_MOUSE(
- hasExternalDisplay = false,
- extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
- ),
- EXTERNAL_MIRROR_CLAMSHELL_NO_PROJECTED_MOUSE(
- hasExternalDisplay = true,
- extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
- ),
- NO_EXTERNAL_MIRROR_CLAMSHELL_NO_PROJECTED_MOUSE(
- hasExternalDisplay = false,
- extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
- ),
- EXTERNAL_EXTENDED_UNKNOWN_NO_PROJECTED_MOUSE(
- hasExternalDisplay = true,
- extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.UNKNOWN,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
- ),
- NO_EXTERNAL_EXTENDED_UNKNOWN_NO_PROJECTED_MOUSE(
- hasExternalDisplay = false,
- extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.UNKNOWN,
- isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = false,
+ expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_MIRROR_UNKNOWN_NO_PROJECTED_MOUSE(
+ EXTERNAL_MIRROR_NO_PROJECTED_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.UNKNOWN,
isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = false,
+ expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_MIRROR_UNKNOWN_NO_PROJECTED_MOUSE(
+ NO_EXTERNAL_MIRROR_NO_PROJECTED_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.UNKNOWN,
isDefaultDisplayDesktopEligible = true,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FREEFORM,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = false,
+ expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_EXTENDED_TABLET_PROJECTED_MOUSE(
+ EXTERNAL_EXTENDED_PROJECTED_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_EXTENDED_TABLET_PROJECTED_MOUSE(
+ NO_EXTERNAL_EXTENDED_PROJECTED_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_MIRROR_TABLET_PROJECTED_MOUSE(
+ EXTERNAL_MIRROR_PROJECTED_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_MIRROR_TABLET_PROJECTED_MOUSE(
+ NO_EXTERNAL_MIRROR_PROJECTED_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.ON,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ hasAnyTouchpadDevice = true,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_EXTENDED_CLAMSHELL_PROJECTED_MOUSE(
+ EXTERNAL_EXTENDED_NO_PROJECTED_NO_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
- expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
+ isDefaultDisplayDesktopEligible = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = false,
+ expectedWindowingMode = WINDOWING_MODE_FREEFORM,
),
- NO_EXTERNAL_EXTENDED_CLAMSHELL_PROJECTED_MOUSE(
+ NO_EXTERNAL_EXTENDED_NO_PROJECTED_NO_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ isDefaultDisplayDesktopEligible = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_MIRROR_CLAMSHELL_PROJECTED_MOUSE(
+ EXTERNAL_MIRROR_NO_PROJECTED_NO_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ isDefaultDisplayDesktopEligible = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_MIRROR_CLAMSHELL_PROJECTED_MOUSE(
+ NO_EXTERNAL_MIRROR_NO_PROJECTED_NO_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.OFF,
- isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ isDefaultDisplayDesktopEligible = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_EXTENDED_UNKNOWN_PROJECTED_MOUSE(
+ EXTERNAL_EXTENDED_PROJECTED_NO_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.UNKNOWN,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_EXTENDED_UNKNOWN_PROJECTED_MOUSE(
+ NO_EXTERNAL_EXTENDED_PROJECTED_NO_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = true,
- tabletModeStatus = SwitchState.UNKNOWN,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- EXTERNAL_MIRROR_UNKNOWN_PROJECTED_MOUSE(
+ EXTERNAL_MIRROR_PROJECTED_NO_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = true,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.UNKNOWN,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
- NO_EXTERNAL_MIRROR_UNKNOWN_PROJECTED_MOUSE(
+ NO_EXTERNAL_MIRROR_PROJECTED_NO_TOUCHPAD_NO_KEYBOARD(
hasExternalDisplay = false,
extendedDisplayEnabled = false,
- tabletModeStatus = SwitchState.UNKNOWN,
isDefaultDisplayDesktopEligible = false,
- hasAnyMouseDevice = true,
+ hasAnyTouchpadDevice = false,
+ hasAnyKeyboardDevice = false,
expectedWindowingMode = WINDOWING_MODE_FULLSCREEN,
),
}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopModeVisualIndicatorTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopModeVisualIndicatorTest.kt
index 652fae01c1b2..a4052890f08a 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopModeVisualIndicatorTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopModeVisualIndicatorTest.kt
@@ -283,14 +283,32 @@ class DesktopModeVisualIndicatorTest : ShellTestCase() {
com.android.wm.shell.Flags.FLAG_ENABLE_BUBBLE_TO_FULLSCREEN,
com.android.wm.shell.Flags.FLAG_ENABLE_CREATE_ANY_BUBBLE,
)
- fun testDefaultIndicators_bubblesEnabled() {
+ fun testDefaultIndicators_enableBubbleToFullscreen() {
createVisualIndicator(DesktopModeVisualIndicator.DragStartState.FROM_FULLSCREEN)
var result = visualIndicator.updateIndicatorType(PointF(10f, 1500f))
assertThat(result)
.isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_BUBBLE_LEFT_INDICATOR)
- result = visualIndicator.updateIndicatorType(PointF(2300f, 1500f))
+ result = visualIndicator.updateIndicatorType(PointF(2390f, 1500f))
assertThat(result)
.isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_BUBBLE_RIGHT_INDICATOR)
+
+ // Check that bubble zones are not available from split
+ createVisualIndicator(DesktopModeVisualIndicator.DragStartState.FROM_SPLIT)
+ result = visualIndicator.updateIndicatorType(PointF(10f, 1500f))
+ assertThat(result)
+ .isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_SPLIT_LEFT_INDICATOR)
+ result = visualIndicator.updateIndicatorType(PointF(2390f, 1500f))
+ assertThat(result)
+ .isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_SPLIT_RIGHT_INDICATOR)
+
+ // Check that bubble zones are not available from desktop
+ createVisualIndicator(DesktopModeVisualIndicator.DragStartState.FROM_FREEFORM)
+ result = visualIndicator.updateIndicatorType(PointF(10f, 1500f))
+ assertThat(result)
+ .isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_SPLIT_LEFT_INDICATOR)
+ result = visualIndicator.updateIndicatorType(PointF(2390f, 1500f))
+ assertThat(result)
+ .isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_SPLIT_RIGHT_INDICATOR)
}
@Test
@@ -298,7 +316,7 @@ class DesktopModeVisualIndicatorTest : ShellTestCase() {
com.android.wm.shell.Flags.FLAG_ENABLE_BUBBLE_TO_FULLSCREEN,
com.android.wm.shell.Flags.FLAG_ENABLE_CREATE_ANY_BUBBLE,
)
- fun testDefaultIndicators_foldable_leftRightSplit() {
+ fun testDefaultIndicators_foldable_enableBubbleToFullscreen_dragFromFullscreen() {
setUpFoldable()
createVisualIndicator(
@@ -325,13 +343,47 @@ class DesktopModeVisualIndicatorTest : ShellTestCase() {
result = visualIndicator.updateIndicatorType(foldRightBottom())
assertThat(result)
.isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_BUBBLE_RIGHT_INDICATOR)
+ }
+
+ @Test
+ @EnableFlags(
+ com.android.wm.shell.Flags.FLAG_ENABLE_BUBBLE_TO_FULLSCREEN,
+ com.android.wm.shell.Flags.FLAG_ENABLE_CREATE_ANY_BUBBLE,
+ )
+ @DisableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_BUBBLE_ANYTHING)
+ fun testDefaultIndicators_foldable_enableBubbleToFullscreen_dragFromSplit() {
+ setUpFoldable()
createVisualIndicator(
DesktopModeVisualIndicator.DragStartState.FROM_SPLIT,
isSmallTablet = true,
isLeftRightSplit = true,
)
- result = visualIndicator.updateIndicatorType(foldCenter())
+ var result = visualIndicator.updateIndicatorType(foldCenter())
+ assertThat(result)
+ .isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_FULLSCREEN_INDICATOR)
+
+ // Check that bubbles are not available from split
+ result = visualIndicator.updateIndicatorType(foldLeftBottom())
+ assertThat(result)
+ .isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_SPLIT_LEFT_INDICATOR)
+
+ result = visualIndicator.updateIndicatorType(foldRightBottom())
+ assertThat(result)
+ .isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_SPLIT_RIGHT_INDICATOR)
+ }
+
+ @Test
+ @EnableFlags(com.android.wm.shell.Flags.FLAG_ENABLE_BUBBLE_ANYTHING)
+ fun testDefaultIndicators_foldable_enableBubbleAnything_dragFromSplit() {
+ setUpFoldable()
+
+ createVisualIndicator(
+ DesktopModeVisualIndicator.DragStartState.FROM_SPLIT,
+ isSmallTablet = true,
+ isLeftRightSplit = true,
+ )
+ var result = visualIndicator.updateIndicatorType(foldCenter())
assertThat(result)
.isEqualTo(DesktopModeVisualIndicator.IndicatorType.TO_FULLSCREEN_INDICATOR)
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopPipTransitionControllerTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopPipTransitionControllerTest.kt
new file mode 100644
index 000000000000..47a9a6c8d840
--- /dev/null
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopPipTransitionControllerTest.kt
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.wm.shell.desktopmode
+
+import android.os.Binder
+import android.platform.test.annotations.EnableFlags
+import android.platform.test.flag.junit.FlagsParameterization
+import android.view.Display.DEFAULT_DISPLAY
+import android.window.WindowContainerTransaction
+import androidx.test.filters.SmallTest
+import com.android.window.flags.Flags
+import com.android.window.flags.Flags.FLAG_ENABLE_DESKTOP_WINDOWING_PIP
+import com.android.window.flags.Flags.FLAG_ENABLE_MULTIPLE_DESKTOPS_BACKEND
+import com.android.wm.shell.ShellTestCase
+import com.android.wm.shell.common.pip.PipDesktopState
+import com.android.wm.shell.desktopmode.DesktopTestHelpers.createFreeformTask
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyBoolean
+import org.mockito.ArgumentMatchers.anyInt
+import org.mockito.ArgumentMatchers.eq
+import org.mockito.kotlin.any
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.never
+import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
+import platform.test.runner.parameterized.ParameterizedAndroidJunit4
+import platform.test.runner.parameterized.Parameters
+
+/**
+ * Tests for [DesktopPipTransitionController].
+ *
+ * Build/Install/Run: atest WMShellUnitTests:DesktopPipTransitionControllerTest
+ */
+@SmallTest
+@RunWith(ParameterizedAndroidJunit4::class)
+@EnableFlags(FLAG_ENABLE_DESKTOP_WINDOWING_PIP)
+class DesktopPipTransitionControllerTest(flags: FlagsParameterization) : ShellTestCase() {
+ private val mockDesktopTasksController = mock<DesktopTasksController>()
+ private val mockDesktopUserRepositories = mock<DesktopUserRepositories>()
+ private val mockDesktopRepository = mock<DesktopRepository>()
+ private val mockPipDesktopState = mock<PipDesktopState>()
+
+ private lateinit var controller: DesktopPipTransitionController
+
+ private val transition = Binder()
+ private val wct = WindowContainerTransaction()
+ private val taskInfo = createFreeformTask()
+
+ init {
+ mSetFlagsRule.setFlagsParameterization(flags)
+ }
+
+ @Before
+ fun setUp() {
+ whenever(mockPipDesktopState.isDesktopWindowingPipEnabled()).thenReturn(true)
+ whenever(mockDesktopUserRepositories.getProfile(anyInt())).thenReturn(mockDesktopRepository)
+ whenever(mockDesktopRepository.isAnyDeskActive(anyInt())).thenReturn(true)
+ whenever(mockDesktopRepository.getActiveDeskId(anyInt())).thenReturn(DESK_ID)
+
+ controller =
+ DesktopPipTransitionController(
+ mockDesktopTasksController,
+ mockDesktopUserRepositories,
+ mockPipDesktopState,
+ )
+ }
+
+ @Test
+ fun handlePipTransition_noDeskActive_doesntPerformDesktopExitCleanup() {
+ whenever(mockDesktopRepository.isAnyDeskActive(eq(taskInfo.displayId))).thenReturn(false)
+
+ controller.handlePipTransition(wct, transition, taskInfo)
+
+ verifyPerformDesktopExitCleanupAfterPip(isCalled = false)
+ }
+
+ @Test
+ fun handlePipTransition_notLastTask_doesntPerformDesktopExitCleanup() {
+ whenever(
+ mockDesktopRepository.isOnlyVisibleNonClosingTaskInDesk(
+ taskId = eq(taskInfo.taskId),
+ deskId = eq(DESK_ID),
+ displayId = eq(taskInfo.displayId),
+ )
+ )
+ .thenReturn(false)
+
+ controller.handlePipTransition(wct, transition, taskInfo)
+
+ verifyPerformDesktopExitCleanupAfterPip(isCalled = false)
+ }
+
+ @Test
+ @EnableFlags(FLAG_ENABLE_MULTIPLE_DESKTOPS_BACKEND)
+ fun handlePipTransition_noActiveDeskId_multiDesk_doesntPerformDesktopExitCleanup() {
+ whenever(mockDesktopRepository.getActiveDeskId(eq(taskInfo.displayId))).thenReturn(null)
+
+ controller.handlePipTransition(wct, transition, taskInfo)
+
+ verifyPerformDesktopExitCleanupAfterPip(isCalled = false)
+ }
+
+ @Test
+ fun handlePipTransition_isLastTask_performDesktopExitCleanup() {
+ whenever(
+ mockDesktopRepository.isOnlyVisibleNonClosingTaskInDesk(
+ taskId = eq(taskInfo.taskId),
+ deskId = eq(DESK_ID),
+ displayId = eq(taskInfo.displayId),
+ )
+ )
+ .thenReturn(true)
+
+ controller.handlePipTransition(wct, transition, taskInfo)
+
+ verifyPerformDesktopExitCleanupAfterPip(isCalled = true)
+ }
+
+ private fun verifyPerformDesktopExitCleanupAfterPip(isCalled: Boolean) {
+ if (isCalled) {
+ verify(mockDesktopTasksController)
+ .performDesktopExitCleanUp(
+ wct = wct,
+ deskId = DESK_ID,
+ displayId = DEFAULT_DISPLAY,
+ willExitDesktop = true,
+ )
+ } else {
+ verify(mockDesktopTasksController, never())
+ .performDesktopExitCleanUp(
+ any(),
+ anyInt(),
+ anyInt(),
+ anyBoolean(),
+ anyBoolean(),
+ anyBoolean(),
+ )
+ }
+ }
+
+ private companion object {
+ const val DESK_ID = 1
+
+ @JvmStatic
+ @Parameters(name = "{0}")
+ fun getParams(): List<FlagsParameterization> =
+ FlagsParameterization.allCombinationsOf(Flags.FLAG_ENABLE_MULTIPLE_DESKTOPS_BACKEND)
+ }
+}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopPipTransitionObserverTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopPipTransitionObserverTest.kt
deleted file mode 100644
index ef394d81cc57..000000000000
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopPipTransitionObserverTest.kt
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2025 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.wm.shell.desktopmode
-
-import android.app.WindowConfiguration.WINDOWING_MODE_PINNED
-import android.os.Binder
-import android.platform.test.annotations.EnableFlags
-import android.platform.test.flag.junit.SetFlagsRule
-import android.testing.AndroidTestingRunner
-import android.view.WindowManager.TRANSIT_PIP
-import android.window.TransitionInfo
-import androidx.test.filters.SmallTest
-import com.android.window.flags.Flags
-import com.android.wm.shell.ShellTestCase
-import com.android.wm.shell.TestRunningTaskInfoBuilder
-import com.google.common.truth.Truth.assertThat
-import org.junit.Before
-import org.junit.Rule
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.mockito.kotlin.mock
-
-/**
- * Tests for [DesktopPipTransitionObserver].
- *
- * Build/Install/Run: atest WMShellUnitTests:DesktopPipTransitionObserverTest
- */
-@SmallTest
-@RunWith(AndroidTestingRunner::class)
-class DesktopPipTransitionObserverTest : ShellTestCase() {
-
- @JvmField @Rule val setFlagsRule = SetFlagsRule()
-
- private lateinit var observer: DesktopPipTransitionObserver
-
- private val transition = Binder()
- private var onSuccessInvokedCount = 0
-
- @Before
- fun setUp() {
- observer = DesktopPipTransitionObserver()
-
- onSuccessInvokedCount = 0
- }
-
- @Test
- @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_PIP)
- fun onTransitionReady_taskInPinnedWindowingMode_onSuccessInvoked() {
- val taskId = 1
- val pipTransition = createPendingPipTransition(taskId)
- val successfulChange = createChange(taskId, WINDOWING_MODE_PINNED)
- observer.addPendingPipTransition(pipTransition)
-
- observer.onTransitionReady(
- transition = transition,
- info = TransitionInfo(
- TRANSIT_PIP, /* flags= */
- 0
- ).apply { addChange(successfulChange) },
- )
-
- assertThat(onSuccessInvokedCount).isEqualTo(1)
- }
-
- private fun createPendingPipTransition(
- taskId: Int
- ): DesktopPipTransitionObserver.PendingPipTransition {
- return DesktopPipTransitionObserver.PendingPipTransition(
- token = transition,
- taskId = taskId,
- onSuccess = { onSuccessInvokedCount += 1 },
- )
- }
-
- private fun createChange(taskId: Int, windowingMode: Int): TransitionInfo.Change {
- return TransitionInfo.Change(mock(), mock()).apply {
- taskInfo =
- TestRunningTaskInfoBuilder()
- .setTaskId(taskId)
- .setWindowingMode(windowingMode)
- .build()
- }
- }
-}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksControllerTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksControllerTest.kt
index b8c2273e1465..bcdff11363ab 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksControllerTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksControllerTest.kt
@@ -265,7 +265,6 @@ class DesktopTasksControllerTest(flags: FlagsParameterization) : ShellTestCase()
@Mock private lateinit var desksOrganizer: DesksOrganizer
@Mock private lateinit var userProfileContexts: UserProfileContexts
@Mock private lateinit var desksTransitionsObserver: DesksTransitionObserver
- @Mock private lateinit var desktopPipTransitionObserver: DesktopPipTransitionObserver
@Mock private lateinit var packageManager: PackageManager
@Mock private lateinit var mockDisplayContext: Context
@Mock private lateinit var dragToDisplayTransitionHandler: DragToDisplayTransitionHandler
@@ -460,7 +459,6 @@ class DesktopTasksControllerTest(flags: FlagsParameterization) : ShellTestCase()
overviewToDesktopTransitionObserver,
desksOrganizer,
desksTransitionsObserver,
- Optional.of(desktopPipTransitionObserver),
userProfileContexts,
desktopModeCompatPolicy,
dragToDisplayTransitionHandler,
@@ -3540,15 +3538,20 @@ class DesktopTasksControllerTest(flags: FlagsParameterization) : ShellTestCase()
.addPendingTransition(DeskTransition.DeactivateDesk(token = transition, deskId = 0))
}
- @Test
- @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_PIP)
- fun onPipTaskMinimize_autoEnterEnabled_startPipTransition() {
- val task = setUpPipTask(autoEnterEnabled = true)
+ private fun minimizePipTask(task: RunningTaskInfo) {
val handler = mock(TransitionHandler::class.java)
whenever(transitions.dispatchRequest(any(), any(), anyOrNull()))
.thenReturn(android.util.Pair(handler, WindowContainerTransaction()))
controller.minimizeTask(task, MinimizeReason.MINIMIZE_BUTTON)
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_PIP)
+ fun onPipTaskMinimize_autoEnterEnabled_startPipTransition() {
+ val task = setUpPipTask(autoEnterEnabled = true)
+
+ minimizePipTask(task)
verify(freeformTaskTransitionStarter).startPipTransition(any())
verify(freeformTaskTransitionStarter, never())
@@ -3568,7 +3571,7 @@ class DesktopTasksControllerTest(flags: FlagsParameterization) : ShellTestCase()
)
.thenReturn(Binder())
- controller.minimizeTask(task, MinimizeReason.MINIMIZE_BUTTON)
+ minimizePipTask(task)
verify(freeformTaskTransitionStarter)
.startMinimizedModeTransition(any(), eq(task.taskId), anyBoolean())
@@ -3579,52 +3582,24 @@ class DesktopTasksControllerTest(flags: FlagsParameterization) : ShellTestCase()
@EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_PIP)
fun onPipTaskMinimize_autoEnterEnabled_sendsTaskbarRoundingUpdate() {
val task = setUpPipTask(autoEnterEnabled = true)
- val handler = mock(TransitionHandler::class.java)
- whenever(transitions.dispatchRequest(any(), any(), anyOrNull()))
- .thenReturn(android.util.Pair(handler, WindowContainerTransaction()))
- controller.minimizeTask(task, MinimizeReason.MINIMIZE_BUTTON)
+ minimizePipTask(task)
verify(taskbarDesktopTaskListener).onTaskbarCornerRoundingUpdate(anyBoolean())
}
@Test
@EnableFlags(
- Flags.FLAG_ENABLE_DESKTOP_WALLPAPER_ACTIVITY_FOR_SYSTEM_USER,
- Flags.FLAG_ENABLE_DESKTOP_WINDOWING_PIP,
- )
- fun onDesktopTaskEnteredPip_pipIsLastTask_removesWallpaper() {
- val task = setUpPipTask(autoEnterEnabled = true)
-
- controller.onDesktopTaskEnteredPip(
- taskId = task.taskId,
- deskId = DEFAULT_DISPLAY,
- displayId = task.displayId,
- taskIsLastVisibleTaskBeforePip = true,
- )
-
- // Wallpaper is moved to the back
- val wct = getLatestTransition()
- wct.assertReorder(wallpaperToken, /* toTop= */ false)
- }
-
- @Test
- @EnableFlags(
Flags.FLAG_ENABLE_DESKTOP_WINDOWING_PIP,
Flags.FLAG_ENABLE_MULTIPLE_DESKTOPS_BACKEND,
)
- fun onDesktopTaskEnteredPip_pipIsLastTask_deactivatesDesk() {
+ fun onPipTaskMinimize_isLastTask_deactivatesDesk() {
val deskId = DEFAULT_DISPLAY
val task = setUpPipTask(autoEnterEnabled = true, deskId = deskId)
val transition = Binder()
- whenever(transitions.startTransition(any(), any(), anyOrNull())).thenReturn(transition)
+ whenever(freeformTaskTransitionStarter.startPipTransition(any())).thenReturn(transition)
- controller.onDesktopTaskEnteredPip(
- taskId = task.taskId,
- deskId = deskId,
- displayId = task.displayId,
- taskIsLastVisibleTaskBeforePip = true,
- )
+ minimizePipTask(task)
verify(desksOrganizer).deactivateDesk(any(), eq(deskId))
verify(desksTransitionsObserver)
@@ -3632,44 +3607,31 @@ class DesktopTasksControllerTest(flags: FlagsParameterization) : ShellTestCase()
}
@Test
- @EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_PIP)
- fun onDesktopTaskEnteredPip_pipIsLastTask_launchesHome() {
+ @EnableFlags(
+ Flags.FLAG_ENABLE_DESKTOP_WINDOWING_PIP,
+ Flags.FLAG_ENABLE_DESKTOP_WALLPAPER_ACTIVITY_FOR_SYSTEM_USER,
+ )
+ fun onPipTaskMinimize_isLastTask_removesWallpaper() {
val task = setUpPipTask(autoEnterEnabled = true)
- controller.onDesktopTaskEnteredPip(
- taskId = task.taskId,
- deskId = DEFAULT_DISPLAY,
- displayId = task.displayId,
- taskIsLastVisibleTaskBeforePip = true,
- )
+ minimizePipTask(task)
- val wct = getLatestTransition()
- wct.assertPendingIntent(launchHomeIntent(DEFAULT_DISPLAY))
+ val arg = argumentCaptor<WindowContainerTransaction>()
+ verify(freeformTaskTransitionStarter).startPipTransition(arg.capture())
+ // Wallpaper is moved to the back
+ arg.lastValue.assertReorder(wallpaperToken, /* toTop= */ false)
}
@Test
@EnableFlags(Flags.FLAG_ENABLE_DESKTOP_WINDOWING_PIP)
- fun onDesktopTaskEnteredPip_pipIsNotLastTask_doesntExitDesktopMode() {
+ fun onPipTaskMinimize_isLastTask_launchesHome() {
val task = setUpPipTask(autoEnterEnabled = true)
- val deskId = DEFAULT_DISPLAY
- setUpFreeformTask(deskId = deskId) // launch another freeform task
- val transition = Binder()
- whenever(transitions.startTransition(any(), any(), anyOrNull())).thenReturn(transition)
- controller.onDesktopTaskEnteredPip(
- taskId = task.taskId,
- deskId = deskId,
- displayId = task.displayId,
- taskIsLastVisibleTaskBeforePip = false,
- )
+ minimizePipTask(task)
- // No transition to exit Desktop mode is started
- verifyWCTNotExecuted()
- verify(desktopModeEnterExitTransitionListener, never())
- .onExitDesktopModeTransitionStarted(FULLSCREEN_ANIMATION_DURATION)
- verify(desksOrganizer, never()).deactivateDesk(any(), eq(deskId))
- verify(desksTransitionsObserver, never())
- .addPendingTransition(DeskTransition.DeactivateDesk(transition, deskId))
+ val arg = argumentCaptor<WindowContainerTransaction>()
+ verify(freeformTaskTransitionStarter).startPipTransition(arg.capture())
+ arg.lastValue.assertPendingIntent(launchHomeIntent(DEFAULT_DISPLAY))
}
@Test
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksTransitionObserverTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksTransitionObserverTest.kt
index 5ef1ace7873d..1e0c94c2452c 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksTransitionObserverTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/DesktopTasksTransitionObserverTest.kt
@@ -50,7 +50,6 @@ import com.android.wm.shell.sysui.ShellInit
import com.android.wm.shell.transition.Transitions
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
-import java.util.Optional
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@@ -86,7 +85,6 @@ class DesktopTasksTransitionObserverTest {
private val userRepositories = mock<DesktopUserRepositories>()
private val taskRepository = mock<DesktopRepository>()
private val mixedHandler = mock<DesktopMixedTransitionHandler>()
- private val pipTransitionObserver = mock<DesktopPipTransitionObserver>()
private val backAnimationController = mock<BackAnimationController>()
private val desktopWallpaperActivityTokenProvider =
mock<DesktopWallpaperActivityTokenProvider>()
@@ -111,7 +109,6 @@ class DesktopTasksTransitionObserverTest {
transitions,
shellTaskOrganizer,
mixedHandler,
- Optional.of(pipTransitionObserver),
backAnimationController,
desktopWallpaperActivityTokenProvider,
shellInit,
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/multidesks/RootTaskDesksOrganizerTest.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/multidesks/RootTaskDesksOrganizerTest.kt
index 9af504797182..e57fc38e3607 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/multidesks/RootTaskDesksOrganizerTest.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/desktopmode/multidesks/RootTaskDesksOrganizerTest.kt
@@ -15,6 +15,7 @@
*/
package com.android.wm.shell.desktopmode.multidesks
+import android.app.ActivityManager
import android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM
import android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED
import android.testing.AndroidTestingRunner
@@ -48,7 +49,9 @@ import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
+import org.mockito.Mockito.never
import org.mockito.Mockito.verify
+import org.mockito.kotlin.any
import org.mockito.kotlin.argThat
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
@@ -67,6 +70,7 @@ class RootTaskDesksOrganizerTest : ShellTestCase() {
private val mockShellCommandHandler = mock<ShellCommandHandler>()
private val mockShellTaskOrganizer = mock<ShellTaskOrganizer>()
private val launchAdjacentController = LaunchAdjacentController(mock())
+ private val taskInfoChangedListener = mock<(ActivityManager.RunningTaskInfo) -> Unit>()
private lateinit var organizer: RootTaskDesksOrganizer
@@ -79,6 +83,7 @@ class RootTaskDesksOrganizerTest : ShellTestCase() {
mockShellTaskOrganizer,
launchAdjacentController,
)
+ organizer.setOnDesktopTaskInfoChangedListener(taskInfoChangedListener)
}
@Test fun testCreateDesk_createsDeskAndMinimizationRoots() = runTest { createDesk() }
@@ -652,6 +657,34 @@ class RootTaskDesksOrganizerTest : ShellTestCase() {
assertThat(launchAdjacentController.launchAdjacentEnabled).isFalse()
}
+ @Test
+ fun onTaskInfoChanged_taskNotRoot_invokesListener() = runTest {
+ createDesk()
+ val task = createFreeformTask().apply { taskId = TEST_CHILD_TASK_ID }
+
+ organizer.onTaskInfoChanged(task)
+
+ verify(taskInfoChangedListener).invoke(task)
+ }
+
+ @Test
+ fun onTaskInfoChanged_isDeskRoot_doesNotInvokeListener() = runTest {
+ val deskRoot = createDesk().deskRoot
+
+ organizer.onTaskInfoChanged(deskRoot.taskInfo)
+
+ verify(taskInfoChangedListener, never()).invoke(any())
+ }
+
+ @Test
+ fun onTaskInfoChanged_isMinimizationRoot_doesNotInvokeListener() = runTest {
+ val minimizationRoot = createDesk().minimizationRoot
+
+ organizer.onTaskInfoChanged(minimizationRoot.taskInfo)
+
+ verify(taskInfoChangedListener, never()).invoke(any())
+ }
+
private data class DeskRoots(
val deskRoot: DeskRoot,
val minimizationRoot: DeskMinimizationRoot,
@@ -712,4 +745,8 @@ class RootTaskDesksOrganizerTest : ShellTestCase() {
hop.newParent == desk.deskRoot.token.asBinder() &&
hop.toTop
}
+
+ companion object {
+ private const val TEST_CHILD_TASK_ID = 100
+ }
}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/splitscreen/StageCoordinatorTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/splitscreen/StageCoordinatorTests.java
index 82373ff1bc41..64bd86134d92 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/splitscreen/StageCoordinatorTests.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/splitscreen/StageCoordinatorTests.java
@@ -167,6 +167,7 @@ public class StageCoordinatorTests extends ShellTestCase {
private final TestShellExecutor mMainExecutor = new TestShellExecutor();
private final ShellExecutor mAnimExecutor = new TestShellExecutor();
private final Handler mMainHandler = new Handler(Looper.getMainLooper());
+ private final Handler mAnimHandler = mock(Handler.class);
private final DisplayAreaInfo mDisplayAreaInfo = new DisplayAreaInfo(new MockToken().token(),
DEFAULT_DISPLAY, 0);
private final ActivityManager.RunningTaskInfo mMainChildTaskInfo =
@@ -629,7 +630,7 @@ public class StageCoordinatorTests extends ShellTestCase {
ShellInit shellInit = new ShellInit(mMainExecutor);
final Transitions t = new Transitions(mContext, shellInit, mock(ShellController.class),
mTaskOrganizer, mTransactionPool, mock(DisplayController.class),
- mDisplayInsetsController, mMainExecutor, mMainHandler, mAnimExecutor,
+ mDisplayInsetsController, mMainExecutor, mMainHandler, mAnimExecutor, mAnimHandler,
mock(HomeTransitionObserver.class), mock(FocusTransitionObserver.class));
shellInit.init();
return t;
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/DefaultTransitionHandlerTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/DefaultTransitionHandlerTest.java
index 6996d44af034..2dab39184247 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/DefaultTransitionHandlerTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/DefaultTransitionHandlerTest.java
@@ -100,7 +100,8 @@ public class DefaultTransitionHandlerTest extends ShellTestCase {
mTransitionHandler = new DefaultTransitionHandler(
mContext, mShellInit, mDisplayController, mDisplayInsetsController,
mTransactionPool, mMainExecutor, mMainHandler, mAnimExecutor,
- mRootTaskDisplayAreaOrganizer, mock(InteractionJankMonitor.class));
+ mock(Handler.class), mRootTaskDisplayAreaOrganizer,
+ mock(InteractionJankMonitor.class));
mShellInit.init();
}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/HomeTransitionObserverTest.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/HomeTransitionObserverTest.java
index 52634c08dafd..5d77766dc0db 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/HomeTransitionObserverTest.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/HomeTransitionObserverTest.java
@@ -88,6 +88,7 @@ public class HomeTransitionObserverTest extends ShellTestCase {
private final ShellExecutor mAnimExecutor = new TestShellExecutor();
private final TestShellExecutor mMainExecutor = new TestShellExecutor();
private final Handler mMainHandler = new Handler(Looper.getMainLooper());
+ private final Handler mAnimHandler = mock(Handler.class);
private final DisplayController mDisplayController = mock(DisplayController.class);
private final DisplayInsetsController mDisplayInsetsController =
mock(DisplayInsetsController.class);
@@ -105,7 +106,7 @@ public class HomeTransitionObserverTest extends ShellTestCase {
mDisplayInsetsController, mock(ShellInit.class));
mTransition = new Transitions(mContext, mock(ShellInit.class), mock(ShellController.class),
mOrganizer, mTransactionPool, mDisplayController, mDisplayInsetsController,
- mMainExecutor, mMainHandler, mAnimExecutor, mHomeTransitionObserver,
+ mMainExecutor, mMainHandler, mAnimExecutor, mAnimHandler, mHomeTransitionObserver,
mock(FocusTransitionObserver.class));
mHomeTransitionObserver.setHomeTransitionListener(mTransition, mListener);
}
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/ShellTransitionTests.java b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/ShellTransitionTests.java
index 44bb2154f170..4dd9cab1d340 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/ShellTransitionTests.java
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/transition/ShellTransitionTests.java
@@ -146,6 +146,7 @@ public class ShellTransitionTests extends ShellTestCase {
private final ShellExecutor mAnimExecutor = new TestShellExecutor();
private final TestTransitionHandler mDefaultHandler = new TestTransitionHandler();
private final Handler mMainHandler = new Handler(Looper.getMainLooper());
+ private final Handler mAnimHandler = mock(Handler.class);
private final DisplayInsetsController mDisplayInsets =
mock(DisplayInsetsController.class);
@@ -160,7 +161,7 @@ public class ShellTransitionTests extends ShellTestCase {
ShellInit shellInit = mock(ShellInit.class);
final Transitions t = new Transitions(mContext, shellInit, mock(ShellController.class),
mOrganizer, mTransactionPool, createTestDisplayController(), mDisplayInsets,
- mMainExecutor, mMainHandler, mAnimExecutor,
+ mMainExecutor, mMainHandler, mAnimExecutor, mAnimHandler,
mock(HomeTransitionObserver.class), mock(FocusTransitionObserver.class));
// One from Transitions, one from RootTaskDisplayAreaOrganizer
verify(shellInit).addInitCallback(any(), eq(t));
@@ -173,7 +174,7 @@ public class ShellTransitionTests extends ShellTestCase {
ShellController shellController = mock(ShellController.class);
final Transitions t = new Transitions(mContext, shellInit, shellController,
mOrganizer, mTransactionPool, createTestDisplayController(), mDisplayInsets,
- mMainExecutor, mMainHandler, mAnimExecutor,
+ mMainExecutor, mMainHandler, mAnimExecutor, mAnimHandler,
mock(HomeTransitionObserver.class), mock(FocusTransitionObserver.class));
shellInit.init();
verify(shellController, times(1)).addExternalInterface(
@@ -1318,7 +1319,7 @@ public class ShellTransitionTests extends ShellTestCase {
final Transitions transitions =
new Transitions(mContext, shellInit, mock(ShellController.class), mOrganizer,
mTransactionPool, createTestDisplayController(), mDisplayInsets,
- mMainExecutor, mMainHandler, mAnimExecutor,
+ mMainExecutor, mMainHandler, mAnimExecutor, mAnimHandler,
mock(HomeTransitionObserver.class),
mock(FocusTransitionObserver.class));
final RecentTasksController mockRecentsTaskController = mock(RecentTasksController.class);
@@ -1914,7 +1915,8 @@ public class ShellTransitionTests extends ShellTestCase {
ShellInit shellInit = new ShellInit(mMainExecutor);
final Transitions t = new Transitions(mContext, shellInit, mock(ShellController.class),
mOrganizer, mTransactionPool, createTestDisplayController(), mDisplayInsets,
- mMainExecutor, mMainHandler, mAnimExecutor, mock(HomeTransitionObserver.class),
+ mMainExecutor, mMainHandler, mAnimExecutor, mAnimHandler,
+ mock(HomeTransitionObserver.class),
mock(FocusTransitionObserver.class));
shellInit.init();
return t;
diff --git a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModelTestsBase.kt b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModelTestsBase.kt
index 80dcd7d69f00..23994a2bd547 100644
--- a/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModelTestsBase.kt
+++ b/libs/WindowManager/Shell/tests/unittest/src/com/android/wm/shell/windowdecor/DesktopModeWindowDecorViewModelTestsBase.kt
@@ -67,6 +67,7 @@ import com.android.wm.shell.desktopmode.DesktopUserRepositories
import com.android.wm.shell.desktopmode.WindowDecorCaptionHandleRepository
import com.android.wm.shell.desktopmode.education.AppHandleEducationController
import com.android.wm.shell.desktopmode.education.AppToWebEducationController
+import com.android.wm.shell.desktopmode.multidesks.DesksOrganizer
import com.android.wm.shell.freeform.FreeformTaskTransitionStarter
import com.android.wm.shell.recents.RecentsTransitionHandler
import com.android.wm.shell.recents.RecentsTransitionStateListener
@@ -146,6 +147,7 @@ open class DesktopModeWindowDecorViewModelTestsBase : ShellTestCase() {
protected val mockMultiDisplayDragMoveIndicatorController =
mock<MultiDisplayDragMoveIndicatorController>()
protected val mockCompatUIHandler = mock<CompatUIHandler>()
+ protected val mockDesksOrganizer = mock<DesksOrganizer>()
protected val mockInputManager = mock<InputManager>()
private val mockTaskPositionerFactory =
mock<DesktopModeWindowDecorViewModel.TaskPositionerFactory>()
@@ -246,6 +248,7 @@ open class DesktopModeWindowDecorViewModelTestsBase : ShellTestCase() {
mockTilingWindowDecoration,
mockMultiDisplayDragMoveIndicatorController,
mockCompatUIHandler,
+ mockDesksOrganizer
)
desktopModeWindowDecorViewModel.setSplitScreenController(mockSplitScreenController)
whenever(mockDisplayController.getDisplayLayout(any())).thenReturn(mockDisplayLayout)
diff --git a/location/java/android/location/flags/location.aconfig b/location/java/android/location/flags/location.aconfig
index 9cc58ae35692..4b460c6ab039 100644
--- a/location/java/android/location/flags/location.aconfig
+++ b/location/java/android/location/flags/location.aconfig
@@ -199,6 +199,16 @@ flag {
}
flag {
+ name: "fix_is_in_emergency_anr"
+ namespace: "location"
+ description: "Avoid calling IPC with a lock to avoid deadlock"
+ bug: "355384257"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
+flag {
name: "gnss_assistance_interface_jni"
namespace: "location"
description: "Flag for GNSS assistance interface JNI"
diff --git a/media/java/android/media/flags/media_better_together.aconfig b/media/java/android/media/flags/media_better_together.aconfig
index 7221f1ddeb7f..15e87f80ef64 100644
--- a/media/java/android/media/flags/media_better_together.aconfig
+++ b/media/java/android/media/flags/media_better_together.aconfig
@@ -62,6 +62,16 @@ flag {
}
flag {
+ name: "enable_fix_for_empty_system_routes_crash"
+ namespace: "media_better_together"
+ description: "Fixes a bug causing SystemUI to crash due to an empty system routes list in the routing framework."
+ bug: "357468728"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
+
+flag {
name: "enable_suggested_device_api"
is_exported: true
namespace: "media_better_together"
diff --git a/media/java/android/media/tv/extension/scan/IScanInterface.aidl b/media/java/android/media/tv/extension/scan/IScanInterface.aidl
index b44d1d243150..ea6e8a1d4104 100644
--- a/media/java/android/media/tv/extension/scan/IScanInterface.aidl
+++ b/media/java/android/media/tv/extension/scan/IScanInterface.aidl
@@ -24,7 +24,7 @@ import android.os.Bundle;
*/
interface IScanInterface {
IBinder createSession(int broadcastType, String countryCode, String operator,
- in IScanListener listener);
+ in IScanListener listener, in Bundle optionalParams);
Bundle getParameters(int broadcastType, String countryCode, String operator,
in Bundle params);
}
diff --git a/packages/CompanionDeviceManager/res/values/strings.xml b/packages/CompanionDeviceManager/res/values/strings.xml
index 60f209b47482..574671376e2e 100644
--- a/packages/CompanionDeviceManager/res/values/strings.xml
+++ b/packages/CompanionDeviceManager/res/values/strings.xml
@@ -106,16 +106,13 @@
<!-- Description of the helper dialog for NEARBY_DEVICE_STREAMING profile. [CHAR LIMIT=NONE] -->
<string name="helper_summary_nearby_device_streaming"><xliff:g id="app_name" example="Exo">%1$s</xliff:g> is requesting permission on behalf of <xliff:g id="device_name" example="Chromebook">%2$s</xliff:g> to stream apps from your <xliff:g id="device_type" example="phone">%3$s</xliff:g></string>
- <!-- ================= DEVICE_PROFILE_SENSOR_DEVICE_STREAMING ================= -->
+ <!-- ================= DEVICE_PROFILE_VIRTUAL_DEVICE ================= -->
- <!-- Confirmation for associating an application with a companion device of SENSOR_DEVICE_STREAMING profile (type) [CHAR LIMIT=NONE] -->
- <string name="title_sensor_device_streaming">Allow &lt;strong&gt;<xliff:g id="app_name" example="Exo">%1$s</xliff:g>&lt;/strong&gt; to stream audio and system features between your <xliff:g id="device_type" example="phone">%2$s</xliff:g> and &lt;strong&gt;<xliff:g id="device_name" example="Chromebook">%3$s</xliff:g>&lt;/strong&gt;?</string>
+ <!-- Confirmation for associating an application with a companion device of VIRTUAL_DEVICE profile (type) [CHAR LIMIT=NONE] -->
+ <string name="title_virtual_device">Allow &lt;strong&gt;<xliff:g id="app_name" example="Exo">%1$s</xliff:g>&lt;/strong&gt; to stream audio and system features between your <xliff:g id="device_type" example="phone">%3$s</xliff:g> and &lt;strong&gt;<xliff:g id="device_name" example="Chromebook">%2$s</xliff:g>&lt;/strong&gt;?</string>
- <!-- Summary for associating an application with a companion device of SENSOR_DEVICE_STREAMING profile [CHAR LIMIT=NONE] -->
- <string name="summary_sensor_device_streaming"><xliff:g id="app_name" example="Exo">%1$s</xliff:g> will have access to anything that’s played on your <xliff:g id="device_name" example="Chromebook">%3$s</xliff:g>.&lt;br/>&lt;br/><xliff:g id="app_name" example="Exo">%1$s</xliff:g> will be able to stream audio to <xliff:g id="device_name" example="Chromebook">%3$s</xliff:g> until you remove access to this permission.</string>
-
- <!-- Description of the helper dialog for SENSOR_DEVICE_STREAMING profile. [CHAR LIMIT=NONE] -->
- <string name="helper_summary_sensor_device_streaming"><xliff:g id="app_name" example="Exo">%1$s</xliff:g> is requesting permission on behalf of <xliff:g id="device_name" example="Chromebook">%2$s</xliff:g> to stream audio and system features between your devices.</string>
+ <!-- Summary for associating an application with a companion device of VIRTUAL_DEVICE profile [CHAR LIMIT=NONE] -->
+ <string name="summary_virtual_device"><xliff:g id="app_name" example="Exo">%2$s</xliff:g> will have access to anything that’s played on <xliff:g id="device_name" example="Chromebook">%3$s</xliff:g>.&lt;br/>&lt;br/><xliff:g id="app_name" example="Exo">%2$s</xliff:g> will be able to stream audio to <xliff:g id="device_name" example="Chromebook">%3$s</xliff:g> until you remove access to this permission.</string>
<!-- ================= null profile ================= -->
diff --git a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionAssociationActivity.java b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionAssociationActivity.java
index 518757dd0d5c..c07e572eb649 100644
--- a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionAssociationActivity.java
+++ b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionAssociationActivity.java
@@ -667,7 +667,8 @@ public class CompanionAssociationActivity extends FragmentActivity implements
final int summaryResourceId = PROFILE_SUMMARIES.get(deviceProfile);
final String remoteDeviceName = mSelectedDevice.getDisplayName();
final Spanned title = getHtmlFromResources(
- this, PROFILE_TITLES.get(deviceProfile), mAppLabel, remoteDeviceName);
+ this, PROFILE_TITLES.get(deviceProfile), mAppLabel, remoteDeviceName,
+ getString(R.string.device_type));
final Spanned summary;
if (deviceProfile == null && mRequest.isSingleDevice()) {
@@ -675,7 +676,8 @@ public class CompanionAssociationActivity extends FragmentActivity implements
mConstraintList.setVisibility(View.GONE);
} else {
summary = getHtmlFromResources(
- this, summaryResourceId, getString(R.string.device_type));
+ this, summaryResourceId, getString(R.string.device_type), mAppLabel,
+ remoteDeviceName);
setupPermissionList(deviceProfile);
}
diff --git a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceResources.java b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceResources.java
index f756a6235c14..f6e680207530 100644
--- a/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceResources.java
+++ b/packages/CompanionDeviceManager/src/com/android/companiondevicemanager/CompanionDeviceResources.java
@@ -21,7 +21,7 @@ import static android.companion.AssociationRequest.DEVICE_PROFILE_AUTOMOTIVE_PRO
import static android.companion.AssociationRequest.DEVICE_PROFILE_COMPUTER;
import static android.companion.AssociationRequest.DEVICE_PROFILE_GLASSES;
import static android.companion.AssociationRequest.DEVICE_PROFILE_NEARBY_DEVICE_STREAMING;
-import static android.companion.AssociationRequest.DEVICE_PROFILE_SENSOR_DEVICE_STREAMING;
+import static android.companion.AssociationRequest.DEVICE_PROFILE_VIRTUAL_DEVICE;
import static android.companion.AssociationRequest.DEVICE_PROFILE_WATCH;
import static android.companion.AssociationRequest.DEVICE_PROFILE_WEARABLE_SENSING;
import static android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
@@ -118,7 +118,7 @@ final class CompanionDeviceResources {
map.put(DEVICE_PROFILE_AUTOMOTIVE_PROJECTION, R.string.title_automotive_projection);
map.put(DEVICE_PROFILE_COMPUTER, R.string.title_computer);
map.put(DEVICE_PROFILE_NEARBY_DEVICE_STREAMING, R.string.title_nearby_device_streaming);
- map.put(DEVICE_PROFILE_SENSOR_DEVICE_STREAMING, R.string.title_sensor_device_streaming);
+ map.put(DEVICE_PROFILE_VIRTUAL_DEVICE, R.string.title_virtual_device);
map.put(DEVICE_PROFILE_WATCH, R.string.confirmation_title);
map.put(DEVICE_PROFILE_GLASSES, R.string.confirmation_title_glasses);
map.put(null, R.string.confirmation_title);
@@ -133,7 +133,7 @@ final class CompanionDeviceResources {
map.put(DEVICE_PROFILE_GLASSES, R.string.summary_glasses);
map.put(DEVICE_PROFILE_APP_STREAMING, R.string.summary_app_streaming);
map.put(DEVICE_PROFILE_NEARBY_DEVICE_STREAMING, R.string.summary_nearby_device_streaming);
- map.put(DEVICE_PROFILE_SENSOR_DEVICE_STREAMING, R.string.summary_sensor_device_streaming);
+ map.put(DEVICE_PROFILE_VIRTUAL_DEVICE, R.string.summary_virtual_device);
map.put(null, R.string.summary_generic);
PROFILE_SUMMARIES = unmodifiableMap(map);
@@ -145,8 +145,6 @@ final class CompanionDeviceResources {
map.put(DEVICE_PROFILE_APP_STREAMING, R.string.helper_summary_app_streaming);
map.put(DEVICE_PROFILE_NEARBY_DEVICE_STREAMING,
R.string.helper_summary_nearby_device_streaming);
- map.put(DEVICE_PROFILE_SENSOR_DEVICE_STREAMING,
- R.string.helper_summary_sensor_device_streaming);
map.put(DEVICE_PROFILE_COMPUTER, R.string.helper_summary_computer);
PROFILE_HELPER_SUMMARIES = unmodifiableMap(map);
@@ -178,6 +176,7 @@ final class CompanionDeviceResources {
final Map<String, Integer> map = new ArrayMap<>();
map.put(DEVICE_PROFILE_WATCH, R.string.profile_name_watch);
map.put(DEVICE_PROFILE_GLASSES, R.string.profile_name_glasses);
+ map.put(DEVICE_PROFILE_VIRTUAL_DEVICE, R.string.profile_name_generic);
map.put(null, R.string.profile_name_generic);
PROFILE_NAMES = unmodifiableMap(map);
@@ -188,6 +187,7 @@ final class CompanionDeviceResources {
final Map<String, Integer> map = new ArrayMap<>();
map.put(DEVICE_PROFILE_WATCH, R.drawable.ic_watch);
map.put(DEVICE_PROFILE_GLASSES, R.drawable.ic_glasses);
+ map.put(DEVICE_PROFILE_VIRTUAL_DEVICE, R.drawable.ic_device_other);
map.put(null, R.drawable.ic_device_other);
PROFILE_ICONS = unmodifiableMap(map);
@@ -198,6 +198,7 @@ final class CompanionDeviceResources {
final Set<String> set = new ArraySet<>();
set.add(DEVICE_PROFILE_WATCH);
set.add(DEVICE_PROFILE_GLASSES);
+ set.add(DEVICE_PROFILE_VIRTUAL_DEVICE);
set.add(null);
SUPPORTED_PROFILES = unmodifiableSet(set);
@@ -210,7 +211,6 @@ final class CompanionDeviceResources {
set.add(DEVICE_PROFILE_COMPUTER);
set.add(DEVICE_PROFILE_AUTOMOTIVE_PROJECTION);
set.add(DEVICE_PROFILE_NEARBY_DEVICE_STREAMING);
- set.add(DEVICE_PROFILE_SENSOR_DEVICE_STREAMING);
set.add(DEVICE_PROFILE_WEARABLE_SENSING);
set.add(null);
diff --git a/packages/ExternalStorageProvider/src/com/android/externalstorage/ExternalStorageProvider.java b/packages/ExternalStorageProvider/src/com/android/externalstorage/ExternalStorageProvider.java
index defbc1142adb..28b891ebc3c9 100644
--- a/packages/ExternalStorageProvider/src/com/android/externalstorage/ExternalStorageProvider.java
+++ b/packages/ExternalStorageProvider/src/com/android/externalstorage/ExternalStorageProvider.java
@@ -596,7 +596,10 @@ public class ExternalStorageProvider extends FileSystemProvider {
}
@Override
- protected void onDocIdDeleted(String docId) {
+ protected void onDocIdDeleted(String docId, boolean shouldRevokeUriPermission) {
+ if (!shouldRevokeUriPermission) {
+ return;
+ }
Uri uri = DocumentsContract.buildDocumentUri(AUTHORITY, docId);
getContext().revokeUriPermission(uri, ~0);
}
diff --git a/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_button_background_normal.xml b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_button_background_normal.xml
index 8037a8bb75be..8a234fa6ca9e 100644
--- a/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_button_background_normal.xml
+++ b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_button_background_normal.xml
@@ -17,8 +17,8 @@
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false"
- android:alpha="@dimen/material_emphasis_disabled_background" android:color="?attr/colorOnSurface"/>
+ android:alpha="@dimen/material_emphasis_disabled_background" android:color="@color/settingslib_materialColorPrimary"/>
<item android:state_checked="true" android:color="?attr/colorContainerChecked"/>
<item android:state_checkable="true" android:color="?attr/colorContainerUnchecked"/>
- <item android:color="?attr/colorContainer" />
+ <item android:color="@color/settingslib_materialColorPrimary" />
</selector> \ No newline at end of file
diff --git a/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_high.xml b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_high.xml
new file mode 100644
index 000000000000..43b236938956
--- /dev/null
+++ b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_high.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2025 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.
+ -->
+
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_enabled="false"
+ android:alpha="@dimen/material_emphasis_disabled" android:color="@color/settingslib_colorContentLevel_high"/>
+ <item android:color="@color/settingslib_colorContentLevel_high" />
+</selector> \ No newline at end of file
diff --git a/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_low.xml b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_low.xml
new file mode 100644
index 000000000000..b7a9d7c5175b
--- /dev/null
+++ b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_low.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2025 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.
+ -->
+
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_enabled="false"
+ android:alpha="@dimen/material_emphasis_disabled" android:color="@color/settingslib_colorContentLevel_low"/>
+ <item android:color="@color/settingslib_colorContentLevel_low" />
+</selector> \ No newline at end of file
diff --git a/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_medium.xml b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_medium.xml
new file mode 100644
index 000000000000..8e41cb03f4d1
--- /dev/null
+++ b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_medium.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2025 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.
+ -->
+
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_enabled="false"
+ android:alpha="@dimen/material_emphasis_disabled" android:color="@color/settingslib_colorContentLevel_medium"/>
+ <item android:color="@color/settingslib_colorContentLevel_medium" />
+</selector> \ No newline at end of file
diff --git a/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_normal.xml b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_normal.xml
new file mode 100644
index 000000000000..1dd5cdecfffc
--- /dev/null
+++ b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_filled_button_content_normal.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2025 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.
+ -->
+
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_enabled="false"
+ android:alpha="@dimen/material_emphasis_disabled" android:color="@color/settingslib_materialColorOnPrimary"/>
+ <item android:color="@color/settingslib_materialColorOnPrimary" />
+</selector> \ No newline at end of file
diff --git a/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_outline_button_content.xml b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_outline_button_content.xml
new file mode 100644
index 000000000000..3a06fb38d5d8
--- /dev/null
+++ b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_outline_button_content.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2025 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.
+ -->
+
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_enabled="false"
+ android:alpha="@dimen/material_emphasis_disabled" android:color="@color/settingslib_materialColorOnSurface"/>
+ <item android:color="@color/settingslib_materialColorOnSurface" />
+</selector> \ No newline at end of file
diff --git a/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_outline_button_stroke_normal.xml b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_outline_button_stroke_normal.xml
new file mode 100644
index 000000000000..8d0b65712d35
--- /dev/null
+++ b/packages/SettingsLib/BannerMessagePreference/res/color/settingslib_banner_outline_button_stroke_normal.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2025 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.
+ -->
+
+<selector xmlns:android="http://schemas.android.com/apk/res/android">
+ <item android:state_enabled="false"
+ android:alpha="@dimen/material_emphasis_disabled_background" android:color="@color/settingslib_materialColorOutline"/>
+ <item android:color="@color/settingslib_materialColorOutline" />
+</selector> \ No newline at end of file
diff --git a/packages/SettingsLib/BannerMessagePreference/res/values-v36/styles_expressive.xml b/packages/SettingsLib/BannerMessagePreference/res/values-v36/styles_expressive.xml
index 09e07ccef683..cd9faecc49c4 100644
--- a/packages/SettingsLib/BannerMessagePreference/res/values-v36/styles_expressive.xml
+++ b/packages/SettingsLib/BannerMessagePreference/res/values-v36/styles_expressive.xml
@@ -64,7 +64,6 @@
<style name="Banner.PositiveButton.SettingsLib.Expressive"
parent="@style/SettingsLibButtonStyle.Expressive.Filled.Extra">
- <item name="android:textColor">?android:attr/textColorPrimaryInverse</item>
<item name="materialSizeOverlay">@style/SizeOverlay.Material3Expressive.Button.Small</item>
</style>
diff --git a/packages/SettingsLib/BannerMessagePreference/src/com/android/settingslib/widget/BannerMessagePreference.java b/packages/SettingsLib/BannerMessagePreference/src/com/android/settingslib/widget/BannerMessagePreference.java
index c90a76a39510..dbd0f6424ff8 100644
--- a/packages/SettingsLib/BannerMessagePreference/src/com/android/settingslib/widget/BannerMessagePreference.java
+++ b/packages/SettingsLib/BannerMessagePreference/src/com/android/settingslib/widget/BannerMessagePreference.java
@@ -58,35 +58,42 @@ public class BannerMessagePreference extends Preference implements GroupSectionD
HIGH(0,
R.color.banner_background_attention_high,
R.color.banner_accent_attention_high,
- R.color.settingslib_banner_button_background_high),
+ R.color.settingslib_banner_button_background_high,
+ R.color.settingslib_banner_filled_button_content_high),
MEDIUM(1,
R.color.banner_background_attention_medium,
R.color.banner_accent_attention_medium,
- R.color.settingslib_banner_button_background_medium),
+ R.color.settingslib_banner_button_background_medium,
+ R.color.settingslib_banner_filled_button_content_medium),
LOW(2,
R.color.banner_background_attention_low,
R.color.banner_accent_attention_low,
- R.color.settingslib_banner_button_background_low),
+ R.color.settingslib_banner_button_background_low,
+ R.color.settingslib_banner_filled_button_content_low),
NORMAL(3,
R.color.banner_background_attention_normal,
R.color.banner_accent_attention_normal,
- R.color.settingslib_banner_button_background_normal);
+ R.color.settingslib_banner_button_background_normal,
+ R.color.settingslib_banner_filled_button_content_normal);
// Corresponds to the enum value of R.attr.attentionLevel
private final int mAttrValue;
@ColorRes private final int mBackgroundColorResId;
@ColorRes private final int mAccentColorResId;
@ColorRes private final int mButtonBackgroundColorResId;
+ @ColorRes private final int mButtonContentColorResId;
AttentionLevel(
int attrValue,
@ColorRes int backgroundColorResId,
@ColorRes int accentColorResId,
- @ColorRes int buttonBackgroundColorResId) {
+ @ColorRes int buttonBackgroundColorResId,
+ @ColorRes int buttonContentColorResId) {
mAttrValue = attrValue;
mBackgroundColorResId = backgroundColorResId;
mAccentColorResId = accentColorResId;
mButtonBackgroundColorResId = buttonBackgroundColorResId;
+ mButtonContentColorResId = buttonContentColorResId;
}
static AttentionLevel fromAttr(int attrValue) {
@@ -109,6 +116,10 @@ public class BannerMessagePreference extends Preference implements GroupSectionD
public @ColorRes int getButtonBackgroundColorResId() {
return mButtonBackgroundColorResId;
}
+
+ public @ColorRes int getButtonContentColorResId() {
+ return mButtonContentColorResId;
+ }
}
private static final String TAG = "BannerPreference";
@@ -181,6 +192,7 @@ public class BannerMessagePreference extends Preference implements GroupSectionD
public void onBindViewHolder(@NonNull PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
final Context context = getContext();
+ final Resources resources = context.getResources();
final TextView titleView = (TextView) holder.findViewById(R.id.banner_title);
CharSequence title = getTitle();
@@ -200,7 +212,7 @@ public class BannerMessagePreference extends Preference implements GroupSectionD
final Resources.Theme theme = context.getTheme();
@ColorInt final int accentColor =
- context.getResources().getColor(mAttentionLevel.getAccentColorResId(), theme);
+ resources.getColor(mAttentionLevel.getAccentColorResId(), theme);
final ImageView iconView = (ImageView) holder.findViewById(R.id.banner_icon);
if (iconView != null) {
@@ -211,9 +223,7 @@ public class BannerMessagePreference extends Preference implements GroupSectionD
} else {
iconView.setVisibility(View.VISIBLE);
iconView.setImageDrawable(
- icon == null
- ? getContext().getDrawable(R.drawable.ic_warning)
- : icon);
+ icon == null ? context.getDrawable(R.drawable.ic_warning) : icon);
if (mAttentionLevel != AttentionLevel.NORMAL
&& !SettingsThemeHelper.isExpressiveTheme(context)) {
iconView.setColorFilter(
@@ -224,14 +234,24 @@ public class BannerMessagePreference extends Preference implements GroupSectionD
if (IS_AT_LEAST_S) {
@ColorInt final int backgroundColor =
- context.getResources().getColor(
- mAttentionLevel.getBackgroundColorResId(), theme);
-
- @ColorInt final int btnBackgroundColor =
- context.getResources().getColor(mAttentionLevel.getButtonBackgroundColorResId(),
- theme);
- ColorStateList strokeColor = context.getResources().getColorStateList(
- mAttentionLevel.getButtonBackgroundColorResId(), theme);
+ resources.getColor(mAttentionLevel.getBackgroundColorResId(), theme);
+
+ ColorStateList btnBackgroundColor =
+ resources.getColorStateList(
+ mAttentionLevel.getButtonBackgroundColorResId(), theme);
+ ColorStateList btnStrokeColor =
+ mAttentionLevel == AttentionLevel.NORMAL
+ ? resources.getColorStateList(
+ R.color.settingslib_banner_outline_button_stroke_normal, theme)
+ : btnBackgroundColor;
+ ColorStateList filledBtnTextColor =
+ resources.getColorStateList(
+ mAttentionLevel.getButtonContentColorResId(), theme);
+ ColorStateList outlineBtnTextColor =
+ mAttentionLevel == AttentionLevel.NORMAL
+ ? btnBackgroundColor
+ : resources.getColorStateList(
+ R.color.settingslib_banner_outline_button_content, theme);
holder.setDividerAllowedAbove(false);
holder.setDividerAllowedBelow(false);
@@ -242,10 +262,10 @@ public class BannerMessagePreference extends Preference implements GroupSectionD
mPositiveButtonInfo.mColor = accentColor;
mNegativeButtonInfo.mColor = accentColor;
- if (mAttentionLevel != AttentionLevel.NORMAL) {
- mPositiveButtonInfo.mBackgroundColor = btnBackgroundColor;
- mNegativeButtonInfo.mStrokeColor = strokeColor;
- }
+ mPositiveButtonInfo.mBackgroundColor = btnBackgroundColor;
+ mPositiveButtonInfo.mTextColor = filledBtnTextColor;
+ mNegativeButtonInfo.mStrokeColor = btnStrokeColor;
+ mNegativeButtonInfo.mTextColor = outlineBtnTextColor;
mDismissButtonInfo.mButton = (ImageButton) holder.findViewById(R.id.banner_dismiss_btn);
mDismissButtonInfo.setUpButton();
@@ -261,8 +281,6 @@ public class BannerMessagePreference extends Preference implements GroupSectionD
headerView.setText(mHeader);
headerView.setVisibility(TextUtils.isEmpty(mHeader) ? View.GONE : View.VISIBLE);
}
-
-
} else {
holder.setDividerAllowedAbove(true);
holder.setDividerAllowedBelow(true);
@@ -567,8 +585,9 @@ public class BannerMessagePreference extends Preference implements GroupSectionD
private boolean mIsVisible = true;
private boolean mIsEnabled = true;
@ColorInt private int mColor;
- @ColorInt private int mBackgroundColor;
+ @Nullable private ColorStateList mBackgroundColor;
@Nullable private ColorStateList mStrokeColor;
+ @Nullable private ColorStateList mTextColor;
void setUpButton() {
if (mButton == null) {
@@ -586,12 +605,15 @@ public class BannerMessagePreference extends Preference implements GroupSectionD
if (IS_AT_LEAST_S) {
if (btn != null && SettingsThemeHelper.isExpressiveTheme(btn.getContext())) {
- if (mBackgroundColor != 0) {
- btn.setBackgroundColor(mBackgroundColor);
+ if (mBackgroundColor != null) {
+ btn.setBackgroundTintList(mBackgroundColor);
}
if (mStrokeColor != null) {
btn.setStrokeColor(mStrokeColor);
}
+ if (mTextColor != null) {
+ btn.setTextColor(mTextColor);
+ }
} else {
mButton.setTextColor(mColor);
}
diff --git a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/dialog/SettingsAlterDialogContent.kt b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/dialog/SettingsAlterDialogContent.kt
index 9f2210d852a9..058fe53f7201 100644
--- a/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/dialog/SettingsAlterDialogContent.kt
+++ b/packages/SettingsLib/Spa/spa/src/com/android/settingslib/spa/widget/dialog/SettingsAlterDialogContent.kt
@@ -46,6 +46,7 @@ import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.fastForEach
import androidx.compose.ui.util.fastForEachIndexed
@@ -226,7 +227,12 @@ internal fun AlertDialogFlowRow(
val childrenMainAxisSizes =
IntArray(placeables.size) { j ->
placeables[j].width +
- if (j < placeables.lastIndex) mainAxisSpacing.roundToPx() else 0
+ if ((layoutDirection == LayoutDirection.Ltr && j < placeables.lastIndex)
+ || (layoutDirection == LayoutDirection.Rtl && j > 0)) {
+ mainAxisSpacing.roundToPx()
+ } else {
+ 0
+ }
}
val arrangement = Arrangement.End
val mainAxisPositions = IntArray(childrenMainAxisSizes.size) { 0 }
diff --git a/packages/SettingsLib/StatusBannerPreference/src/com/android/settingslib/widget/StatusBannerPreference.kt b/packages/SettingsLib/StatusBannerPreference/src/com/android/settingslib/widget/StatusBannerPreference.kt
index e6c6638f7de4..c62aed1da352 100644
--- a/packages/SettingsLib/StatusBannerPreference/src/com/android/settingslib/widget/StatusBannerPreference.kt
+++ b/packages/SettingsLib/StatusBannerPreference/src/com/android/settingslib/widget/StatusBannerPreference.kt
@@ -49,6 +49,7 @@ class StatusBannerPreference @JvmOverloads constructor(
var iconLevel: BannerStatus = BannerStatus.GENERIC
set(value) {
field = value
+ updateIconTint(value)
notifyChanged()
}
var buttonLevel: BannerStatus = BannerStatus.GENERIC
@@ -81,7 +82,7 @@ class StatusBannerPreference @JvmOverloads constructor(
if (icon == null) {
icon = getIconDrawable(iconLevel)
} else {
- icon!!.setTintList(ColorStateList.valueOf(getBackgroundColor(iconLevel)))
+ updateIconTint(iconLevel)
}
buttonLevel = getInteger(R.styleable.StatusBanner_buttonLevel, 0).toBannerStatus()
buttonText = getString(R.styleable.StatusBanner_buttonText) ?: ""
@@ -252,4 +253,12 @@ class StatusBannerPreference @JvmOverloads constructor(
)
}
}
-} \ No newline at end of file
+
+ /**
+ * Sets the icon's tint color based on the icon level. If an icon is not defined, this is a
+ * no-op.
+ */
+ private fun updateIconTint(iconLevel: BannerStatus) {
+ icon?.setTintList(ColorStateList.valueOf(getBackgroundColor(iconLevel)))
+ }
+}
diff --git a/packages/SettingsLib/res/xml/timezones.xml b/packages/SettingsLib/res/xml/timezones.xml
index 6a8d7802f9fd..4cea32aa05f9 100644
--- a/packages/SettingsLib/res/xml/timezones.xml
+++ b/packages/SettingsLib/res/xml/timezones.xml
@@ -35,6 +35,7 @@
<timezone id="Europe/Brussels"></timezone>
<timezone id="Europe/Madrid"></timezone>
<timezone id="Europe/Sarajevo"></timezone>
+ <timezone id="Europe/Warsaw"></timezone>
<timezone id="Africa/Windhoek"></timezone>
<timezone id="Africa/Brazzaville"></timezone>
<timezone id="Asia/Amman"></timezone>
diff --git a/packages/SettingsLib/src/com/android/settingslib/RestrictedLockUtilsInternal.java b/packages/SettingsLib/src/com/android/settingslib/RestrictedLockUtilsInternal.java
index 4de64769b425..f89bd9c43a37 100644
--- a/packages/SettingsLib/src/com/android/settingslib/RestrictedLockUtilsInternal.java
+++ b/packages/SettingsLib/src/com/android/settingslib/RestrictedLockUtilsInternal.java
@@ -77,6 +77,10 @@ public class RestrictedLockUtilsInternal extends RestrictedLockUtils {
private static final String ROLE_DEVICE_LOCK_CONTROLLER =
"android.app.role.SYSTEM_FINANCED_DEVICE_CONTROLLER";
+ //TODO(b/378931989): Switch to android.app.admin.DevicePolicyIdentifiers.MEMORY_TAGGING_POLICY
+ //when the appropriate flag is launched.
+ private static final String MEMORY_TAGGING_POLICY = "memoryTagging";
+
/**
* @return drawables for displaying with settings that are locked by a device admin.
*/
@@ -244,14 +248,23 @@ public class RestrictedLockUtilsInternal extends RestrictedLockUtils {
*/
public static EnforcedAdmin checkIfKeyguardFeaturesDisabled(Context context,
int keyguardFeatures, final @UserIdInt int userId) {
- final LockSettingCheck check = (dpm, admin, checkUser) -> {
- int effectiveFeatures = dpm.getKeyguardDisabledFeatures(admin, checkUser);
- if (checkUser != userId) {
- effectiveFeatures &= PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
- }
- return (effectiveFeatures & keyguardFeatures) != KEYGUARD_DISABLE_FEATURES_NONE;
- };
- if (UserManager.get(context).getUserInfo(userId).isManagedProfile()) {
+ UserInfo userInfo = UserManager.get(context).getUserInfo(userId);
+ if (userInfo == null) {
+ Log.w(LOG_TAG, "User " + userId + " does not exist");
+ return null;
+ }
+
+ final LockSettingCheck check =
+ (dpm, admin, checkUser) -> {
+ int effectiveFeatures = dpm.getKeyguardDisabledFeatures(admin, checkUser);
+ if (checkUser != userId) {
+ // This case is reached when {@code checkUser} is a managed profile and
+ // {@code userId} is the parent user.
+ effectiveFeatures &= PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
+ }
+ return (effectiveFeatures & keyguardFeatures) != KEYGUARD_DISABLE_FEATURES_NONE;
+ };
+ if (userInfo.isManagedProfile()) {
DevicePolicyManager dpm =
(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
return findEnforcedAdmin(dpm.getActiveAdminsAsUser(userId), dpm, userId, check);
@@ -838,14 +851,13 @@ public class RestrictedLockUtilsInternal extends RestrictedLockUtils {
if (dpm.getMtePolicy() == MTE_NOT_CONTROLLED_BY_POLICY) {
return null;
}
- EnforcedAdmin admin =
- RestrictedLockUtils.getProfileOrDeviceOwner(
- context, context.getUser());
- if (admin != null) {
- return admin;
+ EnforcingAdmin enforcingAdmin = context.getSystemService(DevicePolicyManager.class)
+ .getEnforcingAdmin(context.getUserId(), MEMORY_TAGGING_POLICY);
+ if (enforcingAdmin == null) {
+ Log.w(LOG_TAG, "MTE is controlled by policy but could not find enforcing admin.");
}
- int profileId = getManagedProfileId(context, context.getUserId());
- return RestrictedLockUtils.getProfileOrDeviceOwner(context, UserHandle.of(profileId));
+
+ return EnforcedAdmin.createDefaultEnforcedAdminWithRestriction(MEMORY_TAGGING_POLICY);
}
/**
diff --git a/packages/SettingsLib/src/com/android/settingslib/display/OWNERS b/packages/SettingsLib/src/com/android/settingslib/display/OWNERS
new file mode 100644
index 000000000000..aafc2f79611b
--- /dev/null
+++ b/packages/SettingsLib/src/com/android/settingslib/display/OWNERS
@@ -0,0 +1,5 @@
+# Default reviewers for this and subdirectories.
+pbdr@google.com
+ebrukurnaz@google.com
+lihongyu@google.com
+wilczynskip@google.com
diff --git a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiUtils.kt b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiUtils.kt
index 4d38f1d551bb..cca43b92ef19 100644
--- a/packages/SettingsLib/src/com/android/settingslib/wifi/WifiUtils.kt
+++ b/packages/SettingsLib/src/com/android/settingslib/wifi/WifiUtils.kt
@@ -510,9 +510,9 @@ open class WifiUtils {
AdvancedProtectionManager.FEATURE_ID_DISALLOW_WEP,
AdvancedProtectionManager.SUPPORT_DIALOG_TYPE_BLOCKED_INTERACTION)
intent.putExtra(DIALOG_WINDOW_TYPE, dialogWindowType)
- onStartActivity(intent)
+ withContext(Dispatchers.Main) { onStartActivity(intent) }
} else if (wifiManager.isWepSupported == true && wifiManager.queryWepAllowed()) {
- onAllowed()
+ withContext(Dispatchers.Main) { onAllowed() }
} else {
val intent = Intent(Intent.ACTION_MAIN).apply {
component = ComponentName(
@@ -522,7 +522,7 @@ open class WifiUtils {
putExtra(DIALOG_WINDOW_TYPE, dialogWindowType)
putExtra(SSID, ssid)
}.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- onStartActivity(intent)
+ withContext(Dispatchers.Main) { onStartActivity(intent) }
}
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/RestrictedLockUtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/RestrictedLockUtilsTest.java
index 785bcbf5a91c..71e11ba55850 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/RestrictedLockUtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/RestrictedLockUtilsTest.java
@@ -458,6 +458,16 @@ public class RestrictedLockUtilsTest {
assertThat(intentCaptor.getValue().getExtra(EXTRA_RESTRICTION)).isNull();
}
+ /** See b/386971405. Ensure that the code does not crash when the user is not found. */
+ @Test
+ public void checkIfKeyguardFeaturesDisabled_returnsNull_whenUserDoesNotExist() {
+ when(mUserManager.getUserInfo(mUserId)).thenReturn(null);
+ assertThat(
+ RestrictedLockUtilsInternal.checkIfKeyguardFeaturesDisabled(
+ mContext, KEYGUARD_DISABLE_FINGERPRINT, mUserId))
+ .isNull();
+ }
+
private UserInfo setUpUser(int userId, ComponentName[] admins) {
UserInfo userInfo = new UserInfo(userId, "primary", 0);
when(mUserManager.getUserInfo(userId)).thenReturn(userInfo);
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BannerMessagePreferenceTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BannerMessagePreferenceTest.java
index 7f4bdaeac855..83471ae9513e 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BannerMessagePreferenceTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/widget/BannerMessagePreferenceTest.java
@@ -18,6 +18,7 @@ package com.android.settingslib.widget;
import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.robolectric.Robolectric.setupActivity;
@@ -25,6 +26,8 @@ import static org.robolectric.Shadows.shadowOf;
import android.app.Activity;
import android.content.Context;
+import android.content.res.ColorStateList;
+import android.content.res.Configuration;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
@@ -38,24 +41,34 @@ import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.ColorRes;
+import androidx.annotation.NonNull;
import androidx.preference.PreferenceViewHolder;
-import com.android.settingslib.testutils.OverpoweredReflectionHelper;
import com.android.settingslib.widget.preference.banner.R;
+import com.google.android.material.button.MaterialButton;
+
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+import org.robolectric.annotation.Implementation;
+import org.robolectric.annotation.Implements;
import org.robolectric.shadows.ShadowDrawable;
import org.robolectric.shadows.ShadowTouchDelegate;
import org.robolectric.util.ReflectionHelpers;
-@Ignore("b/359066481")
+import java.util.List;
+
@RunWith(RobolectricTestRunner.class)
+@Config(shadows = {BannerMessagePreferenceTest.ShadowSettingsThemeHelper.class})
public class BannerMessagePreferenceTest {
private Context mContext;
@@ -66,14 +79,23 @@ public class BannerMessagePreferenceTest {
private boolean mClickListenerCalled = false;
private final View.OnClickListener mClickListener = v -> mClickListenerCalled = true;
private final int mMinimumTargetSize =
- RuntimeEnvironment.application.getResources()
- .getDimensionPixelSize(com.android.settingslib.widget.theme.R.dimen.settingslib_preferred_minimum_touch_target);
+ RuntimeEnvironment.application
+ .getResources()
+ .getDimensionPixelSize(
+ com.android.settingslib.widget.theme.R.dimen
+ .settingslib_preferred_minimum_touch_target);
- private static final int TEST_STRING_RES_ID =
- R.string.accessibility_banner_message_dismiss;
+ private static final int TEST_STRING_RES_ID = R.string.accessibility_banner_message_dismiss;
+
+ @Mock private View mMockBackgroundView;
+ @Mock private Drawable mMockCardBackground;
+ @Mock private MaterialButton mMockPositiveBtn;
+ @Mock private MaterialButton mMockNegativeBtn;
@Before
public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ ShadowSettingsThemeHelper.setExpressiveTheme(false);
mContext = RuntimeEnvironment.application;
mClickListenerCalled = false;
mBannerPreference = new BannerMessagePreference(mContext);
@@ -90,6 +112,7 @@ public class BannerMessagePreferenceTest {
.isEqualTo("test");
}
+ @Ignore("b/359066481")
@Test
public void onBindViewHolder_andOnLayoutView_dismissButtonTouchDelegate_isCorrectSize() {
assumeAndroidS();
@@ -155,9 +178,8 @@ public class BannerMessagePreferenceTest {
@Test
public void onBindViewHolder_whenAtLeastS_whenSubtitleXmlAttribute_shouldSetSubtitle() {
assumeAndroidS();
- AttributeSet mAttributeSet = Robolectric.buildAttributeSet()
- .addAttribute(R.attr.subtitle, "Test")
- .build();
+ AttributeSet mAttributeSet =
+ Robolectric.buildAttributeSet().addAttribute(R.attr.subtitle, "Test").build();
mBannerPreference = new BannerMessagePreference(mContext, mAttributeSet);
mBannerPreference.onBindViewHolder(mHolder);
@@ -185,8 +207,7 @@ public class BannerMessagePreferenceTest {
ImageView mIcon = mRootView.findViewById(R.id.banner_icon);
ShadowDrawable shadowDrawable = shadowOf(mIcon.getDrawable());
- assertThat(shadowDrawable.getCreatedFromResId())
- .isEqualTo(R.drawable.settingslib_ic_cross);
+ assertThat(shadowDrawable.getCreatedFromResId()).isEqualTo(R.drawable.settingslib_ic_cross);
}
@Test
@@ -207,6 +228,7 @@ public class BannerMessagePreferenceTest {
Button mPositiveButton = mRootView.findViewById(R.id.banner_positive_btn);
assertThat(mPositiveButton.getVisibility()).isEqualTo(View.VISIBLE);
+
assertThat(mPositiveButton.getText()).isEqualTo(mContext.getString(TEST_STRING_RES_ID));
}
@@ -218,6 +240,7 @@ public class BannerMessagePreferenceTest {
Button mNegativeButton = mRootView.findViewById(R.id.banner_negative_btn);
assertThat(mNegativeButton.getVisibility()).isEqualTo(View.VISIBLE);
+
assertThat(mNegativeButton.getText()).isEqualTo(mContext.getString(TEST_STRING_RES_ID));
}
@@ -359,8 +382,6 @@ public class BannerMessagePreferenceTest {
@Test
public void onBindViewHolder_whenAtLeastS_whenAttentionUnset_setsHighTheme() {
assumeAndroidS();
- Drawable mCardBackgroundSpy = spy(mRootView.getBackground());
- mRootView.setBackground(mCardBackgroundSpy);
mBannerPreference.onBindViewHolder(mHolder);
@@ -370,17 +391,15 @@ public class BannerMessagePreferenceTest {
.isEqualTo(getColorId(R.color.banner_accent_attention_high));
assertThat(getButtonColor(R.id.banner_negative_btn))
.isEqualTo(getColorId(R.color.banner_accent_attention_high));
- verify(mCardBackgroundSpy).setTint(getColorId(R.color.banner_background_attention_high));
+
+ verify(mMockCardBackground).setTint(getColorId(R.color.banner_background_attention_high));
}
@Test
public void onBindViewHolder_whenAtLeastS_whenAttentionHighByXML_setsHighTheme() {
assumeAndroidS();
- Drawable mCardBackgroundSpy = spy(mRootView.getBackground());
- mRootView.setBackground(mCardBackgroundSpy);
- AttributeSet mAttributeSet = Robolectric.buildAttributeSet()
- .addAttribute(R.attr.attentionLevel, "high")
- .build();
+ AttributeSet mAttributeSet =
+ Robolectric.buildAttributeSet().addAttribute(R.attr.attentionLevel, "high").build();
mBannerPreference = new BannerMessagePreference(mContext, mAttributeSet);
mBannerPreference.onBindViewHolder(mHolder);
@@ -391,17 +410,17 @@ public class BannerMessagePreferenceTest {
.isEqualTo(getColorId(R.color.banner_accent_attention_high));
assertThat(getButtonColor(R.id.banner_negative_btn))
.isEqualTo(getColorId(R.color.banner_accent_attention_high));
- verify(mCardBackgroundSpy).setTint(getColorId(R.color.banner_background_attention_high));
+
+ verify(mMockCardBackground).setTint(getColorId(R.color.banner_background_attention_high));
}
@Test
public void onBindViewHolder_whenAtLeastS_whenAttentionMediumByXML_setsMediumTheme() {
assumeAndroidS();
- Drawable mCardBackgroundSpy = spy(mRootView.getBackground());
- mRootView.setBackground(mCardBackgroundSpy);
- AttributeSet mAttributeSet = Robolectric.buildAttributeSet()
- .addAttribute(R.attr.attentionLevel, "medium")
- .build();
+ AttributeSet mAttributeSet =
+ Robolectric.buildAttributeSet()
+ .addAttribute(R.attr.attentionLevel, "medium")
+ .build();
mBannerPreference = new BannerMessagePreference(mContext, mAttributeSet);
mBannerPreference.onBindViewHolder(mHolder);
@@ -412,17 +431,15 @@ public class BannerMessagePreferenceTest {
.isEqualTo(getColorId(R.color.banner_accent_attention_medium));
assertThat(getButtonColor(R.id.banner_negative_btn))
.isEqualTo(getColorId(R.color.banner_accent_attention_medium));
- verify(mCardBackgroundSpy).setTint(getColorId(R.color.banner_background_attention_medium));
+
+ verify(mMockCardBackground).setTint(getColorId(R.color.banner_background_attention_medium));
}
@Test
public void onBindViewHolder_whenAtLeastS_whenAttentionLowByXML_setsLowTheme() {
assumeAndroidS();
- Drawable mCardBackgroundSpy = spy(mRootView.getBackground());
- mRootView.setBackground(mCardBackgroundSpy);
- AttributeSet mAttributeSet = Robolectric.buildAttributeSet()
- .addAttribute(R.attr.attentionLevel, "low")
- .build();
+ AttributeSet mAttributeSet =
+ Robolectric.buildAttributeSet().addAttribute(R.attr.attentionLevel, "low").build();
mBannerPreference = new BannerMessagePreference(mContext, mAttributeSet);
mBannerPreference.onBindViewHolder(mHolder);
@@ -433,14 +450,13 @@ public class BannerMessagePreferenceTest {
.isEqualTo(getColorId(R.color.banner_accent_attention_low));
assertThat(getButtonColor(R.id.banner_negative_btn))
.isEqualTo(getColorId(R.color.banner_accent_attention_low));
- verify(mCardBackgroundSpy).setTint(getColorId(R.color.banner_background_attention_low));
+
+ verify(mMockCardBackground).setTint(getColorId(R.color.banner_background_attention_low));
}
@Test
public void setAttentionLevel_whenAtLeastS_whenHighAttention_setsHighTheme() {
assumeAndroidS();
- Drawable mCardBackgroundSpy = spy(mRootView.getBackground());
- mRootView.setBackground(mCardBackgroundSpy);
mBannerPreference.setAttentionLevel(BannerMessagePreference.AttentionLevel.HIGH);
mBannerPreference.onBindViewHolder(mHolder);
@@ -451,14 +467,44 @@ public class BannerMessagePreferenceTest {
.isEqualTo(getColorId(R.color.banner_accent_attention_high));
assertThat(getButtonColor(R.id.banner_negative_btn))
.isEqualTo(getColorId(R.color.banner_accent_attention_high));
- verify(mCardBackgroundSpy).setTint(getColorId(R.color.banner_background_attention_high));
+
+ verify(mMockCardBackground).setTint(getColorId(R.color.banner_background_attention_high));
}
@Test
- public void setAttentionLevel_whenAtLeastS_whenMedAttention_setsMediumTheme() {
+ public void setAttentionLevel_whenAtLeastS_whenHighAttentionAndExpressiveTheme_setsBtnTheme() {
+ setExpressiveTheme(true);
+ assumeAndroidS();
+ assertThat(SettingsThemeHelper.isExpressiveTheme(mContext)).isTrue();
+ assertThat(SettingsThemeHelper.isExpressiveTheme(mContext)).isTrue();
+ doReturn(mMockPositiveBtn).when(mHolder).findViewById(R.id.banner_positive_btn);
+ doReturn(mMockNegativeBtn).when(mHolder).findViewById(R.id.banner_negative_btn);
+ assertThat(SettingsThemeHelper.isExpressiveTheme(mContext)).isTrue();
+ mBannerPreference.setAttentionLevel(BannerMessagePreference.AttentionLevel.HIGH);
+ final ArgumentCaptor<ColorStateList> captor = ArgumentCaptor.forClass(ColorStateList.class);
+ ColorStateList filledBtnBackground =
+ getColorStateList(R.color.settingslib_banner_button_background_high);
+ ColorStateList filledBtnTextColor =
+ getColorStateList(R.color.settingslib_banner_filled_button_content_high);
+ ColorStateList outlineBtnTextColor =
+ getColorStateList(R.color.settingslib_banner_outline_button_content);
+
+ mBannerPreference.onBindViewHolder(mHolder);
+
+ verify(mMockPositiveBtn).setBackgroundTintList(captor.capture());
+ verify(mMockPositiveBtn).setTextColor(captor.capture());
+ verify(mMockNegativeBtn).setStrokeColor(captor.capture());
+ verify(mMockNegativeBtn).setTextColor(captor.capture());
+ List<ColorStateList> colors = captor.getAllValues();
+ assertThat(colors.get(0).getColors()).isEqualTo(filledBtnBackground.getColors());
+ assertThat(colors.get(1).getColors()).isEqualTo(filledBtnTextColor.getColors());
+ assertThat(colors.get(2).getColors()).isEqualTo(filledBtnBackground.getColors());
+ assertThat(colors.get(3).getColors()).isEqualTo(outlineBtnTextColor.getColors());
+ }
+
+ @Test
+ public void setAttentionLevel_whenAtLeastS_whenMedAttention_setsBtnMediumTheme() {
assumeAndroidS();
- Drawable mCardBackgroundSpy = spy(mRootView.getBackground());
- mRootView.setBackground(mCardBackgroundSpy);
mBannerPreference.setAttentionLevel(BannerMessagePreference.AttentionLevel.MEDIUM);
mBannerPreference.onBindViewHolder(mHolder);
@@ -469,14 +515,42 @@ public class BannerMessagePreferenceTest {
.isEqualTo(getColorId(R.color.banner_accent_attention_medium));
assertThat(getButtonColor(R.id.banner_negative_btn))
.isEqualTo(getColorId(R.color.banner_accent_attention_medium));
- verify(mCardBackgroundSpy).setTint(getColorId(R.color.banner_background_attention_medium));
+
+ verify(mMockCardBackground).setTint(getColorId(R.color.banner_background_attention_medium));
+ }
+
+ @Test
+ public void setAttentionLevel_whenAtLeastS_whenMedAttentionAndExpressiveTheme_setsBtnTheme() {
+ setExpressiveTheme(true);
+ mContext.getResources().getConfiguration().uiMode = Configuration.UI_MODE_NIGHT_NO;
+ assumeAndroidS();
+ doReturn(mMockPositiveBtn).when(mHolder).findViewById(R.id.banner_positive_btn);
+ doReturn(mMockNegativeBtn).when(mHolder).findViewById(R.id.banner_negative_btn);
+ mBannerPreference.setAttentionLevel(BannerMessagePreference.AttentionLevel.MEDIUM);
+ final ArgumentCaptor<ColorStateList> captor = ArgumentCaptor.forClass(ColorStateList.class);
+ ColorStateList filledBtnBackground =
+ getColorStateList(R.color.settingslib_banner_button_background_medium);
+ ColorStateList filledBtnTextColor =
+ getColorStateList(R.color.settingslib_banner_filled_button_content_medium);
+ ColorStateList outlineBtnTextColor =
+ getColorStateList(R.color.settingslib_banner_outline_button_content);
+
+ mBannerPreference.onBindViewHolder(mHolder);
+
+ verify(mMockPositiveBtn).setBackgroundTintList(captor.capture());
+ verify(mMockPositiveBtn).setTextColor(captor.capture());
+ verify(mMockNegativeBtn).setStrokeColor(captor.capture());
+ verify(mMockNegativeBtn).setTextColor(captor.capture());
+ List<ColorStateList> colors = captor.getAllValues();
+ assertThat(colors.get(0).getColors()).isEqualTo(filledBtnBackground.getColors());
+ assertThat(colors.get(1).getColors()).isEqualTo(filledBtnTextColor.getColors());
+ assertThat(colors.get(2).getColors()).isEqualTo(filledBtnBackground.getColors());
+ assertThat(colors.get(3).getColors()).isEqualTo(outlineBtnTextColor.getColors());
}
@Test
public void setAttentionLevel_whenAtLeastS_whenLowAttention_setsLowTheme() {
assumeAndroidS();
- Drawable mCardBackgroundSpy = spy(mRootView.getBackground());
- mRootView.setBackground(mCardBackgroundSpy);
mBannerPreference.setAttentionLevel(BannerMessagePreference.AttentionLevel.LOW);
mBannerPreference.onBindViewHolder(mHolder);
@@ -487,7 +561,37 @@ public class BannerMessagePreferenceTest {
.isEqualTo(getColorId(R.color.banner_accent_attention_low));
assertThat(getButtonColor(R.id.banner_negative_btn))
.isEqualTo(getColorId(R.color.banner_accent_attention_low));
- verify(mCardBackgroundSpy).setTint(getColorId(R.color.banner_background_attention_low));
+ verify(mMockCardBackground).setTint(getColorId(R.color.banner_background_attention_low));
+ }
+
+ @Test
+ public void
+ setAttentionLevel_whenAtLeastS_whenNormalAttentionAndExpressiveTheme_setsBtnTheme() {
+ setExpressiveTheme(true);
+ mContext.getResources().getConfiguration().uiMode = Configuration.UI_MODE_NIGHT_NO;
+ assumeAndroidS();
+ doReturn(mMockPositiveBtn).when(mHolder).findViewById(R.id.banner_positive_btn);
+ doReturn(mMockNegativeBtn).when(mHolder).findViewById(R.id.banner_negative_btn);
+ mBannerPreference.setAttentionLevel(BannerMessagePreference.AttentionLevel.NORMAL);
+ final ArgumentCaptor<ColorStateList> captor = ArgumentCaptor.forClass(ColorStateList.class);
+ ColorStateList filledBtnBackground =
+ getColorStateList(R.color.settingslib_banner_button_background_normal);
+ ColorStateList filledBtnTextColor =
+ getColorStateList(R.color.settingslib_banner_filled_button_content_normal);
+ ColorStateList outlineBtnStrokeColor =
+ getColorStateList(R.color.settingslib_banner_outline_button_stroke_normal);
+
+ mBannerPreference.onBindViewHolder(mHolder);
+
+ verify(mMockPositiveBtn).setBackgroundTintList(captor.capture());
+ verify(mMockPositiveBtn).setTextColor(captor.capture());
+ verify(mMockNegativeBtn).setStrokeColor(captor.capture());
+ verify(mMockNegativeBtn).setTextColor(captor.capture());
+ List<ColorStateList> colors = captor.getAllValues();
+ assertThat(colors.get(0).getColors()).isEqualTo(filledBtnBackground.getColors());
+ assertThat(colors.get(1).getColors()).isEqualTo(filledBtnTextColor.getColors());
+ assertThat(colors.get(2).getColors()).isEqualTo(outlineBtnStrokeColor.getColors());
+ assertThat(colors.get(3).getColors()).isEqualTo(filledBtnBackground.getColors());
}
private int getButtonColor(int buttonResId) {
@@ -495,6 +599,11 @@ public class BannerMessagePreferenceTest {
return mButton.getTextColors().getDefaultColor();
}
+ private ColorStateList getButtonTextColor(int buttonResId) {
+ Button mButton = mRootView.findViewById(buttonResId);
+ return mButton.getTextColors();
+ }
+
private ColorFilter getColorFilter(@ColorRes int colorResId) {
return new PorterDuffColorFilter(getColorId(colorResId), PorterDuff.Mode.SRC_IN);
}
@@ -503,28 +612,57 @@ public class BannerMessagePreferenceTest {
return mContext.getResources().getColor(colorResId, mContext.getTheme());
}
+ private ColorStateList getColorStateList(@ColorRes int colorResId) {
+ return mContext.getResources().getColorStateList(colorResId, mContext.getTheme());
+ }
+
private void assumeAndroidR() {
ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 30);
ReflectionHelpers.setStaticField(Build.VERSION.class, "CODENAME", "R");
- OverpoweredReflectionHelper
- .setStaticField(BannerMessagePreference.class, "IS_AT_LEAST_S", false);
- // Reset view holder to use correct layout.
- }
-
+ // Refresh the static final field IS_AT_LEAST_S
+ mBannerPreference = new BannerMessagePreference(mContext);
+ setUpViewHolder();
+ }
private void assumeAndroidS() {
ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 31);
ReflectionHelpers.setStaticField(Build.VERSION.class, "CODENAME", "S");
- OverpoweredReflectionHelper
- .setStaticField(BannerMessagePreference.class, "IS_AT_LEAST_S", true);
- // Re-inflate view to update layout.
+
+ // Refresh the static final field IS_AT_LEAST_S
+ mBannerPreference = new BannerMessagePreference(mContext);
setUpViewHolder();
}
+ private void setExpressiveTheme(boolean isExpressiveTheme) {
+ ShadowSettingsThemeHelper.setExpressiveTheme(isExpressiveTheme);
+ assertThat(SettingsThemeHelper.isExpressiveTheme(mContext)).isEqualTo(isExpressiveTheme);
+ if (isExpressiveTheme) {
+ doReturn(mContext).when(mMockPositiveBtn).getContext();
+ doReturn(mContext).when(mMockNegativeBtn).getContext();
+ }
+ }
+
private void setUpViewHolder() {
mRootView =
View.inflate(mContext, mBannerPreference.getLayoutResource(), null /* parent */);
- mHolder = PreferenceViewHolder.createInstanceForTests(mRootView);
+ mHolder = spy(PreferenceViewHolder.createInstanceForTests(mRootView));
+ doReturn(mMockBackgroundView).when(mHolder).findViewById(R.id.banner_background);
+ doReturn(mMockCardBackground).when(mMockBackgroundView).getBackground();
+ }
+
+ @Implements(SettingsThemeHelper.class)
+ public static class ShadowSettingsThemeHelper {
+ private static boolean sIsExpressiveTheme;
+
+ /** Shadow implementation of isExpressiveTheme */
+ @Implementation
+ public static boolean isExpressiveTheme(@NonNull Context context) {
+ return sIsExpressiveTheme;
+ }
+
+ static void setExpressiveTheme(boolean isExpressiveTheme) {
+ sIsExpressiveTheme = isExpressiveTheme;
+ }
}
}
diff --git a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/WifiUtilsTest.java b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/WifiUtilsTest.java
index d8b6707b9118..97473fffaeb1 100644
--- a/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/WifiUtilsTest.java
+++ b/packages/SettingsLib/tests/robotests/src/com/android/settingslib/wifi/WifiUtilsTest.java
@@ -50,6 +50,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
@@ -211,10 +212,12 @@ public class WifiUtilsTest {
WifiUtils.InternetIconInjector iconInjector = new WifiUtils.InternetIconInjector(mContext);
for (int level = 0; level <= 4; level++) {
+ Mockito.reset(mContext);
iconInjector.getIcon(false /* noInternet */, level);
verify(mContext).getDrawable(
WifiUtils.getInternetIconResource(level, false /* noInternet */));
+ Mockito.reset(mContext);
iconInjector.getIcon(true /* noInternet */, level);
verify(mContext).getDrawable(
WifiUtils.getInternetIconResource(level, true /* noInternet */));
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
index 527a1f16a84f..5bbfdf7bab81 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsHelper.java
@@ -672,6 +672,7 @@ public class SettingsHelper {
public static LocaleList resolveLocales(LocaleList restore, LocaleList current,
String[] supportedLocales) {
final HashMap<Locale, Locale> allLocales = new HashMap<>(supportedLocales.length);
+ final HashSet<String> existingLanguageAndScript = new HashSet<>();
for (String supportedLocaleStr : supportedLocales) {
final Locale locale = Locale.forLanguageTag(supportedLocaleStr);
allLocales.put(toFullLocale(locale), locale);
@@ -679,30 +680,26 @@ public class SettingsHelper {
// After restoring to reset locales, need to get extensions from restored locale. Get the
// first restored locale to check its extension.
- final Locale restoredLocale = restore.isEmpty()
+ final Locale firstRestoredLocale = restore.isEmpty()
? Locale.ROOT
: restore.get(0);
final ArrayList<Locale> filtered = new ArrayList<>(current.size());
for (int i = 0; i < current.size(); i++) {
- Locale locale = copyExtensionToTargetLocale(restoredLocale, current.get(i));
- allLocales.remove(toFullLocale(locale));
- filtered.add(locale);
+ Locale locale = copyExtensionToTargetLocale(firstRestoredLocale, current.get(i));
+
+ if (locale != null && existingLanguageAndScript.add(getLanguageAndScript(locale))) {
+ allLocales.remove(toFullLocale(locale));
+ filtered.add(locale);
+ }
}
- final HashSet<String> existingLanguageAndScript = new HashSet<>();
for (int i = 0; i < restore.size(); i++) {
- final Locale restoredLocaleWithExtension = copyExtensionToTargetLocale(restoredLocale,
- getFilteredLocale(restore.get(i), allLocales));
-
- if (restoredLocaleWithExtension != null) {
- String language = restoredLocaleWithExtension.getLanguage();
- String script = restoredLocaleWithExtension.getScript();
+ final Locale restoredLocaleWithExtension = copyExtensionToTargetLocale(
+ firstRestoredLocale, getFilteredLocale(restore.get(i), allLocales));
- String restoredLanguageAndScript =
- script == null ? language : language + "-" + script;
- if (existingLanguageAndScript.add(restoredLanguageAndScript)) {
- filtered.add(restoredLocaleWithExtension);
- }
+ if (restoredLocaleWithExtension != null && existingLanguageAndScript.add(
+ getLanguageAndScript(restoredLocaleWithExtension))) {
+ filtered.add(restoredLocaleWithExtension);
}
}
@@ -713,6 +710,16 @@ public class SettingsHelper {
return new LocaleList(filtered.toArray(new Locale[filtered.size()]));
}
+ private static String getLanguageAndScript(Locale locale) {
+ if (locale == null) {
+ return "";
+ }
+
+ String language = locale.getLanguage();
+ String script = locale.getScript();
+ return script == null ? language : String.join("-", language, script);
+ }
+
private static Locale copyExtensionToTargetLocale(Locale restoredLocale,
Locale targetLocale) {
if (!restoredLocale.hasExtensions()) {
diff --git a/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java
index 48c778542d66..2160d3164b17 100644
--- a/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java
+++ b/packages/SettingsProvider/test/src/com/android/providers/settings/SettingsHelperTest.java
@@ -388,11 +388,18 @@ public class SettingsHelperTest {
LocaleList.forLanguageTags("zh-Hant-TW"), // current
new String[] { "fa-Arab-AF-u-nu-latn", "zh-Hant-TW" })); // supported
- assertEquals(LocaleList.forLanguageTags("en-US,zh-Hans-TW"),
+ assertEquals(LocaleList.forLanguageTags("en-US,zh-Hans-TW,fr-FR"),
SettingsHelper.resolveLocales(
- LocaleList.forLanguageTags("en-UK,en-GB,zh-Hans-HK"), // restore
- LocaleList.forLanguageTags("en-US,zh-Hans-TW"), // current
- new String[] { "en-US,zh-Hans-TW,en-UK,en-GB,zh-Hans-HK" })); // supported
+ // restore
+ LocaleList.forLanguageTags("en-UK,en-GB,zh-Hans-HK,fr-FR"),
+
+ // current
+ LocaleList.forLanguageTags("en-US,zh-Hans-TW"),
+
+ // supported
+ new String[] {
+ "en-US" , "zh-Hans-TW" , "en-UK", "en-GB", "zh-Hans-HK", "fr-FR"
+ }));
}
@Test
diff --git a/packages/Shell/AndroidManifest.xml b/packages/Shell/AndroidManifest.xml
index 758ad797f761..ea09d634b82b 100644
--- a/packages/Shell/AndroidManifest.xml
+++ b/packages/Shell/AndroidManifest.xml
@@ -349,7 +349,7 @@
<uses-permission android:name="android.permission.REQUEST_COMPANION_PROFILE_COMPUTER" />
<uses-permission android:name="android.permission.REQUEST_COMPANION_PROFILE_AUTOMOTIVE_PROJECTION" />
<uses-permission android:name="android.permission.REQUEST_COMPANION_PROFILE_NEARBY_DEVICE_STREAMING" />
- <uses-permission android:name="android.permission.REQUEST_COMPANION_PROFILE_SENSOR_DEVICE_STREAMING" />
+ <uses-permission android:name="android.permission.REQUEST_COMPANION_PROFILE_VIRTUAL_DEVICE" />
<uses-permission android:name="android.permission.REQUEST_COMPANION_PROFILE_WATCH" />
<uses-permission android:name="android.permission.REQUEST_COMPANION_PROFILE_GLASSES" />
<uses-permission android:name="android.permission.REQUEST_COMPANION_SELF_MANAGED" />
@@ -961,6 +961,7 @@
android:featureFlag="android.security.aapm_api"/>
<uses-permission android:name="android.permission.QUERY_ADVANCED_PROTECTION_MODE"
android:featureFlag="android.security.aapm_api"/>
+ <uses-permission android:name="android.permission.MANAGE_DEVICE_POLICY_MTE" />
<!-- Permission required for CTS test - IntrusionDetectionManagerTest -->
<uses-permission android:name="android.permission.READ_INTRUSION_DETECTION_STATE"
diff --git a/packages/SystemUI/OWNERS b/packages/SystemUI/OWNERS
index ab3fa1b06255..728d206e2786 100644
--- a/packages/SystemUI/OWNERS
+++ b/packages/SystemUI/OWNERS
@@ -97,7 +97,6 @@ spdonghao@google.com
steell@google.com
stevenckng@google.com
stwu@google.com
-syeonlee@google.com
sunnygoyal@google.com
thiruram@google.com
tracyzhou@google.com
diff --git a/packages/SystemUI/aconfig/systemui.aconfig b/packages/SystemUI/aconfig/systemui.aconfig
index 17d8bbfd2240..91492b2959d8 100644
--- a/packages/SystemUI/aconfig/systemui.aconfig
+++ b/packages/SystemUI/aconfig/systemui.aconfig
@@ -512,13 +512,6 @@ flag {
}
flag {
- name: "status_bar_notification_chips"
- namespace: "systemui"
- description: "Show promoted ongoing notifications as chips in the status bar"
- bug: "364653005"
-}
-
-flag {
name: "status_bar_popup_chips"
namespace: "systemui"
description: "Show rich ongoing processes as chips in the status bar"
@@ -2038,13 +2031,6 @@ flag {
}
flag {
- name: "ui_rich_ongoing_force_expanded"
- namespace: "systemui"
- description: "Force promoted notifications to always be expanded"
- bug: "380901479"
-}
-
-flag {
name: "permission_helper_ui_rich_ongoing"
namespace: "systemui"
description: "[RONs] Guards inline permission helper for demoting RONs [Guts/card version]"
@@ -2059,13 +2045,6 @@ flag {
}
flag {
- name: "aod_ui_rich_ongoing"
- namespace: "systemui"
- description: "Show a rich ongoing notification on the always-on display (depends on ui_rich_ongoing)"
- bug: "369151941"
-}
-
-flag {
name: "stabilize_heads_up_group_v2"
namespace: "systemui"
description: "Stabilize heads up groups in VisualStabilityCoordinator"
diff --git a/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityTransitionAnimator.kt b/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityTransitionAnimator.kt
index 440a81fc2152..0680faf5226a 100644
--- a/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityTransitionAnimator.kt
+++ b/packages/SystemUI/animation/src/com/android/systemui/animation/ActivityTransitionAnimator.kt
@@ -1483,7 +1483,8 @@ constructor(
// TODO(b/397646693): remove this exception.
val isEligibleForReparenting = controller.isLaunching
val viewRoot = controller.transitionContainer.viewRootImpl
- val skipReparenting = skipReparentTransaction || viewRoot == null
+ val skipReparenting =
+ skipReparentTransaction || !window.leash.isValid || viewRoot == null
if (moveTransitionAnimationLayer() && isEligibleForReparenting && !skipReparenting) {
reparent = true
}
diff --git a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt
index 2b8fe39c4870..16a8f987ba83 100644
--- a/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt
+++ b/packages/SystemUI/compose/features/src/com/android/systemui/communal/ui/compose/CommunalContainer.kt
@@ -1,5 +1,6 @@
package com.android.systemui.communal.ui.compose
+import android.content.res.Configuration
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
@@ -15,6 +16,7 @@ import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
@@ -26,6 +28,7 @@ import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.disabled
@@ -55,6 +58,7 @@ import com.android.systemui.communal.ui.compose.Dimensions.Companion.SlideOffset
import com.android.systemui.communal.ui.compose.extensions.allowGestures
import com.android.systemui.communal.ui.viewmodel.CommunalViewModel
import com.android.systemui.communal.util.CommunalColors
+import com.android.systemui.keyguard.domain.interactor.FromGlanceableHubTransitionInteractor.Companion.TO_LOCKSCREEN_DURATION
import com.android.systemui.keyguard.domain.interactor.FromPrimaryBouncerTransitionInteractor.Companion.TO_GONE_DURATION
import com.android.systemui.scene.shared.model.SceneDataSourceDelegator
import com.android.systemui.scene.ui.composable.SceneTransitionLayoutDataSource
@@ -98,6 +102,17 @@ val sceneTransitionsV2 = transitions {
spec = tween(durationMillis = TO_GONE_DURATION.toInt(DurationUnit.MILLISECONDS))
fade(AllElements)
}
+ to(CommunalScenes.Blank, key = CommunalTransitionKeys.SwipeInLandscape) {
+ spec = tween(durationMillis = TO_LOCKSCREEN_DURATION.toInt(DurationUnit.MILLISECONDS))
+ translate(Communal.Elements.Grid, Edge.End)
+ timestampRange(endMillis = 167) {
+ fade(Communal.Elements.Grid)
+ fade(Communal.Elements.IndicationArea)
+ fade(Communal.Elements.LockIcon)
+ fade(Communal.Elements.StatusBar)
+ }
+ timestampRange(startMillis = 167, endMillis = 500) { fade(Communal.Elements.Scrim) }
+ }
to(CommunalScenes.Blank, key = CommunalTransitionKeys.Swipe) {
spec = tween(durationMillis = TransitionDuration.TO_GLANCEABLE_HUB_DURATION_MS)
translate(Communal.Elements.Grid, Edge.End)
@@ -214,6 +229,9 @@ fun CommunalContainer(
val blurRadius = with(LocalDensity.current) { viewModel.blurRadiusPx.toDp() }
+ val swipeFromHubInLandscape by
+ viewModel.swipeFromHubInLandscape.collectAsStateWithLifecycle(false)
+
SceneTransitionLayout(
state = state,
modifier = modifier.fillMaxSize().thenIf(isUiBlurred) { Modifier.blur(blurRadius) },
@@ -241,7 +259,14 @@ fun CommunalContainer(
userActions =
mapOf(
Swipe.End to
- UserActionResult(CommunalScenes.Blank, CommunalTransitionKeys.Swipe)
+ UserActionResult(
+ CommunalScenes.Blank,
+ if (swipeFromHubInLandscape) {
+ CommunalTransitionKeys.SwipeInLandscape
+ } else {
+ CommunalTransitionKeys.Swipe
+ },
+ )
),
) {
CommunalScene(
@@ -258,6 +283,20 @@ fun CommunalContainer(
Box(modifier = Modifier.fillMaxSize().allowGestures(touchesAllowed))
}
+/** Listens to orientation changes on communal scene and reset when scene is disposed. */
+@Composable
+fun ObserveOrientationChange(viewModel: CommunalViewModel) {
+ val configuration = LocalConfiguration.current
+
+ LaunchedEffect(configuration.orientation) {
+ viewModel.onOrientationChange(configuration.orientation)
+ }
+
+ DisposableEffect(Unit) {
+ onDispose { viewModel.onOrientationChange(Configuration.ORIENTATION_UNDEFINED) }
+ }
+}
+
/** Scene containing the glanceable hub UI. */
@Composable
fun ContentScope.CommunalScene(
@@ -269,6 +308,8 @@ fun ContentScope.CommunalScene(
) {
val isFocusable by viewModel.isFocusable.collectAsStateWithLifecycle(initialValue = false)
+ // Observe screen rotation while Communal Scene is active.
+ ObserveOrientationChange(viewModel)
Box(
modifier =
Modifier.element(Communal.Elements.Scrim)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/clipboardoverlay/ActionIntentCreatorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/clipboardoverlay/ActionIntentCreatorTest.kt
index 652a2ff21e9b..87eea82ef30d 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/clipboardoverlay/ActionIntentCreatorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/clipboardoverlay/ActionIntentCreatorTest.kt
@@ -19,12 +19,17 @@ package com.android.systemui.clipboardoverlay
import android.content.ClipData
import android.content.ComponentName
import android.content.Intent
+import android.content.pm.ActivityInfo
+import android.content.pm.PackageInfo
+import android.content.pm.PackageManager
import android.net.Uri
import android.text.SpannableString
import androidx.test.filters.SmallTest
import androidx.test.runner.AndroidJUnit4
import com.android.systemui.SysuiTestCase
import com.android.systemui.res.R
+import com.android.systemui.util.mockito.eq
+import com.android.systemui.util.mockito.mock
import kotlinx.coroutines.test.TestCoroutineScheduler
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
@@ -33,6 +38,8 @@ import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyInt
+import org.mockito.kotlin.whenever
@SmallTest
@RunWith(AndroidJUnit4::class)
@@ -40,8 +47,10 @@ class ActionIntentCreatorTest : SysuiTestCase() {
private val scheduler = TestCoroutineScheduler()
private val mainDispatcher = UnconfinedTestDispatcher(scheduler)
private val testScope = TestScope(mainDispatcher)
+ val packageManager = mock<PackageManager>()
- val creator = ActionIntentCreator(testScope.backgroundScope)
+ val creator =
+ ActionIntentCreator(context, packageManager, testScope.backgroundScope, mainDispatcher)
@Test
fun test_getTextEditorIntent() {
@@ -73,7 +82,7 @@ class ActionIntentCreatorTest : SysuiTestCase() {
}
@Test
- fun test_getImageEditIntent() = runTest {
+ fun test_getImageEditIntent_noDefault() = runTest {
context.getOrCreateTestableResources().addOverride(R.string.config_screenshotEditor, "")
val fakeUri = Uri.parse("content://foo")
var intent = creator.getImageEditIntent(fakeUri, context)
@@ -83,18 +92,82 @@ class ActionIntentCreatorTest : SysuiTestCase() {
assertEquals(null, intent.component)
assertEquals("clipboard", intent.getStringExtra("edit_source"))
assertFlags(intent, EXTERNAL_INTENT_FLAGS)
+ }
+
+ @Test
+ fun test_getImageEditIntent_defaultProvided() = runTest {
+ val fakeUri = Uri.parse("content://foo")
- // try again with an editor component
val fakeComponent =
ComponentName("com.android.remotecopy", "com.android.remotecopy.RemoteCopyActivity")
context
.getOrCreateTestableResources()
.addOverride(R.string.config_screenshotEditor, fakeComponent.flattenToString())
- intent = creator.getImageEditIntent(fakeUri, context)
+ val intent = creator.getImageEditIntent(fakeUri, context)
assertEquals(fakeComponent, intent.component)
}
@Test
+ fun test_getImageEditIntent_preferredProvidedButDisabled() = runTest {
+ val fakeUri = Uri.parse("content://foo")
+
+ val defaultComponent = ComponentName("com.android.foo", "com.android.foo.Something")
+ val preferredComponent = ComponentName("com.android.bar", "com.android.bar.Something")
+
+ val packageInfo =
+ PackageInfo().apply {
+ activities = arrayOf() // no activities
+ }
+ whenever(packageManager.getPackageInfo(eq(preferredComponent.packageName), anyInt()))
+ .thenReturn(packageInfo)
+
+ context
+ .getOrCreateTestableResources()
+ .addOverride(R.string.config_screenshotEditor, defaultComponent.flattenToString())
+ context
+ .getOrCreateTestableResources()
+ .addOverride(
+ R.string.config_preferredScreenshotEditor,
+ preferredComponent.flattenToString(),
+ )
+ val intent = creator.getImageEditIntent(fakeUri, context)
+ assertEquals(defaultComponent, intent.component)
+ }
+
+ @Test
+ fun test_getImageEditIntent_preferredProvided() = runTest {
+ val fakeUri = Uri.parse("content://foo")
+
+ val defaultComponent = ComponentName("com.android.foo", "com.android.foo.Something")
+ val preferredComponent = ComponentName("com.android.bar", "com.android.bar.Something")
+
+ val packageInfo =
+ PackageInfo().apply {
+ activities =
+ arrayOf(
+ ActivityInfo().apply {
+ packageName = preferredComponent.packageName
+ name = preferredComponent.className
+ }
+ )
+ }
+ whenever(packageManager.getPackageInfo(eq(preferredComponent.packageName), anyInt()))
+ .thenReturn(packageInfo)
+
+ context
+ .getOrCreateTestableResources()
+ .addOverride(R.string.config_screenshotEditor, defaultComponent.flattenToString())
+ context
+ .getOrCreateTestableResources()
+ .addOverride(
+ R.string.config_preferredScreenshotEditor,
+ preferredComponent.flattenToString(),
+ )
+ val intent = creator.getImageEditIntent(fakeUri, context)
+ assertEquals(preferredComponent, intent.component)
+ }
+
+ @Test
fun test_getShareIntent_plaintext() {
val clipData = ClipData.newPlainText("Test", "Test Item")
val intent = creator.getShareIntent(clipData, context)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalAutoOpenInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalAutoOpenInteractorTest.kt
index 856a62e3f5a7..a6be3ce43b6a 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalAutoOpenInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalAutoOpenInteractorTest.kt
@@ -16,9 +16,11 @@
package com.android.systemui.communal.domain.interactor
+import android.platform.test.annotations.EnableFlags
import android.provider.Settings
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
+import com.android.systemui.Flags.FLAG_GLANCEABLE_HUB_V2
import com.android.systemui.SysuiTestCase
import com.android.systemui.common.data.repository.batteryRepository
import com.android.systemui.common.data.repository.fake
@@ -47,6 +49,7 @@ import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
+@EnableFlags(FLAG_GLANCEABLE_HUB_V2)
class CommunalAutoOpenInteractorTest : SysuiTestCase() {
private val kosmos = testKosmos().useUnconfinedTestDispatcher()
@@ -54,6 +57,7 @@ class CommunalAutoOpenInteractorTest : SysuiTestCase() {
@Before
fun setUp() {
+ kosmos.setCommunalV2ConfigEnabled(true)
runBlocking { kosmos.fakeUserRepository.asMainUser() }
with(kosmos.fakeSettings) {
putIntForUser(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractorTest.kt
index dc21f0692c9e..7bdac476641b 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractorTest.kt
@@ -16,6 +16,8 @@
package com.android.systemui.communal.domain.interactor
+import android.content.res.Configuration.ORIENTATION_LANDSCAPE
+import android.content.res.Configuration.ORIENTATION_PORTRAIT
import android.platform.test.annotations.DisableFlags
import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.FlagsParameterization
@@ -33,11 +35,15 @@ import com.android.systemui.flags.andSceneContainer
import com.android.systemui.kosmos.testScope
import com.android.systemui.scene.initialSceneKey
import com.android.systemui.scene.shared.model.Scenes
+import com.android.systemui.statusbar.policy.KeyguardStateController
+import com.android.systemui.statusbar.policy.keyguardStateController
import com.android.systemui.testKosmos
import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.advanceTimeBy
+import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Test
import org.junit.runner.RunWith
@@ -46,9 +52,11 @@ import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
+import org.mockito.kotlin.whenever
import platform.test.runner.parameterized.ParameterizedAndroidJunit4
import platform.test.runner.parameterized.Parameters
+@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(ParameterizedAndroidJunit4::class)
class CommunalSceneInteractorTest(flags: FlagsParameterization) : SysuiTestCase() {
@@ -70,6 +78,7 @@ class CommunalSceneInteractorTest(flags: FlagsParameterization) : SysuiTestCase(
private val repository = kosmos.communalSceneRepository
private val underTest by lazy { kosmos.communalSceneInteractor }
+ private val keyguardStateController: KeyguardStateController = kosmos.keyguardStateController
@DisableFlags(FLAG_SCENE_CONTAINER)
@Test
@@ -551,4 +560,57 @@ class CommunalSceneInteractorTest(flags: FlagsParameterization) : SysuiTestCase(
transitionState.value = ObservableTransitionState.Idle(Scenes.Lockscreen)
assertThat(isCommunalVisible).isEqualTo(false)
}
+
+ @Test
+ fun willRotateToPortrait_whenKeyguardRotationNotAllowed() =
+ testScope.runTest {
+ whenever(keyguardStateController.isKeyguardScreenRotationAllowed()).thenReturn(false)
+ val willRotateToPortrait by collectLastValue(underTest.willRotateToPortrait)
+
+ repository.setCommunalContainerOrientation(ORIENTATION_LANDSCAPE)
+ runCurrent()
+
+ assertThat(willRotateToPortrait).isEqualTo(true)
+
+ repository.setCommunalContainerOrientation(ORIENTATION_PORTRAIT)
+ runCurrent()
+
+ assertThat(willRotateToPortrait).isEqualTo(false)
+ }
+
+ @Test
+ fun willRotateToPortrait_isFalse_whenKeyguardRotationIsAllowed() =
+ testScope.runTest {
+ whenever(keyguardStateController.isKeyguardScreenRotationAllowed()).thenReturn(true)
+ val willRotateToPortrait by collectLastValue(underTest.willRotateToPortrait)
+
+ repository.setCommunalContainerOrientation(ORIENTATION_LANDSCAPE)
+ runCurrent()
+
+ assertThat(willRotateToPortrait).isEqualTo(false)
+
+ repository.setCommunalContainerOrientation(ORIENTATION_PORTRAIT)
+ runCurrent()
+
+ assertThat(willRotateToPortrait).isEqualTo(false)
+ }
+
+ @Test
+ fun rotatedToPortrait() =
+ testScope.runTest {
+ val rotatedToPortrait by collectLastValue(underTest.rotatedToPortrait)
+ assertThat(rotatedToPortrait).isEqualTo(false)
+
+ repository.setCommunalContainerOrientation(ORIENTATION_PORTRAIT)
+ runCurrent()
+ assertThat(rotatedToPortrait).isEqualTo(false)
+
+ repository.setCommunalContainerOrientation(ORIENTATION_LANDSCAPE)
+ runCurrent()
+ assertThat(rotatedToPortrait).isEqualTo(false)
+
+ repository.setCommunalContainerOrientation(ORIENTATION_PORTRAIT)
+ runCurrent()
+ assertThat(rotatedToPortrait).isEqualTo(true)
+ }
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalSettingsInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalSettingsInteractorTest.kt
index d6f7145bd770..c671aed1f4a1 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalSettingsInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/domain/interactor/CommunalSettingsInteractorTest.kt
@@ -21,9 +21,11 @@ import android.app.admin.devicePolicyManager
import android.content.Intent
import android.content.pm.UserInfo
import android.os.UserManager
+import android.platform.test.annotations.EnableFlags
import android.provider.Settings
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
+import com.android.systemui.Flags.FLAG_GLANCEABLE_HUB_V2
import com.android.systemui.SysuiTestCase
import com.android.systemui.broadcast.broadcastDispatcher
import com.android.systemui.communal.shared.model.WhenToStartHub
@@ -86,8 +88,10 @@ class CommunalSettingsInteractorTest : SysuiTestCase() {
}
@Test
+ @EnableFlags(FLAG_GLANCEABLE_HUB_V2)
fun whenToStartHub_matchesRepository() =
kosmos.runTest {
+ setCommunalV2ConfigEnabled(true)
fakeSettings.putIntForUser(
Settings.Secure.WHEN_TO_START_GLANCEABLE_HUB,
Settings.Secure.GLANCEABLE_HUB_START_CHARGING,
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/posturing/domain/interactor/PosturingInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/posturing/domain/interactor/PosturingInteractorTest.kt
index b4708d97c4c3..80f0005cb73f 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/posturing/domain/interactor/PosturingInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/communal/posturing/domain/interactor/PosturingInteractorTest.kt
@@ -53,7 +53,7 @@ class PosturingInteractorTest : SysuiTestCase() {
private val kosmos = testKosmos().useUnconfinedTestDispatcher()
- private val underTest by lazy { kosmos.posturingInteractor }
+ private val Kosmos.underTest by Kosmos.Fixture { kosmos.posturingInteractor }
@Test
fun testNoDebugOverride() =
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryFaceAuthInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryFaceAuthInteractorTest.kt
index d2d8ab9d5cb7..e6153e8ab337 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryFaceAuthInteractorTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/interactor/DeviceEntryFaceAuthInteractorTest.kt
@@ -20,6 +20,8 @@ import android.content.pm.UserInfo
import android.hardware.biometrics.BiometricFaceConstants
import android.hardware.biometrics.BiometricSourceType
import android.os.PowerManager
+import android.platform.test.annotations.EnableFlags
+import android.service.dreams.Flags.FLAG_DREAMS_V2
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.compose.animation.scene.ObservableTransitionState
@@ -157,6 +159,33 @@ class DeviceEntryFaceAuthInteractorTest : SysuiTestCase() {
}
@Test
+ @EnableFlags(FLAG_DREAMS_V2)
+ fun faceAuthIsRequestedWhenTransitioningFromDreamToLockscreen() =
+ testScope.runTest {
+ underTest.start()
+ runCurrent()
+
+ powerInteractor.setAwakeForTest(reason = PowerManager.WAKE_REASON_LID)
+ faceWakeUpTriggersConfig.setTriggerFaceAuthOnWakeUpFrom(
+ setOf(WakeSleepReason.LID.powerManagerWakeReason)
+ )
+
+ keyguardTransitionRepository.sendTransitionStep(
+ TransitionStep(
+ KeyguardState.DREAMING,
+ KeyguardState.LOCKSCREEN,
+ transitionState = TransitionState.STARTED,
+ )
+ )
+
+ runCurrent()
+ assertThat(faceAuthRepository.runningAuthRequest.value)
+ .isEqualTo(
+ Pair(FaceAuthUiEvent.FACE_AUTH_UPDATED_KEYGUARD_VISIBILITY_CHANGED, true)
+ )
+ }
+
+ @Test
fun whenFaceIsLockedOutAnyAttemptsToTriggerFaceAuthMustProvideLockoutError() =
testScope.runTest {
underTest.start()
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/ui/viewmodel/UdfpsAccessibilityOverlayViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/ui/viewmodel/UdfpsAccessibilityOverlayViewModelTest.kt
index 90500839c8ad..a7810a69265a 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/ui/viewmodel/UdfpsAccessibilityOverlayViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/deviceentry/domain/ui/viewmodel/UdfpsAccessibilityOverlayViewModelTest.kt
@@ -16,13 +16,17 @@
package com.android.systemui.deviceentry.domain.ui.viewmodel
+import android.graphics.Point
import android.platform.test.flag.junit.FlagsParameterization
+import android.view.MotionEvent
+import android.view.View
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
import com.android.systemui.accessibility.data.repository.fakeAccessibilityRepository
import com.android.systemui.biometrics.data.repository.fingerprintPropertyRepository
+import com.android.systemui.biometrics.udfpsUtils
import com.android.systemui.coroutines.collectLastValue
-import com.android.systemui.deviceentry.data.repository.fakeDeviceEntryRepository
+import com.android.systemui.deviceentry.data.ui.viewmodel.alternateBouncerUdfpsAccessibilityOverlayViewModel
import com.android.systemui.deviceentry.data.ui.viewmodel.deviceEntryUdfpsAccessibilityOverlayViewModel
import com.android.systemui.deviceentry.ui.viewmodel.DeviceEntryUdfpsAccessibilityOverlayViewModel
import com.android.systemui.flags.Flags.FULL_SCREEN_USER_SWITCHER
@@ -34,6 +38,7 @@ import com.android.systemui.keyguard.data.repository.fakeKeyguardTransitionRepos
import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.keyguard.shared.model.TransitionState
import com.android.systemui.keyguard.shared.model.TransitionStep
+import com.android.systemui.keyguard.ui.viewmodel.accessibilityActionsViewModelKosmos
import com.android.systemui.keyguard.ui.viewmodel.fakeDeviceEntryIconViewModelTransition
import com.android.systemui.kosmos.testScope
import com.android.systemui.res.R
@@ -41,14 +46,22 @@ import com.android.systemui.shade.shadeTestUtil
import com.android.systemui.testKosmos
import com.google.common.truth.Truth.assertThat
import kotlin.test.Test
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Before
import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers.anyBoolean
+import org.mockito.ArgumentMatchers.anyInt
+import org.mockito.kotlin.any
+import org.mockito.kotlin.eq
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.whenever
import platform.test.runner.parameterized.ParameterizedAndroidJunit4
import platform.test.runner.parameterized.Parameters
+@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(ParameterizedAndroidJunit4::class)
class UdfpsAccessibilityOverlayViewModelTest(flags: FlagsParameterization) : SysuiTestCase() {
@@ -63,7 +76,6 @@ class UdfpsAccessibilityOverlayViewModelTest(flags: FlagsParameterization) : Sys
private val keyguardTransitionRepository = kosmos.fakeKeyguardTransitionRepository
private val fingerprintPropertyRepository = kosmos.fingerprintPropertyRepository
private val deviceEntryFingerprintAuthRepository = kosmos.deviceEntryFingerprintAuthRepository
- private val deviceEntryRepository = kosmos.fakeDeviceEntryRepository
private val shadeTestUtil by lazy { kosmos.shadeTestUtil }
@@ -83,6 +95,22 @@ class UdfpsAccessibilityOverlayViewModelTest(flags: FlagsParameterization) : Sys
@Before
fun setup() {
+ whenever(kosmos.udfpsUtils.isWithinSensorArea(any(), any(), any())).thenReturn(false)
+ whenever(
+ kosmos.udfpsUtils.getTouchInNativeCoordinates(anyInt(), any(), any(), anyBoolean())
+ )
+ .thenReturn(Point(0, 0))
+ whenever(
+ kosmos.udfpsUtils.onTouchOutsideOfSensorArea(
+ anyBoolean(),
+ eq(null),
+ anyInt(),
+ anyInt(),
+ any(),
+ anyBoolean(),
+ )
+ )
+ .thenReturn("Move left")
underTest = kosmos.deviceEntryUdfpsAccessibilityOverlayViewModel
overrideResource(R.integer.udfps_padding_debounce_duration, 0)
}
@@ -101,6 +129,55 @@ class UdfpsAccessibilityOverlayViewModelTest(flags: FlagsParameterization) : Sys
}
@Test
+ fun contentDescription_setOnUdfpsTouchOutsideSensorArea() =
+ testScope.runTest {
+ val contentDescription by collectLastValue(underTest.contentDescription)
+ setupVisibleStateOnLockscreen()
+ underTest.onHoverEvent(mock<View>(), mock<MotionEvent>())
+ runCurrent()
+ assertThat(contentDescription).isEqualTo("Move left")
+ }
+
+ @Test
+ fun clearAccessibilityOverlayMessageReason_updatesWhenFocusChangesFromUdfpsOverlayToLockscreen() =
+ testScope.runTest {
+ val clearAccessibilityOverlayMessageReason by
+ collectLastValue(underTest.clearAccessibilityOverlayMessageReason)
+ val contentDescription by collectLastValue(underTest.contentDescription)
+ setupVisibleStateOnLockscreen()
+ kosmos.accessibilityActionsViewModelKosmos.clearUdfpsAccessibilityOverlayMessage("test")
+ runCurrent()
+ assertThat(clearAccessibilityOverlayMessageReason).isEqualTo("test")
+
+ // UdfpsAccessibilityOverlayViewBinder collects clearAccessibilityOverlayMessageReason
+ // and calls
+ // viewModel.setContentDescription(null) - mock this here
+ underTest.setContentDescription(null)
+ runCurrent()
+ assertThat(contentDescription).isNull()
+ }
+
+ @Test
+ fun clearAccessibilityOverlayMessageReason_updatesAfterUdfpsOverlayFocusOnAlternateBouncer() =
+ testScope.runTest {
+ val clearAccessibilityOverlayMessageReason by
+ collectLastValue(underTest.clearAccessibilityOverlayMessageReason)
+ val contentDescription by collectLastValue(underTest.contentDescription)
+ setupVisibleStateOnLockscreen()
+ kosmos.alternateBouncerUdfpsAccessibilityOverlayViewModel
+ .clearUdfpsAccessibilityOverlayMessage("test")
+ runCurrent()
+ assertThat(clearAccessibilityOverlayMessageReason).isEqualTo("test")
+
+ // UdfpsAccessibilityOverlayViewBinder collects clearAccessibilityOverlayMessageReason
+ // and calls
+ // viewModel.setContentDescription(null) - mock this here
+ underTest.setContentDescription(null)
+ runCurrent()
+ assertThat(contentDescription).isNull()
+ }
+
+ @Test
fun touchExplorationNotEnabled_overlayNotVisible() =
testScope.runTest {
val visible by collectLastValue(underTest.visible)
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyboard/shortcut/data/source/TestShortcuts.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyboard/shortcut/data/source/TestShortcuts.kt
index af6c65ec6d6d..1f74ad496bbb 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyboard/shortcut/data/source/TestShortcuts.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyboard/shortcut/data/source/TestShortcuts.kt
@@ -533,7 +533,7 @@ object TestShortcuts {
val expectedShortcutCategoriesWithSimpleShortcutCombination =
listOf(
- simpleShortcutCategory(System, "System apps", "Open assistant"),
+ simpleShortcutCategory(System, "System apps", "Open digital assistant"),
simpleShortcutCategory(System, "System controls", "Go to home screen"),
simpleShortcutCategory(System, "System apps", "Open settings"),
simpleShortcutCategory(System, "System controls", "Lock screen"),
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerTransitionViewModelTest.kt
new file mode 100644
index 000000000000..c515fc394bda
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerTransitionViewModelTest.kt
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.systemui.keyguard.ui.viewmodel
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectValues
+import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.keyguard.shared.model.TransitionState
+import com.android.systemui.keyguard.shared.model.TransitionState.RUNNING
+import com.android.systemui.keyguard.shared.model.TransitionStep
+import com.android.systemui.keyguard.ui.transitions.blurConfig
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.testKosmos
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class DreamingToPrimaryBouncerTransitionViewModelTest : SysuiTestCase() {
+ private val kosmos = testKosmos()
+ private val testScope = kosmos.testScope
+ private val underTest by lazy { kosmos.dreamingToPrimaryBouncerViewModel }
+
+ @Test
+ fun dreamingToPrimaryBouncerChangesBlurToMax() =
+ testScope.runTest {
+ val values by collectValues(underTest.windowBlurRadius)
+
+ kosmos.keyguardWindowBlurTestUtil.assertTransitionToBlurRadius(
+ transitionProgress = listOf(0.0f, 0.0f, 0.3f, 0.4f, 0.5f, 1.0f),
+ startValue = kosmos.blurConfig.maxBlurRadiusPx,
+ endValue = kosmos.blurConfig.maxBlurRadiusPx,
+ transitionFactory = ::step,
+ actualValuesProvider = { values },
+ checkInterpolatedValues = false,
+ )
+ }
+
+ private fun step(value: Float, transitionState: TransitionState = RUNNING) =
+ TransitionStep(
+ from = KeyguardState.DREAMING,
+ to = KeyguardState.PRIMARY_BOUNCER,
+ value = value,
+ transitionState = transitionState,
+ ownerName = "dreamingToPrimaryBouncerTransitionViewModelTest",
+ )
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModelTest.kt
index 3ab920a46084..cdd093a410df 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModelTest.kt
@@ -17,11 +17,20 @@
package com.android.systemui.keyguard.ui.viewmodel
import android.content.res.Configuration
+import android.content.res.mainResources
+import android.platform.test.annotations.DisableFlags
+import android.platform.test.annotations.EnableFlags
+import android.platform.test.flag.junit.FlagsParameterization
import android.util.LayoutDirection
-import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
+import com.android.compose.animation.scene.ObservableTransitionState
+import com.android.systemui.Flags.FLAG_GLANCEABLE_HUB_V2
import com.android.systemui.SysuiTestCase
import com.android.systemui.common.ui.data.repository.fakeConfigurationRepository
+import com.android.systemui.communal.data.repository.communalSceneRepository
+import com.android.systemui.communal.domain.interactor.communalSceneInteractor
+import com.android.systemui.communal.domain.interactor.setCommunalV2ConfigEnabled
+import com.android.systemui.communal.shared.model.CommunalScenes
import com.android.systemui.flags.DisableSceneContainer
import com.android.systemui.keyguard.data.repository.fakeKeyguardTransitionRepository
import com.android.systemui.keyguard.shared.model.KeyguardState
@@ -29,30 +38,53 @@ import com.android.systemui.keyguard.shared.model.TransitionState
import com.android.systemui.keyguard.shared.model.TransitionStep
import com.android.systemui.keyguard.ui.transitions.blurConfig
import com.android.systemui.kosmos.collectValues
+import com.android.systemui.kosmos.runCurrent
import com.android.systemui.kosmos.runTest
import com.android.systemui.kosmos.testScope
import com.android.systemui.res.R
+import com.android.systemui.statusbar.policy.KeyguardStateController
+import com.android.systemui.statusbar.policy.keyguardStateController
import com.android.systemui.testKosmos
import com.google.common.collect.Range
import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.flowOf
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
+import platform.test.runner.parameterized.ParameterizedAndroidJunit4
+import platform.test.runner.parameterized.Parameters
@SmallTest
-@RunWith(AndroidJUnit4::class)
-class GlanceableHubToLockscreenTransitionViewModelTest : SysuiTestCase() {
- val kosmos = testKosmos()
+@RunWith(ParameterizedAndroidJunit4::class)
+class GlanceableHubToLockscreenTransitionViewModelTest(flags: FlagsParameterization) :
+ SysuiTestCase() {
+ val kosmos = testKosmos().apply { mainResources = mContext.orCreateTestableResources.resources }
val testScope = kosmos.testScope
val keyguardTransitionRepository = kosmos.fakeKeyguardTransitionRepository
val configurationRepository = kosmos.fakeConfigurationRepository
+ val keyguardStateController: KeyguardStateController = kosmos.keyguardStateController
val underTest by lazy { kosmos.glanceableHubToLockscreenTransitionViewModel }
+ companion object {
+ @JvmStatic
+ @Parameters(name = "{0}")
+ fun getParams(): List<FlagsParameterization> {
+ return FlagsParameterization.allCombinationsOf(FLAG_GLANCEABLE_HUB_V2)
+ }
+ }
+
+ init {
+ mSetFlagsRule.setFlagsParameterization(flags)
+ }
+
@Test
fun lockscreenFadeIn() =
kosmos.runTest {
+ communalSceneInteractor.changeScene(CommunalScenes.Communal, "test")
+
val values by collectValues(underTest.keyguardAlpha)
assertThat(values).isEmpty()
@@ -79,6 +111,116 @@ class GlanceableHubToLockscreenTransitionViewModelTest : SysuiTestCase() {
}
@Test
+ @EnableFlags(FLAG_GLANCEABLE_HUB_V2)
+ fun lockscreenFadeIn_fromHubInLandscape() =
+ kosmos.runTest {
+ kosmos.setCommunalV2ConfigEnabled(true)
+ whenever(keyguardStateController.isKeyguardScreenRotationAllowed).thenReturn(false)
+ communalSceneInteractor.changeScene(CommunalScenes.Communal, "test")
+ communalSceneRepository.setCommunalContainerOrientation(
+ Configuration.ORIENTATION_LANDSCAPE
+ )
+
+ val values by collectValues(underTest.keyguardAlpha)
+ assertThat(values).isEmpty()
+
+ // Exit hub to lockscreen
+ val progress = MutableStateFlow(0f)
+ val transitionState =
+ MutableStateFlow(
+ ObservableTransitionState.Transition(
+ fromScene = CommunalScenes.Communal,
+ toScene = CommunalScenes.Blank,
+ currentScene = flowOf(CommunalScenes.Blank),
+ progress = progress,
+ isInitiatedByUserInput = false,
+ isUserInputOngoing = flowOf(false),
+ )
+ )
+ communalSceneInteractor.setTransitionState(transitionState)
+ progress.value = .2f
+
+ // Still in landscape
+ keyguardTransitionRepository.sendTransitionSteps(
+ listOf(
+ step(0f, TransitionState.STARTED),
+ step(0.1f),
+ // start here..
+ step(0.5f),
+ ),
+ testScope,
+ )
+
+ // Communal container is rotated to portrait
+ communalSceneRepository.setCommunalContainerOrientation(
+ Configuration.ORIENTATION_PORTRAIT
+ )
+ runCurrent()
+
+ keyguardTransitionRepository.sendTransitionSteps(
+ listOf(
+ step(0.6f),
+ step(0.7f),
+ // should stop here..
+ step(0.8f),
+ step(1f),
+ ),
+ testScope,
+ )
+ // Scene transition finished.
+ progress.value = 1f
+ keyguardTransitionRepository.sendTransitionSteps(
+ listOf(step(1f, TransitionState.FINISHED)),
+ testScope,
+ )
+
+ assertThat(values).hasSize(4)
+ // onStart
+ assertThat(values[0]).isEqualTo(0f)
+ assertThat(values[1]).isEqualTo(0f)
+ assertThat(values[2]).isEqualTo(1f)
+ // onFinish
+ assertThat(values[3]).isEqualTo(1f)
+ }
+
+ @Test
+ @DisableFlags(FLAG_GLANCEABLE_HUB_V2)
+ fun lockscreenFadeIn_v2FlagDisabledAndFromHubInLandscape() =
+ kosmos.runTest {
+ whenever(keyguardStateController.isKeyguardScreenRotationAllowed).thenReturn(false)
+ communalSceneInteractor.changeScene(CommunalScenes.Communal, "test")
+ // Rotation is not enabled so communal container is in portrait.
+ communalSceneRepository.setCommunalContainerOrientation(
+ Configuration.ORIENTATION_PORTRAIT
+ )
+
+ val values by collectValues(underTest.keyguardAlpha)
+ assertThat(values).isEmpty()
+
+ // Exit hub to lockscreen
+ keyguardTransitionRepository.sendTransitionSteps(
+ listOf(
+ step(0f, TransitionState.STARTED),
+ // Should start running here...
+ step(0.1f),
+ step(0.2f),
+ step(0.3f),
+ step(0.4f),
+ // ...up to here
+ step(0.5f),
+ step(0.6f),
+ step(0.7f),
+ step(0.8f),
+ step(1f),
+ ),
+ testScope,
+ )
+
+ assertThat(values).hasSize(4)
+ values.forEach { assertThat(it).isIn(Range.closed(0f, 1f)) }
+ }
+
+ @Test
fun lockscreenTranslationX() =
kosmos.runTest {
val config: Configuration = mock()
@@ -89,6 +231,8 @@ class GlanceableHubToLockscreenTransitionViewModelTest : SysuiTestCase() {
R.dimen.hub_to_lockscreen_transition_lockscreen_translation_x,
100,
)
+ communalSceneInteractor.changeScene(CommunalScenes.Communal, "test")
+
val values by collectValues(underTest.keyguardTranslationX)
assertThat(values).isEmpty()
@@ -108,6 +252,44 @@ class GlanceableHubToLockscreenTransitionViewModelTest : SysuiTestCase() {
}
@Test
+ @EnableFlags(FLAG_GLANCEABLE_HUB_V2)
+ fun lockscreenTranslationX_fromHubInLandscape() =
+ kosmos.runTest {
+ kosmos.setCommunalV2ConfigEnabled(true)
+ val config: Configuration = mock()
+ whenever(config.layoutDirection).thenReturn(LayoutDirection.LTR)
+ configurationRepository.onConfigurationChange(config)
+
+ configurationRepository.setDimensionPixelSize(
+ R.dimen.hub_to_lockscreen_transition_lockscreen_translation_x,
+ 100,
+ )
+ whenever(keyguardStateController.isKeyguardScreenRotationAllowed).thenReturn(false)
+
+ communalSceneInteractor.changeScene(CommunalScenes.Communal, "test")
+ communalSceneRepository.setCommunalContainerOrientation(
+ Configuration.ORIENTATION_LANDSCAPE
+ )
+
+ val values by collectValues(underTest.keyguardTranslationX)
+ assertThat(values).isEmpty()
+
+ keyguardTransitionRepository.sendTransitionSteps(
+ listOf(
+ step(0f, TransitionState.STARTED),
+ step(0.3f),
+ step(0.5f),
+ step(0.7f),
+ step(1f),
+ step(1f, TransitionState.FINISHED),
+ ),
+ testScope,
+ )
+ // no translation-x animation
+ values.forEach { assertThat(it.value).isEqualTo(0f) }
+ }
+
+ @Test
fun lockscreenTranslationX_resetsAfterCancellation() =
kosmos.runTest {
val config: Configuration = mock()
@@ -118,6 +300,9 @@ class GlanceableHubToLockscreenTransitionViewModelTest : SysuiTestCase() {
R.dimen.hub_to_lockscreen_transition_lockscreen_translation_x,
100,
)
+
+ communalSceneInteractor.changeScene(CommunalScenes.Communal, "test")
+
val values by collectValues(underTest.keyguardTranslationX)
assertThat(values).isEmpty()
@@ -137,6 +322,42 @@ class GlanceableHubToLockscreenTransitionViewModelTest : SysuiTestCase() {
}
@Test
+ @EnableFlags(FLAG_GLANCEABLE_HUB_V2)
+ fun lockscreenTranslationX_resetsAfterCancellation_fromHubInLandscape() =
+ kosmos.runTest {
+ kosmos.setCommunalV2ConfigEnabled(true)
+ val config: Configuration = mock()
+ whenever(config.layoutDirection).thenReturn(LayoutDirection.LTR)
+ configurationRepository.onConfigurationChange(config)
+
+ configurationRepository.setDimensionPixelSize(
+ R.dimen.hub_to_lockscreen_transition_lockscreen_translation_x,
+ 100,
+ )
+ whenever(keyguardStateController.isKeyguardScreenRotationAllowed).thenReturn(false)
+
+ communalSceneInteractor.changeScene(CommunalScenes.Communal, "test")
+ communalSceneRepository.setCommunalContainerOrientation(
+ Configuration.ORIENTATION_LANDSCAPE
+ )
+
+ val values by collectValues(underTest.keyguardTranslationX)
+ assertThat(values).isEmpty()
+
+ keyguardTransitionRepository.sendTransitionSteps(
+ listOf(
+ step(0f, TransitionState.STARTED),
+ step(0.3f),
+ step(0.6f),
+ step(0.9f, TransitionState.CANCELED),
+ ),
+ testScope,
+ )
+ // no translation-x animation
+ values.forEach { assertThat(it.value).isEqualTo(0f) }
+ }
+
+ @Test
@DisableSceneContainer
fun blurBecomesMinValueImmediately() =
kosmos.runTest {
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
index fe213a6ebbf0..71e09d982494 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/KeyguardRootViewModelTest.kt
@@ -17,12 +17,19 @@
package com.android.systemui.keyguard.ui.viewmodel
+import android.content.res.Configuration
+import android.content.res.mainResources
+import android.platform.test.annotations.DisableFlags
+import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.FlagsParameterization
import android.view.View
import androidx.test.filters.SmallTest
import com.android.compose.animation.scene.ObservableTransitionState
+import com.android.systemui.Flags.FLAG_GLANCEABLE_HUB_V2
import com.android.systemui.SysuiTestCase
import com.android.systemui.communal.data.repository.communalSceneRepository
+import com.android.systemui.communal.domain.interactor.communalSceneInteractor
+import com.android.systemui.communal.domain.interactor.setCommunalV2ConfigEnabled
import com.android.systemui.communal.shared.model.CommunalScenes
import com.android.systemui.coroutines.collectLastValue
import com.android.systemui.deviceentry.data.repository.fakeDeviceEntryRepository
@@ -35,6 +42,9 @@ import com.android.systemui.keyguard.domain.interactor.pulseExpansionInteractor
import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.keyguard.shared.model.TransitionState
import com.android.systemui.keyguard.shared.model.TransitionStep
+import com.android.systemui.kosmos.collectLastValue
+import com.android.systemui.kosmos.runCurrent
+import com.android.systemui.kosmos.runTest
import com.android.systemui.kosmos.testScope
import com.android.systemui.scene.data.repository.Idle
import com.android.systemui.scene.data.repository.sceneContainerRepository
@@ -48,6 +58,7 @@ import com.android.systemui.statusbar.notification.data.repository.activeNotific
import com.android.systemui.statusbar.notification.stack.domain.interactor.notificationsKeyguardInteractor
import com.android.systemui.statusbar.phone.dozeParameters
import com.android.systemui.statusbar.phone.screenOffAnimationController
+import com.android.systemui.statusbar.policy.keyguardStateController
import com.android.systemui.testKosmos
import com.android.systemui.util.mockito.mock
import com.android.systemui.util.mockito.whenever
@@ -69,7 +80,8 @@ import platform.test.runner.parameterized.Parameters
@SmallTest
@RunWith(ParameterizedAndroidJunit4::class)
class KeyguardRootViewModelTest(flags: FlagsParameterization) : SysuiTestCase() {
- private val kosmos = testKosmos()
+ private val kosmos =
+ testKosmos().apply { mainResources = mContext.orCreateTestableResources.resources }
private val testScope = kosmos.testScope
private val keyguardTransitionRepository by lazy { kosmos.fakeKeyguardTransitionRepository }
private val keyguardRepository by lazy { kosmos.fakeKeyguardRepository }
@@ -419,6 +431,7 @@ class KeyguardRootViewModelTest(flags: FlagsParameterization) : SysuiTestCase()
}
@Test
+ @DisableFlags(FLAG_GLANCEABLE_HUB_V2)
fun alpha_transitionFromHubToLockscreen_isOne() =
testScope.runTest {
val alpha by collectLastValue(underTest.alpha(viewState))
@@ -439,6 +452,84 @@ class KeyguardRootViewModelTest(flags: FlagsParameterization) : SysuiTestCase()
}
@Test
+ @DisableSceneContainer
+ @EnableFlags(FLAG_GLANCEABLE_HUB_V2)
+ fun alpha_transitionFromHubToLockscreenInLandscape_isOne() =
+ kosmos.runTest {
+ setCommunalV2ConfigEnabled(true)
+ whenever(keyguardStateController.isKeyguardScreenRotationAllowed).thenReturn(false)
+ communalSceneInteractor.changeScene(CommunalScenes.Communal, "test")
+ communalSceneRepository.setCommunalContainerOrientation(
+ Configuration.ORIENTATION_LANDSCAPE
+ )
+
+ val alpha by collectLastValue(underTest.alpha(viewState))
+
+ // Transition to the glanceable hub and back.
+ keyguardTransitionRepository.sendTransitionSteps(
+ from = KeyguardState.LOCKSCREEN,
+ to = KeyguardState.GLANCEABLE_HUB,
+ testScope,
+ )
+
+ communalSceneInteractor.changeScene(CommunalScenes.Communal, "test")
+ runCurrent()
+
+ // Exit hub to lockscreen
+ val progress = MutableStateFlow(0f)
+ val transitionState =
+ MutableStateFlow(
+ ObservableTransitionState.Transition(
+ fromScene = CommunalScenes.Communal,
+ toScene = CommunalScenes.Blank,
+ currentScene = flowOf(CommunalScenes.Blank),
+ progress = progress,
+ isInitiatedByUserInput = false,
+ isUserInputOngoing = flowOf(false),
+ )
+ )
+ communalSceneInteractor.setTransitionState(transitionState)
+ progress.value = .4f
+
+ keyguardTransitionRepository.sendTransitionSteps(
+ listOf(
+ TransitionStep(
+ from = KeyguardState.GLANCEABLE_HUB,
+ to = KeyguardState.LOCKSCREEN,
+ transitionState = TransitionState.STARTED,
+ value = 0f,
+ ),
+ TransitionStep(
+ from = KeyguardState.GLANCEABLE_HUB,
+ to = KeyguardState.LOCKSCREEN,
+ transitionState = TransitionState.RUNNING,
+ value = 0.4f,
+ ),
+ ),
+ testScope,
+ )
+
+ communalSceneRepository.setCommunalContainerOrientation(
+ Configuration.ORIENTATION_PORTRAIT
+ )
+ runCurrent()
+
+ keyguardTransitionRepository.sendTransitionSteps(
+ listOf(
+ TransitionStep(
+ from = KeyguardState.GLANCEABLE_HUB,
+ to = KeyguardState.LOCKSCREEN,
+ transitionState = TransitionState.FINISHED,
+ value = 1f,
+ )
+ ),
+ testScope,
+ )
+
+ assertThat(alpha).isEqualTo(1.0f)
+ }
+
+ @Test
fun alpha_emitsOnShadeExpansion() =
testScope.runTest {
val alpha by collectLastValue(underTest.alpha(viewState))
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModelTest.kt
new file mode 100644
index 000000000000..9c2c3c3f1498
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModelTest.kt
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard.ui.viewmodel
+
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.coroutines.collectValues
+import com.android.systemui.keyguard.data.repository.FakeKeyguardTransitionRepository
+import com.android.systemui.keyguard.data.repository.fakeKeyguardTransitionRepository
+import com.android.systemui.keyguard.shared.model.KeyguardState
+import com.android.systemui.keyguard.shared.model.TransitionState
+import com.android.systemui.keyguard.shared.model.TransitionState.RUNNING
+import com.android.systemui.keyguard.shared.model.TransitionStep
+import com.android.systemui.keyguard.ui.transitions.blurConfig
+import com.android.systemui.kosmos.testScope
+import com.android.systemui.testKosmos
+import kotlinx.coroutines.test.runTest
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class PrimaryBouncerToDreamingTransitionViewModelTest : SysuiTestCase() {
+ private val kosmos = testKosmos()
+ private val testScope = kosmos.testScope
+ private lateinit var keyguardTransitionRepository: FakeKeyguardTransitionRepository
+ private lateinit var underTest: PrimaryBouncerToDreamingTransitionViewModel
+
+ @Before
+ fun setUp() {
+ keyguardTransitionRepository = kosmos.fakeKeyguardTransitionRepository
+ underTest = kosmos.primaryBouncerToDreamingTransitionViewModel
+ }
+
+ @Test
+ fun blurRadiusGoesToMinImmediately() =
+ testScope.runTest {
+ val values by collectValues(underTest.windowBlurRadius)
+
+ kosmos.keyguardWindowBlurTestUtil.assertTransitionToBlurRadius(
+ transitionProgress = listOf(0.0f, 0.2f, 0.3f, 0.65f, 0.7f, 1.0f),
+ startValue = kosmos.blurConfig.maxBlurRadiusPx,
+ endValue = kosmos.blurConfig.minBlurRadiusPx,
+ actualValuesProvider = { values },
+ transitionFactory = ::step,
+ )
+ }
+
+ private fun step(value: Float, state: TransitionState = RUNNING): TransitionStep {
+ return TransitionStep(
+ from = KeyguardState.PRIMARY_BOUNCER,
+ to = KeyguardState.DREAMING,
+ value = value,
+ transitionState = state,
+ ownerName = "PrimaryBouncerToDreamingTransitionViewModelTest",
+ )
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
index 6d4fffdefb1b..00710dc037fa 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/scene/domain/startable/SceneContainerStartableTest.kt
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+@file:OptIn(ExperimentalCoroutinesApi::class)
+
package com.android.systemui.scene.domain.startable
import android.app.StatusBarManager
@@ -121,6 +123,7 @@ import com.android.systemui.util.mockito.mock
import com.android.systemui.util.settings.data.repository.userAwareSecureSettingsRepository
import com.google.android.msdl.data.model.MSDLToken
import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
@@ -2608,6 +2611,75 @@ class SceneContainerStartableTest : SysuiTestCase() {
}
@Test
+ fun handleDeviceUnlockStatus_returnsToLsFromBouncer_whenGoesToSleep() =
+ testScope.runTest {
+ val authMethod by collectLastValue(kosmos.authenticationInteractor.authenticationMethod)
+ val isUnlocked by
+ collectLastValue(
+ kosmos.deviceUnlockedInteractor.deviceUnlockStatus.map { it.isUnlocked }
+ )
+ val currentScene by collectLastValue(sceneInteractor.currentScene)
+ val currentOverlays by collectLastValue(sceneInteractor.currentOverlays)
+ val isAwake by collectLastValue(powerInteractor.isAwake)
+ prepareState(
+ isDeviceUnlocked = false,
+ initialSceneKey = Scenes.Lockscreen,
+ authenticationMethod = AuthenticationMethodModel.Pin,
+ startsAwake = true,
+ )
+ underTest.start()
+ assertThat(authMethod).isEqualTo(AuthenticationMethodModel.Pin)
+ assertThat(isUnlocked).isFalse()
+ assertThat(currentScene).isEqualTo(Scenes.Lockscreen)
+ assertThat(currentOverlays).doesNotContain(Overlays.Bouncer)
+ assertThat(isAwake).isTrue()
+
+ sceneInteractor.showOverlay(Overlays.Bouncer, "")
+ assertThat(authMethod).isEqualTo(AuthenticationMethodModel.Pin)
+ assertThat(isUnlocked).isFalse()
+ assertThat(currentScene).isEqualTo(Scenes.Lockscreen)
+ assertThat(currentOverlays).contains(Overlays.Bouncer)
+ assertThat(isAwake).isTrue()
+
+ powerInteractor.setAsleepForTest()
+ assertThat(authMethod).isEqualTo(AuthenticationMethodModel.Pin)
+ assertThat(isUnlocked).isFalse()
+ assertThat(currentScene).isEqualTo(Scenes.Lockscreen)
+ assertThat(currentOverlays).doesNotContain(Overlays.Bouncer)
+ assertThat(isAwake).isFalse()
+ }
+
+ @Test
+ fun hidesBouncer_whenAuthMethodChangesToNonSecure() =
+ testScope.runTest {
+ val authMethod by collectLastValue(kosmos.authenticationInteractor.authenticationMethod)
+ val currentScene by collectLastValue(kosmos.sceneInteractor.currentScene)
+ val currentOverlays by collectLastValue(kosmos.sceneInteractor.currentOverlays)
+ prepareState(
+ authenticationMethod = AuthenticationMethodModel.Password,
+ initialSceneKey = Scenes.Lockscreen,
+ )
+ underTest.start()
+ assertThat(authMethod).isEqualTo(AuthenticationMethodModel.Password)
+ assertThat(currentScene).isEqualTo(Scenes.Lockscreen)
+ assertThat(currentOverlays).doesNotContain(Overlays.Bouncer)
+
+ sceneInteractor.showOverlay(Overlays.Bouncer, "")
+ assertThat(authMethod).isEqualTo(AuthenticationMethodModel.Password)
+ assertThat(currentScene).isEqualTo(Scenes.Lockscreen)
+ assertThat(currentOverlays).contains(Overlays.Bouncer)
+
+ kosmos.fakeAuthenticationRepository.setAuthenticationMethod(
+ AuthenticationMethodModel.None
+ )
+ runCurrent()
+
+ assertThat(authMethod).isEqualTo(AuthenticationMethodModel.None)
+ assertThat(currentScene).isEqualTo(Scenes.Lockscreen)
+ assertThat(currentOverlays).doesNotContain(Overlays.Bouncer)
+ }
+
+ @Test
fun replacesLockscreenSceneOnBackStack_whenFaceUnlocked_fromShade_noAlternateBouncer() =
testScope.runTest {
val transitionState =
@@ -2898,7 +2970,10 @@ class SceneContainerStartableTest : SysuiTestCase() {
sceneInteractor.changeScene(it, "prepareState, initialSceneKey isn't null")
}
for (overlay in initialOverlays) {
- sceneInteractor.showOverlay(overlay, "prepareState, initialOverlays isn't empty")
+ sceneInteractor.instantlyShowOverlay(
+ overlay,
+ "prepareState, initialOverlays isn't empty",
+ )
}
if (startsAwake) {
powerInteractor.setAwakeForTest()
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/ShadeControllerSceneImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/ShadeControllerSceneImplTest.kt
index b376558371f3..0289c58f6e93 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/ShadeControllerSceneImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/shade/ShadeControllerSceneImplTest.kt
@@ -34,6 +34,7 @@ import com.android.systemui.scene.domain.interactor.sceneInteractor
import com.android.systemui.scene.shared.model.Overlays
import com.android.systemui.scene.shared.model.Scenes
import com.android.systemui.shade.domain.interactor.ShadeInteractor
+import com.android.systemui.shade.domain.interactor.disableDualShade
import com.android.systemui.shade.domain.interactor.enableDualShade
import com.android.systemui.shade.domain.interactor.shadeInteractor
import com.android.systemui.statusbar.CommandQueue
@@ -214,6 +215,21 @@ class ShadeControllerSceneImplTest : SysuiTestCase() {
assertThat(currentOverlays).isEmpty()
}
+ @Test
+ fun instantCollapseShade_singleShade_doesntSwitchToShadeScene() =
+ testScope.runTest {
+ kosmos.disableDualShade()
+ runCurrent()
+ val currentScene by collectLastValue(sceneInteractor.currentScene)
+ val homeScene = currentScene
+ sceneInteractor.changeScene(Scenes.QuickSettings, "")
+ assertThat(currentScene).isEqualTo(Scenes.QuickSettings)
+
+ underTest.instantCollapseShade()
+
+ assertThat(currentScene).isEqualTo(homeScene)
+ }
+
private fun setScene(key: SceneKey) {
sceneInteractor.changeScene(key, "test")
sceneInteractor.setTransitionState(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/NotificationShadeDepthControllerTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/NotificationShadeDepthControllerTest.kt
index 039a32ba9127..b4c6b33463b0 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/NotificationShadeDepthControllerTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/NotificationShadeDepthControllerTest.kt
@@ -48,6 +48,7 @@ import com.android.wm.shell.appzoomout.AppZoomOut
import com.google.common.truth.Truth.assertThat
import java.util.Optional
import java.util.function.Consumer
+import kotlinx.coroutines.flow.MutableStateFlow
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@@ -120,6 +121,8 @@ class NotificationShadeDepthControllerTest : SysuiTestCase() {
`when`(blurUtils.supportsBlursOnWindows()).thenReturn(true)
`when`(blurUtils.maxBlurRadius).thenReturn(maxBlur.toFloat())
`when`(blurUtils.maxBlurRadius).thenReturn(maxBlur.toFloat())
+ `when`(windowRootViewBlurInteractor.isBlurCurrentlySupported)
+ .thenReturn(MutableStateFlow(true))
notificationShadeDepthController =
NotificationShadeDepthController(
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryTest.java
index bfd700dcc302..52996ee1e369 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/NotificationEntryTest.java
@@ -309,24 +309,6 @@ public class NotificationEntryTest extends SysuiTestCase {
}
@Test
- @EnableFlags(PromotedNotificationUi.FLAG_NAME)
- @DisableFlags(StatusBarNotifChips.FLAG_NAME)
- public void isPromotedOngoing_uiFlagOnAndNotifHasFlag_true() {
- mEntry.getSbn().getNotification().flags |= FLAG_PROMOTED_ONGOING;
-
- assertTrue(mEntry.isPromotedOngoing());
- }
-
- @Test
- @EnableFlags(StatusBarNotifChips.FLAG_NAME)
- @DisableFlags(PromotedNotificationUi.FLAG_NAME)
- public void isPromotedOngoing_statusBarNotifChipsFlagOnAndNotifHasFlag_true() {
- mEntry.getSbn().getNotification().flags |= FLAG_PROMOTED_ONGOING;
-
- assertTrue(mEntry.isPromotedOngoing());
- }
-
- @Test
public void testIsNotificationVisibilityPrivate_true() {
assertTrue(mEntry.isNotificationVisibilityPrivate());
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java
index f9405af3f85d..340ce673e01e 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/collection/coordinator/RankingCoordinatorTest.java
@@ -19,6 +19,7 @@ package com.android.systemui.statusbar.notification.collection.coordinator;
import static android.app.NotificationChannel.SYSTEM_RESERVED_IDS;
import static android.app.NotificationManager.IMPORTANCE_DEFAULT;
import static android.app.NotificationManager.IMPORTANCE_LOW;
+import static android.app.NotificationManager.IMPORTANCE_MIN;
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_AMBIENT;
import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_NOTIFICATION_LIST;
@@ -36,7 +37,6 @@ import static org.mockito.Mockito.when;
import android.app.Notification;
import android.app.NotificationChannel;
-import android.app.NotificationManager;
import android.platform.test.annotations.EnableFlags;
import androidx.annotation.Nullable;
@@ -265,18 +265,35 @@ public class RankingCoordinatorTest extends SysuiTestCase {
}
@Test
- public void testIncludeInSectionSilent() {
- // GIVEN the entry isn't high priority
+ public void testSilentSectioner_accepts_highPriorityFalse_ambientFalse() {
when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(false);
setRankingAmbient(false);
+ assertOnlyInSection(mEntry, mSilentSectioner);
+ }
+
+ @Test
+ public void testSilentSectioner_rejects_highPriorityFalse_ambientTrue() {
+ when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(false);
+ setRankingAmbient(true);
+ assertFalse(mSilentSectioner.isInSection(mEntry));
+ }
+
+ @Test
+ public void testSilentSectioner_rejects_highPriorityTrue_ambientFalse() {
+ when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(true);
+ setRankingAmbient(false);
+ assertFalse(mSilentSectioner.isInSection(mEntry));
+ }
- // THEN entry is in the silent section
- assertFalse(mAlertingSectioner.isInSection(mEntry));
- assertTrue(mSilentSectioner.isInSection(mEntry));
+ @Test
+ public void testSilentSectioner_rejects_highPriorityTrue_ambientTrue() {
+ when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(true);
+ setRankingAmbient(true);
+ assertFalse(mSilentSectioner.isInSection(mEntry));
}
@Test
- public void testSilentSectioner_acceptsBundle() {
+ public void testSilentSectioner_accepts_bundle() {
BundleEntry bundleEntry = new BundleEntry("testBundleKey");
assertTrue(mSilentSectioner.isInSection(bundleEntry));
}
@@ -291,14 +308,7 @@ public class RankingCoordinatorTest extends SysuiTestCase {
public void testMinSection() {
when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(false);
setRankingAmbient(true);
- assertInSection(mEntry, mMinimizedSectioner);
- }
-
- @Test
- public void testSilentSection() {
- when(mHighPriorityProvider.isHighPriority(mEntry)).thenReturn(false);
- setRankingAmbient(false);
- assertInSection(mEntry, mSilentSectioner);
+ assertOnlyInSection(mEntry, mMinimizedSectioner);
}
@Test
@@ -344,7 +354,8 @@ public class RankingCoordinatorTest extends SysuiTestCase {
@Test
public void testAlertingSectioner_rejectsBundle() {
for (String id : SYSTEM_RESERVED_IDS) {
- assertFalse(mAlertingSectioner.isInSection(makeClassifiedNotifEntry(id)));
+ assertFalse(
+ mAlertingSectioner.isInSection(makeClassifiedNotifEntry(id, IMPORTANCE_LOW)));
}
}
@@ -369,7 +380,7 @@ public class RankingCoordinatorTest extends SysuiTestCase {
reset(mInvalidationListener);
}
- private void assertInSection(NotificationEntry entry, NotifSectioner section) {
+ private void assertOnlyInSection(NotificationEntry entry, NotifSectioner section) {
for (NotifSectioner current: mSections) {
if (current == section) {
assertTrue(current.isInSection(entry));
@@ -396,16 +407,17 @@ public class RankingCoordinatorTest extends SysuiTestCase {
private void setRankingAmbient(boolean ambient) {
mEntry.setRanking(new RankingBuilder(mEntry.getRanking())
.setImportance(ambient
- ? NotificationManager.IMPORTANCE_MIN
+ ? IMPORTANCE_MIN
: IMPORTANCE_DEFAULT)
.build());
assertEquals(ambient, mEntry.getRanking().isAmbient());
}
- private NotificationEntry makeClassifiedNotifEntry(String channelId) {
- NotificationChannel channel = new NotificationChannel(channelId, channelId, IMPORTANCE_LOW);
+ private NotificationEntry makeClassifiedNotifEntry(String channelId, int importance) {
+ NotificationChannel channel = new NotificationChannel(channelId, channelId, importance);
return new NotificationEntryBuilder()
- .updateRanking((rankingBuilder -> rankingBuilder.setChannel(channel)))
+ .updateRanking((rankingBuilder ->
+ rankingBuilder.setChannel(channel).setImportance(importance)))
.build();
}
}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/headsup/HeadsUpManagerImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/headsup/HeadsUpManagerImplTest.kt
index 8560b66d961f..5b0e4e139d4e 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/headsup/HeadsUpManagerImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/headsup/HeadsUpManagerImplTest.kt
@@ -749,20 +749,6 @@ class HeadsUpManagerImplTest(flags: FlagsParameterization) : SysuiTestCase() {
assertThat(getIsSticky_promotedAndExpanded()).isFalse()
}
- @Test
- @EnableFlags(PromotedNotificationUi.FLAG_NAME)
- @DisableFlags(StatusBarNotifChips.FLAG_NAME)
- fun testIsSticky_promotedAndExpanded_promotedUiFlagOn_false() {
- assertThat(getIsSticky_promotedAndExpanded()).isFalse()
- }
-
- @Test
- @EnableFlags(StatusBarNotifChips.FLAG_NAME)
- @DisableFlags(PromotedNotificationUi.FLAG_NAME)
- fun testIsSticky_promotedAndExpanded_notifChipsFlagOn_false() {
- assertThat(getIsSticky_promotedAndExpanded()).isFalse()
- }
-
private fun getIsSticky_promotedAndExpanded(): Boolean {
val notif = Notification.Builder(mContext, "").setSmallIcon(R.drawable.ic_person).build()
notif.flags = FLAG_PROMOTED_ONGOING
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationContentExtractorImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationContentExtractorImplTest.kt
index cc016b9768b7..df77b5ad46e8 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationContentExtractorImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationContentExtractorImplTest.kt
@@ -33,6 +33,8 @@ import android.platform.test.annotations.EnableFlags
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.android.systemui.SysuiTestCase
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.runTest
import com.android.systemui.statusbar.NotificationLockscreenUserManager.REDACTION_TYPE_NONE
import com.android.systemui.statusbar.NotificationLockscreenUserManager.REDACTION_TYPE_PUBLIC
import com.android.systemui.statusbar.chips.notification.shared.StatusBarNotifChips
@@ -58,132 +60,122 @@ import org.junit.runner.RunWith
class PromotedNotificationContentExtractorImplTest : SysuiTestCase() {
private val kosmos = testKosmos().apply { systemClock = fakeSystemClock }
- private val underTest = kosmos.promotedNotificationContentExtractor
- private val systemClock = kosmos.fakeSystemClock
- private val rowImageInflater =
- RowImageInflater.newInstance(previousIndex = null, reinflating = false)
- private val imageModelProvider by lazy { rowImageInflater.useForContentModel() }
+ private val Kosmos.underTest by Kosmos.Fixture { promotedNotificationContentExtractor }
+ private val Kosmos.rowImageInflater by
+ Kosmos.Fixture { RowImageInflater.newInstance(previousIndex = null, reinflating = false) }
+ private val Kosmos.imageModelProvider by
+ Kosmos.Fixture { rowImageInflater.useForContentModel() }
@Test
@DisableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun shouldNotExtract_bothFlagsDisabled() {
- val notif = createEntry()
- val content = extractContent(notif)
- assertThat(content).isNull()
- }
-
- @Test
- @EnableFlags(PromotedNotificationUi.FLAG_NAME)
- @DisableFlags(StatusBarNotifChips.FLAG_NAME)
- fun shouldExtract_promotedNotificationUiFlagEnabled() {
- val entry = createEntry()
- val content = extractContent(entry)
- assertThat(content).isNotNull()
- }
-
- @Test
- @EnableFlags(StatusBarNotifChips.FLAG_NAME)
- @DisableFlags(PromotedNotificationUi.FLAG_NAME)
- fun shouldExtract_statusBarNotifChipsFlagEnabled() {
- val entry = createEntry()
- val content = extractContent(entry)
- assertThat(content).isNotNull()
- }
+ fun shouldNotExtract_bothFlagsDisabled() =
+ kosmos.runTest {
+ val notif = createEntry()
+ val content = extractContent(notif)
+ assertThat(content).isNull()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun shouldExtract_bothFlagsEnabled() {
- val entry = createEntry()
- val content = extractContent(entry)
- assertThat(content).isNotNull()
- }
+ fun shouldExtract_bothFlagsEnabled() =
+ kosmos.runTest {
+ val entry = createEntry()
+ val content = extractContent(entry)
+ assertThat(content).isNotNull()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun shouldNotExtract_becauseNotPromoted() {
- val entry = createEntry(promoted = false)
- val content = extractContent(entry)
- assertThat(content).isNull()
- }
+ fun shouldNotExtract_becauseNotPromoted() =
+ kosmos.runTest {
+ val entry = createEntry(promoted = false)
+ val content = extractContent(entry)
+ assertThat(content).isNull()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractsContent_commonFields() {
- val entry = createEntry {
- setSubText(TEST_SUB_TEXT)
- setContentTitle(TEST_CONTENT_TITLE)
- setContentText(TEST_CONTENT_TEXT)
- }
+ fun extractsContent_commonFields() =
+ kosmos.runTest {
+ val entry = createEntry {
+ setSubText(TEST_SUB_TEXT)
+ setContentTitle(TEST_CONTENT_TITLE)
+ setContentText(TEST_CONTENT_TEXT)
+ }
- val content = requireContent(entry)
+ val content = requireContent(entry)
- content.privateVersion.apply {
- assertThat(subText).isEqualTo(TEST_SUB_TEXT)
- assertThat(title).isEqualTo(TEST_CONTENT_TITLE)
- assertThat(text).isEqualTo(TEST_CONTENT_TEXT)
- }
+ content.privateVersion.apply {
+ assertThat(subText).isEqualTo(TEST_SUB_TEXT)
+ assertThat(title).isEqualTo(TEST_CONTENT_TITLE)
+ assertThat(text).isEqualTo(TEST_CONTENT_TEXT)
+ }
- content.publicVersion.apply {
- assertThat(subText).isNull()
- assertThat(title).isNull()
- assertThat(text).isNull()
+ content.publicVersion.apply {
+ assertThat(subText).isNull()
+ assertThat(title).isNull()
+ assertThat(text).isNull()
+ }
}
- }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractsContent_commonFields_noRedaction() {
- val entry = createEntry {
- setSubText(TEST_SUB_TEXT)
- setContentTitle(TEST_CONTENT_TITLE)
- setContentText(TEST_CONTENT_TEXT)
- }
+ fun extractsContent_commonFields_noRedaction() =
+ kosmos.runTest {
+ val entry = createEntry {
+ setSubText(TEST_SUB_TEXT)
+ setContentTitle(TEST_CONTENT_TITLE)
+ setContentText(TEST_CONTENT_TEXT)
+ }
- val content = requireContent(entry, redactionType = REDACTION_TYPE_NONE)
+ val content = requireContent(entry, redactionType = REDACTION_TYPE_NONE)
- content.privateVersion.apply {
- assertThat(subText).isEqualTo(TEST_SUB_TEXT)
- assertThat(title).isEqualTo(TEST_CONTENT_TITLE)
- assertThat(text).isEqualTo(TEST_CONTENT_TEXT)
- }
+ content.privateVersion.apply {
+ assertThat(subText).isEqualTo(TEST_SUB_TEXT)
+ assertThat(title).isEqualTo(TEST_CONTENT_TITLE)
+ assertThat(text).isEqualTo(TEST_CONTENT_TEXT)
+ }
- content.publicVersion.apply {
- assertThat(subText).isEqualTo(TEST_SUB_TEXT)
- assertThat(title).isEqualTo(TEST_CONTENT_TITLE)
- assertThat(text).isEqualTo(TEST_CONTENT_TEXT)
+ content.publicVersion.apply {
+ assertThat(subText).isEqualTo(TEST_SUB_TEXT)
+ assertThat(title).isEqualTo(TEST_CONTENT_TITLE)
+ assertThat(text).isEqualTo(TEST_CONTENT_TEXT)
+ }
}
- }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_wasPromotedAutomatically_false() {
- val entry = createEntry { extras.putBoolean(EXTRA_WAS_AUTOMATICALLY_PROMOTED, false) }
+ fun extractContent_wasPromotedAutomatically_false() =
+ kosmos.runTest {
+ val entry = createEntry { extras.putBoolean(EXTRA_WAS_AUTOMATICALLY_PROMOTED, false) }
- val content = requireContent(entry).privateVersion
+ val content = requireContent(entry).privateVersion
- assertThat(content.wasPromotedAutomatically).isFalse()
- }
+ assertThat(content.wasPromotedAutomatically).isFalse()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_wasPromotedAutomatically_true() {
- val entry = createEntry { extras.putBoolean(EXTRA_WAS_AUTOMATICALLY_PROMOTED, true) }
+ fun extractContent_wasPromotedAutomatically_true() =
+ kosmos.runTest {
+ val entry = createEntry { extras.putBoolean(EXTRA_WAS_AUTOMATICALLY_PROMOTED, true) }
- val content = requireContent(entry).privateVersion
+ val content = requireContent(entry).privateVersion
- assertThat(content.wasPromotedAutomatically).isTrue()
- }
+ assertThat(content.wasPromotedAutomatically).isTrue()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
@DisableFlags(android.app.Flags.FLAG_API_RICH_ONGOING)
- fun extractContent_apiFlagOff_shortCriticalTextNotExtracted() {
- val entry = createEntry { setShortCriticalText(TEST_SHORT_CRITICAL_TEXT) }
+ fun extractContent_apiFlagOff_shortCriticalTextNotExtracted() =
+ kosmos.runTest {
+ val entry = createEntry { setShortCriticalText(TEST_SHORT_CRITICAL_TEXT) }
- val content = requireContent(entry).privateVersion
+ val content = requireContent(entry).privateVersion
- assertThat(content.text).isNull()
- }
+ assertThat(content.text).isNull()
+ }
@Test
@EnableFlags(
@@ -191,13 +183,14 @@ class PromotedNotificationContentExtractorImplTest : SysuiTestCase() {
StatusBarNotifChips.FLAG_NAME,
android.app.Flags.FLAG_API_RICH_ONGOING,
)
- fun extractContent_apiFlagOn_shortCriticalTextExtracted() {
- val entry = createEntry { setShortCriticalText(TEST_SHORT_CRITICAL_TEXT) }
+ fun extractContent_apiFlagOn_shortCriticalTextExtracted() =
+ kosmos.runTest {
+ val entry = createEntry { setShortCriticalText(TEST_SHORT_CRITICAL_TEXT) }
- val content = requireContent(entry).privateVersion
+ val content = requireContent(entry).privateVersion
- assertThat(content.shortCriticalText).isEqualTo(TEST_SHORT_CRITICAL_TEXT)
- }
+ assertThat(content.shortCriticalText).isEqualTo(TEST_SHORT_CRITICAL_TEXT)
+ }
@Test
@EnableFlags(
@@ -205,165 +198,188 @@ class PromotedNotificationContentExtractorImplTest : SysuiTestCase() {
StatusBarNotifChips.FLAG_NAME,
android.app.Flags.FLAG_API_RICH_ONGOING,
)
- fun extractContent_noShortCriticalTextSet_textIsNull() {
- val entry = createEntry { setShortCriticalText(null) }
+ fun extractContent_noShortCriticalTextSet_textIsNull() =
+ kosmos.runTest {
+ val entry = createEntry { setShortCriticalText(null) }
- val content = requireContent(entry).privateVersion
+ val content = requireContent(entry).privateVersion
- assertThat(content.shortCriticalText).isNull()
- }
+ assertThat(content.shortCriticalText).isNull()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_none() {
- assertExtractedTime(hasTime = false, hasChronometer = false, expected = ExpectedTime.Null)
- }
+ fun extractTime_none() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = false,
+ hasChronometer = false,
+ expected = ExpectedTime.Null,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_basicTimeZero() {
- assertExtractedTime(
- hasTime = true,
- hasChronometer = false,
- provided = ProvidedTime.Value(0L),
- expected = ExpectedTime.Time,
- )
- }
+ fun extractTime_basicTimeZero() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = true,
+ hasChronometer = false,
+ provided = ProvidedTime.Value(0L),
+ expected = ExpectedTime.Time,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_basicTimeNow() {
- assertExtractedTime(
- hasTime = true,
- hasChronometer = false,
- provided = ProvidedTime.Offset(Duration.ZERO),
- expected = ExpectedTime.Time,
- )
- }
+ fun extractTime_basicTimeNow() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = true,
+ hasChronometer = false,
+ provided = ProvidedTime.Offset(Duration.ZERO),
+ expected = ExpectedTime.Time,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_basicTimePast() {
- assertExtractedTime(
- hasTime = true,
- hasChronometer = false,
- provided = ProvidedTime.Offset((-5).minutes),
- expected = ExpectedTime.Time,
- )
- }
+ fun extractTime_basicTimePast() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = true,
+ hasChronometer = false,
+ provided = ProvidedTime.Offset((-5).minutes),
+ expected = ExpectedTime.Time,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_basicTimeFuture() {
- assertExtractedTime(
- hasTime = true,
- hasChronometer = false,
- provided = ProvidedTime.Offset(5.minutes),
- expected = ExpectedTime.Time,
- )
- }
+ fun extractTime_basicTimeFuture() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = true,
+ hasChronometer = false,
+ provided = ProvidedTime.Offset(5.minutes),
+ expected = ExpectedTime.Time,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_countUpZero() {
- assertExtractedTime(
- hasTime = false,
- hasChronometer = true,
- isCountDown = false,
- provided = ProvidedTime.Value(0L),
- expected = ExpectedTime.CountUp,
- )
- }
+ fun extractTime_countUpZero() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = false,
+ hasChronometer = true,
+ isCountDown = false,
+ provided = ProvidedTime.Value(0L),
+ expected = ExpectedTime.CountUp,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_countUpNow() {
- assertExtractedTime(
- hasTime = false,
- hasChronometer = true,
- isCountDown = false,
- provided = ProvidedTime.Offset(Duration.ZERO),
- expected = ExpectedTime.CountUp,
- )
- }
+ fun extractTime_countUpNow() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = false,
+ hasChronometer = true,
+ isCountDown = false,
+ provided = ProvidedTime.Offset(Duration.ZERO),
+ expected = ExpectedTime.CountUp,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_countUpPast() {
- assertExtractedTime(
- hasTime = false,
- hasChronometer = true,
- isCountDown = false,
- provided = ProvidedTime.Offset((-5).minutes),
- expected = ExpectedTime.CountUp,
- )
- }
+ fun extractTime_countUpPast() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = false,
+ hasChronometer = true,
+ isCountDown = false,
+ provided = ProvidedTime.Offset((-5).minutes),
+ expected = ExpectedTime.CountUp,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_countUpFuture() {
- assertExtractedTime(
- hasTime = false,
- hasChronometer = true,
- isCountDown = false,
- provided = ProvidedTime.Offset(5.minutes),
- expected = ExpectedTime.CountUp,
- )
- }
+ fun extractTime_countUpFuture() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = false,
+ hasChronometer = true,
+ isCountDown = false,
+ provided = ProvidedTime.Offset(5.minutes),
+ expected = ExpectedTime.CountUp,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_countDownZero() {
- assertExtractedTime(
- hasTime = false,
- hasChronometer = true,
- isCountDown = true,
- provided = ProvidedTime.Value(0L),
- expected = ExpectedTime.CountDown,
- )
- }
+ fun extractTime_countDownZero() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = false,
+ hasChronometer = true,
+ isCountDown = true,
+ provided = ProvidedTime.Value(0L),
+ expected = ExpectedTime.CountDown,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_countDownNow() {
- assertExtractedTime(
- hasTime = false,
- hasChronometer = true,
- isCountDown = true,
- provided = ProvidedTime.Offset(Duration.ZERO),
- expected = ExpectedTime.CountDown,
- )
- }
+ fun extractTime_countDownNow() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = false,
+ hasChronometer = true,
+ isCountDown = true,
+ provided = ProvidedTime.Offset(Duration.ZERO),
+ expected = ExpectedTime.CountDown,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_countDownPast() {
- assertExtractedTime(
- hasTime = false,
- hasChronometer = true,
- isCountDown = true,
- provided = ProvidedTime.Offset((-5).minutes),
- expected = ExpectedTime.CountDown,
- )
- }
+ fun extractTime_countDownPast() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = false,
+ hasChronometer = true,
+ isCountDown = true,
+ provided = ProvidedTime.Offset((-5).minutes),
+ expected = ExpectedTime.CountDown,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_countDownFuture() {
- assertExtractedTime(
- hasTime = false,
- hasChronometer = true,
- isCountDown = true,
- provided = ProvidedTime.Offset(5.minutes),
- expected = ExpectedTime.CountDown,
- )
- }
+ fun extractTime_countDownFuture() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = false,
+ hasChronometer = true,
+ isCountDown = true,
+ provided = ProvidedTime.Offset(5.minutes),
+ expected = ExpectedTime.CountDown,
+ )
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractTime_prefersChronometerToWhen() {
- assertExtractedTime(hasTime = true, hasChronometer = true, expected = ExpectedTime.CountUp)
- }
+ fun extractTime_prefersChronometerToWhen() =
+ kosmos.runTest {
+ assertExtractedTime(
+ hasTime = true,
+ hasChronometer = true,
+ expected = ExpectedTime.CountUp,
+ )
+ }
private sealed class ProvidedTime {
data class Value(val value: Long) : ProvidedTime()
@@ -378,7 +394,7 @@ class PromotedNotificationContentExtractorImplTest : SysuiTestCase() {
CountDown,
}
- private fun assertExtractedTime(
+ private fun Kosmos.assertExtractedTime(
hasTime: Boolean = false,
hasChronometer: Boolean = false,
isCountDown: Boolean = false,
@@ -387,8 +403,8 @@ class PromotedNotificationContentExtractorImplTest : SysuiTestCase() {
) {
// Set the two timebases to different (arbitrary) numbers, so we can verify whether the
// extractor is doing the timebase adjustment correctly.
- systemClock.setCurrentTimeMillis(1_739_570_992_579L)
- systemClock.setElapsedRealtime(1_380_967_080L)
+ fakeSystemClock.setCurrentTimeMillis(1_739_570_992_579L)
+ fakeSystemClock.setElapsedRealtime(1_380_967_080L)
val providedCurrentTime =
when (provided) {
@@ -437,122 +453,130 @@ class PromotedNotificationContentExtractorImplTest : SysuiTestCase() {
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_fromBaseStyle() {
- val entry = createEntry { setStyle(null) }
+ fun extractContent_fromBaseStyle() =
+ kosmos.runTest {
+ val entry = createEntry { setStyle(null) }
- val content = requireContent(entry)
+ val content = requireContent(entry)
- assertThat(content.privateVersion.style).isEqualTo(Style.Base)
- assertThat(content.publicVersion.style).isEqualTo(Style.Base)
- }
+ assertThat(content.privateVersion.style).isEqualTo(Style.Base)
+ assertThat(content.publicVersion.style).isEqualTo(Style.Base)
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_fromBigPictureStyle() {
- val entry = createEntry { setStyle(BigPictureStyle()) }
+ fun extractContent_fromBigPictureStyle() =
+ kosmos.runTest {
+ val entry = createEntry { setStyle(BigPictureStyle()) }
- val content = requireContent(entry)
+ val content = requireContent(entry)
- assertThat(content.privateVersion.style).isEqualTo(Style.BigPicture)
- assertThat(content.publicVersion.style).isEqualTo(Style.Base)
- }
+ assertThat(content.privateVersion.style).isEqualTo(Style.BigPicture)
+ assertThat(content.publicVersion.style).isEqualTo(Style.Base)
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_fromBigTextStyle() {
- val entry = createEntry {
- setContentTitle(TEST_CONTENT_TITLE)
- setContentText(TEST_CONTENT_TEXT)
- setStyle(
- BigTextStyle()
- .bigText(TEST_BIG_TEXT)
- .setBigContentTitle(TEST_BIG_CONTENT_TITLE)
- .setSummaryText(TEST_SUMMARY_TEXT)
- )
- }
+ fun extractContent_fromBigTextStyle() =
+ kosmos.runTest {
+ val entry = createEntry {
+ setContentTitle(TEST_CONTENT_TITLE)
+ setContentText(TEST_CONTENT_TEXT)
+ setStyle(
+ BigTextStyle()
+ .bigText(TEST_BIG_TEXT)
+ .setBigContentTitle(TEST_BIG_CONTENT_TITLE)
+ .setSummaryText(TEST_SUMMARY_TEXT)
+ )
+ }
- val content = requireContent(entry)
+ val content = requireContent(entry)
- assertThat(content.privateVersion.style).isEqualTo(Style.BigText)
- assertThat(content.privateVersion.title).isEqualTo(TEST_BIG_CONTENT_TITLE)
- assertThat(content.privateVersion.text).isEqualTo(TEST_BIG_TEXT)
+ assertThat(content.privateVersion.style).isEqualTo(Style.BigText)
+ assertThat(content.privateVersion.title).isEqualTo(TEST_BIG_CONTENT_TITLE)
+ assertThat(content.privateVersion.text).isEqualTo(TEST_BIG_TEXT)
- assertThat(content.publicVersion.style).isEqualTo(Style.Base)
- assertThat(content.publicVersion.title).isNull()
- assertThat(content.publicVersion.text).isNull()
- }
+ assertThat(content.publicVersion.style).isEqualTo(Style.Base)
+ assertThat(content.publicVersion.title).isNull()
+ assertThat(content.publicVersion.text).isNull()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_fromBigTextStyle_fallbackToContentTitle() {
- val entry = createEntry {
- setContentTitle(TEST_CONTENT_TITLE)
- setContentText(TEST_CONTENT_TEXT)
- setStyle(
- BigTextStyle()
- .bigText(TEST_BIG_TEXT)
- // bigContentTitle unset
- .setSummaryText(TEST_SUMMARY_TEXT)
- )
- }
+ fun extractContent_fromBigTextStyle_fallbackToContentTitle() =
+ kosmos.runTest {
+ val entry = createEntry {
+ setContentTitle(TEST_CONTENT_TITLE)
+ setContentText(TEST_CONTENT_TEXT)
+ setStyle(
+ BigTextStyle()
+ .bigText(TEST_BIG_TEXT)
+ // bigContentTitle unset
+ .setSummaryText(TEST_SUMMARY_TEXT)
+ )
+ }
- val content = requireContent(entry)
+ val content = requireContent(entry)
- assertThat(content.privateVersion.style).isEqualTo(Style.BigText)
- assertThat(content.privateVersion.title).isEqualTo(TEST_CONTENT_TITLE)
- assertThat(content.privateVersion.text).isEqualTo(TEST_BIG_TEXT)
+ assertThat(content.privateVersion.style).isEqualTo(Style.BigText)
+ assertThat(content.privateVersion.title).isEqualTo(TEST_CONTENT_TITLE)
+ assertThat(content.privateVersion.text).isEqualTo(TEST_BIG_TEXT)
- assertThat(content.publicVersion.style).isEqualTo(Style.Base)
- assertThat(content.publicVersion.title).isNull()
- assertThat(content.publicVersion.text).isNull()
- }
+ assertThat(content.publicVersion.style).isEqualTo(Style.Base)
+ assertThat(content.publicVersion.title).isNull()
+ assertThat(content.publicVersion.text).isNull()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_fromBigTextStyle_fallbackToContentText() {
- val entry = createEntry {
- setContentTitle(TEST_CONTENT_TITLE)
- setContentText(TEST_CONTENT_TEXT)
- setStyle(
- BigTextStyle()
- // bigText unset
- .setBigContentTitle(TEST_BIG_CONTENT_TITLE)
- .setSummaryText(TEST_SUMMARY_TEXT)
- )
- }
+ fun extractContent_fromBigTextStyle_fallbackToContentText() =
+ kosmos.runTest {
+ val entry = createEntry {
+ setContentTitle(TEST_CONTENT_TITLE)
+ setContentText(TEST_CONTENT_TEXT)
+ setStyle(
+ BigTextStyle()
+ // bigText unset
+ .setBigContentTitle(TEST_BIG_CONTENT_TITLE)
+ .setSummaryText(TEST_SUMMARY_TEXT)
+ )
+ }
- val content = requireContent(entry)
+ val content = requireContent(entry)
- assertThat(content.privateVersion.style).isEqualTo(Style.BigText)
- assertThat(content.privateVersion.title).isEqualTo(TEST_BIG_CONTENT_TITLE)
- assertThat(content.privateVersion.text).isEqualTo(TEST_CONTENT_TEXT)
+ assertThat(content.privateVersion.style).isEqualTo(Style.BigText)
+ assertThat(content.privateVersion.title).isEqualTo(TEST_BIG_CONTENT_TITLE)
+ assertThat(content.privateVersion.text).isEqualTo(TEST_CONTENT_TEXT)
- assertThat(content.publicVersion.style).isEqualTo(Style.Base)
- assertThat(content.publicVersion.title).isNull()
- assertThat(content.publicVersion.text).isNull()
- }
+ assertThat(content.publicVersion.style).isEqualTo(Style.Base)
+ assertThat(content.publicVersion.title).isNull()
+ assertThat(content.publicVersion.text).isNull()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_fromCallStyle() {
- val hangUpIntent =
- PendingIntent.getBroadcast(
- context,
- 0,
- Intent("hangup_action"),
- PendingIntent.FLAG_IMMUTABLE,
- )
- val entry = createEntry { setStyle(CallStyle.forOngoingCall(TEST_PERSON, hangUpIntent)) }
+ fun extractContent_fromCallStyle() =
+ kosmos.runTest {
+ val hangUpIntent =
+ PendingIntent.getBroadcast(
+ context,
+ 0,
+ Intent("hangup_action"),
+ PendingIntent.FLAG_IMMUTABLE,
+ )
+ val entry = createEntry {
+ setStyle(CallStyle.forOngoingCall(TEST_PERSON, hangUpIntent))
+ }
- val content = requireContent(entry)
+ val content = requireContent(entry)
- assertThat(content.privateVersion.style).isEqualTo(Style.Call)
- assertThat(content.privateVersion.title).isEqualTo(TEST_PERSON_NAME)
+ assertThat(content.privateVersion.style).isEqualTo(Style.Call)
+ assertThat(content.privateVersion.title).isEqualTo(TEST_PERSON_NAME)
- assertThat(content.publicVersion.style).isEqualTo(Style.Base)
- assertThat(content.publicVersion.title).isNull()
- assertThat(content.publicVersion.text).isNull()
- }
+ assertThat(content.publicVersion.style).isEqualTo(Style.Base)
+ assertThat(content.publicVersion.title).isNull()
+ assertThat(content.publicVersion.text).isNull()
+ }
@Test
@EnableFlags(
@@ -560,75 +584,79 @@ class PromotedNotificationContentExtractorImplTest : SysuiTestCase() {
StatusBarNotifChips.FLAG_NAME,
android.app.Flags.FLAG_API_RICH_ONGOING,
)
- fun extractContent_fromProgressStyle() {
- val entry = createEntry {
- setStyle(ProgressStyle().addProgressSegment(Segment(100)).setProgress(75))
- }
+ fun extractContent_fromProgressStyle() =
+ kosmos.runTest {
+ val entry = createEntry {
+ setStyle(ProgressStyle().addProgressSegment(Segment(100)).setProgress(75))
+ }
- val content = requireContent(entry)
+ val content = requireContent(entry)
- assertThat(content.privateVersion.style).isEqualTo(Style.Progress)
- val newProgress = assertNotNull(content.privateVersion.newProgress)
- assertThat(newProgress.progress).isEqualTo(75)
- assertThat(newProgress.progressMax).isEqualTo(100)
+ assertThat(content.privateVersion.style).isEqualTo(Style.Progress)
+ val newProgress = assertNotNull(content.privateVersion.newProgress)
+ assertThat(newProgress.progress).isEqualTo(75)
+ assertThat(newProgress.progressMax).isEqualTo(100)
- assertThat(content.publicVersion.style).isEqualTo(Style.Base)
- assertThat(content.publicVersion.title).isNull()
- assertThat(content.publicVersion.text).isNull()
- assertThat(content.publicVersion.newProgress).isNull()
- }
+ assertThat(content.publicVersion.style).isEqualTo(Style.Base)
+ assertThat(content.publicVersion.title).isNull()
+ assertThat(content.publicVersion.text).isNull()
+ assertThat(content.publicVersion.newProgress).isNull()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_fromIneligibleStyle() {
- val entry = createEntry {
- setStyle(MessagingStyle(TEST_PERSON).addMessage("message text", 0L, TEST_PERSON))
- }
+ fun extractContent_fromIneligibleStyle() =
+ kosmos.runTest {
+ val entry = createEntry {
+ setStyle(MessagingStyle(TEST_PERSON).addMessage("message text", 0L, TEST_PERSON))
+ }
- val content = requireContent(entry)
+ val content = requireContent(entry)
- assertThat(content.privateVersion.style).isEqualTo(Style.Ineligible)
+ assertThat(content.privateVersion.style).isEqualTo(Style.Ineligible)
- assertThat(content.publicVersion.style).isEqualTo(Style.Ineligible)
- }
+ assertThat(content.publicVersion.style).isEqualTo(Style.Ineligible)
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_fromOldProgressDeterminate() {
- val entry = createEntry {
- setProgress(TEST_PROGRESS_MAX, TEST_PROGRESS, /* indeterminate= */ false)
- }
+ fun extractContent_fromOldProgressDeterminate() =
+ kosmos.runTest {
+ val entry = createEntry {
+ setProgress(TEST_PROGRESS_MAX, TEST_PROGRESS, /* indeterminate= */ false)
+ }
- val content = requireContent(entry)
+ val content = requireContent(entry)
- val oldProgress = assertNotNull(content.privateVersion.oldProgress)
+ val oldProgress = assertNotNull(content.privateVersion.oldProgress)
- assertThat(oldProgress.progress).isEqualTo(TEST_PROGRESS)
- assertThat(oldProgress.max).isEqualTo(TEST_PROGRESS_MAX)
- assertThat(oldProgress.isIndeterminate).isFalse()
- }
+ assertThat(oldProgress.progress).isEqualTo(TEST_PROGRESS)
+ assertThat(oldProgress.max).isEqualTo(TEST_PROGRESS_MAX)
+ assertThat(oldProgress.isIndeterminate).isFalse()
+ }
@Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
- fun extractContent_fromOldProgressIndeterminate() {
- val entry = createEntry {
- setProgress(TEST_PROGRESS_MAX, TEST_PROGRESS, /* indeterminate= */ true)
- }
+ fun extractContent_fromOldProgressIndeterminate() =
+ kosmos.runTest {
+ val entry = createEntry {
+ setProgress(TEST_PROGRESS_MAX, TEST_PROGRESS, /* indeterminate= */ true)
+ }
- val content = requireContent(entry)
- val oldProgress = assertNotNull(content.privateVersion.oldProgress)
+ val content = requireContent(entry)
+ val oldProgress = assertNotNull(content.privateVersion.oldProgress)
- assertThat(oldProgress.progress).isEqualTo(TEST_PROGRESS)
- assertThat(oldProgress.max).isEqualTo(TEST_PROGRESS_MAX)
- assertThat(oldProgress.isIndeterminate).isTrue()
- }
+ assertThat(oldProgress.progress).isEqualTo(TEST_PROGRESS)
+ assertThat(oldProgress.max).isEqualTo(TEST_PROGRESS_MAX)
+ assertThat(oldProgress.isIndeterminate).isTrue()
+ }
- private fun requireContent(
+ private fun Kosmos.requireContent(
entry: NotificationEntry,
redactionType: Int = REDACTION_TYPE_PUBLIC,
): PromotedNotificationContentModels = assertNotNull(extractContent(entry, redactionType))
- private fun extractContent(
+ private fun Kosmos.extractContent(
entry: NotificationEntry,
redactionType: Int = REDACTION_TYPE_PUBLIC,
): PromotedNotificationContentModels? {
@@ -636,7 +664,7 @@ class PromotedNotificationContentExtractorImplTest : SysuiTestCase() {
return underTest.extractContent(entry, recoveredBuilder, redactionType, imageModelProvider)
}
- private fun createEntry(
+ private fun Kosmos.createEntry(
promoted: Boolean = true,
builderBlock: Notification.Builder.() -> Unit = {},
): NotificationEntry {
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationsInteractorTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationsInteractorTest.kt
new file mode 100644
index 000000000000..bad33a402ff7
--- /dev/null
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationsInteractorTest.kt
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.notification.promoted.domain.interactor
+
+import android.app.Notification
+import android.content.applicationContext
+import android.platform.test.annotations.EnableFlags
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.systemui.SysuiTestCase
+import com.android.systemui.dump.dumpManager
+import com.android.systemui.keyguard.data.repository.fakeKeyguardRepository
+import com.android.systemui.keyguard.domain.interactor.keyguardInteractor
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.Kosmos.Fixture
+import com.android.systemui.kosmos.collectLastValue
+import com.android.systemui.kosmos.runTest
+import com.android.systemui.kosmos.useUnconfinedTestDispatcher
+import com.android.systemui.statusbar.chips.notification.domain.interactor.statusBarNotificationChipsInteractor
+import com.android.systemui.statusbar.chips.notification.shared.StatusBarNotifChips
+import com.android.systemui.statusbar.core.StatusBarRootModernization
+import com.android.systemui.statusbar.notification.collection.NotificationEntry
+import com.android.systemui.statusbar.notification.collection.buildPromotedOngoingEntry
+import com.android.systemui.statusbar.notification.domain.interactor.renderNotificationListInteractor
+import com.android.systemui.statusbar.notification.promoted.PromotedNotificationUi
+import com.android.systemui.statusbar.phone.ongoingcall.StatusBarChipsModernization
+import com.android.systemui.statusbar.policy.domain.interactor.sensitiveNotificationProtectionInteractor
+import com.android.systemui.statusbar.policy.mockSensitiveNotificationProtectionController
+import com.android.systemui.testKosmos
+import com.google.common.truth.Truth.assertThat
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.kotlin.any
+import org.mockito.kotlin.whenever
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+@EnableFlags(
+ PromotedNotificationUi.FLAG_NAME,
+ StatusBarNotifChips.FLAG_NAME,
+ StatusBarChipsModernization.FLAG_NAME,
+ StatusBarRootModernization.FLAG_NAME,
+)
+class AODPromotedNotificationsInteractorTest : SysuiTestCase() {
+ private val kosmos = testKosmos().useUnconfinedTestDispatcher()
+
+ private val Kosmos.underTest by Fixture {
+ AODPromotedNotificationInteractor(
+ promotedNotificationsInteractor = promotedNotificationsInteractor,
+ keyguardInteractor = keyguardInteractor,
+ sensitiveNotificationProtectionInteractor = sensitiveNotificationProtectionInteractor,
+ dumpManager = dumpManager,
+ )
+ }
+
+ @Before
+ fun setUp() {
+ kosmos.statusBarNotificationChipsInteractor.start()
+ }
+
+ private fun Kosmos.buildPublicPrivatePromotedOngoing(): NotificationEntry =
+ buildPromotedOngoingEntry {
+ modifyNotification(applicationContext)
+ .setContentTitle("SENSITIVE")
+ .setPublicVersion(
+ Notification.Builder(applicationContext, "channel")
+ .setContentTitle("REDACTED")
+ .build()
+ )
+ }
+
+ @Test
+ fun content_sensitive_unlocked() =
+ kosmos.runTest {
+ // GIVEN a promoted entry
+ val ronEntry = buildPublicPrivatePromotedOngoing()
+
+ setKeyguardLocked(false)
+ setScreenSharingProtectionActive(false)
+
+ renderNotificationListInteractor.setRenderedList(listOf(ronEntry))
+
+ // THEN aod content is sensitive
+ val content by collectLastValue(underTest.content)
+ assertThat(content?.title).isEqualTo("SENSITIVE")
+ }
+
+ @Test
+ fun content_sensitive_locked() =
+ kosmos.runTest {
+ // GIVEN a promoted entry
+ val ronEntry = buildPublicPrivatePromotedOngoing()
+
+ setKeyguardLocked(true)
+ setScreenSharingProtectionActive(false)
+
+ renderNotificationListInteractor.setRenderedList(listOf(ronEntry))
+
+ // THEN aod content is sensitive
+ val content by collectLastValue(underTest.content)
+ assertThat(content).isNotNull()
+ assertThat(content?.title).isNull() // SOON: .isEqualTo("REDACTED")
+ }
+
+ @Test
+ fun content_sensitive_unlocked_screensharing() =
+ kosmos.runTest {
+ // GIVEN a promoted entry
+ val ronEntry = buildPublicPrivatePromotedOngoing()
+
+ setKeyguardLocked(false)
+ setScreenSharingProtectionActive(true)
+
+ renderNotificationListInteractor.setRenderedList(listOf(ronEntry))
+
+ // THEN aod content is sensitive
+ val content by collectLastValue(underTest.content)
+ assertThat(content).isNotNull()
+ assertThat(content?.title).isNull() // SOON: .isEqualTo("REDACTED")
+ }
+
+ private fun Kosmos.setKeyguardLocked(locked: Boolean) {
+ fakeKeyguardRepository.setKeyguardDismissible(!locked)
+ }
+
+ private fun Kosmos.setScreenSharingProtectionActive(active: Boolean) {
+ whenever(mockSensitiveNotificationProtectionController.isSensitiveStateActive)
+ .thenReturn(active)
+ whenever(mockSensitiveNotificationProtectionController.shouldProtectNotification(any()))
+ .thenReturn(active)
+ }
+}
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java
index 19b1046f1931..4aa21a68b2e0 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/row/NotificationContentInflaterTest.java
@@ -399,35 +399,6 @@ public class NotificationContentInflaterTest extends SysuiTestCase {
}
@Test
- @EnableFlags(PromotedNotificationUi.FLAG_NAME)
- @DisableFlags(StatusBarNotifChips.FLAG_NAME)
- public void testExtractsPromotedContent_whePromotedNotificationUiFlagEnabled()
- throws Exception {
- final PromotedNotificationContentModels content =
- new PromotedNotificationContentBuilder("key").build();
- mPromotedNotificationContentExtractor.resetForEntry(mRow.getEntry(), content);
-
- inflateAndWait(mNotificationInflater, FLAG_CONTENT_VIEW_ALL, mRow);
-
- mPromotedNotificationContentExtractor.verifyOneExtractCall();
- assertEquals(content, mRow.getEntry().getPromotedNotificationContentModels());
- }
-
- @Test
- @EnableFlags(StatusBarNotifChips.FLAG_NAME)
- @DisableFlags(PromotedNotificationUi.FLAG_NAME)
- public void testExtractsPromotedContent_whenStatusBarNotifChipsFlagEnabled() throws Exception {
- final PromotedNotificationContentModels content =
- new PromotedNotificationContentBuilder("key").build();
- mPromotedNotificationContentExtractor.resetForEntry(mRow.getEntry(), content);
-
- inflateAndWait(mNotificationInflater, FLAG_CONTENT_VIEW_ALL, mRow);
-
- mPromotedNotificationContentExtractor.verifyOneExtractCall();
- assertEquals(content, mRow.getEntry().getPromotedNotificationContentModels());
- }
-
- @Test
@EnableFlags({PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME})
public void testExtractsPromotedContent_whenBothFlagsEnabled() throws Exception {
final PromotedNotificationContentModels content =
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/row/NotificationRowContentBinderImplTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/row/NotificationRowContentBinderImplTest.kt
index dcba3e447dda..21b0c9013b5f 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/row/NotificationRowContentBinderImplTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/row/NotificationRowContentBinderImplTest.kt
@@ -465,32 +465,6 @@ class NotificationRowContentBinderImplTest : SysuiTestCase() {
}
@Test
- @EnableFlags(PromotedNotificationUi.FLAG_NAME)
- @DisableFlags(StatusBarNotifChips.FLAG_NAME)
- fun testExtractsPromotedContent_whenPromotedNotificationUiFlagEnabled() {
- val content = PromotedNotificationContentBuilder("key").build()
- promotedNotificationContentExtractor.resetForEntry(row.entry, content)
-
- inflateAndWait(notificationInflater, FLAG_CONTENT_VIEW_ALL, row)
-
- promotedNotificationContentExtractor.verifyOneExtractCall()
- Assert.assertEquals(content, row.entry.promotedNotificationContentModels)
- }
-
- @Test
- @EnableFlags(StatusBarNotifChips.FLAG_NAME)
- @DisableFlags(PromotedNotificationUi.FLAG_NAME)
- fun testExtractsPromotedContent_whenStatusBarNotifChipsFlagEnabled() {
- val content = PromotedNotificationContentBuilder("key").build()
- promotedNotificationContentExtractor.resetForEntry(row.entry, content)
-
- inflateAndWait(notificationInflater, FLAG_CONTENT_VIEW_ALL, row)
-
- promotedNotificationContentExtractor.verifyOneExtractCall()
- Assert.assertEquals(content, row.entry.promotedNotificationContentModels)
- }
-
- @Test
@EnableFlags(PromotedNotificationUi.FLAG_NAME, StatusBarNotifChips.FLAG_NAME)
fun testExtractsPromotedContent_whenBothFlagsEnabled() {
val content = PromotedNotificationContentBuilder("key").build()
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainerTest.java b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainerTest.java
index 761ed6186afc..ca4dc0e5e546 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainerTest.java
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/notification/stack/NotificationChildrenContainerTest.java
@@ -16,6 +16,8 @@
package com.android.systemui.statusbar.notification.stack;
+import static com.android.systemui.statusbar.notification.row.NotificationRowContentBinder.FLAG_CONTENT_VIEW_ALL;
+
import static org.junit.Assert.assertNull;
import android.app.Notification;
@@ -64,6 +66,7 @@ public class NotificationChildrenContainerTest extends SysuiTestCase {
mContext,
mDependency,
TestableLooper.get(this));
+ mNotificationTestHelper.setDefaultInflationFlags(FLAG_CONTENT_VIEW_ALL);
mGroup = mNotificationTestHelper.createGroup();
mChildrenContainer = mGroup.getChildrenContainer();
}
@@ -172,9 +175,12 @@ public class NotificationChildrenContainerTest extends SysuiTestCase {
@Test
@EnableFlags(AsyncGroupHeaderViewInflation.FLAG_NAME)
public void testSetLowPriorityWithAsyncInflation_noHeaderReInflation() {
+ mChildrenContainer.setLowPriorityGroupHeader(null, null);
mChildrenContainer.setIsMinimized(true);
+
+ // THEN
assertNull("We don't inflate header from the main thread with Async "
- + "Inflation enabled", mChildrenContainer.getCurrentHeaderView());
+ + "Inflation enabled", mChildrenContainer.getMinimizedNotificationHeader());
}
@Test
@@ -182,7 +188,7 @@ public class NotificationChildrenContainerTest extends SysuiTestCase {
public void setLowPriorityBeforeLowPriorityHeaderSet() {
//Given: the children container does not have a low-priority header, and is not low-priority
- assertNull(mChildrenContainer.getMinimizedGroupHeaderWrapper());
+ mChildrenContainer.setLowPriorityGroupHeader(null, null);
mGroup.setIsMinimized(false);
//When: set the children container to be low-priority and set the low-priority header
@@ -214,8 +220,8 @@ public class NotificationChildrenContainerTest extends SysuiTestCase {
public void changeLowPriorityAfterHeaderSet() {
//Given: the children container does not have headers, and is not low-priority
- assertNull(mChildrenContainer.getMinimizedGroupHeaderWrapper());
- assertNull(mChildrenContainer.getNotificationHeaderWrapper());
+ mChildrenContainer.setLowPriorityGroupHeader(null, null);
+ mChildrenContainer.setGroupHeader(null, null);
mGroup.setIsMinimized(false);
//When: set the set the normal header
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorKairosAdapterTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorKairosAdapterTest.kt
index e72d0c27e632..8aff622ee772 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorKairosAdapterTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconInteractorKairosAdapterTest.kt
@@ -97,7 +97,7 @@ class MobileIconInteractorKairosAdapterTest : MobileIconInteractorTestBase() {
}
.asIncremental()
.applyLatestSpecForKey(),
- isStackable = interactor.isStackable.toState(),
+ isStackable = interactor.isStackable.toState(false),
activeDataConnectionHasDataEnabled =
interactor.activeDataConnectionHasDataEnabled.toState(),
activeDataIconInteractor =
diff --git a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModelTest.kt b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModelTest.kt
index 3d37914b1a7d..7dbcb270190c 100644
--- a/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModelTest.kt
+++ b/packages/SystemUI/multivalentTests/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModelTest.kt
@@ -60,7 +60,6 @@ class MobileIconsViewModelTest : SysuiTestCase() {
private val interactor = FakeMobileIconsInteractor(FakeMobileMappingsProxy(), mock())
private lateinit var airplaneModeInteractor: AirplaneModeInteractor
- @Mock private lateinit var constants: ConnectivityConstants
@Mock private lateinit var logger: MobileViewLogger
@Mock private lateinit var verboseLogger: VerboseMobileViewLogger
@@ -84,7 +83,10 @@ class MobileIconsViewModelTest : SysuiTestCase() {
verboseLogger,
interactor,
airplaneModeInteractor,
- constants,
+ object : ConnectivityConstants {
+ override val hasDataCapabilities = true
+ override val shouldShowActivityConfig = false
+ },
testScope.backgroundScope,
)
@@ -349,7 +351,42 @@ class MobileIconsViewModelTest : SysuiTestCase() {
// WHEN sub2 becomes last and sub2 has a network type icon
interactor.filteredSubscriptions.value = listOf(SUB_1, SUB_2)
- // THEN the flow updates
+ assertThat(latest).isTrue()
+ job.cancel()
+ }
+
+ @Test
+ fun isStackable_apmEnabled_false() =
+ testScope.runTest {
+ var latest: Boolean? = null
+ val job = underTest.isStackable.onEach { latest = it }.launchIn(this)
+
+ // Set the interactor to true to test APM
+ interactor.isStackable.value = true
+
+ // Enable APM
+ airplaneModeInteractor.setIsAirplaneMode(true)
+
+ interactor.filteredSubscriptions.value = listOf(SUB_1, SUB_2)
+
+ assertThat(latest).isFalse()
+ job.cancel()
+ }
+
+ @Test
+ fun isStackable_apmDisabled_true() =
+ testScope.runTest {
+ var latest: Boolean? = null
+ val job = underTest.isStackable.onEach { latest = it }.launchIn(this)
+
+ // Set the interactor to true to test APM
+ interactor.isStackable.value = true
+
+ // Disable APM
+ airplaneModeInteractor.setIsAirplaneMode(false)
+
+ interactor.filteredSubscriptions.value = listOf(SUB_1, SUB_2)
+
assertThat(latest).isTrue()
job.cancel()
diff --git a/packages/SystemUI/res/drawable/ic_qs_category_accessibility.xml b/packages/SystemUI/res/drawable/ic_qs_category_accessibility.xml
new file mode 100644
index 000000000000..bc62d38f1932
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_qs_category_accessibility.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2025 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.
+ -->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:tint="?attr/colorControlNormal"
+ android:viewportHeight="960"
+ android:viewportWidth="960">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M480,240Q447,240 423.5,216.5Q400,193 400,160Q400,127 423.5,103.5Q447,80 480,80Q513,80 536.5,103.5Q560,127 560,160Q560,193 536.5,216.5Q513,240 480,240ZM360,840L360,360Q311,356 261,349Q211,342 163,331Q146,327 135.5,312Q125,297 130,280Q135,263 151,255Q167,247 185,251Q255,266 330.5,273Q406,280 480,280Q554,280 629.5,273Q705,266 775,251Q793,247 809,255Q825,263 830,280Q835,297 824.5,312Q814,327 797,331Q749,342 699,349Q649,356 600,360L600,840Q600,857 588.5,868.5Q577,880 560,880Q543,880 531.5,868.5Q520,857 520,840L520,640L440,640L440,840Q440,857 428.5,868.5Q417,880 400,880Q383,880 371.5,868.5Q360,857 360,840Z" />
+</vector> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/ic_qs_category_connectivty.xml b/packages/SystemUI/res/drawable/ic_qs_category_connectivty.xml
new file mode 100644
index 000000000000..91644873c064
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_qs_category_connectivty.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2025 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.
+ -->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:tint="?attr/colorControlNormal"
+ android:viewportHeight="960"
+ android:viewportWidth="960">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M480,840Q438,840 409,811Q380,782 380,740Q380,698 409,669Q438,640 480,640Q522,640 551,669Q580,698 580,740Q580,782 551,811Q522,840 480,840ZM480,400Q555,400 622.5,424Q690,448 745,490Q765,505 765.5,529.5Q766,554 748,572Q731,589 706,589.5Q681,590 661,576Q623,550 577,535Q531,520 480,520Q429,520 383,535Q337,550 299,576Q279,590 254,589Q229,588 212,571Q195,553 195,528.5Q195,504 215,489Q270,447 337.5,423.5Q405,400 480,400ZM480,160Q605,160 715.5,201Q826,242 914,317Q934,334 935,359Q936,384 918,402Q901,419 876,419.5Q851,420 831,404Q759,345 669.5,312.5Q580,280 480,280Q380,280 290.5,312.5Q201,345 129,404Q109,420 84,419.5Q59,419 42,402Q24,384 25,359Q26,334 46,317Q134,242 244.5,201Q355,160 480,160Z" />
+</vector> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/ic_qs_category_display.xml b/packages/SystemUI/res/drawable/ic_qs_category_display.xml
new file mode 100644
index 000000000000..c238e940eb01
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_qs_category_display.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2025 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.
+ -->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:tint="?attr/colorControlNormal"
+ android:viewportHeight="960"
+ android:viewportWidth="960">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M346,800L240,800Q207,800 183.5,776.5Q160,753 160,720L160,614L83,536Q72,524 66,509.5Q60,495 60,480Q60,465 66,450.5Q72,436 83,424L160,346L160,240Q160,207 183.5,183.5Q207,160 240,160L346,160L424,83Q436,72 450.5,66Q465,60 480,60Q495,60 509.5,66Q524,72 536,83L614,160L720,160Q753,160 776.5,183.5Q800,207 800,240L800,346L877,424Q888,436 894,450.5Q900,465 900,480Q900,495 894,509.5Q888,524 877,536L800,614L800,720Q800,753 776.5,776.5Q753,800 720,800L614,800L536,877Q524,888 509.5,894Q495,900 480,900Q465,900 450.5,894Q436,888 424,877L346,800ZM380,720L480,820Q480,820 480,820Q480,820 480,820L580,720L720,720Q720,720 720,720Q720,720 720,720L720,580L820,480Q820,480 820,480Q820,480 820,480L720,380L720,240Q720,240 720,240Q720,240 720,240L580,240L480,140Q480,140 480,140Q480,140 480,140L380,240L240,240Q240,240 240,240Q240,240 240,240L240,380L140,480Q140,480 140,480Q140,480 140,480L240,580L240,720Q240,720 240,720Q240,720 240,720L380,720ZM480,680Q563,680 621.5,621.5Q680,563 680,480Q680,397 621.5,338.5Q563,280 480,280L480,680Z" />
+</vector> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/ic_qs_category_privacy.xml b/packages/SystemUI/res/drawable/ic_qs_category_privacy.xml
new file mode 100644
index 000000000000..915cf41ba1f6
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_qs_category_privacy.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2025 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.
+ -->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:tint="?attr/colorControlNormal"
+ android:viewportHeight="960"
+ android:viewportWidth="960">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M444,600L516,600Q525,600 531.5,592.5Q538,585 536,576L517,471Q537,461 548.5,442Q560,423 560,400Q560,367 536.5,343.5Q513,320 480,320Q447,320 423.5,343.5Q400,367 400,400Q400,423 411.5,442Q423,461 443,471L424,576Q422,585 428.5,592.5Q435,600 444,600ZM480,876Q473,876 467,875Q461,874 455,872Q320,827 240,705.5Q160,584 160,444L160,255Q160,230 174.5,210Q189,190 212,181L452,91Q466,86 480,86Q494,86 508,91L748,181Q771,190 785.5,210Q800,230 800,255L800,444Q800,584 720,705.5Q640,827 505,872Q499,874 493,875Q487,876 480,876Z" />
+</vector> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/ic_qs_category_provided_by_apps.xml b/packages/SystemUI/res/drawable/ic_qs_category_provided_by_apps.xml
new file mode 100644
index 000000000000..cea43ae1bc2f
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_qs_category_provided_by_apps.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2025 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.
+ -->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:tint="?attr/colorControlNormal"
+ android:viewportHeight="960"
+ android:viewportWidth="960">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M240,800Q207,800 183.5,776.5Q160,753 160,720Q160,687 183.5,663.5Q207,640 240,640Q273,640 296.5,663.5Q320,687 320,720Q320,753 296.5,776.5Q273,800 240,800ZM480,800Q447,800 423.5,776.5Q400,753 400,720Q400,687 423.5,663.5Q447,640 480,640Q513,640 536.5,663.5Q560,687 560,720Q560,753 536.5,776.5Q513,800 480,800ZM720,800Q687,800 663.5,776.5Q640,753 640,720Q640,687 663.5,663.5Q687,640 720,640Q753,640 776.5,663.5Q800,687 800,720Q800,753 776.5,776.5Q753,800 720,800ZM240,560Q207,560 183.5,536.5Q160,513 160,480Q160,447 183.5,423.5Q207,400 240,400Q273,400 296.5,423.5Q320,447 320,480Q320,513 296.5,536.5Q273,560 240,560ZM480,560Q447,560 423.5,536.5Q400,513 400,480Q400,447 423.5,423.5Q447,400 480,400Q513,400 536.5,423.5Q560,447 560,480Q560,513 536.5,536.5Q513,560 480,560ZM720,560Q687,560 663.5,536.5Q640,513 640,480Q640,447 663.5,423.5Q687,400 720,400Q753,400 776.5,423.5Q800,447 800,480Q800,513 776.5,536.5Q753,560 720,560ZM240,320Q207,320 183.5,296.5Q160,273 160,240Q160,207 183.5,183.5Q207,160 240,160Q273,160 296.5,183.5Q320,207 320,240Q320,273 296.5,296.5Q273,320 240,320ZM480,320Q447,320 423.5,296.5Q400,273 400,240Q400,207 423.5,183.5Q447,160 480,160Q513,160 536.5,183.5Q560,207 560,240Q560,273 536.5,296.5Q513,320 480,320ZM720,320Q687,320 663.5,296.5Q640,273 640,240Q640,207 663.5,183.5Q687,160 720,160Q753,160 776.5,183.5Q800,207 800,240Q800,273 776.5,296.5Q753,320 720,320Z" />
+</vector> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/ic_qs_category_unknown.xml b/packages/SystemUI/res/drawable/ic_qs_category_unknown.xml
new file mode 100644
index 000000000000..ec2ce15e2d01
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_qs_category_unknown.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2025 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.
+ -->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:tint="?attr/colorControlNormal"
+ android:viewportHeight="960"
+ android:viewportWidth="960">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M200,840Q167,840 143.5,816.5Q120,793 120,760L120,640Q120,623 131.5,611.5Q143,600 160,600Q177,600 188.5,611.5Q200,623 200,640L200,760Q200,760 200,760Q200,760 200,760L320,760Q337,760 348.5,771.5Q360,783 360,800Q360,817 348.5,828.5Q337,840 320,840L200,840ZM760,840L640,840Q623,840 611.5,828.5Q600,817 600,800Q600,783 611.5,771.5Q623,760 640,760L760,760Q760,760 760,760Q760,760 760,760L760,640Q760,623 771.5,611.5Q783,600 800,600Q817,600 828.5,611.5Q840,623 840,640L840,760Q840,793 816.5,816.5Q793,840 760,840ZM120,200Q120,167 143.5,143.5Q167,120 200,120L320,120Q337,120 348.5,131.5Q360,143 360,160Q360,177 348.5,188.5Q337,200 320,200L200,200Q200,200 200,200Q200,200 200,200L200,320Q200,337 188.5,348.5Q177,360 160,360Q143,360 131.5,348.5Q120,337 120,320L120,200ZM840,200L840,320Q840,337 828.5,348.5Q817,360 800,360Q783,360 771.5,348.5Q760,337 760,320L760,200Q760,200 760,200Q760,200 760,200L640,200Q623,200 611.5,188.5Q600,177 600,160Q600,143 611.5,131.5Q623,120 640,120L760,120Q793,120 816.5,143.5Q840,167 840,200ZM480,720Q501,720 515.5,705.5Q530,691 530,670Q530,649 515.5,634.5Q501,620 480,620Q459,620 444.5,634.5Q430,649 430,670Q430,691 444.5,705.5Q459,720 480,720ZM480,308Q506,308 525.5,324Q545,340 545,365Q545,388 530.5,406Q516,424 499,439Q473,462 459.5,482.5Q446,503 444,532Q443,546 454,556.5Q465,567 480,567Q494,567 505.5,557Q517,547 519,532Q521,515 531,502Q541,489 560,470Q595,435 606.5,413.5Q618,392 618,362Q618,308 579,274Q540,240 480,240Q439,240 406.5,258.5Q374,277 357,311Q351,323 356.5,335.5Q362,348 375,353Q388,358 401.5,353Q415,348 423,337Q434,323 448.5,315.5Q463,308 480,308Z" />
+</vector> \ No newline at end of file
diff --git a/packages/SystemUI/res/drawable/ic_qs_category_utilities.xml b/packages/SystemUI/res/drawable/ic_qs_category_utilities.xml
new file mode 100644
index 000000000000..4dfac8393b8e
--- /dev/null
+++ b/packages/SystemUI/res/drawable/ic_qs_category_utilities.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?><!--
+ ~ Copyright (C) 2025 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.
+ -->
+
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp"
+ android:height="24dp"
+ android:tint="?attr/colorControlNormal"
+ android:viewportHeight="960"
+ android:viewportWidth="960">
+ <path
+ android:fillColor="@android:color/white"
+ android:pathData="M433,880Q406,880 386.5,862Q367,844 363,818L354,752Q341,747 329.5,740Q318,733 307,725L245,751Q220,762 195,753Q170,744 156,721L109,639Q95,616 101,590Q107,564 128,547L181,507Q180,500 180,493.5Q180,487 180,480Q180,473 180,466.5Q180,460 181,453L128,413Q107,396 101,370Q95,344 109,321L156,239Q170,216 195,207Q220,198 245,209L307,235Q318,227 330,220Q342,213 354,208L363,142Q367,116 386.5,98Q406,80 433,80L527,80Q554,80 573.5,98Q593,116 597,142L606,208Q619,213 630.5,220Q642,227 653,235L715,209Q740,198 765,207Q790,216 804,239L851,321Q865,344 859,370Q853,396 832,413L779,453Q780,460 780,466.5Q780,473 780,480Q780,487 780,493.5Q780,500 778,507L831,547Q852,564 858,590Q864,616 850,639L802,721Q788,744 763,753Q738,762 713,751L653,725Q642,733 630,740Q618,747 606,752L597,818Q593,844 573.5,862Q554,880 527,880L433,880ZM482,620Q540,620 581,579Q622,538 622,480Q622,422 581,381Q540,340 482,340Q423,340 382.5,381Q342,422 342,480Q342,538 382.5,579Q423,620 482,620Z" />
+</vector> \ No newline at end of file
diff --git a/packages/SystemUI/res/layout/battery_percentage_view.xml b/packages/SystemUI/res/layout/battery_percentage_view.xml
index 8b5aeaac424a..8aa6930a09f9 100644
--- a/packages/SystemUI/res/layout/battery_percentage_view.xml
+++ b/packages/SystemUI/res/layout/battery_percentage_view.xml
@@ -22,7 +22,7 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
- android:textAppearance="@style/TextAppearance.StatusBar.Clock"
+ android:textAppearance="@style/TextAppearance.StatusBar.Default"
android:textColor="?android:attr/textColorPrimary"
android:gravity="center_vertical|start"
android:paddingStart="@dimen/battery_level_padding_start"
diff --git a/packages/SystemUI/res/layout/biometric_prompt_one_pane_layout.xml b/packages/SystemUI/res/layout/biometric_prompt_one_pane_layout.xml
index 4002f7808637..1e4a07f5fc30 100644
--- a/packages/SystemUI/res/layout/biometric_prompt_one_pane_layout.xml
+++ b/packages/SystemUI/res/layout/biometric_prompt_one_pane_layout.xml
@@ -22,7 +22,7 @@
android:layout_width="0dp"
android:layout_height="0dp"
android:accessibilityLiveRegion="assertive"
- android:importantForAccessibility="yes"
+ android:importantForAccessibility="auto"
android:clickable="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/rightGuideline"
diff --git a/packages/SystemUI/res/layout/biometric_prompt_two_pane_layout.xml b/packages/SystemUI/res/layout/biometric_prompt_two_pane_layout.xml
index 3c8cb6860a41..8234c24a7e17 100644
--- a/packages/SystemUI/res/layout/biometric_prompt_two_pane_layout.xml
+++ b/packages/SystemUI/res/layout/biometric_prompt_two_pane_layout.xml
@@ -23,7 +23,7 @@ android:layout_height="match_parent">
android:layout_width="0dp"
android:layout_height="0dp"
android:accessibilityLiveRegion="assertive"
- android:importantForAccessibility="yes"
+ android:importantForAccessibility="auto"
android:clickable="false"
android:paddingHorizontal="16dp"
android:paddingVertical="16dp"
diff --git a/packages/SystemUI/res/layout/combined_qs_header.xml b/packages/SystemUI/res/layout/combined_qs_header.xml
index 5c06585de99c..65d17042412b 100644
--- a/packages/SystemUI/res/layout/combined_qs_header.xml
+++ b/packages/SystemUI/res/layout/combined_qs_header.xml
@@ -85,7 +85,7 @@ frame when animating QS <-> QQS transition
android:paddingEnd="@dimen/status_bar_left_clock_end_padding"
android:singleLine="true"
android:textDirection="locale"
- android:textAppearance="@style/TextAppearance.QS.Status"
+ android:textAppearance="@style/TextAppearance.QS.Status.Clock"
android:fontFeatureSettings="tnum"
android:transformPivotX="0dp"
android:transformPivotY="24dp"
diff --git a/packages/SystemUI/res/layout/keyguard_status_bar.xml b/packages/SystemUI/res/layout/keyguard_status_bar.xml
index d5f9d4cc0954..a81d90bd13fc 100644
--- a/packages/SystemUI/res/layout/keyguard_status_bar.xml
+++ b/packages/SystemUI/res/layout/keyguard_status_bar.xml
@@ -76,7 +76,7 @@
android:gravity="center_vertical"
android:ellipsize="marquee"
android:textDirection="locale"
- android:textAppearance="@style/TextAppearance.StatusBar.Carrier"
+ android:textAppearance="@style/TextAppearance.StatusBar.Default"
android:textColor="?attr/wallpaperTextColorSecondary"
android:singleLine="true"
systemui:showMissingSim="true"
diff --git a/packages/SystemUI/res/layout/notification_conversation_info.xml b/packages/SystemUI/res/layout/notification_conversation_info.xml
index 9560be0d6969..56660139f823 100644
--- a/packages/SystemUI/res/layout/notification_conversation_info.xml
+++ b/packages/SystemUI/res/layout/notification_conversation_info.xml
@@ -391,6 +391,16 @@
android:paddingEnd="4dp"
>
<TextView
+ android:id="@+id/inline_dismiss"
+ android:text="@string/notification_inline_dismiss"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignParentStart="true"
+ android:gravity="center_vertical"
+ android:minWidth="@dimen/notification_importance_toggle_size"
+ android:minHeight="@dimen/notification_importance_toggle_size"
+ style="@style/TextAppearance.NotificationInfo.Button"/>
+ <TextView
android:id="@+id/done"
android:text="@string/inline_ok_button"
android:layout_width="wrap_content"
diff --git a/packages/SystemUI/res/layout/status_bar.xml b/packages/SystemUI/res/layout/status_bar.xml
index e4da4729ad0d..359a69ca1f94 100644
--- a/packages/SystemUI/res/layout/status_bar.xml
+++ b/packages/SystemUI/res/layout/status_bar.xml
@@ -96,7 +96,7 @@
android:layout_width="wrap_content"
android:layout_height="@dimen/status_bar_system_icons_height"
android:layout_gravity="center_vertical"
- android:textAppearance="@style/TextAppearance.StatusBar.Clock"
+ android:textAppearance="@style/TextAppearance.StatusBar.Default.Clock"
android:singleLine="true"
android:paddingStart="@dimen/status_bar_left_clock_starting_padding"
android:paddingEnd="@dimen/status_bar_left_clock_end_padding"
diff --git a/packages/SystemUI/res/layout/system_icons.xml b/packages/SystemUI/res/layout/system_icons.xml
index bb99d581c0b0..f3f4e880c121 100644
--- a/packages/SystemUI/res/layout/system_icons.xml
+++ b/packages/SystemUI/res/layout/system_icons.xml
@@ -45,6 +45,6 @@
android:clipChildren="false"
android:paddingEnd="@dimen/status_bar_battery_end_padding"
android:visibility="gone"
- systemui:textAppearance="@style/TextAppearance.StatusBar.Clock" />
+ systemui:textAppearance="@style/TextAppearance.StatusBar.Default" />
</LinearLayout>
diff --git a/packages/SystemUI/res/values/colors.xml b/packages/SystemUI/res/values/colors.xml
index ff16e063f5b1..fe65f32c6eb0 100644
--- a/packages/SystemUI/res/values/colors.xml
+++ b/packages/SystemUI/res/values/colors.xml
@@ -148,6 +148,7 @@
<!-- Animated Action colors -->
<color name="animated_action_button_text_color">@androidprv:color/materialColorOnSurface</color>
<color name="animated_action_button_stroke_color">@androidprv:color/materialColorOnSurface</color>
+ <color name="animated_action_button_attribution_color">@androidprv:color/materialColorOnSurfaceVariant</color>
<!-- Biometric dialog colors -->
<color name="biometric_dialog_gray">#ff757575</color>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index 2d40c32e29e9..50242f69a755 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -2354,8 +2354,8 @@
<string name="group_system_access_all_apps_search">Open apps list</string>
<!-- User visible title for the keyboard shortcut that accesses [system] settings. [CHAR LIMIT=70] -->
<string name="group_system_access_system_settings">Open settings</string>
- <!-- User visible title for the keyboard shortcut that accesses Assistant app. [CHAR LIMIT=70] -->
- <string name="group_system_access_google_assistant">Open assistant</string>
+ <!-- User visible title for the keyboard shortcut that accesses the default digital assistant app. [CHAR LIMIT=70] -->
+ <string name="group_system_access_google_assistant">Open digital assistant</string>
<!-- User visible title for the keyboard shortcut that locks screen. [CHAR LIMIT=70] -->
<string name="group_system_lock_screen">Lock screen</string>
<!-- User visible title for the keyboard shortcut that pulls up Notes app for quick memo. [CHAR LIMIT=70] -->
diff --git a/packages/SystemUI/res/values/styles.xml b/packages/SystemUI/res/values/styles.xml
index ff4c420744d9..bde750145ff7 100644
--- a/packages/SystemUI/res/values/styles.xml
+++ b/packages/SystemUI/res/values/styles.xml
@@ -17,18 +17,15 @@
<resources xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:androidprv="http://schemas.android.com/apk/prv/res/android">
- <style name="TextAppearance.StatusBar.Clock" parent="@*android:style/TextAppearance.StatusBar.Icon">
+ <style name="TextAppearance.StatusBar.Default" parent="@*android:style/TextAppearance.StatusBar.Icon">
<item name="android:textSize">@dimen/status_bar_clock_size</item>
<item name="android:fontFamily" android:featureFlag="!com.android.systemui.status_bar_font_updates">@*android:string/config_headlineFontFamilyMedium</item>
<item name="android:fontFamily" android:featureFlag="com.android.systemui.status_bar_font_updates">"variable-label-large-emphasized"</item>
<item name="android:textColor">@color/status_bar_clock_color</item>
- <item name="android:fontFeatureSettings">tnum</item>
</style>
- <style name="TextAppearance.StatusBar.Carrier" parent="@*android:style/TextAppearance.StatusBar.Icon">
- <item name="android:textSize">@dimen/status_bar_clock_size</item>
- <item name="android:fontFamily">@*android:string/config_headlineFontFamilyMedium</item>
- <item name="android:textColor">@color/status_bar_clock_color</item>
+ <style name="TextAppearance.StatusBar.Default.Clock">
+ <item name="android:fontFeatureSettings">tnum</item>
</style>
<style name="TextAppearance.StatusBar.UserChip" parent="@*android:style/TextAppearance.StatusBar.Icon">
@@ -184,15 +181,19 @@
<item name="android:textColor">@androidprv:color/materialColorOnSurfaceVariant</item>
</style>
- <!-- This is hard coded to be sans-serif-condensed to match the icons -->
-
<style name="TextAppearance.QS.Status">
- <item name="android:fontFamily">@*android:string/config_headlineFontFamily</item>
+ <item name="android:fontFamily" android:featureFlag="!com.android.systemui.shade_header_font_update">@*android:string/config_headlineFontFamily</item>
+ <item name="android:fontFamily" android:featureFlag="com.android.systemui.shade_header_font_update">variable-body-medium-emphasized</item>
<item name="android:textColor">@color/shade_header_text_color</item>
<item name="android:textSize">14sp</item>
<item name="android:letterSpacing">0.01</item>
</style>
+ <style name="TextAppearance.QS.Status.Clock">
+ <item name="android:fontFamily" android:featureFlag="!com.android.systemui.shade_header_font_update">@*android:string/config_headlineFontFamily</item>
+ <item name="android:fontFamily" android:featureFlag="com.android.systemui.shade_header_font_update">variable-display-small-emphasized</item>
+ </style>
+
<style name="TextAppearance.QS.Status.Build">
<item name="android:textColor">?attr/onShadeInactiveVariant</item>
</style>
diff --git a/packages/SystemUI/src/com/android/systemui/backup/BackupHelper.kt b/packages/SystemUI/src/com/android/systemui/backup/BackupHelper.kt
index a107322423bb..c5cd39ccbc9f 100644
--- a/packages/SystemUI/src/com/android/systemui/backup/BackupHelper.kt
+++ b/packages/SystemUI/src/com/android/systemui/backup/BackupHelper.kt
@@ -28,6 +28,7 @@ import android.os.ParcelFileDescriptor
import android.os.UserHandle
import android.util.Log
import com.android.app.tracing.traceSection
+import com.android.systemui.Flags
import com.android.systemui.backup.BackupHelper.Companion.ACTION_RESTORE_FINISHED
import com.android.systemui.communal.data.backup.CommunalBackupHelper
import com.android.systemui.communal.data.backup.CommunalBackupUtils
@@ -118,7 +119,9 @@ open class BackupHelper : BackupAgentHelper() {
}
private fun communalEnabled(): Boolean {
- return resources.getBoolean(R.bool.config_communalServiceEnabled)
+ return resources.getBoolean(R.bool.config_communalServiceEnabled) ||
+ (Flags.glanceableHubV2() &&
+ resources.getBoolean(com.android.internal.R.bool.config_glanceableHubEnabled))
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/UdfpsOverlayInteractor.kt b/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/UdfpsOverlayInteractor.kt
index 8a5e011cd3ce..2bb9809af30e 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/UdfpsOverlayInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/domain/interactor/UdfpsOverlayInteractor.kt
@@ -16,6 +16,7 @@
package com.android.systemui.biometrics.domain.interactor
+import android.annotation.SuppressLint
import android.content.Context
import android.hardware.fingerprint.FingerprintManager
import android.util.Log
@@ -32,10 +33,14 @@ import javax.inject.Inject
import kotlin.math.max
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.awaitClose
+import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
@@ -131,6 +136,25 @@ constructor(
}
.distinctUntilChanged()
+ /**
+ * Event flow that emits every time the user taps the screen and a UDFPS guidance message is
+ * surfaced and then cleared. Modeled as a SharedFlow because a StateFlow fails to emit every
+ * event to the subscriber, causing missed Talkback feedback and incorrect focusability state of
+ * the UDFPS accessibility overlay.
+ */
+ @SuppressLint("SharedFlowCreation")
+ private val _clearAccessibilityOverlayMessageReason = MutableSharedFlow<String?>()
+
+ /** Indicates the reason for clearing the UDFPS accessibility overlay content description */
+ val clearAccessibilityOverlayMessageReason: SharedFlow<String?> =
+ _clearAccessibilityOverlayMessageReason.asSharedFlow()
+
+ suspend fun clearUdfpsAccessibilityOverlayMessage(reason: String) {
+ // Add delay to make sure we read the guidance message before clearing it
+ delay(1000)
+ _clearAccessibilityOverlayMessageReason.emit(reason)
+ }
+
companion object {
private const val TAG = "UdfpsOverlayInteractor"
}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
index 3b22e13f29a2..80d06f4a2d37 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/binder/BiometricViewBinder.kt
@@ -27,6 +27,7 @@ import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.IMPORTANT_FOR_ACCESSIBILITY_NO
+import android.view.View.IMPORTANT_FOR_ACCESSIBILITY_YES
import android.view.accessibility.AccessibilityManager
import android.widget.Button
import android.widget.ImageView
@@ -43,7 +44,6 @@ import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieCompositionFactory
-import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.biometrics.Utils.ellipsize
import com.android.systemui.biometrics.shared.model.BiometricModalities
import com.android.systemui.biometrics.shared.model.BiometricModality
@@ -63,6 +63,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.launch
private const val TAG = "BiometricViewBinder"
@@ -123,25 +124,6 @@ object BiometricViewBinder {
val confirmationButton = view.requireViewById<Button>(R.id.button_confirm)
val retryButton = view.requireViewById<Button>(R.id.button_try_again)
- // Handles custom "Cancel Authentication" talkback action
- val cancelDelegate: AccessibilityDelegateCompat =
- object : AccessibilityDelegateCompat() {
- override fun onInitializeAccessibilityNodeInfo(
- host: View,
- info: AccessibilityNodeInfoCompat,
- ) {
- super.onInitializeAccessibilityNodeInfo(host, info)
- info.addAction(
- AccessibilityActionCompat(
- AccessibilityNodeInfoCompat.ACTION_CLICK,
- view.context.getString(R.string.biometric_dialog_cancel_authentication),
- )
- )
- }
- }
- ViewCompat.setAccessibilityDelegate(backgroundView, cancelDelegate)
- ViewCompat.setAccessibilityDelegate(cancelButton, cancelDelegate)
-
// TODO(b/330788871): temporary workaround for the unsafe callbacks & legacy controllers
val adapter =
Spaghetti(
@@ -155,6 +137,33 @@ object BiometricViewBinder {
var boundSize = false
view.repeatWhenAttached {
+ // Handles custom "Cancel Authentication" talkback action
+ val cancelDelegate: AccessibilityDelegateCompat =
+ object : AccessibilityDelegateCompat() {
+ override fun onInitializeAccessibilityNodeInfo(
+ host: View,
+ info: AccessibilityNodeInfoCompat,
+ ) {
+ super.onInitializeAccessibilityNodeInfo(host, info)
+ lifecycleScope.launch {
+ // Clears UDFPS guidance hint after focus moves to cancel view
+ viewModel.onClearUdfpsGuidanceHint(
+ accessibilityManager.isTouchExplorationEnabled
+ )
+ }
+ info.addAction(
+ AccessibilityActionCompat(
+ AccessibilityNodeInfoCompat.ACTION_CLICK,
+ view.context.getString(
+ R.string.biometric_dialog_cancel_authentication
+ ),
+ )
+ )
+ }
+ }
+ ViewCompat.setAccessibilityDelegate(backgroundView, cancelDelegate)
+ ViewCompat.setAccessibilityDelegate(cancelButton, cancelDelegate)
+
// these do not change and need to be set before any size transitions
val modalities = viewModel.modalities.first()
@@ -404,11 +413,16 @@ object BiometricViewBinder {
}
false
}
+
launch {
viewModel.accessibilityHint.collect { message ->
- if (message.isNotBlank()) {
- udfpsGuidanceView.contentDescription = message
- }
+ udfpsGuidanceView.importantForAccessibility =
+ if (message == null) {
+ IMPORTANT_FOR_ACCESSIBILITY_NO
+ } else {
+ IMPORTANT_FOR_ACCESSIBILITY_YES
+ }
+ udfpsGuidanceView.contentDescription = message
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
index 4e17a2658ee7..27fc1878cc99 100644
--- a/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModel.kt
@@ -187,10 +187,10 @@ constructor(
}
}
- private val _accessibilityHint = MutableSharedFlow<String>()
+ private val _accessibilityHint = MutableSharedFlow<String?>()
/** Hint for talkback directional guidance */
- val accessibilityHint: Flow<String> = _accessibilityHint.asSharedFlow()
+ val accessibilityHint: Flow<String?> = _accessibilityHint.asSharedFlow()
private val _isAuthenticating: MutableStateFlow<Boolean> = MutableStateFlow(false)
@@ -923,6 +923,19 @@ constructor(
return false
}
+ /** Clears the message used for UDFPS directional guidance */
+ suspend fun onClearUdfpsGuidanceHint(touchExplorationEnabled: Boolean) {
+ if (
+ modalities.first().hasUdfps &&
+ touchExplorationEnabled &&
+ !isAuthenticated.first().isAuthenticated
+ ) {
+ // Add delay to make sure we read the guidance message before clearing it
+ delay(1000)
+ _accessibilityHint.emit(null)
+ }
+ }
+
/**
* Switch to the credential view.
*
diff --git a/packages/SystemUI/src/com/android/systemui/brightness/ui/compose/BrightnessSlider.kt b/packages/SystemUI/src/com/android/systemui/brightness/ui/compose/BrightnessSlider.kt
index 6aeb35b3b158..99f299918969 100644
--- a/packages/SystemUI/src/com/android/systemui/brightness/ui/compose/BrightnessSlider.kt
+++ b/packages/SystemUI/src/com/android/systemui/brightness/ui/compose/BrightnessSlider.kt
@@ -37,6 +37,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
+import androidx.compose.material3.SliderColors
import androidx.compose.material3.SliderDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
@@ -73,6 +74,7 @@ import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.compose.modifiers.padding
+import com.android.compose.theme.LocalAndroidColorScheme
import com.android.compose.ui.graphics.drawInOverlay
import com.android.systemui.Flags
import com.android.systemui.biometrics.Utils.toBitmap
@@ -139,7 +141,7 @@ fun BrightnessSlider(
} else {
null
}
- val colors = SliderDefaults.colors()
+ val colors = colors()
// The value state is recreated every time gammaValue changes, so we recreate this derivedState
// We have to use value as that's the value that changes when the user is dragging (gammaValue
@@ -211,6 +213,7 @@ fun BrightnessSlider(
interactionSource = interactionSource,
enabled = enabled,
thumbSize = DpSize(4.dp, 52.dp),
+ colors = colors,
)
},
track = { sliderState ->
@@ -293,6 +296,7 @@ fun BrightnessSlider(
trackInsideCornerSize = 2.dp,
drawStopIndicator = null,
thumbTrackGapSize = ThumbTrackGapSize,
+ colors = colors,
)
},
)
@@ -441,3 +445,13 @@ object BrightnessSliderMotionTestKeys {
val ActiveIconAlpha = MotionTestValueKey<Float>("activeIconAlpha")
val InactiveIconAlpha = MotionTestValueKey<Float>("inactiveIconAlpha")
}
+
+@Composable
+private fun colors(): SliderColors {
+ return SliderDefaults.colors()
+ .copy(
+ inactiveTrackColor = LocalAndroidColorScheme.current.surfaceEffect2,
+ activeTickColor = MaterialTheme.colorScheme.onPrimary,
+ inactiveTickColor = MaterialTheme.colorScheme.onSurface,
+ )
+}
diff --git a/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ActionIntentCreator.kt b/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ActionIntentCreator.kt
index 8cebe04d4e01..96dbcc5867c1 100644
--- a/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ActionIntentCreator.kt
+++ b/packages/SystemUI/src/com/android/systemui/clipboardoverlay/ActionIntentCreator.kt
@@ -21,20 +21,30 @@ import android.content.ClipDescription
import android.content.ComponentName
import android.content.Context
import android.content.Intent
+import android.content.pm.PackageManager
+import android.content.pm.PackageManager.NameNotFoundException
import android.net.Uri
import android.text.TextUtils
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.dagger.qualifiers.Background
import com.android.systemui.res.R
import java.util.function.Consumer
import javax.inject.Inject
+import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
@SysUISingleton
class ActionIntentCreator
@Inject
-constructor(@Application private val applicationScope: CoroutineScope) : IntentCreator {
+constructor(
+ private val context: Context,
+ private val packageManager: PackageManager,
+ @Application private val applicationScope: CoroutineScope,
+ @Background private val backgroundDispatcher: CoroutineDispatcher,
+) : IntentCreator {
override fun getTextEditorIntent(context: Context?) =
Intent(context, EditTextActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
@@ -72,11 +82,9 @@ constructor(@Application private val applicationScope: CoroutineScope) : IntentC
}
suspend fun getImageEditIntent(uri: Uri?, context: Context): Intent {
- val editorPackage = context.getString(R.string.config_screenshotEditor)
return Intent(Intent.ACTION_EDIT).apply {
- if (!TextUtils.isEmpty(editorPackage)) {
- setComponent(ComponentName.unflattenFromString(editorPackage))
- }
+ // Use the preferred editor if it's available, otherwise fall back to the default editor
+ component = preferredEditor() ?: defaultEditor()
setDataAndType(uri, "image/*")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
@@ -105,6 +113,39 @@ constructor(@Application private val applicationScope: CoroutineScope) : IntentC
}
}
+ private suspend fun preferredEditor(): ComponentName? =
+ runCatching {
+ val preferredEditor = context.getString(R.string.config_preferredScreenshotEditor)
+ val component = ComponentName.unflattenFromString(preferredEditor) ?: return null
+
+ return if (isComponentAvailable(component)) component else null
+ }
+ .getOrNull()
+
+ private suspend fun isComponentAvailable(component: ComponentName): Boolean =
+ withContext(backgroundDispatcher) {
+ try {
+ val info =
+ packageManager.getPackageInfo(
+ component.packageName,
+ PackageManager.GET_ACTIVITIES,
+ )
+ info.activities?.firstOrNull {
+ it.componentName.className == component.className
+ } != null
+ } catch (e: NameNotFoundException) {
+ false
+ }
+ }
+
+ private fun defaultEditor(): ComponentName? =
+ runCatching {
+ context.getString(R.string.config_screenshotEditor).let {
+ ComponentName.unflattenFromString(it)
+ }
+ }
+ .getOrNull()
+
companion object {
private const val EXTRA_EDIT_SOURCE: String = "edit_source"
private const val EDIT_SOURCE_CLIPBOARD: String = "clipboard"
diff --git a/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalSceneRepository.kt b/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalSceneRepository.kt
index bf4445ba18db..2b8cf008c0c7 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalSceneRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalSceneRepository.kt
@@ -16,6 +16,7 @@
package com.android.systemui.communal.data.repository
+import android.content.res.Configuration
import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.compose.animation.scene.ObservableTransitionState
import com.android.compose.animation.scene.OverlayKey
@@ -49,6 +50,9 @@ interface CommunalSceneRepository {
/** Exposes the transition state of the communal [SceneTransitionLayout]. */
val transitionState: StateFlow<ObservableTransitionState>
+ /** Current orientation of the communal container. */
+ val communalContainerOrientation: StateFlow<Int>
+
/** Updates the requested scene. */
fun changeScene(toScene: SceneKey, transitionKey: TransitionKey? = null)
@@ -64,6 +68,9 @@ interface CommunalSceneRepository {
* Note that you must call is with `null` when the UI is done or risk a memory leak.
*/
fun setTransitionState(transitionState: Flow<ObservableTransitionState>?)
+
+ /** Set the current orientation of the communal container. */
+ fun setCommunalContainerOrientation(orientation: Int)
}
@SysUISingleton
@@ -89,6 +96,11 @@ constructor(
initialValue = defaultTransitionState,
)
+ private val _communalContainerOrientation =
+ MutableStateFlow(Configuration.ORIENTATION_UNDEFINED)
+ override val communalContainerOrientation: StateFlow<Int> =
+ _communalContainerOrientation.asStateFlow()
+
override fun changeScene(toScene: SceneKey, transitionKey: TransitionKey?) {
applicationScope.launch {
// SceneTransitionLayout state updates must be triggered on the thread the STL was
@@ -105,6 +117,10 @@ constructor(
}
}
+ override fun setCommunalContainerOrientation(orientation: Int) {
+ _communalContainerOrientation.value = orientation
+ }
+
override suspend fun showHubFromPowerButton() {
// If keyguard is not showing yet, the hub view is not ready and the
// [SceneDataSourceDelegator] will still be using the default [NoOpSceneDataSource]
diff --git a/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalSettingsRepository.kt b/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalSettingsRepository.kt
index 42a345b7deb4..8d599541b184 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalSettingsRepository.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/data/repository/CommunalSettingsRepository.kt
@@ -206,8 +206,11 @@ constructor(
}
.flowOn(bgDispatcher)
- override fun getWhenToStartHubState(user: UserInfo): Flow<WhenToStartHub> =
- secureSettings
+ override fun getWhenToStartHubState(user: UserInfo): Flow<WhenToStartHub> {
+ if (!getV2FlagEnabled()) {
+ return MutableStateFlow(WhenToStartHub.NEVER)
+ }
+ return secureSettings
.observerFlow(
userId = user.id,
names = arrayOf(Settings.Secure.WHEN_TO_START_GLANCEABLE_HUB),
@@ -225,11 +228,13 @@ constructor(
Settings.Secure.GLANCEABLE_HUB_START_CHARGING -> WhenToStartHub.WHILE_CHARGING
Settings.Secure.GLANCEABLE_HUB_START_CHARGING_UPRIGHT ->
WhenToStartHub.WHILE_CHARGING_AND_POSTURED
+
Settings.Secure.GLANCEABLE_HUB_START_DOCKED -> WhenToStartHub.WHILE_DOCKED
else -> WhenToStartHub.NEVER
}
}
.flowOn(bgDispatcher)
+ }
override fun getAllowedByDevicePolicy(user: UserInfo): Flow<Boolean> =
broadcastDispatcher
diff --git a/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractor.kt b/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractor.kt
index fed99d71fa3b..a112dd25e006 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractor.kt
@@ -16,6 +16,7 @@
package com.android.systemui.communal.domain.interactor
+import android.content.res.Configuration
import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.compose.animation.scene.ObservableTransitionState
import com.android.compose.animation.scene.SceneKey
@@ -32,6 +33,7 @@ import com.android.systemui.keyguard.shared.model.KeyguardState
import com.android.systemui.scene.domain.interactor.SceneInteractor
import com.android.systemui.scene.shared.flag.SceneContainerFlag
import com.android.systemui.scene.shared.model.Scenes
+import com.android.systemui.statusbar.policy.KeyguardStateController
import com.android.systemui.util.kotlin.BooleanFlowOperators.allOf
import com.android.systemui.util.kotlin.pairwiseBy
import javax.inject.Inject
@@ -58,6 +60,7 @@ constructor(
private val repository: CommunalSceneRepository,
private val logger: CommunalSceneLogger,
private val sceneInteractor: SceneInteractor,
+ private val keyguardStateController: KeyguardStateController,
) {
private val _isLaunchingWidget = MutableStateFlow(false)
@@ -68,6 +71,30 @@ constructor(
_isLaunchingWidget.value = launching
}
+ /**
+ * Whether screen will be rotated to portrait if transitioned out of hub to keyguard screens.
+ */
+ var willRotateToPortrait: Flow<Boolean> =
+ repository.communalContainerOrientation
+ .map {
+ it == Configuration.ORIENTATION_LANDSCAPE &&
+ !keyguardStateController.isKeyguardScreenRotationAllowed()
+ }
+ .distinctUntilChanged()
+
+ /** Whether communal container is rotated to portrait. Emits an initial value of false. */
+ val rotatedToPortrait: StateFlow<Boolean> =
+ repository.communalContainerOrientation
+ .pairwiseBy(initialValue = false) { old, new ->
+ old == Configuration.ORIENTATION_LANDSCAPE &&
+ new == Configuration.ORIENTATION_PORTRAIT
+ }
+ .stateIn(applicationScope, SharingStarted.Eagerly, false)
+
+ fun setCommunalContainerOrientation(orientation: Int) {
+ repository.setCommunalContainerOrientation(orientation)
+ }
+
fun interface OnSceneAboutToChangeListener {
/** Notifies that the scene is about to change to [toScene]. */
fun onSceneAboutToChange(toScene: SceneKey, keyguardState: KeyguardState?)
diff --git a/packages/SystemUI/src/com/android/systemui/communal/posturing/domain/interactor/PosturingInteractor.kt b/packages/SystemUI/src/com/android/systemui/communal/posturing/domain/interactor/PosturingInteractor.kt
index e487590d87d7..25c7f477c815 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/posturing/domain/interactor/PosturingInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/posturing/domain/interactor/PosturingInteractor.kt
@@ -20,7 +20,6 @@ import android.annotation.SuppressLint
import android.hardware.Sensor
import android.hardware.TriggerEvent
import android.hardware.TriggerEventListener
-import android.service.dreams.Flags.allowDreamWhenPostured
import com.android.systemui.communal.posturing.data.model.PositionState
import com.android.systemui.communal.posturing.data.repository.PosturingRepository
import com.android.systemui.communal.posturing.shared.model.PosturedState
@@ -170,15 +169,10 @@ constructor(
* NOTE: Due to smoothing, this signal may be delayed to ensure we have a stable reading before
* being considered postured.
*/
- val postured: Flow<Boolean> by lazy {
- if (allowDreamWhenPostured()) {
- combine(posturedSmoothed, debugPostured) { postured, debugValue ->
- debugValue.asBoolean() ?: postured.asBoolean() ?: false
- }
- } else {
- MutableStateFlow(false)
+ val postured: Flow<Boolean> =
+ combine(posturedSmoothed, debugPostured) { postured, debugValue ->
+ debugValue.asBoolean() ?: postured.asBoolean() ?: false
}
- }
/**
* Helper for observing a trigger sensor, which automatically unregisters itself after it
diff --git a/packages/SystemUI/src/com/android/systemui/communal/shared/model/CommunalTransitionKeys.kt b/packages/SystemUI/src/com/android/systemui/communal/shared/model/CommunalTransitionKeys.kt
index a84c45732169..49dc59ac0004 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/shared/model/CommunalTransitionKeys.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/shared/model/CommunalTransitionKeys.kt
@@ -33,4 +33,6 @@ object CommunalTransitionKeys {
val FromEditMode = TransitionKey("FromEditMode")
/** Swipes the glanceable hub in/out of view */
val Swipe = TransitionKey("Swipe")
+ /** Swipes out of glanceable hub in landscape orientation */
+ val SwipeInLandscape = TransitionKey("SwipeInLandscape")
}
diff --git a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
index 5a4b0b0e2d24..a6309d1be03d 100644
--- a/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/communal/ui/viewmodel/CommunalViewModel.kt
@@ -386,6 +386,11 @@ constructor(
}
}
+ val swipeFromHubInLandscape: Flow<Boolean> = communalSceneInteractor.willRotateToPortrait
+
+ fun onOrientationChange(orientation: Int) =
+ communalSceneInteractor.setCommunalContainerOrientation(orientation)
+
companion object {
const val POPUP_AUTO_HIDE_TIMEOUT_MS = 12000L
}
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/SystemUIDeviceEntryFaceAuthInteractor.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/SystemUIDeviceEntryFaceAuthInteractor.kt
index 0d0105404726..1e50205500f9 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/SystemUIDeviceEntryFaceAuthInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/domain/interactor/SystemUIDeviceEntryFaceAuthInteractor.kt
@@ -20,6 +20,7 @@ import android.app.trust.TrustManager
import android.content.Context
import android.hardware.biometrics.BiometricFaceConstants
import android.hardware.biometrics.BiometricSourceType
+import android.service.dreams.Flags.dreamsV2
import com.android.keyguard.KeyguardUpdateMonitor
import com.android.systemui.biometrics.data.repository.FacePropertyRepository
import com.android.systemui.biometrics.shared.model.LockoutMode
@@ -40,6 +41,7 @@ import com.android.systemui.keyguard.shared.model.DevicePosture
import com.android.systemui.keyguard.shared.model.Edge
import com.android.systemui.keyguard.shared.model.KeyguardState.AOD
import com.android.systemui.keyguard.shared.model.KeyguardState.DOZING
+import com.android.systemui.keyguard.shared.model.KeyguardState.DREAMING
import com.android.systemui.keyguard.shared.model.KeyguardState.LOCKSCREEN
import com.android.systemui.keyguard.shared.model.KeyguardState.OFF
import com.android.systemui.keyguard.shared.model.TransitionState
@@ -136,11 +138,18 @@ constructor(
}
.launchIn(applicationScope)
- merge(
- keyguardTransitionInteractor.transition(Edge.create(AOD, LOCKSCREEN)),
- keyguardTransitionInteractor.transition(Edge.create(OFF, LOCKSCREEN)),
- keyguardTransitionInteractor.transition(Edge.create(DOZING, LOCKSCREEN)),
- )
+ val transitionFlows = buildList {
+ add(keyguardTransitionInteractor.transition(Edge.create(AOD, LOCKSCREEN)))
+ add(keyguardTransitionInteractor.transition(Edge.create(OFF, LOCKSCREEN)))
+ add(keyguardTransitionInteractor.transition(Edge.create(DOZING, LOCKSCREEN)))
+
+ if (dreamsV2()) {
+ add(keyguardTransitionInteractor.transition(Edge.create(DREAMING, LOCKSCREEN)))
+ }
+ }
+
+ transitionFlows
+ .merge()
.filter { it.transitionState == TransitionState.STARTED }
.sample(powerInteractor.detailedWakefulness)
.filter { wakefulnessModel ->
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/ui/binder/UdfpsAccessibilityOverlayBinder.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/ui/binder/UdfpsAccessibilityOverlayBinder.kt
index e2172d0773d3..3abc260fdcbd 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/ui/binder/UdfpsAccessibilityOverlayBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/ui/binder/UdfpsAccessibilityOverlayBinder.kt
@@ -18,27 +18,58 @@
package com.android.systemui.deviceentry.ui.binder
import android.annotation.SuppressLint
+import android.util.Log
+import android.view.MotionEvent
+import android.view.View.IMPORTANT_FOR_ACCESSIBILITY_NO
+import android.view.View.IMPORTANT_FOR_ACCESSIBILITY_YES
import androidx.core.view.isInvisible
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.deviceentry.ui.view.UdfpsAccessibilityOverlay
import com.android.systemui.deviceentry.ui.viewmodel.UdfpsAccessibilityOverlayViewModel
import com.android.systemui.lifecycle.repeatWhenAttached
object UdfpsAccessibilityOverlayBinder {
+ private const val TAG = "UdfpsAccessibilityOverlayBinder"
/** Forwards hover events to the view model to make guided announcements for accessibility. */
@SuppressLint("ClickableViewAccessibility")
@JvmStatic
- fun bind(
- view: UdfpsAccessibilityOverlay,
- viewModel: UdfpsAccessibilityOverlayViewModel,
- ) {
- view.setOnHoverListener { v, event -> viewModel.onHoverEvent(v, event) }
+ fun bind(view: UdfpsAccessibilityOverlay, viewModel: UdfpsAccessibilityOverlayViewModel) {
view.repeatWhenAttached {
// Repeat on CREATED because we update the visibility of the view
repeatOnLifecycle(Lifecycle.State.CREATED) {
- viewModel.visible.collect { visible -> view.isInvisible = !visible }
+ view.setOnHoverListener { v, event ->
+ if (event.action == MotionEvent.ACTION_HOVER_ENTER) {
+ launch { viewModel.onHoverEvent(v, event) }
+ }
+ false
+ }
+
+ launch { viewModel.visible.collect { visible -> view.isInvisible = !visible } }
+
+ launch {
+ viewModel.contentDescription.collect { contentDescription ->
+ if (contentDescription != null) {
+ view.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_YES
+ view.contentDescription = contentDescription
+ }
+ }
+ }
+
+ launch {
+ viewModel.clearAccessibilityOverlayMessageReason.collect { reason ->
+ Log.d(
+ TAG,
+ "clearing content description of UDFPS accessibility overlay " +
+ "for reason: $reason",
+ )
+ view.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
+ view.contentDescription = null
+ viewModel.setContentDescription(null)
+ }
+ }
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/ui/view/UdfpsAccessibilityOverlay.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/ui/view/UdfpsAccessibilityOverlay.kt
index 9c3b9b273ab5..0a2d10d10a40 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/ui/view/UdfpsAccessibilityOverlay.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/ui/view/UdfpsAccessibilityOverlay.kt
@@ -23,5 +23,7 @@ import android.view.View
class UdfpsAccessibilityOverlay(context: Context?) : View(context) {
init {
accessibilityLiveRegion = ACCESSIBILITY_LIVE_REGION_ASSERTIVE
+ importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_AUTO
+ isClickable = false
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/AlternateBouncerUdfpsAccessibilityOverlayViewModel.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/AlternateBouncerUdfpsAccessibilityOverlayViewModel.kt
index 5c7cd5f55942..22ed6da2e5bf 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/AlternateBouncerUdfpsAccessibilityOverlayViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/AlternateBouncerUdfpsAccessibilityOverlayViewModel.kt
@@ -17,6 +17,7 @@
package com.android.systemui.deviceentry.ui.viewmodel
import com.android.systemui.accessibility.domain.interactor.AccessibilityInteractor
+import com.android.systemui.biometrics.UdfpsUtils
import com.android.systemui.biometrics.domain.interactor.UdfpsOverlayInteractor
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
@@ -26,13 +27,23 @@ import kotlinx.coroutines.flow.flowOf
class AlternateBouncerUdfpsAccessibilityOverlayViewModel
@Inject
constructor(
- udfpsOverlayInteractor: UdfpsOverlayInteractor,
+ private val udfpsOverlayInteractor: UdfpsOverlayInteractor,
accessibilityInteractor: AccessibilityInteractor,
+ udfpsUtils: UdfpsUtils,
) :
UdfpsAccessibilityOverlayViewModel(
udfpsOverlayInteractor,
accessibilityInteractor,
+ udfpsUtils,
) {
/** Overlay is always visible if touch exploration is enabled on the alternate bouncer. */
override fun isVisibleWhenTouchExplorationEnabled(): Flow<Boolean> = flowOf(true)
+
+ /**
+ * Clears the content description to prevent the view from storing stale UDFPS directional
+ * guidance messages for accessibility.
+ */
+ suspend fun clearUdfpsAccessibilityOverlayMessage(reason: String) {
+ udfpsOverlayInteractor.clearUdfpsAccessibilityOverlayMessage(reason)
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/DeviceEntryUdfpsAccessibilityOverlayViewModel.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/DeviceEntryUdfpsAccessibilityOverlayViewModel.kt
index b84d65a2b430..5c86514775de 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/DeviceEntryUdfpsAccessibilityOverlayViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/DeviceEntryUdfpsAccessibilityOverlayViewModel.kt
@@ -17,6 +17,7 @@
package com.android.systemui.deviceentry.ui.viewmodel
import com.android.systemui.accessibility.domain.interactor.AccessibilityInteractor
+import com.android.systemui.biometrics.UdfpsUtils
import com.android.systemui.biometrics.domain.interactor.UdfpsOverlayInteractor
import com.android.systemui.keyguard.ui.view.DeviceEntryIconView
import com.android.systemui.keyguard.ui.viewmodel.DeviceEntryForegroundViewModel
@@ -33,10 +34,12 @@ constructor(
accessibilityInteractor: AccessibilityInteractor,
private val deviceEntryIconViewModel: DeviceEntryIconViewModel,
private val deviceEntryFgIconViewModel: DeviceEntryForegroundViewModel,
+ udfpsUtils: UdfpsUtils,
) :
UdfpsAccessibilityOverlayViewModel(
udfpsOverlayInteractor,
accessibilityInteractor,
+ udfpsUtils,
) {
/** Overlay is only visible if the UDFPS icon is visible on the keyguard. */
override fun isVisibleWhenTouchExplorationEnabled(): Flow<Boolean> =
diff --git a/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/UdfpsAccessibilityOverlayViewModel.kt b/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/UdfpsAccessibilityOverlayViewModel.kt
index 1849bf20abdb..a58f3681555c 100644
--- a/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/UdfpsAccessibilityOverlayViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/deviceentry/ui/viewmodel/UdfpsAccessibilityOverlayViewModel.kt
@@ -24,7 +24,10 @@ import com.android.systemui.biometrics.UdfpsUtils
import com.android.systemui.biometrics.domain.interactor.UdfpsOverlayInteractor
import com.android.systemui.biometrics.shared.model.UdfpsOverlayParams
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
@@ -32,8 +35,17 @@ import kotlinx.coroutines.flow.flowOf
abstract class UdfpsAccessibilityOverlayViewModel(
udfpsOverlayInteractor: UdfpsOverlayInteractor,
accessibilityInteractor: AccessibilityInteractor,
+ private val udfpsUtils: UdfpsUtils,
) {
- private val udfpsUtils = UdfpsUtils()
+ /** Indicates the reason for clearing the UDFPS accessibility overlay content description */
+ val clearAccessibilityOverlayMessageReason: SharedFlow<String?> =
+ udfpsOverlayInteractor.clearAccessibilityOverlayMessageReason
+
+ private val _contentDescription: MutableStateFlow<CharSequence?> = MutableStateFlow(null)
+
+ /** Content description of the UDFPS accessibility overlay */
+ val contentDescription: Flow<CharSequence?> = _contentDescription.asStateFlow()
+
private val udfpsOverlayParams: StateFlow<UdfpsOverlayParams> =
udfpsOverlayInteractor.udfpsOverlayParams
@@ -46,6 +58,10 @@ abstract class UdfpsAccessibilityOverlayViewModel(
}
}
+ fun setContentDescription(contentDescription: CharSequence?) {
+ _contentDescription.value = contentDescription
+ }
+
abstract fun isVisibleWhenTouchExplorationEnabled(): Flow<Boolean>
/** Give directional feedback to help the user authenticate with UDFPS. */
@@ -77,8 +93,9 @@ abstract class UdfpsAccessibilityOverlayViewModel(
overlayParams,
/* touchRotatedToPortrait */ false,
)
+
if (announceStr != null) {
- v.contentDescription = announceStr
+ _contentDescription.value = announceStr
}
}
// always let the motion events go through to underlying views
diff --git a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialogLite.java b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialogLite.java
index f2a10cc43fd9..8e857b3313a7 100644
--- a/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialogLite.java
+++ b/packages/SystemUI/src/com/android/systemui/globalactions/GlobalActionsDialogLite.java
@@ -58,7 +58,9 @@ import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
+import android.os.PowerManager;
import android.os.RemoteException;
+import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.Trace;
import android.os.UserHandle;
@@ -194,6 +196,7 @@ public class GlobalActionsDialogLite implements DialogInterface.OnDismissListene
static final String GLOBAL_ACTION_KEY_EMERGENCY = "emergency";
static final String GLOBAL_ACTION_KEY_SCREENSHOT = "screenshot";
static final String GLOBAL_ACTION_KEY_SYSTEM_UPDATE = "system_update";
+ static final String GLOBAL_ACTION_KEY_STANDBY = "standby";
// See NotificationManagerService#scheduleDurationReachedLocked
private static final long TOAST_FADE_TIME = 333;
@@ -270,6 +273,7 @@ public class GlobalActionsDialogLite implements DialogInterface.OnDismissListene
private final UserLogoutInteractor mLogoutInteractor;
private final GlobalActionsInteractor mInteractor;
private final Lazy<DisplayWindowPropertiesRepository> mDisplayWindowPropertiesRepositoryLazy;
+ private final PowerManager mPowerManager;
private final Handler mHandler;
private final UserTracker.Callback mOnUserSwitched = new UserTracker.Callback() {
@@ -341,7 +345,10 @@ public class GlobalActionsDialogLite implements DialogInterface.OnDismissListene
GA_CLOSE_POWER_VOLUP(811),
@UiEvent(doc = "System Update button was pressed.")
- GA_SYSTEM_UPDATE_PRESS(1716);
+ GA_SYSTEM_UPDATE_PRESS(1716),
+
+ @UiEvent(doc = "The global actions standby button was pressed.")
+ GA_STANDBY_PRESS(2210);
private final int mId;
@@ -396,7 +403,8 @@ public class GlobalActionsDialogLite implements DialogInterface.OnDismissListene
SelectedUserInteractor selectedUserInteractor,
UserLogoutInteractor logoutInteractor,
GlobalActionsInteractor interactor,
- Lazy<DisplayWindowPropertiesRepository> displayWindowPropertiesRepository) {
+ Lazy<DisplayWindowPropertiesRepository> displayWindowPropertiesRepository,
+ PowerManager powerManager) {
mContext = context;
mWindowManagerFuncs = windowManagerFuncs;
mAudioManager = audioManager;
@@ -434,6 +442,7 @@ public class GlobalActionsDialogLite implements DialogInterface.OnDismissListene
mLogoutInteractor = logoutInteractor;
mInteractor = interactor;
mDisplayWindowPropertiesRepositoryLazy = displayWindowPropertiesRepository;
+ mPowerManager = powerManager;
mHandler = new Handler(mMainHandler.getLooper()) {
public void handleMessage(Message msg) {
@@ -697,6 +706,8 @@ public class GlobalActionsDialogLite implements DialogInterface.OnDismissListene
}
} else if (GLOBAL_ACTION_KEY_SYSTEM_UPDATE.equals(actionKey)) {
addIfShouldShowAction(tempActions, new SystemUpdateAction());
+ } else if (GLOBAL_ACTION_KEY_STANDBY.equals(actionKey)) {
+ addIfShouldShowAction(tempActions, new StandbyAction());
} else {
Log.e(TAG, "Invalid global action key " + actionKey);
}
@@ -1245,6 +1256,36 @@ public class GlobalActionsDialogLite implements DialogInterface.OnDismissListene
}
}
+ @VisibleForTesting
+ class StandbyAction extends SinglePressAction {
+ StandbyAction() {
+ super(R.drawable.ic_standby, R.string.global_action_standby);
+ }
+
+ @Override
+ public void onPress() {
+ // Add a little delay before executing, to give the dialog a chance to go away before
+ // going to sleep. Otherwise, we see screen flicker randomly.
+ mHandler.postDelayed(() -> {
+ mUiEventLogger.log(GlobalActionsEvent.GA_STANDBY_PRESS);
+ mBackgroundExecutor.execute(() -> {
+ mPowerManager.goToSleep(SystemClock.uptimeMillis(),
+ PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON, 0);
+ });
+ }, mDialogPressDelay);
+ }
+
+ @Override
+ public boolean showDuringKeyguard() {
+ return true;
+ }
+
+ @Override
+ public boolean showBeforeProvisioning() {
+ return true;
+ }
+ }
+
private Action getSettingsAction() {
return new SinglePressAction(R.drawable.ic_settings,
R.string.global_action_settings) {
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/dagger/PrimaryBouncerTransitionModule.kt b/packages/SystemUI/src/com/android/systemui/keyguard/dagger/PrimaryBouncerTransitionModule.kt
index 7c4dbfeba50f..7110c37e88e7 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/dagger/PrimaryBouncerTransitionModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/dagger/PrimaryBouncerTransitionModule.kt
@@ -20,11 +20,13 @@ import com.android.systemui.keyguard.ui.transitions.PrimaryBouncerTransition
import com.android.systemui.keyguard.ui.viewmodel.AlternateBouncerToPrimaryBouncerTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.AodToPrimaryBouncerTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.DozingToPrimaryBouncerTransitionViewModel
+import com.android.systemui.keyguard.ui.viewmodel.DreamingToPrimaryBouncerTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.GlanceableHubToPrimaryBouncerTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.LockscreenToPrimaryBouncerTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.OccludedToPrimaryBouncerTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.PrimaryBouncerToAodTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.PrimaryBouncerToDozingTransitionViewModel
+import com.android.systemui.keyguard.ui.viewmodel.PrimaryBouncerToDreamingTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.PrimaryBouncerToGlanceableHubTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.PrimaryBouncerToGoneTransitionViewModel
import com.android.systemui.keyguard.ui.viewmodel.PrimaryBouncerToLockscreenTransitionViewModel
@@ -81,6 +83,10 @@ interface PrimaryBouncerTransitionImplModule {
@Binds
@IntoSet
+ fun fromDreaming(impl: DreamingToPrimaryBouncerTransitionViewModel): PrimaryBouncerTransition
+
+ @Binds
+ @IntoSet
fun toAod(impl: PrimaryBouncerToAodTransitionViewModel): PrimaryBouncerTransition
@Binds
@@ -103,5 +109,9 @@ interface PrimaryBouncerTransitionImplModule {
@Binds
@IntoSet
+ fun toDreaming(impl: PrimaryBouncerToDreamingTransitionViewModel): PrimaryBouncerTransition
+
+ @Binds
+ @IntoSet
fun toOccluded(impl: PrimaryBouncerToOccludedTransitionViewModel): PrimaryBouncerTransition
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDreamingTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDreamingTransitionInteractor.kt
index 3b1b6fcc45f2..09bf478a9338 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDreamingTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromDreamingTransitionInteractor.kt
@@ -316,5 +316,6 @@ constructor(
val TO_LOCKSCREEN_DURATION = 1167.milliseconds
val TO_AOD_DURATION = 300.milliseconds
val TO_GONE_DURATION = DEFAULT_DURATION
+ val TO_PRIMARY_BOUNCER_DURATION = DEFAULT_DURATION
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromGlanceableHubTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromGlanceableHubTransitionInteractor.kt
index 3ad862b761fc..be0cf62b0526 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromGlanceableHubTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromGlanceableHubTransitionInteractor.kt
@@ -251,6 +251,8 @@ constructor(
* Set at 400ms for parity with [FromLockscreenTransitionInteractor]
*/
val DEFAULT_DURATION = 400.milliseconds
+ // To lockscreen duration must be at least 500ms to allow for potential screen rotation
+ // during the transition while the animation begins after 500ms.
val TO_LOCKSCREEN_DURATION = 1.seconds
val TO_BOUNCER_DURATION = 400.milliseconds
val TO_OCCLUDED_DURATION = 450.milliseconds
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractor.kt b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractor.kt
index 75d6631008ca..77fc804d1e82 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/domain/interactor/FromPrimaryBouncerTransitionInteractor.kt
@@ -294,5 +294,6 @@ constructor(
val TO_OCCLUDED_DURATION = 550.milliseconds
val TO_GLANCEABLE_HUB_DURATION = DEFAULT_DURATION
val TO_GONE_SURFACE_BEHIND_VISIBLE_THRESHOLD = 0.1f
+ val TO_DREAMING_DURATION = DEFAULT_DURATION
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/AccessibilityActionsViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/AccessibilityActionsViewBinder.kt
index 824e0228adca..c7c54e95a63b 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/AccessibilityActionsViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/AccessibilityActionsViewBinder.kt
@@ -19,21 +19,19 @@ package com.android.systemui.keyguard.ui.binder
import android.os.Bundle
import android.view.View
+import android.view.accessibility.AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED
import android.view.accessibility.AccessibilityNodeInfo
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.repeatOnLifecycle
+import com.android.app.tracing.coroutines.launchTraced as launch
import com.android.systemui.keyguard.ui.viewmodel.AccessibilityActionsViewModel
import com.android.systemui.lifecycle.repeatWhenAttached
import com.android.systemui.res.R
import kotlinx.coroutines.DisposableHandle
-import com.android.app.tracing.coroutines.launchTraced as launch
/** View binder for accessibility actions placeholder on keyguard. */
object AccessibilityActionsViewBinder {
- fun bind(
- view: View,
- viewModel: AccessibilityActionsViewModel,
- ): DisposableHandle {
+ fun bind(view: View, viewModel: AccessibilityActionsViewModel): DisposableHandle {
val disposableHandle =
view.repeatWhenAttached {
repeatOnLifecycle(Lifecycle.State.STARTED) {
@@ -60,9 +58,10 @@ object AccessibilityActionsViewBinder {
object : View.AccessibilityDelegate() {
override fun onInitializeAccessibilityNodeInfo(
host: View,
- info: AccessibilityNodeInfo
+ info: AccessibilityNodeInfo,
) {
super.onInitializeAccessibilityNodeInfo(host, info)
+
// Add custom actions
if (canOpenGlanceableHub) {
val action =
@@ -80,7 +79,7 @@ object AccessibilityActionsViewBinder {
override fun performAccessibilityAction(
host: View,
action: Int,
- args: Bundle?
+ args: Bundle?,
): Boolean {
return if (
action == R.id.accessibility_action_open_communal_hub
@@ -89,6 +88,20 @@ object AccessibilityActionsViewBinder {
true
} else super.performAccessibilityAction(host, action, args)
}
+
+ override fun sendAccessibilityEvent(
+ host: View,
+ eventType: Int,
+ ) {
+ if (eventType == TYPE_VIEW_ACCESSIBILITY_FOCUSED) {
+ launch {
+ viewModel.clearUdfpsAccessibilityOverlayMessage(
+ "eventType $eventType on view $host"
+ )
+ }
+ }
+ super.sendAccessibilityEvent(host, eventType)
+ }
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/AlternateBouncerViewBinder.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/AlternateBouncerViewBinder.kt
index b8b032719ef8..00d41d0a7aa7 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/AlternateBouncerViewBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/binder/AlternateBouncerViewBinder.kt
@@ -19,8 +19,10 @@ package com.android.systemui.keyguard.ui.binder
import android.util.Log
import android.view.LayoutInflater
import android.view.View
+import android.view.View.IMPORTANT_FOR_ACCESSIBILITY_AUTO
import android.view.ViewGroup
import android.view.WindowManager
+import android.view.accessibility.AccessibilityEvent.TYPE_VIEW_HOVER_EXIT
import android.window.OnBackInvokedCallback
import android.window.OnBackInvokedDispatcher
import androidx.constraintlayout.widget.ConstraintLayout
@@ -47,6 +49,7 @@ import com.android.systemui.scrim.ScrimView
import dagger.Lazy
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.launch
/**
* When necessary, adds the alternate bouncer window above most other windows (including the
@@ -235,6 +238,25 @@ constructor(
udfpsA11yOverlay =
UdfpsAccessibilityOverlay(view.context).apply {
id = udfpsA11yOverlayViewId
+ importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_AUTO
+ }
+ udfpsA11yOverlay.accessibilityDelegate =
+ object : View.AccessibilityDelegate() {
+ override fun sendAccessibilityEvent(
+ host: View,
+ eventType: Int,
+ ) {
+ if (eventType == TYPE_VIEW_HOVER_EXIT) {
+ applicationScope.launch {
+ udfpsA11yOverlayViewModel
+ .get()
+ .clearUdfpsAccessibilityOverlayMessage(
+ "$eventType on view $host"
+ )
+ }
+ }
+ super.sendAccessibilityEvent(host, eventType)
+ }
}
view.addView(udfpsA11yOverlay)
UdfpsAccessibilityOverlayBinder.bind(
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AccessibilityActionsViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AccessibilityActionsViewModel.kt
index 38f5d3e76c7c..678872d0d64d 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AccessibilityActionsViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/AccessibilityActionsViewModel.kt
@@ -16,6 +16,7 @@
package com.android.systemui.keyguard.ui.viewmodel
+import com.android.systemui.biometrics.domain.interactor.UdfpsOverlayInteractor
import com.android.systemui.communal.domain.interactor.CommunalInteractor
import com.android.systemui.communal.shared.model.CommunalScenes
import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
@@ -33,7 +34,8 @@ class AccessibilityActionsViewModel
constructor(
private val communalInteractor: CommunalInteractor,
keyguardInteractor: KeyguardInteractor,
- keyguardTransitionInteractor: KeyguardTransitionInteractor,
+ val keyguardTransitionInteractor: KeyguardTransitionInteractor,
+ private val udfpsOverlayInteractor: UdfpsOverlayInteractor,
) {
val isCommunalAvailable = communalInteractor.isCommunalAvailable
@@ -44,7 +46,7 @@ constructor(
keyguardTransitionInteractor.transitionValue(KeyguardState.LOCKSCREEN).map {
it == 1f
},
- keyguardInteractor.statusBarState
+ keyguardInteractor.statusBarState,
) { transitionFinishedOnLockscreen, statusBarState ->
transitionFinishedOnLockscreen && statusBarState == StatusBarState.KEYGUARD
}
@@ -55,4 +57,12 @@ constructor(
newScene = CommunalScenes.Communal,
loggingReason = "accessibility",
)
+
+ /**
+ * Clears the content description to prevent the view from storing stale UDFPS directional
+ * guidance messages for accessibility.
+ */
+ suspend fun clearUdfpsAccessibilityOverlayMessage(reason: String) {
+ udfpsOverlayInteractor.clearUdfpsAccessibilityOverlayMessage(reason)
+ }
}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerTransitionViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerTransitionViewModel.kt
new file mode 100644
index 000000000000..8771f02326fa
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerTransitionViewModel.kt
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard.ui.viewmodel
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.domain.interactor.FromDreamingTransitionInteractor
+import com.android.systemui.keyguard.shared.model.Edge
+import com.android.systemui.keyguard.shared.model.KeyguardState.DREAMING
+import com.android.systemui.keyguard.shared.model.KeyguardState.PRIMARY_BOUNCER
+import com.android.systemui.keyguard.ui.KeyguardTransitionAnimationFlow
+import com.android.systemui.keyguard.ui.transitions.BlurConfig
+import com.android.systemui.keyguard.ui.transitions.PrimaryBouncerTransition
+import com.android.systemui.scene.shared.model.Overlays
+import javax.inject.Inject
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.emptyFlow
+
+@SysUISingleton
+class DreamingToPrimaryBouncerTransitionViewModel
+@Inject
+constructor(blurConfig: BlurConfig, animationFlow: KeyguardTransitionAnimationFlow) :
+ PrimaryBouncerTransition {
+ private val transitionAnimation =
+ animationFlow
+ .setup(
+ duration = FromDreamingTransitionInteractor.TO_PRIMARY_BOUNCER_DURATION,
+ edge = Edge.create(from = DREAMING, to = Overlays.Bouncer),
+ )
+ .setupWithoutSceneContainer(edge = Edge.create(from = DREAMING, to = PRIMARY_BOUNCER))
+
+ override val windowBlurRadius: Flow<Float> =
+ transitionAnimation.immediatelyTransitionTo(blurConfig.maxBlurRadiusPx)
+
+ override val notificationBlurRadius: Flow<Float> = emptyFlow()
+}
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModel.kt
index bcbe66642d11..fd5783ef7f8e 100644
--- a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModel.kt
@@ -19,7 +19,10 @@ package com.android.systemui.keyguard.ui.viewmodel
import android.util.LayoutDirection
import com.android.app.animation.Interpolators.EMPHASIZED
import com.android.systemui.common.ui.domain.interactor.ConfigurationInteractor
+import com.android.systemui.communal.domain.interactor.CommunalSceneInteractor
+import com.android.systemui.communal.domain.interactor.CommunalSettingsInteractor
import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.dagger.qualifiers.Application
import com.android.systemui.keyguard.dagger.GlanceableHubBlurComponent
import com.android.systemui.keyguard.domain.interactor.FromGlanceableHubTransitionInteractor.Companion.TO_LOCKSCREEN_DURATION
import com.android.systemui.keyguard.shared.model.Edge
@@ -34,21 +37,32 @@ import com.android.systemui.scene.shared.model.Scenes
import com.android.systemui.shade.ShadeDisplayAware
import javax.inject.Inject
import kotlin.time.Duration.Companion.milliseconds
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.stateIn
/**
* Breaks down GLANCEABLE_HUB->LOCKSCREEN transition into discrete steps for corresponding views to
* consume.
*/
+@OptIn(ExperimentalCoroutinesApi::class)
@SysUISingleton
class GlanceableHubToLockscreenTransitionViewModel
@Inject
constructor(
+ @Application applicationScope: CoroutineScope,
@ShadeDisplayAware configurationInteractor: ConfigurationInteractor,
animationFlow: KeyguardTransitionAnimationFlow,
+ communalSceneInteractor: CommunalSceneInteractor,
+ communalSettingsInteractor: CommunalSettingsInteractor,
private val blurFactory: GlanceableHubBlurComponent.Factory,
) : GlanceableHubTransition, DeviceEntryIconTransition {
private val transitionAnimation =
@@ -59,18 +73,45 @@ constructor(
)
.setupWithoutSceneContainer(edge = Edge.create(from = GLANCEABLE_HUB, to = LOCKSCREEN))
+ // Whether screen rotation will happen with the transition. Only emit when idle so ongoing
+ // animation won't be interrupted when orientation is updated during the transition.
+ private val willRotateToPortraitInTransition: StateFlow<Boolean> =
+ if (!communalSettingsInteractor.isV2FlagEnabled()) {
+ flowOf(false)
+ } else {
+ communalSceneInteractor.isIdleOnCommunal.combineTransform(
+ communalSceneInteractor.willRotateToPortrait
+ ) { isIdle, willRotate ->
+ if (isIdle) emit(willRotate)
+ }
+ }
+ .stateIn(applicationScope, SharingStarted.Eagerly, false)
+
override val windowBlurRadius: Flow<Float> =
blurFactory.create(transitionAnimation).getBlurProvider().exitBlurRadius
val keyguardAlpha: Flow<Float> =
- transitionAnimation.sharedFlow(
- duration = 167.milliseconds,
- startTime = 167.milliseconds,
- onStep = { it },
- onFinish = { 1f },
- onCancel = { 0f },
- name = "GLANCEABLE_HUB->LOCKSCREEN: keyguardAlpha",
- )
+ willRotateToPortraitInTransition.flatMapLatest { willRotate ->
+ transitionAnimation.sharedFlow(
+ duration = 167.milliseconds,
+ // If will rotate, start later to leave time for screen rotation.
+ startTime = if (willRotate) 500.milliseconds else 167.milliseconds,
+ onStep = { step ->
+ if (willRotate) {
+ if (!communalSceneInteractor.rotatedToPortrait.value) {
+ 0f
+ } else {
+ 1f
+ }
+ } else {
+ step
+ }
+ },
+ onFinish = { 1f },
+ onCancel = { 0f },
+ name = "GLANCEABLE_HUB->LOCKSCREEN: keyguardAlpha",
+ )
+ }
// Show UMO as long as keyguard is not visible.
val showUmo: Flow<Boolean> = keyguardAlpha.map { alpha -> alpha == 0f }
@@ -84,7 +125,14 @@ constructor(
.flatMapLatest { translatePx: Int ->
transitionAnimation.sharedFlowWithState(
duration = TO_LOCKSCREEN_DURATION,
- onStep = { value -> -translatePx + value * translatePx },
+ onStep = { value ->
+ // do not animate translation-x if screen rotation will happen
+ if (willRotateToPortraitInTransition.value) {
+ 0f
+ } else {
+ -translatePx + value * translatePx
+ }
+ },
interpolator = EMPHASIZED,
// Move notifications back to their original position since they can be
// accessed from the shade, and also keyguard elements in case the animation
diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModel.kt b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModel.kt
new file mode 100644
index 000000000000..9de25fcac64a
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModel.kt
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard.ui.viewmodel
+
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.keyguard.domain.interactor.FromPrimaryBouncerTransitionInteractor
+import com.android.systemui.keyguard.shared.model.Edge
+import com.android.systemui.keyguard.shared.model.KeyguardState.DREAMING
+import com.android.systemui.keyguard.shared.model.KeyguardState.PRIMARY_BOUNCER
+import com.android.systemui.keyguard.ui.KeyguardTransitionAnimationFlow
+import com.android.systemui.keyguard.ui.transitions.BlurConfig
+import com.android.systemui.keyguard.ui.transitions.PrimaryBouncerTransition
+import com.android.systemui.scene.shared.model.Overlays
+import javax.inject.Inject
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.emptyFlow
+
+@SysUISingleton
+class PrimaryBouncerToDreamingTransitionViewModel
+@Inject
+constructor(blurConfig: BlurConfig, animationFlow: KeyguardTransitionAnimationFlow) :
+ PrimaryBouncerTransition {
+ private val transitionAnimation =
+ animationFlow
+ .setup(
+ duration = FromPrimaryBouncerTransitionInteractor.TO_DREAMING_DURATION,
+ edge = Edge.create(from = Overlays.Bouncer, to = DREAMING),
+ )
+ .setupWithoutSceneContainer(edge = Edge.create(from = PRIMARY_BOUNCER, to = DREAMING))
+
+ override val windowBlurRadius: Flow<Float> =
+ transitionAnimation.sharedFlow(
+ onStart = { blurConfig.maxBlurRadiusPx },
+ onStep = {
+ transitionProgressToBlurRadius(
+ blurConfig.maxBlurRadiusPx,
+ endBlurRadius = blurConfig.minBlurRadiusPx,
+ transitionProgress = it,
+ )
+ },
+ onFinish = { blurConfig.minBlurRadiusPx },
+ )
+
+ override val notificationBlurRadius: Flow<Float> = emptyFlow()
+}
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/binder/SeekBarObserver.kt b/packages/SystemUI/src/com/android/systemui/media/controls/ui/binder/SeekBarObserver.kt
index 5b65531cdd55..f81745704d2b 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/binder/SeekBarObserver.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/binder/SeekBarObserver.kt
@@ -157,6 +157,7 @@ open class SeekBarObserver(private val holder: MediaViewHolder) :
return DateUtils.formatElapsedTime(milliseconds / DateUtils.SECOND_IN_MILLIS)
}
+ @UiThread
fun updateContentDescription(
elapsedTimeDescription: CharSequence,
durationDescription: CharSequence,
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaControlPanel.java b/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaControlPanel.java
index f69985ee5364..9cf7356a0ab2 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaControlPanel.java
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaControlPanel.java
@@ -399,7 +399,9 @@ public class MediaControlPanel {
}
private void setSeekbarContentDescription(CharSequence elapsedTime, CharSequence duration) {
- mSeekBarObserver.updateContentDescription(elapsedTime, duration);
+ mMainExecutor.execute(() -> {
+ mSeekBarObserver.updateContentDescription(elapsedTime, duration);
+ });
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaViewController.kt b/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaViewController.kt
index e87d5de56177..8c683e8f9749 100644
--- a/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaViewController.kt
+++ b/packages/SystemUI/src/com/android/systemui/media/controls/ui/controller/MediaViewController.kt
@@ -236,10 +236,12 @@ constructor(
durationDescription: CharSequence,
) {
if (!SceneContainerFlag.isEnabled) return
- seekBarObserver.updateContentDescription(
- elapsedTimeDescription,
- durationDescription,
- )
+ mainExecutor.execute {
+ seekBarObserver.updateContentDescription(
+ elapsedTimeDescription,
+ durationDescription,
+ )
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt
index 699778f3b6f9..1a0af514cf87 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/CommonTile.kt
@@ -162,6 +162,7 @@ fun LargeTileContent(
colors = colors,
accessibilityUiState = accessibilityUiState,
isVisible = isVisible,
+ modifier = Modifier.weight(1f),
)
if (sideDrawable != null) {
diff --git a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/EditTile.kt b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/EditTile.kt
index f8eaa6c3bcfb..b8cb2c4844e4 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/EditTile.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/panels/ui/compose/infinitegrid/EditTile.kt
@@ -22,8 +22,11 @@ import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.LinearEasing
+import androidx.compose.animation.core.Spring
+import androidx.compose.animation.core.VisibilityThreshold
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloatAsState
+import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
@@ -108,6 +111,7 @@ import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.dimensionResource
+import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.CustomAccessibilityAction
import androidx.compose.ui.semantics.contentDescription
@@ -118,6 +122,7 @@ import androidx.compose.ui.text.style.Hyphens
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
+import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.fastMap
import com.android.compose.gesture.effect.rememberOffsetOverscrollEffectFactory
@@ -157,9 +162,9 @@ import com.android.systemui.qs.panels.ui.model.AvailableTileGridCell
import com.android.systemui.qs.panels.ui.model.GridCell
import com.android.systemui.qs.panels.ui.model.SpacerGridCell
import com.android.systemui.qs.panels.ui.model.TileGridCell
-import com.android.systemui.qs.panels.ui.viewmodel.BounceableTileViewModel
import com.android.systemui.qs.panels.ui.viewmodel.EditTileViewModel
import com.android.systemui.qs.pipeline.shared.TileSpec
+import com.android.systemui.qs.shared.model.TileCategory
import com.android.systemui.qs.shared.model.groupAndSort
import com.android.systemui.res.R
import kotlin.math.abs
@@ -220,7 +225,6 @@ private fun EditModeTopBar(onStopEditing: () -> Unit, onReset: (() -> Unit)?) {
)
}
-@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
fun DefaultEditTileGrid(
listState: EditTileListState,
@@ -526,11 +530,7 @@ private fun CurrentTilesGrid(
var gridContentOffset by remember { mutableStateOf(Offset(0f, 0f)) }
val coroutineScope = rememberCoroutineScope()
- val cells =
- remember(listState.tiles) {
- listState.tiles.fastMap { Pair(it, BounceableTileViewModel()) }
- }
-
+ val cells = listState.tiles
val primaryColor = MaterialTheme.colorScheme.primary
TileLazyGrid(
state = gridState,
@@ -561,11 +561,11 @@ private fun CurrentTilesGrid(
.testTag(CURRENT_TILES_GRID_TEST_TAG),
) {
EditTiles(
- cells,
- listState,
- selectionState,
- coroutineScope,
- largeTilesSpan,
+ cells = cells,
+ dragAndDropState = listState,
+ selectionState = selectionState,
+ coroutineScope = coroutineScope,
+ largeTilesSpan = largeTilesSpan,
onRemoveTile = onRemoveTile,
) { resizingOperation ->
when (resizingOperation) {
@@ -618,11 +618,9 @@ private fun AvailableTileGrid(
}
.padding(16.dp),
) {
- Text(
- text = category.label.load() ?: "",
- style = MaterialTheme.typography.titleMediumEmphasized,
- color = MaterialTheme.colorScheme.onSurface,
- modifier = Modifier.fillMaxWidth().padding(start = 8.dp, bottom = 16.dp),
+ CategoryHeader(
+ category,
+ modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp),
)
tiles.chunked(columns).forEach { row ->
Row(
@@ -662,7 +660,7 @@ private fun GridCell.key(index: Int): Any {
/**
* Adds a list of [GridCell] to the lazy grid
*
- * @param cells the pairs of [GridCell] to [BounceableTileViewModel]
+ * @param cells the list of [GridCell]
* @param dragAndDropState the [DragAndDropState] for this grid
* @param selectionState the [MutableSelectionState] for this grid
* @param coroutineScope the [CoroutineScope] to be used for the tiles
@@ -671,7 +669,7 @@ private fun GridCell.key(index: Int): Any {
* @param onResize the callback when a tile has a new [ResizeOperation]
*/
fun LazyGridScope.EditTiles(
- cells: List<Pair<GridCell, BounceableTileViewModel>>,
+ cells: List<GridCell>,
dragAndDropState: DragAndDropState,
selectionState: MutableSelectionState,
coroutineScope: CoroutineScope,
@@ -681,11 +679,11 @@ fun LazyGridScope.EditTiles(
) {
items(
count = cells.size,
- key = { cells[it].first.key(it) },
- span = { cells[it].first.span },
+ key = { cells[it].key(it) },
+ span = { cells[it].span },
contentType = { TileType },
) { index ->
- when (val cell = cells[index].first) {
+ when (val cell = cells[index]) {
is TileGridCell ->
if (dragAndDropState.isMoving(cell.tile.tileSpec)) {
// If the tile is being moved, replace it with a visible spacer
@@ -708,7 +706,15 @@ fun LazyGridScope.EditTiles(
onRemoveTile = onRemoveTile,
coroutineScope = coroutineScope,
largeTilesSpan = largeTilesSpan,
- modifier = Modifier.animateItem(),
+ modifier =
+ Modifier.animateItem(
+ placementSpec =
+ spring(
+ stiffness = Spring.StiffnessMediumLow,
+ dampingRatio = Spring.DampingRatioLowBouncy,
+ visibilityThreshold = IntOffset.VisibilityThreshold,
+ )
+ ),
)
}
is SpacerGridCell ->
@@ -853,6 +859,26 @@ private fun TileGridCell(
@OptIn(ExperimentalMaterial3ExpressiveApi::class)
@Composable
+private fun CategoryHeader(category: TileCategory, modifier: Modifier = Modifier) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = spacedBy(8.dp),
+ modifier = modifier,
+ ) {
+ Icon(
+ painter = painterResource(category.iconId),
+ contentDescription = null,
+ tint = MaterialTheme.colorScheme.onSurface,
+ )
+ Text(
+ text = category.label.load() ?: "",
+ style = MaterialTheme.typography.titleMediumEmphasized,
+ color = MaterialTheme.colorScheme.onSurface,
+ )
+ }
+}
+
+@Composable
private fun AvailableTileGridCell(
cell: AvailableTileGridCell,
dragAndDropState: DragAndDropState,
diff --git a/packages/SystemUI/src/com/android/systemui/qs/shared/model/TileCategory.kt b/packages/SystemUI/src/com/android/systemui/qs/shared/model/TileCategory.kt
index 59cb7d3d5345..c8225e7a3509 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/shared/model/TileCategory.kt
+++ b/packages/SystemUI/src/com/android/systemui/qs/shared/model/TileCategory.kt
@@ -20,14 +20,35 @@ import com.android.systemui.common.shared.model.Text
import com.android.systemui.res.R
/** Categories for tiles. This can be used to sort tiles in edit mode. */
-enum class TileCategory(val label: Text) {
- CONNECTIVITY(Text.Resource(R.string.qs_edit_mode_category_connectivity)),
- UTILITIES(Text.Resource(R.string.qs_edit_mode_category_utilities)),
- DISPLAY(Text.Resource(R.string.qs_edit_mode_category_display)),
- PRIVACY(Text.Resource(R.string.qs_edit_mode_category_privacy)),
- ACCESSIBILITY(Text.Resource(R.string.qs_edit_mode_category_accessibility)),
- PROVIDED_BY_APP(Text.Resource(R.string.qs_edit_mode_category_providedByApps)),
- UNKNOWN(Text.Resource(R.string.qs_edit_mode_category_unknown)),
+enum class TileCategory(val label: Text, val iconId: Int) {
+ CONNECTIVITY(
+ Text.Resource(R.string.qs_edit_mode_category_connectivity),
+ R.drawable.ic_qs_category_connectivty,
+ ),
+ UTILITIES(
+ Text.Resource(R.string.qs_edit_mode_category_utilities),
+ R.drawable.ic_qs_category_utilities,
+ ),
+ DISPLAY(
+ Text.Resource(R.string.qs_edit_mode_category_display),
+ R.drawable.ic_qs_category_display,
+ ),
+ PRIVACY(
+ Text.Resource(R.string.qs_edit_mode_category_privacy),
+ R.drawable.ic_qs_category_privacy,
+ ),
+ ACCESSIBILITY(
+ Text.Resource(R.string.qs_edit_mode_category_accessibility),
+ R.drawable.ic_qs_category_accessibility,
+ ),
+ PROVIDED_BY_APP(
+ Text.Resource(R.string.qs_edit_mode_category_providedByApps),
+ R.drawable.ic_qs_category_provided_by_apps,
+ ),
+ UNKNOWN(
+ Text.Resource(R.string.qs_edit_mode_category_unknown),
+ R.drawable.ic_qs_category_unknown,
+ ),
}
interface CategoryAndName {
diff --git a/packages/SystemUI/src/com/android/systemui/scene/domain/startable/SceneContainerStartable.kt b/packages/SystemUI/src/com/android/systemui/scene/domain/startable/SceneContainerStartable.kt
index 06fc8610c97b..daaa2db54775 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/domain/startable/SceneContainerStartable.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/domain/startable/SceneContainerStartable.kt
@@ -332,6 +332,7 @@ constructor(
/** Switches between scenes based on ever-changing application state. */
private fun automaticallySwitchScenes() {
handleBouncerImeVisibility()
+ handleBouncerHiding()
handleSimUnlock()
handleDeviceUnlockStatus()
handlePowerState()
@@ -352,6 +353,24 @@ constructor(
}
}
+ private fun handleBouncerHiding() {
+ applicationScope.launch {
+ repeatWhen(
+ condition =
+ authenticationInteractor
+ .get()
+ .authenticationMethod
+ .map { !it.isSecure }
+ .distinctUntilChanged()
+ ) {
+ sceneInteractor.hideOverlay(
+ overlay = Overlays.Bouncer,
+ loggingReason = "Authentication method changed to a non-secure one.",
+ )
+ }
+ }
+ }
+
private fun handleSimUnlock() {
applicationScope.launch {
simBouncerInteractor
@@ -434,6 +453,12 @@ constructor(
}
}
+ if (powerInteractor.detailedWakefulness.value.isAsleep()) {
+ // The logic below is for when the device becomes unlocked. That must be a
+ // no-op if the device is not awake.
+ return@mapNotNull null
+ }
+
if (
isOnPrimaryBouncer &&
deviceUnlockStatus.deviceUnlockSource == DeviceUnlockSource.TrustAgent
@@ -833,7 +858,7 @@ constructor(
}
.collect {
val loggingReason = "Falsing detected."
- switchToScene(Scenes.Lockscreen, loggingReason)
+ switchToScene(targetSceneKey = Scenes.Lockscreen, loggingReason = loggingReason)
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt b/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt
index 73c71f6088e1..452ea3f719fa 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/shared/logger/SceneLogger.kt
@@ -90,7 +90,7 @@ class SceneLogger @Inject constructor(@SceneFrameworkLog private val logBuffer:
fun logSceneChangeRejection(
from: ContentKey?,
to: ContentKey?,
- originalChangeReason: String,
+ originalChangeReason: String?,
rejectionReason: String,
) {
logBuffer.log(
@@ -112,8 +112,10 @@ class SceneLogger @Inject constructor(@SceneFrameworkLog private val logBuffer:
"scene "
}
)
- append("change $str1 because \"$str2\" ")
- append("(original change reason: \"$str3\")")
+ append("change $str1 because \"$str2\"")
+ if (str3 != null) {
+ append(" (original change reason: \"$str3\")")
+ }
}
},
)
@@ -136,8 +138,11 @@ class SceneLogger @Inject constructor(@SceneFrameworkLog private val logBuffer:
logBuffer.log(
tag = TAG,
level = LogLevel.INFO,
- messageInitializer = { str1 = transitionState.currentScene.toString() },
- messagePrinter = { "Scene transition idle on: $str1" },
+ messageInitializer = {
+ str1 = transitionState.currentScene.toString()
+ str2 = transitionState.currentOverlays.joinToString()
+ },
+ messagePrinter = { "Scene transition idle on: $str1, overlays: $str2" },
)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt
index a81fcec94989..d8bb84af6023 100644
--- a/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/scene/ui/viewmodel/SceneContainerViewModel.kt
@@ -219,15 +219,24 @@ constructor(
* it being a false touch.
*/
fun canChangeScene(toScene: SceneKey): Boolean {
- return isInteractionAllowedByFalsing(toScene).also {
- // A scene change is guaranteed; log it.
- logger.logSceneChanged(
- from = currentScene.value,
- to = toScene,
- sceneState = null,
- reason = "user interaction",
- isInstant = false,
- )
+ return isInteractionAllowedByFalsing(toScene).also { sceneChangeAllowed ->
+ if (sceneChangeAllowed) {
+ // A scene change is guaranteed; log it.
+ logger.logSceneChanged(
+ from = currentScene.value,
+ to = toScene,
+ sceneState = null,
+ reason = "user interaction",
+ isInstant = false,
+ )
+ } else {
+ logger.logSceneChangeRejection(
+ from = currentScene.value,
+ to = toScene,
+ originalChangeReason = null,
+ rejectionReason = "Falsing: false touch detected",
+ )
+ }
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/shade/OWNERS b/packages/SystemUI/src/com/android/systemui/shade/OWNERS
index 89454b84a528..47ca531b8502 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/OWNERS
+++ b/packages/SystemUI/src/com/android/systemui/shade/OWNERS
@@ -1,5 +1,4 @@
justinweir@google.com
-syeonlee@google.com
nicomazz@google.com
burakov@google.com
@@ -8,16 +7,16 @@ per-file *Notification* = file:../statusbar/notification/OWNERS
per-file NotificationsQuickSettingsContainer.java = kozynski@google.com, asc@google.com
per-file NotificationsQSContainerController.kt = kozynski@google.com, asc@google.com
-per-file *ShadeHeader* = syeonlee@google.com, kozynski@google.com, asc@google.com
+per-file *ShadeHeader* = kozynski@google.com, asc@google.com
per-file *Interactor* = set noparent
-per-file *Interactor* = justinweir@google.com, syeonlee@google.com, nijamkin@google.com, nicomazz@google.com, burakov@google.com
+per-file *Interactor* = justinweir@google.com, nijamkin@google.com, nicomazz@google.com, burakov@google.com
per-file *Repository* = set noparent
-per-file *Repository* = justinweir@google.com, syeonlee@google.com, nijamkin@google.com, nicomazz@google.com, burakov@google.com
+per-file *Repository* = justinweir@google.com, nijamkin@google.com, nicomazz@google.com, burakov@google.com
-per-file NotificationShadeWindow* = pixel@google.com, cinek@google.com, juliacr@google.com, justinweir@google.com, syeonlee@google.com, nicomazz@google.com, burakov@google.com
+per-file NotificationShadeWindow* = pixel@google.com, cinek@google.com, juliacr@google.com, justinweir@google.com, nicomazz@google.com, burakov@google.com
per-file NotificationPanelUnfoldAnimationController.kt = alexflo@google.com, jeffdq@google.com, juliacr@google.com
-per-file NotificationPanelView.java = pixel@google.com, cinek@google.com, juliacr@google.com, justinweir@google.com, syeonlee@google.com, nicomazz@google.com, burakov@google.com
-per-file NotificationPanelViewController.java = pixel@google.com, cinek@google.com, juliacr@google.com, justinweir@google.com, syeonlee@google.com, nicomazz@google.com, burakov@google.com
+per-file NotificationPanelView.java = pixel@google.com, cinek@google.com, juliacr@google.com, justinweir@google.com, nicomazz@google.com, burakov@google.com
+per-file NotificationPanelViewController.java = pixel@google.com, cinek@google.com, juliacr@google.com, justinweir@google.com, nicomazz@google.com, burakov@google.com
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerSceneImpl.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerSceneImpl.kt
index b211f0729318..82d361797f96 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerSceneImpl.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeControllerSceneImpl.kt
@@ -101,6 +101,7 @@ constructor(
shadeInteractor.collapseQuickSettingsShade(
loggingReason = "ShadeControllerSceneImpl.instantCollapseShade",
transitionKey = Instant,
+ bypassNotificationsShade = true,
)
}
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt
index 446d4b450edc..0132390f9ce8 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeDisplayAwareModule.kt
@@ -23,6 +23,7 @@ import android.view.WindowManager
import android.view.WindowManager.LayoutParams
import android.view.WindowManager.LayoutParams.TYPE_NOTIFICATION_SHADE
import android.window.WindowContext
+import com.android.app.tracing.TrackGroupUtils.trackGroup
import com.android.systemui.CoreStartable
import com.android.systemui.common.ui.ConfigurationState
import com.android.systemui.common.ui.ConfigurationStateImpl
@@ -34,6 +35,8 @@ import com.android.systemui.common.ui.view.ChoreographerUtils
import com.android.systemui.common.ui.view.ChoreographerUtilsImpl
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.LogBufferFactory
import com.android.systemui.res.R
import com.android.systemui.scene.ui.view.WindowRootView
import com.android.systemui.shade.data.repository.MutableShadeDisplaysRepository
@@ -266,6 +269,20 @@ object ShadeDisplayAwareModule {
@Provides
@ShadeOnDefaultDisplayWhenLocked
fun provideShadeOnDefaultDisplayWhenLocked(): Boolean = true
+
+ /** Provides a [LogBuffer] for use by classes related to shade movement */
+ @Provides
+ @SysUISingleton
+ @ShadeDisplayLog
+ fun provideShadeDisplayLogLogBuffer(factory: LogBufferFactory): LogBuffer {
+ val logBufferName = "ShadeDisplayLog"
+ return factory.create(
+ logBufferName,
+ maxSize = 400,
+ alwaysLogToLogcat = true,
+ systraceTrackName = trackGroup("shade", logBufferName),
+ )
+ }
}
/** Module that should be included only if the shade window [WindowRootView] is available. */
@@ -298,3 +315,6 @@ object ShadeDisplayAwareWithShadeWindowModule {
* how well this solution behaves from the performance point of view.
*/
@Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class ShadeOnDefaultDisplayWhenLocked
+
+/** A [com.android.systemui.log.LogBuffer] for changes to the shade display. */
+@Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class ShadeDisplayLog
diff --git a/packages/SystemUI/src/com/android/systemui/shade/ShadeStateTraceLogger.kt b/packages/SystemUI/src/com/android/systemui/shade/ShadeStateTraceLogger.kt
index de1b180f5a7a..1ec83835ab43 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/ShadeStateTraceLogger.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/ShadeStateTraceLogger.kt
@@ -24,6 +24,8 @@ import com.android.systemui.CoreStartable
import com.android.systemui.common.ui.data.repository.ConfigurationRepository
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Application
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.core.LogLevel
import com.android.systemui.shade.data.repository.ShadeDisplaysRepository
import com.android.systemui.shade.domain.interactor.ShadeInteractor
import com.android.systemui.shade.domain.interactor.ShadeModeInteractor
@@ -42,6 +44,7 @@ constructor(
private val shadeDisplaysRepository: Lazy<ShadeDisplaysRepository>,
@ShadeDisplayAware private val configurationRepository: ConfigurationRepository,
@Application private val scope: CoroutineScope,
+ @ShadeDisplayLog private val logBuffer: LogBuffer,
) : CoreStartable {
override fun start() {
scope.launchTraced("ShadeStateTraceLogger") {
@@ -72,6 +75,18 @@ constructor(
"configurationChange#smallestScreenWidthDp",
it.smallestScreenWidthDp,
)
+ logBuffer.log(
+ "ShadeStateTraceLogger",
+ LogLevel.DEBUG,
+ {
+ int1 = it.smallestScreenWidthDp
+ int2 = it.densityDpi
+ },
+ {
+ "New configuration change from Shade window. " +
+ "smallestScreenWidthDp: $int1, densityDpi: $int2"
+ },
+ )
}
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractor.kt b/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractor.kt
index 0e0f58dc8d0e..d48d56c2403b 100644
--- a/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractor.kt
@@ -27,8 +27,11 @@ import com.android.systemui.common.ui.data.repository.ConfigurationRepository
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Background
import com.android.systemui.dagger.qualifiers.Main
+import com.android.systemui.log.LogBuffer
+import com.android.systemui.log.core.LogLevel
import com.android.systemui.shade.ShadeDisplayAware
import com.android.systemui.shade.ShadeDisplayChangeLatencyTracker
+import com.android.systemui.shade.ShadeDisplayLog
import com.android.systemui.shade.ShadeTraceLogger.logMoveShadeWindowTo
import com.android.systemui.shade.ShadeTraceLogger.t
import com.android.systemui.shade.ShadeTraceLogger.traceReparenting
@@ -69,6 +72,7 @@ constructor(
private val notificationRebindingTracker: NotificationRebindingTracker,
private val notificationStackRebindingHider: NotificationStackRebindingHider,
@ShadeDisplayAware private val configForwarder: ConfigurationForwarder,
+ @ShadeDisplayLog private val logBuffer: LogBuffer,
) : CoreStartable {
private val hasActiveNotifications: Boolean
@@ -101,7 +105,12 @@ constructor(
/** Tries to move the shade. If anything wrong happens, fails gracefully without crashing. */
private suspend fun moveShadeWindowTo(destinationId: Int) {
- Log.d(TAG, "Trying to move shade window to display with id $destinationId")
+ logBuffer.log(
+ TAG,
+ LogLevel.DEBUG,
+ { int1 = destinationId },
+ { "Trying to move shade window to display with id $int1" },
+ )
logMoveShadeWindowTo(destinationId)
var currentId = -1
try {
@@ -113,7 +122,12 @@ constructor(
val currentDisplay = shadeContext.display ?: error("Current shade display is null")
currentId = currentDisplay.displayId
if (currentId == destinationId) {
- Log.w(TAG, "Trying to move the shade to a display ($currentId) it was already in ")
+ logBuffer.log(
+ TAG,
+ LogLevel.WARNING,
+ { int1 = currentId },
+ { "Trying to move the shade to a display ($int1) it was already in." },
+ )
return
}
@@ -128,9 +142,14 @@ constructor(
}
}
} catch (e: IllegalStateException) {
- Log.e(
+ logBuffer.log(
TAG,
- "Unable to move the shade window from display $currentId to $destinationId",
+ LogLevel.ERROR,
+ {
+ int1 = currentId
+ int2 = destinationId
+ },
+ { "Unable to move the shade window from display $int1 to $int2" },
e,
)
}
@@ -200,7 +219,7 @@ constructor(
}
private fun errorLog(s: String) {
- Log.e(TAG, s)
+ logBuffer.log(TAG, LogLevel.ERROR, s)
}
private fun checkContextDisplayMatchesExpected(destinationId: Int) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
index f844d1da1a8d..50d634f6ac54 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationShadeDepthController.kt
@@ -334,6 +334,14 @@ constructor(
private fun onBlurApplied(appliedBlurRadius: Int, zoomOutFromShadeRadius: Float) {
lastAppliedBlur = appliedBlurRadius
+ onZoomOutChanged(zoomOutFromShadeRadius)
+ listeners.forEach { it.onBlurRadiusChanged(appliedBlurRadius) }
+ notificationShadeWindowController.setBackgroundBlurRadius(appliedBlurRadius)
+ }
+
+ private fun onZoomOutChanged(zoomOutFromShadeRadius: Float) {
+ TrackTracer.instantForGroup("shade", "zoom_out", zoomOutFromShadeRadius)
+ Log.v(TAG, "onZoomOutChanged $zoomOutFromShadeRadius")
wallpaperController.setNotificationShadeZoom(zoomOutFromShadeRadius)
if (spatialModelAppPushback()) {
appZoomOutOptional.ifPresent { appZoomOut ->
@@ -341,12 +349,15 @@ constructor(
}
keyguardInteractor.setZoomOut(zoomOutFromShadeRadius)
}
- listeners.forEach {
- it.onBlurRadiusChanged(appliedBlurRadius)
- }
- notificationShadeWindowController.setBackgroundBlurRadius(appliedBlurRadius)
}
+ private val applyZoomOutForFrame =
+ Choreographer.FrameCallback {
+ updateScheduled = false
+ val (_, zoomOutFromShadeRadius) = computeBlurAndZoomOut()
+ onZoomOutChanged(zoomOutFromShadeRadius)
+ }
+
/** Animate blurs when unlocking. */
private val keyguardStateCallback =
object : KeyguardStateController.Callback {
@@ -627,8 +638,17 @@ constructor(
val (blur, zoomOutFromShadeRadius) = computeBlurAndZoomOut()
zoomOutCalculatedFromShadeRadius = zoomOutFromShadeRadius
if (Flags.bouncerUiRevamp() || Flags.glanceableHubBlurredBackground()) {
- updateScheduled =
- windowRootViewBlurInteractor.requestBlurForShade(blur, shouldBlurBeOpaque)
+ if (windowRootViewBlurInteractor.isBlurCurrentlySupported.value) {
+ updateScheduled =
+ windowRootViewBlurInteractor.requestBlurForShade(blur, shouldBlurBeOpaque)
+ return
+ }
+ // When blur is not supported, zoom out still needs to happen when scheduleUpdate
+ // is invoked and a separate frame callback has to be wired-up to support that.
+ if (!updateScheduled) {
+ updateScheduled = true
+ choreographer.postFrameCallback(applyZoomOutForFrame)
+ }
return
}
if (updateScheduled) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/chips/notification/shared/StatusBarNotifChips.kt b/packages/SystemUI/src/com/android/systemui/statusbar/chips/notification/shared/StatusBarNotifChips.kt
index 6431f303089f..5b989d8e1e7c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/chips/notification/shared/StatusBarNotifChips.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/chips/notification/shared/StatusBarNotifChips.kt
@@ -16,15 +16,18 @@
package com.android.systemui.statusbar.chips.notification.shared
-import com.android.systemui.Flags
+import android.app.Flags
import com.android.systemui.flags.FlagToken
import com.android.systemui.flags.RefactorFlagUtils
+// NOTE: We're merging this flag with the `ui_rich_ongoing` flag.
+// We'll replace all usages of this class with PromotedNotificationUi as a follow-up.
+
/** Helper for reading or using the status bar promoted notification chips flag state. */
@Suppress("NOTHING_TO_INLINE")
object StatusBarNotifChips {
/** The aconfig flag name */
- const val FLAG_NAME = Flags.FLAG_STATUS_BAR_NOTIFICATION_CHIPS
+ const val FLAG_NAME = Flags.FLAG_UI_RICH_ONGOING
/** A token used for dependency declaration */
val token: FlagToken
@@ -33,7 +36,7 @@ object StatusBarNotifChips {
/** Is the refactor enabled */
@JvmStatic
inline val isEnabled
- get() = Flags.statusBarNotificationChips()
+ get() = Flags.uiRichOngoing()
/**
* Called to ensure code is only run when the flag is enabled. This protects users from the
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/compose/ChipContent.kt b/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/compose/ChipContent.kt
index fa8d25623d67..18cecb4abc31 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/compose/ChipContent.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/compose/ChipContent.kt
@@ -132,7 +132,11 @@ fun ChipContent(viewModel: OngoingActivityChipModel.Active, modifier: Modifier =
}
is OngoingActivityChipModel.Active.ShortTimeDelta -> {
- val timeRemainingState = rememberTimeRemainingState(futureTimeMillis = viewModel.time)
+ val timeRemainingState =
+ rememberTimeRemainingState(
+ futureTimeMillis = viewModel.time,
+ timeSource = viewModel.timeSource,
+ )
timeRemainingState.timeRemainingData?.let {
val text = formatTimeRemainingData(it)
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/model/OngoingActivityChipModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/model/OngoingActivityChipModel.kt
index d7b67b1f7bfb..2c4746f5fafb 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/model/OngoingActivityChipModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/model/OngoingActivityChipModel.kt
@@ -136,7 +136,8 @@ sealed class OngoingActivityChipModel {
/**
* The [TimeSource] that should be used to track the current time for this timer. Should
- * be compatible with [startTimeMs].
+ * be compatible units with [startTimeMs]. Only used in the Compose version of the
+ * chips.
*/
val timeSource: TimeSource = TimeSource { SystemClock.elapsedRealtime() },
@@ -187,6 +188,12 @@ sealed class OngoingActivityChipModel {
* this model and the [Timer] model use the same units.
*/
@CurrentTimeMillisLong val time: Long,
+
+ /**
+ * The [TimeSource] that should be used to track the current time for this timer. Should
+ * be compatible units with [time]. Only used in the Compose version of the chips.
+ */
+ val timeSource: TimeSource = TimeSource { System.currentTimeMillis() },
override val onClickListenerLegacy: View.OnClickListener?,
override val clickBehavior: ClickBehavior,
override val transitionManager: TransitionManager? = null,
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/viewmodel/TimeRemainingState.kt b/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/viewmodel/TimeRemainingState.kt
index 803d422c0f0f..2d2d13ce6c27 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/viewmodel/TimeRemainingState.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/chips/ui/viewmodel/TimeRemainingState.kt
@@ -100,10 +100,7 @@ class TimeRemainingState(private val timeSource: TimeSource, private val futureT
/** Remember and manage the TimeRemainingState */
@Composable
-fun rememberTimeRemainingState(
- futureTimeMillis: Long,
- timeSource: TimeSource = remember { TimeSource { System.currentTimeMillis() } },
-): TimeRemainingState {
+fun rememberTimeRemainingState(futureTimeMillis: Long, timeSource: TimeSource): TimeRemainingState {
val state =
remember(timeSource, futureTimeMillis) { TimeRemainingState(timeSource, futureTimeMillis) }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java
index 6b32c6a18ec0..a0b3c1729154 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/inflation/NotificationRowBinderImpl.java
@@ -298,6 +298,7 @@ public class NotificationRowBinderImpl implements NotificationRowBinder {
mRowContentBindStage.requestRebind(entry, en -> {
mLogger.logRebindComplete(entry);
row.setIsMinimized(isMinimized);
+ row.setRedactionType(redactionType);
if (inflationCallback != null) {
inflationCallback.onAsyncInflationFinished(en);
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationUiAod.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationUiAod.kt
index c6e3da1c5750..69e27dcc2e6c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationUiAod.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationUiAod.kt
@@ -16,14 +16,17 @@
package com.android.systemui.statusbar.notification.promoted
-import com.android.systemui.Flags
+import android.app.Flags
import com.android.systemui.flags.FlagToken
import com.android.systemui.flags.RefactorFlagUtils
+// NOTE: We're merging this flag with the `ui_rich_ongoing` flag.
+// We'll replace all usages of this class with PromotedNotificationUi as a follow-up.
+
/** Helper for reading or using the promoted ongoing notifications AOD flag state. */
object PromotedNotificationUiAod {
/** The aconfig flag name */
- const val FLAG_NAME = Flags.FLAG_AOD_UI_RICH_ONGOING
+ const val FLAG_NAME = Flags.FLAG_UI_RICH_ONGOING
/** A token used for dependency declaration */
val token: FlagToken
@@ -32,7 +35,7 @@ object PromotedNotificationUiAod {
/** Is the refactor enabled */
@JvmStatic
inline val isEnabled
- get() = Flags.aodUiRichOngoing()
+ get() = Flags.uiRichOngoing()
/**
* Called to ensure code is only run when the flag is enabled. This protects users from the
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationUiForceExpanded.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationUiForceExpanded.kt
index adeddde8ccc3..5c0991059dec 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationUiForceExpanded.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationUiForceExpanded.kt
@@ -16,15 +16,18 @@
package com.android.systemui.statusbar.notification.promoted
-import com.android.systemui.Flags
+import android.app.Flags
import com.android.systemui.flags.FlagToken
import com.android.systemui.flags.RefactorFlagUtils
+// NOTE: We're merging this flag with the `ui_rich_ongoing` flag.
+// We'll replace all usages of this class with PromotedNotificationUi as a follow-up.
+
/** Helper for reading or using the expanded ui rich ongoing flag state. */
@Suppress("NOTHING_TO_INLINE")
object PromotedNotificationUiForceExpanded {
/** The aconfig flag name */
- const val FLAG_NAME = Flags.FLAG_UI_RICH_ONGOING_FORCE_EXPANDED
+ const val FLAG_NAME = Flags.FLAG_UI_RICH_ONGOING
/** A token used for dependency declaration */
val token: FlagToken
@@ -33,7 +36,7 @@ object PromotedNotificationUiForceExpanded {
/** Is the refactor enabled */
@JvmStatic
inline val isEnabled
- get() = Flags.uiRichOngoingForceExpanded()
+ get() = Flags.uiRichOngoing()
/**
* Called to ensure code is only run when the flag is enabled. This protects users from the
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationInteractor.kt
index d9778bdde0a5..fa9a7b9b524e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationInteractor.kt
@@ -18,10 +18,13 @@ package com.android.systemui.statusbar.notification.promoted.domain.interactor
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dump.DumpManager
+import com.android.systemui.keyguard.domain.interactor.KeyguardInteractor
import com.android.systemui.statusbar.notification.promoted.shared.model.PromotedNotificationContentModel
+import com.android.systemui.statusbar.policy.domain.interactor.SensitiveNotificationProtectionInteractor
import com.android.systemui.util.kotlin.FlowDumperImpl
import javax.inject.Inject
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
@@ -30,14 +33,31 @@ class AODPromotedNotificationInteractor
@Inject
constructor(
promotedNotificationsInteractor: PromotedNotificationsInteractor,
+ keyguardInteractor: KeyguardInteractor,
+ sensitiveNotificationProtectionInteractor: SensitiveNotificationProtectionInteractor,
dumpManager: DumpManager,
) : FlowDumperImpl(dumpManager) {
+
+ /**
+ * Whether the system is unlocked and not screensharing such that private notification content
+ * is allowed to show on the aod
+ */
+ private val canShowPrivateNotificationContent: Flow<Boolean> =
+ combine(
+ keyguardInteractor.isKeyguardDismissible,
+ sensitiveNotificationProtectionInteractor.isSensitiveStateActive,
+ ) { isKeyguardDismissible, isSensitive ->
+ isKeyguardDismissible && !isSensitive
+ }
+
/** The content to show as the promoted notification on AOD */
val content: Flow<PromotedNotificationContentModel?> =
- promotedNotificationsInteractor.aodPromotedNotification
- .map {
- // TODO(b/400991304): show the private version when unlocked
- it?.publicVersion
+ combine(
+ promotedNotificationsInteractor.aodPromotedNotification,
+ canShowPrivateNotificationContent,
+ ) { promotedContent, showPrivateContent ->
+ if (showPrivateContent) promotedContent?.privateVersion
+ else promotedContent?.publicVersion
}
.distinctUntilNewInstance()
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
index bef3c691cb4d..740391d7010e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java
@@ -26,6 +26,7 @@ import static com.android.systemui.Flags.notificationRowAccessibilityExpanded;
import static com.android.systemui.Flags.notificationRowTransparency;
import static com.android.systemui.Flags.notificationsPinnedHunInShade;
import static com.android.systemui.flags.Flags.ENABLE_NOTIFICATIONS_SIMULATE_SLOW_MEASURE;
+import static com.android.systemui.statusbar.NotificationLockscreenUserManager.REDACTION_TYPE_NONE;
import static com.android.systemui.statusbar.notification.NotificationUtils.logKey;
import static com.android.systemui.statusbar.notification.collection.NotificationEntry.DismissState.PARENT_DISMISSED;
import static com.android.systemui.statusbar.notification.row.NotificationContentView.VISIBLE_TYPE_HEADSUP;
@@ -102,6 +103,7 @@ import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin.MenuItem
import com.android.systemui.plugins.statusbar.StatusBarStateController;
import com.android.systemui.res.R;
import com.android.systemui.scene.shared.flag.SceneContainerFlag;
+import com.android.systemui.statusbar.NotificationLockscreenUserManager.RedactionType;
import com.android.systemui.statusbar.RemoteInputController;
import com.android.systemui.statusbar.SmartReplyController;
import com.android.systemui.statusbar.StatusBarIconView;
@@ -503,7 +505,8 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
private final ListenerSet<DismissButtonTargetVisibilityListener>
mDismissButtonTargetVisibilityListeners = new ListenerSet<>();
-
+ @RedactionType
+ private int mRedactionType = REDACTION_TYPE_NONE;
public NotificationContentView[] getLayouts() {
return Arrays.copyOf(mLayouts, mLayouts.length);
}
@@ -1867,6 +1870,13 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
}
/**
+ * Set the redaction type of the row.
+ */
+ public void setRedactionType(@RedactionType int redactionType) {
+ mRedactionType = redactionType;
+ }
+
+ /**
* Init the bundle header view. The ComposeView is initialized within with the passed viewModel.
* This can only be init once and not in conjunction with any other header view.
*/
@@ -4516,6 +4526,7 @@ public class ExpandableNotificationRow extends ActivatableNotificationView
pw.print(", expandedWhenPinned: " + mExpandedWhenPinned);
pw.print(", isMinimized: " + mIsMinimized);
pw.print(", isAboveShelf: " + isAboveShelf());
+ pw.print(", redactionType: " + mRedactionType);
pw.println();
if (NotificationContentView.INCLUDE_HEIGHTS_TO_DUMP) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
index 488aa44ddd3b..756a2c19c10e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationContentView.java
@@ -1248,7 +1248,7 @@ public class NotificationContentView extends FrameLayout implements Notification
final boolean isSingleLineViewPresent = mSingleLineView != null;
if (shouldShowSingleLineView && !isSingleLineViewPresent) {
- Log.e(TAG, "calculateVisibleType: SingleLineView is not available!");
+ Log.wtf(TAG, "calculateVisibleType: SingleLineView is not available!");
}
final int collapsedVisualType = shouldShowSingleLineView && isSingleLineViewPresent
@@ -1274,9 +1274,6 @@ public class NotificationContentView extends FrameLayout implements Notification
}
final boolean shouldShowSingleLineView = mIsChildInGroup && !isGroupExpanded();
final boolean isSingleLinePresent = mSingleLineView != null;
- if (shouldShowSingleLineView && !isSingleLinePresent) {
- Log.e(TAG, "getVisualTypeForHeight: singleLineView is not available.");
- }
if (!mUserExpanding && shouldShowSingleLineView && isSingleLinePresent) {
return VISIBLE_TYPE_SINGLELINE;
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfo.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfo.java
index 2cf3b14bb8c5..0257b4c2397e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfo.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfo.java
@@ -218,7 +218,7 @@ public class NotificationConversationInfo extends LinearLayout implements
@Background Handler bgHandler,
OnConversationSettingsClickListener onConversationSettingsClickListener,
Optional<BubblesManager> bubblesManagerOptional,
- ShadeController shadeController) {
+ ShadeController shadeController, boolean isDismissable, OnClickListener onCloseClick) {
mINotificationManager = iNotificationManager;
mPeopleSpaceWidgetManager = peopleSpaceWidgetManager;
mOnUserInteractionCallback = onUserInteractionCallback;
@@ -263,6 +263,11 @@ public class NotificationConversationInfo extends LinearLayout implements
bindHeader();
bindActions();
+ View dismissButton = findViewById(R.id.inline_dismiss);
+ dismissButton.setOnClickListener(onCloseClick);
+ dismissButton.setVisibility(dismissButton.hasOnClickListeners() && isDismissable
+ ? VISIBLE : GONE);
+
View done = findViewById(R.id.done);
done.setOnClickListener(mOnDone);
done.setAccessibilityDelegate(mGutsContainer.getAccessibilityDelegate());
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java
index 6c7c7a79348f..d0567f08c2f1 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/NotificationGutsManager.java
@@ -608,7 +608,9 @@ public class NotificationGutsManager implements NotifGutsViewManager, CoreStarta
mBgHandler,
onConversationSettingsListener,
mBubblesManagerOptional,
- mShadeController);
+ mShadeController,
+ row.canViewBeDismissed(),
+ row.getCloseButtonOnClickListener(row));
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationTemplateViewWrapper.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationTemplateViewWrapper.java
index 19321dcef5c7..d5e2e7eb3a9c 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationTemplateViewWrapper.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/wrapper/NotificationTemplateViewWrapper.java
@@ -43,7 +43,6 @@ import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.ContrastColorUtil;
import com.android.internal.widget.NotificationActionListLayout;
import com.android.systemui.Dependency;
-import com.android.systemui.Flags;
import com.android.systemui.UiOffloadThread;
import com.android.systemui.res.R;
import com.android.systemui.statusbar.CrossFadeHelper;
@@ -51,6 +50,7 @@ import com.android.systemui.statusbar.TransformableView;
import com.android.systemui.statusbar.ViewTransformationHelper;
import com.android.systemui.statusbar.notification.ImageTransformState;
import com.android.systemui.statusbar.notification.TransformState;
+import com.android.systemui.statusbar.notification.promoted.PromotedNotificationUiForceExpanded;
import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow;
import com.android.systemui.statusbar.notification.row.HybridNotificationView;
import com.android.systemui.statusbar.notification.shared.NotificationBundleUi;
@@ -196,7 +196,8 @@ public class NotificationTemplateViewWrapper extends NotificationHeaderViewWrapp
}
private void adjustTitleAndRightIconForPromotedOngoing() {
- if (Flags.uiRichOngoingForceExpanded() && mRow.isPromotedOngoing() && mRightIcon != null) {
+ if (PromotedNotificationUiForceExpanded.isEnabled() &&
+ mRow.isPromotedOngoing() && mRightIcon != null) {
final int horizontalMargin;
if (notificationsRedesignTemplates()) {
horizontalMargin = mView.getResources().getDimensionPixelSize(
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
index fa4fe46e690c..83e5db4db6fe 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java
@@ -459,7 +459,7 @@ public class KeyguardStatusBarView extends RelativeLayout {
/** Should only be called from {@link KeyguardStatusBarViewController}. */
void onOverlayChanged() {
- final int carrierTheme = R.style.TextAppearance_StatusBar_Clock;
+ final int carrierTheme = R.style.TextAppearance_StatusBar_Default;
mCarrierLabel.setTextAppearance(carrierTheme);
if (mBatteryView != null) {
mBatteryView.updatePercentView();
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt
index 10821dffd394..1f4ccd59b063 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/MobileIconsInteractor.kt
@@ -84,7 +84,7 @@ interface MobileIconsInteractor {
val icons: StateFlow<List<MobileIconInteractor>>
/** Whether the mobile icons can be stacked vertically. */
- val isStackable: StateFlow<Boolean>
+ val isStackable: Flow<Boolean>
/**
* Observable for the subscriptionId of the current mobile data connection. Null if we don't
@@ -309,21 +309,20 @@ constructor(
override val isStackable =
if (NewStatusBarIcons.isEnabled && StatusBarRootModernization.isEnabled) {
- icons.flatMapLatest { icons ->
- combine(icons.map { it.signalLevelIcon }) { signalLevelIcons ->
- // These are only stackable if:
- // - They are cellular
- // - There's exactly two
- // - They have the same number of levels
- signalLevelIcons.filterIsInstance<SignalIconModel.Cellular>().let {
- it.size == 2 && it[0].numberOfLevels == it[1].numberOfLevels
- }
+ icons.flatMapLatest { icons ->
+ combine(icons.map { it.signalLevelIcon }) { signalLevelIcons ->
+ // These are only stackable if:
+ // - They are cellular
+ // - There's exactly two
+ // - They have the same number of levels
+ signalLevelIcons.filterIsInstance<SignalIconModel.Cellular>().let {
+ it.size == 2 && it[0].numberOfLevels == it[1].numberOfLevels
}
}
- } else {
- flowOf(false)
}
- .stateIn(scope, SharingStarted.WhileSubscribed(), false)
+ } else {
+ flowOf(false)
+ }
/**
* Copied from the old pipeline. We maintain a 2s period of time where we will keep the
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/StackedMobileIconBinder.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/StackedMobileIconBinder.kt
index 54cd8e3c46e4..72ff3b67c317 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/StackedMobileIconBinder.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/binder/StackedMobileIconBinder.kt
@@ -18,9 +18,11 @@ package com.android.systemui.statusbar.pipeline.mobile.ui.binder
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.runtime.getValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.lifecycle.Lifecycle
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.repeatOnLifecycle
import com.android.systemui.Flags
import com.android.systemui.kairos.ExperimentalKairosApi
@@ -48,7 +50,7 @@ object StackedMobileIconBinder {
return SingleBindableStatusBarComposeIconView.withDefaultBinding(
view = view,
shouldBeVisible = { mobileIconsViewModel.isStackable.value },
- ) { _, tint ->
+ ) { _, tintFlow ->
view.repeatWhenAttached {
repeatOnLifecycle(Lifecycle.State.STARTED) {
view.composeView.apply {
@@ -66,8 +68,9 @@ object StackedMobileIconBinder {
viewModelFactory.create()
}
}
+ val tint by tintFlow.collectAsStateWithLifecycle()
if (viewModel.isIconVisible) {
- CompositionLocalProvider(LocalContentColor provides Color(tint())) {
+ CompositionLocalProvider(LocalContentColor provides Color(tint)) {
StackedMobileIcon(viewModel)
}
}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt
index 494d95e7f177..997b185fdee5 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/mobile/ui/viewmodel/MobileIconsViewModel.kt
@@ -36,6 +36,8 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
@@ -99,7 +101,17 @@ constructor(
}
.stateIn(scope, SharingStarted.WhileSubscribed(), false)
- val isStackable: StateFlow<Boolean> = interactor.isStackable
+ /** Whether all of [mobileSubViewModels] are visible or not. */
+ private val iconsAreAllVisible =
+ mobileSubViewModels.flatMapLatest { viewModels ->
+ combine(viewModels.map { it.isVisible }) { isVisibleArray -> isVisibleArray.all { it } }
+ }
+
+ val isStackable: StateFlow<Boolean> =
+ combine(iconsAreAllVisible, interactor.isStackable) { isVisible, isStackable ->
+ isVisible && isStackable
+ }
+ .stateIn(scope, SharingStarted.WhileSubscribed(), false)
init {
scope.launch { subscriptionIdsFlow.collect { invalidateCaches(it) } }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/ui/view/SingleBindableStatusBarComposeIconView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/ui/view/SingleBindableStatusBarComposeIconView.kt
index 8076040564fb..9d1df8967fc0 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/ui/view/SingleBindableStatusBarComposeIconView.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/pipeline/shared/ui/view/SingleBindableStatusBarComposeIconView.kt
@@ -35,6 +35,7 @@ import com.android.systemui.statusbar.pipeline.shared.ui.binder.ModernStatusBarV
import com.android.systemui.statusbar.pipeline.shared.ui.binder.ModernStatusBarViewVisibilityHelper
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
/** Compose view that is bound to bindable_status_bar_compose_icon.xml */
class SingleBindableStatusBarComposeIconView(context: Context, attrs: AttributeSet?) :
@@ -78,7 +79,7 @@ class SingleBindableStatusBarComposeIconView(context: Context, attrs: AttributeS
fun withDefaultBinding(
view: SingleBindableStatusBarComposeIconView,
shouldBeVisible: () -> Boolean,
- block: suspend LifecycleOwner.(View, () -> Int) -> Unit,
+ block: suspend LifecycleOwner.(View, StateFlow<Int>) -> Unit,
): ModernStatusBarViewBinding {
@StatusBarIconView.VisibleState
val visibilityState: MutableStateFlow<Int> = MutableStateFlow(STATE_HIDDEN)
@@ -90,7 +91,7 @@ class SingleBindableStatusBarComposeIconView(context: Context, attrs: AttributeS
view.repeatWhenAttached {
// Child binding
- block(view) { iconTint.value }
+ block(view, iconTint)
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyStateInflater.kt b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyStateInflater.kt
index b33c2005479e..4e18935834cf 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyStateInflater.kt
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyStateInflater.kt
@@ -34,6 +34,10 @@ import android.graphics.drawable.Icon
import android.os.Build
import android.os.Bundle
import android.os.SystemClock
+import android.text.Annotation
+import android.text.SpannableStringBuilder
+import android.text.Spanned
+import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
@@ -504,15 +508,40 @@ constructor(
choice: CharSequence,
delayOnClickListener: Boolean,
): Button {
- val layoutRes =
+ val enableAnimatedReply = Flags.notificationAnimatedActionsTreatment() &&
+ smartReplies.fromAssistant && isAnimatedReply(choice)
+ val layoutRes = if (enableAnimatedReply) {
+ R.layout.animated_action_button
+ } else {
if (notificationsRedesignTemplates()) R.layout.notification_2025_smart_reply_button
else R.layout.smart_reply_button
+ }
+
return (LayoutInflater.from(parent.context).inflate(layoutRes, parent, false) as Button)
.apply {
- text = choice
+ // choiceToDeliver does not contain Annotation with extra data
+ val choiceToDeliver: CharSequence
+ if (enableAnimatedReply) {
+ choiceToDeliver = choice.toString()
+ // If the choice is animated reply, format the text by concatenating
+ // attributionText with different color to choice text
+ val fullTextWithAttribution = formatChoiceWithAttribution(choice)
+ text = fullTextWithAttribution
+ } else {
+ choiceToDeliver = choice
+ text = choice
+ }
+
val onClickListener =
View.OnClickListener {
- onSmartReplyClick(entry, smartReplies, replyIndex, parent, this, choice)
+ onSmartReplyClick(
+ entry,
+ smartReplies,
+ replyIndex,
+ parent,
+ this,
+ choiceToDeliver
+ )
}
setOnClickListener(
if (delayOnClickListener)
@@ -600,6 +629,47 @@ constructor(
RemoteInput.setResultsSource(intent, RemoteInput.SOURCE_CHOICE)
return intent
}
+
+ // Check if the choice is animated reply
+ private fun isAnimatedReply(choice: CharSequence): Boolean {
+ if (choice is Spanned) {
+ val annotations = choice.getSpans(0, choice.length, Annotation::class.java)
+ for (annotation in annotations) {
+ if (annotation.key == "isAnimatedReply" && annotation.value == "1") {
+ return true
+ }
+ }
+ }
+ return false
+ }
+
+ // Format the text by concatenating attributionText with attribution text color to choice text
+ private fun formatChoiceWithAttribution(choice: CharSequence): CharSequence {
+ val colorInt = context.getColor(R.color.animated_action_button_attribution_color)
+ if (choice is Spanned) {
+ val annotations = choice.getSpans(0, choice.length, Annotation::class.java)
+ for (annotation in annotations) {
+ if (annotation.key == "attributionText") {
+ // Extract the attribution text
+ val extraText = annotation.value
+ // Concatenate choice text and attribution text
+ val spannableWithColor = SpannableStringBuilder(choice)
+ spannableWithColor.append(" $extraText")
+ // Apply color to attribution text
+ spannableWithColor.setSpan(
+ ForegroundColorSpan(colorInt),
+ choice.length,
+ spannableWithColor.length,
+ Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
+ )
+ return spannableWithColor
+ }
+ }
+ }
+
+ // Return the original if no attributionText found
+ return choice.toString()
+ }
}
/**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/domain/interactor/SensitiveNotificationProtectionInteractor.kt b/packages/SystemUI/src/com/android/systemui/statusbar/policy/domain/interactor/SensitiveNotificationProtectionInteractor.kt
new file mode 100644
index 000000000000..0a6a4c2e44e7
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/domain/interactor/SensitiveNotificationProtectionInteractor.kt
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.policy.domain.interactor
+
+import com.android.server.notification.Flags
+import com.android.systemui.dagger.SysUISingleton
+import com.android.systemui.statusbar.policy.SensitiveNotificationProtectionController
+import com.android.systemui.utils.coroutines.flow.conflatedCallbackFlow
+import javax.inject.Inject
+import kotlinx.coroutines.channels.awaitClose
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.flowOf
+
+/** A interactor which provides the current sensitive notification protections status */
+@SysUISingleton
+class SensitiveNotificationProtectionInteractor
+@Inject
+constructor(private val controller: SensitiveNotificationProtectionController) {
+
+ /** sensitive notification protections status */
+ val isSensitiveStateActive: Flow<Boolean> =
+ if (Flags.screenshareNotificationHiding()) {
+ conflatedCallbackFlow {
+ val listener = Runnable { trySend(controller.isSensitiveStateActive) }
+ controller.registerSensitiveStateListener(listener)
+ trySend(controller.isSensitiveStateActive)
+ awaitClose { controller.unregisterSensitiveStateListener(listener) }
+ }
+ .distinctUntilChanged()
+ } else {
+ flowOf(false)
+ }
+}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
index bf79d11b2fb8..515a10792c02 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
+++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/ui/viewmodel/PromptViewModelTest.kt
@@ -1482,6 +1482,14 @@ internal class PromptViewModelTest(private val testCase: TestCase) : SysuiTestCa
} else {
assertThat(hint.isNullOrBlank()).isTrue()
}
+
+ kosmos.promptViewModel.onClearUdfpsGuidanceHint(true)
+
+ if (testCase.modalities.hasUdfps) {
+ assertThat(hint).isNull()
+ } else {
+ assertThat(hint.isNullOrBlank()).isTrue()
+ }
}
@Test
diff --git a/packages/SystemUI/tests/src/com/android/systemui/globalactions/GlobalActionsDialogLiteTest.java b/packages/SystemUI/tests/src/com/android/systemui/globalactions/GlobalActionsDialogLiteTest.java
index 2898a02a1da8..cd6757c6e7ea 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/globalactions/GlobalActionsDialogLiteTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/globalactions/GlobalActionsDialogLiteTest.java
@@ -38,6 +38,7 @@ import android.content.res.Resources;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Handler;
+import android.os.PowerManager;
import android.os.UserManager;
import android.provider.Settings;
import android.testing.TestableLooper;
@@ -142,6 +143,7 @@ public class GlobalActionsDialogLiteTest extends SysuiTestCase {
@Mock private SelectedUserInteractor mSelectedUserInteractor;
@Mock private UserLogoutInteractor mLogoutInteractor;
@Mock private OnBackInvokedDispatcher mOnBackInvokedDispatcher;
+ @Mock private PowerManager mPowerManager;
@Captor private ArgumentCaptor<OnBackInvokedCallback> mOnBackInvokedCallback;
private TestableLooper mTestableLooper;
@@ -204,7 +206,8 @@ public class GlobalActionsDialogLiteTest extends SysuiTestCase {
mSelectedUserInteractor,
mLogoutInteractor,
mInteractor,
- () -> new FakeDisplayWindowPropertiesRepository(mContext)
+ () -> new FakeDisplayWindowPropertiesRepository(mContext),
+ mPowerManager
);
mGlobalActionsDialogLite.setZeroDialogPressDelayForTesting();
@@ -806,6 +809,101 @@ public class GlobalActionsDialogLiteTest extends SysuiTestCase {
assertThat(mGlobalActionsDialogLite.mDialog).isNull();
}
+ @Test
+ public void testShouldLogStandbyPress() {
+ GlobalActionsDialogLite.StandbyAction standbyAction =
+ mGlobalActionsDialogLite.new StandbyAction();
+ standbyAction.onPress();
+ verifyLogPosted(GlobalActionsDialogLite.GlobalActionsEvent.GA_STANDBY_PRESS);
+ }
+
+ @Test
+ public void testCreateActionItems_standbyEnabled_doesShowStandby() {
+ // Test like a TV, which only has standby and shut down
+ mGlobalActionsDialogLite = spy(mGlobalActionsDialogLite);
+ doReturn(2).when(mGlobalActionsDialogLite).getMaxShownPowerItems();
+ String[] actions = {
+ GlobalActionsDialogLite.GLOBAL_ACTION_KEY_STANDBY,
+ GlobalActionsDialogLite.GLOBAL_ACTION_KEY_POWER
+ };
+ doReturn(actions).when(mGlobalActionsDialogLite).getDefaultActions();
+ mGlobalActionsDialogLite.createActionItems();
+
+ assertItemsOfType(mGlobalActionsDialogLite.mItems,
+ GlobalActionsDialogLite.StandbyAction.class,
+ GlobalActionsDialogLite.ShutDownAction.class);
+ assertThat(mGlobalActionsDialogLite.mOverflowItems).isEmpty();
+ assertThat(mGlobalActionsDialogLite.mPowerItems).isEmpty();
+ }
+
+ @Test
+ public void testCreateActionItems_standbyDisabled_doesntStandbyAction() {
+ mGlobalActionsDialogLite = spy(mGlobalActionsDialogLite);
+ doReturn(5).when(mGlobalActionsDialogLite).getMaxShownPowerItems();
+ doReturn(true).when(mGlobalActionsDialogLite).shouldDisplayEmergency();
+ doReturn(true).when(mGlobalActionsDialogLite).shouldDisplayLockdown(any());
+ doReturn(true).when(mGlobalActionsDialogLite).shouldShowAction(any());
+ String[] actions = {
+ GlobalActionsDialogLite.GLOBAL_ACTION_KEY_EMERGENCY,
+ GlobalActionsDialogLite.GLOBAL_ACTION_KEY_LOCKDOWN,
+ GlobalActionsDialogLite.GLOBAL_ACTION_KEY_POWER,
+ GlobalActionsDialogLite.GLOBAL_ACTION_KEY_RESTART
+ };
+ doReturn(actions).when(mGlobalActionsDialogLite).getDefaultActions();
+ mGlobalActionsDialogLite.createActionItems();
+
+ assertNoItemsOfType(mGlobalActionsDialogLite.mItems,
+ GlobalActionsDialogLite.StandbyAction.class);
+ assertThat(mGlobalActionsDialogLite.mOverflowItems).isEmpty();
+ assertThat(mGlobalActionsDialogLite.mPowerItems).isEmpty();
+ }
+
+ @Test
+ public void testCreateActionItems_standbyEnabled_locked_showsStandby() {
+ // Test like a TV, which only has standby and shut down
+ mGlobalActionsDialogLite = spy(mGlobalActionsDialogLite);
+ doReturn(2).when(mGlobalActionsDialogLite).getMaxShownPowerItems();
+ String[] actions = {
+ GlobalActionsDialogLite.GLOBAL_ACTION_KEY_STANDBY,
+ GlobalActionsDialogLite.GLOBAL_ACTION_KEY_POWER
+ };
+ doReturn(actions).when(mGlobalActionsDialogLite).getDefaultActions();
+
+ // Show dialog with keyguard showing and provisioned
+ mGlobalActionsDialogLite.showOrHideDialog(true, true, null, Display.DEFAULT_DISPLAY);
+ // Clear the dismiss override so we don't have behavior after dismissing the dialog
+ mGlobalActionsDialogLite.mDialog.setDismissOverride(null);
+
+ assertOneItemOfType(mGlobalActionsDialogLite.mItems,
+ GlobalActionsDialogLite.StandbyAction.class);
+
+ // Hide dialog
+ mGlobalActionsDialogLite.showOrHideDialog(true, true, null, Display.DEFAULT_DISPLAY);
+ }
+
+ @Test
+ public void testCreateActionItems_standbyEnabled_notProvisioned_showsStandby() {
+ // Test like a TV, which only has standby and shut down.
+ mGlobalActionsDialogLite = spy(mGlobalActionsDialogLite);
+ doReturn(2).when(mGlobalActionsDialogLite).getMaxShownPowerItems();
+ String[] actions = {
+ GlobalActionsDialogLite.GLOBAL_ACTION_KEY_STANDBY,
+ GlobalActionsDialogLite.GLOBAL_ACTION_KEY_POWER
+ };
+ doReturn(actions).when(mGlobalActionsDialogLite).getDefaultActions();
+
+ // Show dialog without keyguard showing and not provisioned
+ mGlobalActionsDialogLite.showOrHideDialog(false, false, null, Display.DEFAULT_DISPLAY);
+ // Clear the dismiss override so we don't have behavior after dismissing the dialog
+ mGlobalActionsDialogLite.mDialog.setDismissOverride(null);
+
+ assertOneItemOfType(mGlobalActionsDialogLite.mItems,
+ GlobalActionsDialogLite.StandbyAction.class);
+
+ // Hide dialog
+ mGlobalActionsDialogLite.showOrHideDialog(false, false, null, Display.DEFAULT_DISPLAY);
+ }
+
private UserInfo mockCurrentUser(int flags) {
return new UserInfo(10, "A User", flags);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfoTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfoTest.java
index 2c800bd87ef5..a515c3f6ed6e 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfoTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/NotificationConversationInfoTest.java
@@ -171,6 +171,8 @@ public class NotificationConversationInfoTest extends SysuiTestCase {
private ConversationIconFactory mIconFactory;
@Mock
private Notification.BubbleMetadata mBubbleMetadata;
+ @Mock
+ private View.OnClickListener mCloseListener;
private Handler mTestHandler;
@Rule
public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
@@ -298,7 +300,7 @@ public class NotificationConversationInfoTest extends SysuiTestCase {
true,
mTestHandler,
mTestHandler, null, Optional.of(mBubblesManager),
- mShadeController);
+ mShadeController, true, mCloseListener);
}
@Test
@@ -402,7 +404,7 @@ public class NotificationConversationInfoTest extends SysuiTestCase {
true,
mTestHandler,
mTestHandler, null, Optional.of(mBubblesManager),
- mShadeController);
+ mShadeController, true, null);
final TextView nameView = mNotificationInfo.findViewById(R.id.delegate_name);
assertEquals(VISIBLE, nameView.getVisibility());
assertTrue(nameView.getText().toString().contains("Proxied"));
@@ -442,7 +444,7 @@ public class NotificationConversationInfoTest extends SysuiTestCase {
true,
mTestHandler,
mTestHandler, null, Optional.of(mBubblesManager),
- mShadeController);
+ mShadeController, true, null);
final View feedback = mNotificationInfo.findViewById(R.id.feedback);
assertEquals(VISIBLE, feedback.getVisibility());
@@ -484,7 +486,7 @@ public class NotificationConversationInfoTest extends SysuiTestCase {
true,
mTestHandler,
mTestHandler, null, Optional.of(mBubblesManager),
- mShadeController);
+ mShadeController, true, null);
final View settingsButton = mNotificationInfo.findViewById(R.id.info);
settingsButton.performClick();
@@ -524,7 +526,7 @@ public class NotificationConversationInfoTest extends SysuiTestCase {
false,
mTestHandler,
mTestHandler, null, Optional.of(mBubblesManager),
- mShadeController);
+ mShadeController, true, null);
final View settingsButton = mNotificationInfo.findViewById(R.id.info);
assertTrue(settingsButton.getVisibility() != View.VISIBLE);
}
@@ -601,7 +603,7 @@ public class NotificationConversationInfoTest extends SysuiTestCase {
true,
mTestHandler,
mTestHandler, null, Optional.of(mBubblesManager),
- mShadeController);
+ mShadeController, true, null);
assertThat(((TextView) mNotificationInfo.findViewById(R.id.priority_summary)).getText())
.isEqualTo(mContext.getString(
R.string.notification_channel_summary_priority_dnd));
@@ -633,7 +635,7 @@ public class NotificationConversationInfoTest extends SysuiTestCase {
true,
mTestHandler,
mTestHandler, null, Optional.of(mBubblesManager),
- mShadeController);
+ mShadeController, true, null);
assertThat(((TextView) mNotificationInfo.findViewById(R.id.priority_summary)).getText())
.isEqualTo(mContext.getString(
R.string.notification_channel_summary_priority_baseline));
@@ -1018,4 +1020,19 @@ public class NotificationConversationInfoTest extends SysuiTestCase {
// THEN the user is not presented with the People Tile pinning request
verify(mPeopleSpaceWidgetManager, never()).requestPinAppWidget(eq(mShortcutInfo), any());
}
+
+
+ @Test
+ public void testDismiss() throws Exception {
+ doStandardBind();
+
+ View dismiss = mNotificationInfo.findViewById(R.id.inline_dismiss);
+ dismiss.performClick();
+ mTestableLooper.processAllMessages();
+
+ // Verify action performed on button click
+ verify(mCloseListener).onClick(any());
+
+ }
+
}
diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
index 4a0445d5543a..5b29bffc5148 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/policy/RemoteInputViewTest.java
@@ -67,6 +67,7 @@ import androidx.test.filters.SmallTest;
import com.android.internal.logging.UiEventLogger;
import com.android.internal.logging.testing.UiEventLoggerFake;
import com.android.systemui.Dependency;
+import com.android.systemui.Flags;
import com.android.systemui.SysuiTestCase;
import com.android.systemui.animation.AnimatorTestRule;
import com.android.systemui.flags.FakeFeatureFlags;
@@ -409,9 +410,14 @@ public class RemoteInputViewTest extends SysuiTestCase {
// fast forward to end of animation
mAnimatorTestRule.advanceTimeBy(1);
- // assert that fadeOutView's alpha is reset to 1f after the animation (hidden behind
- // RemoteInputView)
- assertEquals(1f, fadeOutView.getAlpha());
+ if (Flags.notificationRowTransparency()) {
+ // With transparent rows, fadeOutView should be hidden after the animation.
+ assertEquals(0f, fadeOutView.getAlpha());
+ } else {
+ // assert that fadeOutView's alpha is reset to 1f after the animation (hidden behind
+ // RemoteInputView)
+ assertEquals(1f, fadeOutView.getAlpha());
+ }
assertFalse(view.isAnimatingAppearance());
assertEquals(View.VISIBLE, view.getVisibility());
assertEquals(1f, view.getAlpha());
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/communal/data/repository/FakeCommunalSceneRepository.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/communal/data/repository/FakeCommunalSceneRepository.kt
index 3f35bb9f3520..38e6c8a0cdea 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/communal/data/repository/FakeCommunalSceneRepository.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/communal/data/repository/FakeCommunalSceneRepository.kt
@@ -1,5 +1,6 @@
package com.android.systemui.communal.data.repository
+import android.content.res.Configuration
import com.android.compose.animation.scene.ObservableTransitionState
import com.android.compose.animation.scene.SceneKey
import com.android.compose.animation.scene.TransitionKey
@@ -9,6 +10,7 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.stateIn
@@ -48,4 +50,13 @@ class FakeCommunalSceneRepository(
override fun setTransitionState(transitionState: Flow<ObservableTransitionState>?) {
_transitionState.value = transitionState
}
+
+ private val _communalContainerOrientation =
+ MutableStateFlow(Configuration.ORIENTATION_UNDEFINED)
+ override val communalContainerOrientation: StateFlow<Int> =
+ _communalContainerOrientation.asStateFlow()
+
+ override fun setCommunalContainerOrientation(orientation: Int) {
+ _communalContainerOrientation.value = orientation
+ }
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractorKosmos.kt
index 209d1636e380..8834af581e73 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/communal/domain/interactor/CommunalSceneInteractorKosmos.kt
@@ -21,6 +21,7 @@ import com.android.systemui.communal.shared.log.communalSceneLogger
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.applicationCoroutineScope
import com.android.systemui.scene.domain.interactor.sceneInteractor
+import com.android.systemui.statusbar.policy.keyguardStateController
val Kosmos.communalSceneInteractor: CommunalSceneInteractor by
Kosmos.Fixture {
@@ -29,5 +30,6 @@ val Kosmos.communalSceneInteractor: CommunalSceneInteractor by
repository = communalSceneRepository,
logger = communalSceneLogger,
sceneInteractor = sceneInteractor,
+ keyguardStateController = keyguardStateController,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/data/ui/viewmodel/UdfpsAccessibilityOverlayViewModelKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/data/ui/viewmodel/UdfpsAccessibilityOverlayViewModelKosmos.kt
index 2a46437ed33e..2a3bd335bf98 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/data/ui/viewmodel/UdfpsAccessibilityOverlayViewModelKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/deviceentry/data/ui/viewmodel/UdfpsAccessibilityOverlayViewModelKosmos.kt
@@ -18,6 +18,8 @@ package com.android.systemui.deviceentry.data.ui.viewmodel
import com.android.systemui.accessibility.domain.interactor.accessibilityInteractor
import com.android.systemui.biometrics.domain.interactor.udfpsOverlayInteractor
+import com.android.systemui.biometrics.udfpsUtils
+import com.android.systemui.deviceentry.ui.viewmodel.AlternateBouncerUdfpsAccessibilityOverlayViewModel
import com.android.systemui.deviceentry.ui.viewmodel.DeviceEntryUdfpsAccessibilityOverlayViewModel
import com.android.systemui.keyguard.ui.viewmodel.deviceEntryForegroundIconViewModel
import com.android.systemui.keyguard.ui.viewmodel.deviceEntryIconViewModel
@@ -30,5 +32,15 @@ val Kosmos.deviceEntryUdfpsAccessibilityOverlayViewModel by
accessibilityInteractor = accessibilityInteractor,
deviceEntryIconViewModel = deviceEntryIconViewModel,
deviceEntryFgIconViewModel = deviceEntryForegroundIconViewModel,
+ udfpsUtils = udfpsUtils,
+ )
+ }
+
+val Kosmos.alternateBouncerUdfpsAccessibilityOverlayViewModel by
+ Kosmos.Fixture {
+ AlternateBouncerUdfpsAccessibilityOverlayViewModel(
+ udfpsOverlayInteractor = udfpsOverlayInteractor,
+ accessibilityInteractor = accessibilityInteractor,
+ udfpsUtils = udfpsUtils,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/AccessibilityActionsViewModelKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/AccessibilityActionsViewModelKosmos.kt
index bc35dc8052ec..be5431c3d0d7 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/AccessibilityActionsViewModelKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/AccessibilityActionsViewModelKosmos.kt
@@ -16,6 +16,7 @@
package com.android.systemui.keyguard.ui.viewmodel
+import com.android.systemui.biometrics.domain.interactor.udfpsOverlayInteractor
import com.android.systemui.communal.domain.interactor.communalInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardInteractor
import com.android.systemui.keyguard.domain.interactor.keyguardTransitionInteractor
@@ -27,5 +28,6 @@ val Kosmos.accessibilityActionsViewModelKosmos by Fixture {
communalInteractor = communalInteractor,
keyguardTransitionInteractor = keyguardTransitionInteractor,
keyguardInteractor = keyguardInteractor,
+ udfpsOverlayInteractor = udfpsOverlayInteractor,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerViewModelKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerViewModelKosmos.kt
new file mode 100644
index 000000000000..625e751c8b65
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/DreamingToPrimaryBouncerViewModelKosmos.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard.ui.viewmodel
+
+import com.android.systemui.keyguard.ui.keyguardTransitionAnimationFlow
+import com.android.systemui.keyguard.ui.transitions.blurConfig
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.Kosmos.Fixture
+
+val Kosmos.dreamingToPrimaryBouncerViewModel by Fixture {
+ DreamingToPrimaryBouncerTransitionViewModel(
+ animationFlow = keyguardTransitionAnimationFlow,
+ blurConfig = blurConfig,
+ )
+}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModelKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModelKosmos.kt
index 530981c489e8..02e63a42d87d 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModelKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/GlanceableHubToLockscreenTransitionViewModelKosmos.kt
@@ -17,15 +17,21 @@
package com.android.systemui.keyguard.ui.viewmodel
import com.android.systemui.common.ui.domain.interactor.configurationInteractor
+import com.android.systemui.communal.domain.interactor.communalSceneInteractor
+import com.android.systemui.communal.domain.interactor.communalSettingsInteractor
import com.android.systemui.keyguard.ui.glanceableHubBlurComponentFactory
import com.android.systemui.keyguard.ui.keyguardTransitionAnimationFlow
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.Kosmos.Fixture
+import com.android.systemui.kosmos.applicationCoroutineScope
val Kosmos.glanceableHubToLockscreenTransitionViewModel by Fixture {
GlanceableHubToLockscreenTransitionViewModel(
+ applicationScope = applicationCoroutineScope,
configurationInteractor = configurationInteractor,
animationFlow = keyguardTransitionAnimationFlow,
+ communalSceneInteractor = communalSceneInteractor,
+ communalSettingsInteractor = communalSettingsInteractor,
blurFactory = glanceableHubBlurComponentFactory,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModelKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModelKosmos.kt
new file mode 100644
index 000000000000..c53bf9556aca
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/keyguard/ui/viewmodel/PrimaryBouncerToDreamingTransitionViewModelKosmos.kt
@@ -0,0 +1,29 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.keyguard.ui.viewmodel
+
+import com.android.systemui.keyguard.ui.keyguardTransitionAnimationFlow
+import com.android.systemui.keyguard.ui.transitions.blurConfig
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.kosmos.Kosmos.Fixture
+
+val Kosmos.primaryBouncerToDreamingTransitionViewModel by Fixture {
+ PrimaryBouncerToDreamingTransitionViewModel(
+ animationFlow = keyguardTransitionAnimationFlow,
+ blurConfig = blurConfig,
+ )
+}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractorKosmos.kt
index 1397d974cbc5..20d3682c6964 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/shade/domain/interactor/ShadeDisplaysInteractorKosmos.kt
@@ -21,6 +21,7 @@ import android.window.WindowContext
import com.android.systemui.common.ui.data.repository.configurationRepository
import com.android.systemui.kosmos.Kosmos
import com.android.systemui.kosmos.testScope
+import com.android.systemui.log.logcatLogBuffer
import com.android.systemui.shade.ShadeDisplayChangeLatencyTracker
import com.android.systemui.shade.ShadeWindowLayoutParams
import com.android.systemui.shade.data.repository.fakeShadeDisplaysRepository
@@ -60,5 +61,6 @@ val Kosmos.shadeDisplaysInteractor by
notificationRebindingTracker,
notificationStackRebindingHider,
configurationController,
+ logcatLogBuffer("ShadeDisplaysInteractor"),
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationContentExtractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationContentExtractorKosmos.kt
index c4542c4e709b..00b26c944b90 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationContentExtractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/promoted/PromotedNotificationContentExtractorKosmos.kt
@@ -19,7 +19,7 @@ package com.android.systemui.statusbar.notification.promoted
import android.app.Notification
import android.content.applicationContext
import com.android.systemui.kosmos.Kosmos
-import com.android.systemui.statusbar.NotificationLockscreenUserManager.REDACTION_TYPE_NONE
+import com.android.systemui.statusbar.NotificationLockscreenUserManager.REDACTION_TYPE_PUBLIC
import com.android.systemui.statusbar.notification.collection.NotificationEntry
import com.android.systemui.statusbar.notification.row.RowImageInflater
import com.android.systemui.statusbar.notification.row.shared.skeletonImageTransform
@@ -40,7 +40,7 @@ fun Kosmos.setPromotedContent(entry: NotificationEntry) {
promotedNotificationContentExtractor.extractContent(
entry,
Notification.Builder.recoverBuilder(applicationContext, entry.sbn.notification),
- REDACTION_TYPE_NONE,
+ REDACTION_TYPE_PUBLIC,
RowImageInflater.newInstance(previousIndex = null, reinflating = false)
.useForContentModel(),
)
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationInteractorKosmos.kt
index fcd484353011..ea459a95728a 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationInteractorKosmos.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/notification/promoted/domain/interactor/AODPromotedNotificationInteractorKosmos.kt
@@ -17,12 +17,16 @@
package com.android.systemui.statusbar.notification.promoted.domain.interactor
import com.android.systemui.dump.dumpManager
+import com.android.systemui.keyguard.domain.interactor.keyguardInteractor
import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.statusbar.policy.domain.interactor.sensitiveNotificationProtectionInteractor
val Kosmos.aodPromotedNotificationInteractor by
Kosmos.Fixture {
AODPromotedNotificationInteractor(
promotedNotificationsInteractor = promotedNotificationsInteractor,
+ keyguardInteractor = keyguardInteractor,
+ sensitiveNotificationProtectionInteractor = sensitiveNotificationProtectionInteractor,
dumpManager = dumpManager,
)
}
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt
index 8fa82cad5c32..72f9d550eb4d 100644
--- a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/pipeline/mobile/domain/interactor/FakeMobileIconsInteractor.kt
@@ -26,7 +26,6 @@ import com.android.systemui.log.table.TableLogBuffer
import com.android.systemui.statusbar.pipeline.mobile.data.model.SubscriptionModel
import com.android.systemui.statusbar.pipeline.mobile.util.MobileMappingsProxy
import kotlinx.coroutines.flow.MutableStateFlow
-import kotlinx.coroutines.flow.StateFlow
class FakeMobileIconsInteractor(
mobileMappings: MobileMappingsProxy,
@@ -76,7 +75,7 @@ class FakeMobileIconsInteractor(
override val icons: MutableStateFlow<List<MobileIconInteractor>> = MutableStateFlow(emptyList())
- override val isStackable: StateFlow<Boolean> = MutableStateFlow(false)
+ override val isStackable: MutableStateFlow<Boolean> = MutableStateFlow(false)
private val _defaultMobileIconMapping = MutableStateFlow(TEST_MAPPING)
override val defaultMobileIconMapping = _defaultMobileIconMapping
diff --git a/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/policy/domain/interactor/SensitiveNotificationProtectionInteractorKosmos.kt b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/policy/domain/interactor/SensitiveNotificationProtectionInteractorKosmos.kt
new file mode 100644
index 000000000000..ba4410b51b75
--- /dev/null
+++ b/packages/SystemUI/tests/utils/src/com/android/systemui/statusbar/policy/domain/interactor/SensitiveNotificationProtectionInteractorKosmos.kt
@@ -0,0 +1,25 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.statusbar.policy.domain.interactor
+
+import com.android.systemui.kosmos.Kosmos
+import com.android.systemui.statusbar.policy.sensitiveNotificationProtectionController
+
+var Kosmos.sensitiveNotificationProtectionInteractor: SensitiveNotificationProtectionInteractor by
+ Kosmos.Fixture {
+ SensitiveNotificationProtectionInteractor(sensitiveNotificationProtectionController)
+ }
diff --git a/ravenwood/README.md b/ravenwood/README.md
index 9c4fda7a50a6..62f2ffae56ba 100644
--- a/ravenwood/README.md
+++ b/ravenwood/README.md
@@ -4,25 +4,4 @@ Ravenwood is an officially-supported lightweight unit testing environment for An
Ravenwood’s focus on Android platform use-cases, improved maintainability, and device consistency distinguishes it from Robolectric, which remains a popular choice for app testing.
-## Background
-
-Executing tests on a typical Android device has substantial overhead, such as flashing the build, waiting for the boot to complete, and retrying tests that fail due to general flakiness.
-
-In contrast, defining a lightweight unit testing environment mitigates these issues by running directly from build artifacts (no flashing required), runs immediately (no booting required), and runs in an isolated environment (less flakiness).
-
-## Guiding principles
-Here’s a summary of the guiding principles for Ravenwood, aimed at addressing Robolectric design concerns and better supporting Android platform developers:
-
-* **API support for Ravenwood is opt-in.** Teams that own APIs decide exactly what, and how, they support their API functionality being available to tests. When an API hasn’t opted-in, the API signatures remain available for tests to compile against and/or mock, but they throw when called under a Ravenwood environment.
- * _Contrasted with Robolectric which attempts to run API implementations as-is, causing maintenance pains as teams maintain or redesign their API internals._
-* **API support and customizations for Ravenwood appear directly inline with relevant code.** This improves maintenance of APIs by providing awareness of what code runs under Ravenwood, including the ability to replace code at a per-method level when Ravenwood-specific customization is needed.
- * _Contrasted with Robolectric which maintains customized behavior in separate “Shadow” classes that are difficult for maintainers to be aware of._
-* **APIs supported under Ravenwood are tested to remain consistent with physical devices.** As teams progressively opt-in supporting APIs under Ravenwood, we’re requiring they bring along “bivalent” tests (such as the relevant CTS) to validate that Ravenwood behaves just like a physical device.
- * _Contrasted with Robolectric, which has limited (and forked) testing of their environment, increasing their risk of accidental divergence over time and misleading “passing” signals._
-* **Ravenwood aims to support more “real” code.** As API owners progressively opt-in their code, they have the freedom to provide either a limited “fake” that is a faithful emulation of how a device behaves, or they can bring more “real” code that runs on physical devices.
- * _Contrasted with Robolectric, where support for “real” code ends at the app process boundary, such as a call into `system_server`._
-
-## More details
-
-* [Ravenwood for Test Authors](test-authors.md)
-* [Ravenwood for API Maintainers](api-maintainers.md)
+Documents have been moved to go/ravenwood.
diff --git a/ravenwood/api-maintainers.md b/ravenwood/api-maintainers.md
deleted file mode 100644
index 4b2f96804c97..000000000000
--- a/ravenwood/api-maintainers.md
+++ /dev/null
@@ -1,94 +0,0 @@
-# Ravenwood for API Maintainers
-
-By default, Android APIs aren’t opted-in to Ravenwood, and they default to throwing when called under the Ravenwood environment.
-
-To opt-in to supporting an API under Ravenwood, you can use the inline annotations documented below to customize your API behavior when running under Ravenwood. Because these annotations are inline in the relevant platform source code, they serve as valuable reminders to future API maintainers of Ravenwood support expectations.
-
-> **Note:** to ensure that API teams are well-supported during early Ravenwood onboarding, the Ravenwood team is manually maintaining an allow-list of classes that are able to use Ravenwood annotations. Please reach out to ravenwood@ so we can offer design advice and allow-list your APIs.
-
-These Ravenwood-specific annotations have no bearing on the status of an API being public, `@SystemApi`, `@TestApi`, `@hide`, etc. Ravenwood annotations are an orthogonal concept that are only consumed by the internal `hoststubgen` tool during a post-processing step that generates the Ravenwood runtime environment. Teams that own APIs can continue to refactor opted-in `@hide` implementation details, as long as the test-visible behavior continues passing.
-
-As described in our Guiding Principles, when a team opts-in an API, we’re requiring that they bring along “bivalent” tests (such as the relevant CTS) to validate that Ravenwood behaves just like a physical device. At the moment this means adding the bivalent tests to relevant `TEST_MAPPING` files to ensure they remain consistently passing over time. These bivalent tests are important because they progressively provide the foundation on which higher-level unit tests place their trust.
-
-## Opt-in to supporting a single method while other methods remained opt-out
-
-```
-@RavenwoodKeepPartialClass
-public class MyManager {
- @RavenwoodKeep
- public static String modeToString(int mode) {
- // This method implementation runs as-is on both devices and Ravenwood
- }
-
- public static void doComplex() {
- // This method implementation runs as-is on devices, but because there
- // is no method-level annotation, and the class-level default is
- // “keep partial”, this method is not supported under Ravenwood and
- // will throw
- }
-}
-```
-
-## Opt-in an entire class with opt-out of specific methods
-
-```
-@RavenwoodKeepWholeClass
-public class MyStruct {
- public void doSimple() {
- // This method implementation runs as-is on both devices and Ravenwood,
- // implicitly inheriting the class-level annotation
- }
-
- @RavenwoodThrow
- public void doComplex() {
- // This method implementation runs as-is on devices, but the
- // method-level annotation overrides the class-level annotation, so
- // this method is not supported under Ravenwood and will throw
- }
-}
-```
-
-## Replace a complex method when under Ravenwood
-
-```
-@RavenwoodKeepWholeClass
-public class MyStruct {
- @RavenwoodReplace
- public void doComplex() {
- // This method implementation runs as-is on devices, but the
- // implementation is replaced/substituted by the
- // doComplex$ravenwood() method implementation under Ravenwood
- }
-
- public void doComplex$ravenwood() {
- // This method implementation only runs under Ravenwood
- }
-}
-```
-
-## General strategies for side-stepping tricky dependencies
-
-The “replace” strategy described above is quite powerful, and can be used in creative ways to sidestep tricky underlying dependencies that aren’t ready yet.
-
-For example, consider a constructor or static initializer that relies on unsupported functionality from another team. By factoring the unsupported logic into a dedicated method, that method can then be replaced under Ravenwood to offer baseline functionality.
-
-## Strategies for JNI
-
-At the moment, JNI isn't yet supported under Ravenwood, but you may still want to support APIs that are partially implemented with JNI. The current approach is to use the “replace” strategy to offer a pure-Java alternative implementation for any JNI-provided logic.
-
-Since this approach requires potentially complex re-implementation, it should only be considered for core infrastructure that is critical to unblocking widespread testing use-cases. Other less-common usages of JNI should instead wait for offical JNI support in the Ravenwood environment.
-
-When a pure-Java implementation grows too large or complex to host within the original class, the `@RavenwoodNativeSubstitutionClass` annotation can be used to host it in a separate source file:
-
-```
-@RavenwoodKeepWholeClass
-@RavenwoodNativeSubstitutionClass("com.android.platform.test.ravenwood.nativesubstitution.MyComplexClass_host")
-public class MyComplexClass {
- private static native void nativeDoThing(long nativePtr);
-...
-
-public class MyComplexClass_host {
- public static void nativeDoThing(long nativePtr) {
- // ...
- }
-```
diff --git a/ravenwood/test-authors.md b/ravenwood/test-authors.md
deleted file mode 100644
index 6d82a744bc4f..000000000000
--- a/ravenwood/test-authors.md
+++ /dev/null
@@ -1,193 +0,0 @@
-# Ravenwood for Test Authors
-
-The Ravenwood testing environment runs inside a single Java process on the host side, and provides a limited yet growing set of Android API functionality.
-
-Ravenwood explicitly does not support “large” integration tests that expect a fully booted Android OS. Instead, it’s more suited for “small” and “medium” tests where your code-under-test has been factored to remove dependencies on a fully booted device.
-
-When writing tests under Ravenwood, all Android API symbols associated with your declared `sdk_version` are available to link against using, but unsupported APIs will throw an exception. This design choice enables mocking of unsupported APIs, and supports sharing of test code to build “bivalent” test suites that run against either Ravenwood or a traditional device.
-
-## Manually running tests
-
-To run all Ravenwood tests, use:
-
-```
-./frameworks/base/ravenwood/scripts/run-ravenwood-tests.sh
-```
-
-To run a specific test, use "atest" as normal, selecting the test from a Ravenwood suite such as:
-
-```
-atest CtsOsTestCasesRavenwood:ParcelTest\#testSetDataCapacityNegative
-```
-
-## Typical test structure
-
-Below are the typical steps needed to add a straightforward “small” unit test:
-
-* Define an `android_ravenwood_test` rule in your `Android.bp` file:
-
-```
-android_ravenwood_test {
- name: "MyTestsRavenwood",
- static_libs: [
- "androidx.annotation_annotation",
- "androidx.test.ext.junit",
- "androidx.test.rules",
- ],
- srcs: [
- "src/com/example/MyCode.java",
- "tests/src/com/example/MyCodeTest.java",
- ],
- sdk_version: "test_current",
- auto_gen_config: true,
-}
-```
-
-* Write your unit test just like you would for an Android device:
-
-```
-import android.platform.test.annotations.DisabledOnRavenwood;
-import android.platform.test.ravenwood.RavenwoodRule;
-
-import androidx.test.ext.junit.runners.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(AndroidJUnit4.class)
-public class MyCodeTest {
- @Test
- public void testSimple() {
- // ...
- }
-}
-```
-
-* APIs available under Ravenwood are stateless by default. If your test requires explicit states (such as defining the UID you’re running under, or requiring a main `Looper` thread), add a `RavenwoodRule` to declare that:
-
-```
-import android.platform.test.annotations.DisabledOnRavenwood;
-import android.platform.test.ravenwood.RavenwoodRule;
-
-import androidx.test.runner.AndroidJUnit4;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(AndroidJUnit4.class)
-public class MyCodeTest {
- @Rule
- public final RavenwoodRule mRavenwood = new RavenwoodRule.Builder()
- .setProcessApp()
- .setProvideMainThread(true)
- .build();
-```
-
-Once you’ve defined your test, you can use typical commands to execute it locally:
-
-```
-$ atest --host MyTestsRavenwood
-```
-
-> **Note:** There's a known bug #312525698 where `atest` currently requires a connected device to run Ravenwood tests, but that device isn't used for testing. Using the `--host` argument above is a way to bypass this requirement until the bug is fixed.
-
-You can also run your new tests automatically via `TEST_MAPPING` rules like this:
-
-```
-{
- "ravenwood-presubmit": [
- {
- "name": "MyTestsRavenwood",
- "host": true
- }
- ]
-}
-```
-
-> **Note:** There's a known bug #308854804 where `TEST_MAPPING` is not being applied, so we're currently planning to run all Ravenwood tests unconditionally in presubmit for changes to `frameworks/base/` and `cts/` until there is a better path forward.
-
-## Strategies for migration/bivalent tests
-
-Ravenwood aims to support tests that are written in a “bivalent” way, where the same test code can be dual-compiled to run on both a real Android device and under a Ravenwood environment.
-
-In situations where a test method depends on API functionality not yet available under Ravenwood, we provide an annotation to quietly “ignore” that test under Ravenwood, while continuing to validate that test on real devices. The annotation can be applied to either individual methods or to an entire test class. Please note that your test class must declare a `RavenwoodRule` for the annotation to take effect.
-
-Test authors are encouraged to provide a `blockedBy` or `reason` argument to help future maintainers understand why a test is being ignored, and under what conditions it might be supported in the future.
-
-```
-@RunWith(AndroidJUnit4.class)
-public class MyCodeTest {
- @Rule
- public final RavenwoodRule mRavenwood = new RavenwoodRule();
-
- @Test
- public void testSimple() {
- // Simple test that runs on both devices and Ravenwood
- }
-
- @Test
- @DisabledOnRavenwood(blockedBy = PackageManager.class)
- public void testComplex() {
- // Complex test that runs on devices, but is ignored under Ravenwood
- }
-}
-```
-
-At the moment, the `android.content.res.Resources` subsystem isn't yet supported under Ravenwood, but you may still want to dual-compile test suites that depend on references to resources. Below is a strategy for supporting dual-compiliation, where you can "borrow" the generated resource symbols from your traditional `android_test` target:
-
-```
-android_test {
- name: "MyTestsDevice",
- resource_dirs: ["res"],
-...
-
-android_ravenwood_test {
- name: "MyTestsRavenwood",
- srcs: [
- ":MyTestsDevice{.aapt.srcjar}",
-...
-```
-
-## Strategies for unsupported APIs
-
-As you write tests against Ravenwood, you’ll likely discover API dependencies that aren’t supported yet. Here’s a few strategies that can help you make progress:
-
-* Your code-under-test may benefit from subtle dependency refactoring to reduce coupling. (For example, providing a specific `File` argument instead of deriving paths internally from a `Context` or `Environment`.)
- * One common use-case is providing a directory for your test to store temporary files, which can easily be accomplished using the `Files.createTempDirectory()` API which works on both physical devices and under Ravenwood:
-
-```
-import java.nio.file.Files;
-
-@RunWith(AndroidJUnit4.class)
-public class MyTest {
- @Before
- public void setUp() throws Exception {
- File tempDir = Files.createTempDirectory("MyTest").toFile();
-...
-```
-
-* Although mocking code that your team doesn’t own is a generally discouraged testing practice, it can be a valuable pressure relief valve when a dependency isn’t yet supported.
-
-## Strategies for debugging test development
-
-When writing tests you may encounter odd or hard to debug behaviors. One good place to start is at the beginning of the logs stored by atest:
-
-```
-$ atest MyTestsRavenwood
-...
-Test Logs have saved in /tmp/atest_result/20231128_094010_0e90t8v8/log
-Run 'atest --history' to review test result history.
-```
-
-The most useful logs are in the `isolated-java-logs` text file, which can typically be tab-completed by copy-pasting the logs path mentioned in the atest output:
-
-```
-$ less /tmp/atest_result/20231128_133105_h9al__79/log/i*/i*/isolated-java-logs*
-```
-
-Here are some common known issues and recommended workarounds:
-
-* Some code may unconditionally interact with unsupported APIs, such as via static initializers. One strategy is to shift the logic into `@Before` methods and make it conditional by testing `RavenwoodRule.isUnderRavenwood()`.
-* Some code may reference API symbols not yet present in the Ravenwood runtime, such as ART or ICU internals, or APIs from Mainline modules. One strategy is to refactor to avoid these internal dependencies, but Ravenwood aims to better support them soon.
- * This may also manifest as very odd behavior, such as test not being executed at all, tracked by bug #312517322
- * This may also manifest as an obscure Mockito error claiming “Mockito can only mock non-private & non-final classes”
diff --git a/ravenwood/texts/ravenwood-annotation-allowed-classes.txt b/ravenwood/texts/ravenwood-annotation-allowed-classes.txt
index 7462cc2f384a..c035688a8c84 100644
--- a/ravenwood/texts/ravenwood-annotation-allowed-classes.txt
+++ b/ravenwood/texts/ravenwood-annotation-allowed-classes.txt
@@ -323,6 +323,10 @@ com.android.internal.graphics.cam.Frame
com.android.internal.graphics.cam.HctSolver
com.android.internal.graphics.ColorUtils
+com.android.internal.protolog.common.LogLevel
+com.android.internal.protolog.LogcatOnlyProtoLogImpl
+com.android.internal.protolog.ProtoLog
+
com.android.internal.util.BitUtils
com.android.internal.util.BitwiseInputStream
com.android.internal.util.BitwiseOutputStream
diff --git a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
index 39c1fa73b7ce..b4c45aba0131 100644
--- a/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
+++ b/services/accessibility/java/com/android/server/accessibility/AccessibilityManagerService.java
@@ -1823,11 +1823,10 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
public void notifyQuickSettingsTilesChanged(
@UserIdInt int userId, @NonNull List<ComponentName> tileComponentNames) {
notifyQuickSettingsTilesChanged_enforcePermission();
- if (DEBUG) {
- Slog.d(LOG_TAG, TextUtils.formatSimple(
- "notifyQuickSettingsTilesChanged userId: %d, tileComponentNames: %s",
- userId, tileComponentNames));
- }
+
+ Slog.d(LOG_TAG, String.format(
+ "notifyQuickSettingsTilesChanged userId: %s, tileComponentNames: %s",
+ userId, tileComponentNames));
final Set<ComponentName> newTileComponentNames = new ArraySet<>(tileComponentNames);
final Set<ComponentName> addedTiles;
final Set<ComponentName> removedTiles;
@@ -2131,6 +2130,7 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
parsedAccessibilityShortcutInfos = parseAccessibilityShortcutInfos(userId);
synchronized (mLock) {
if (mCurrentUserId == userId && mInitialized) {
+ Slog.w(LOG_TAG, String.format("userId: %d is already initialized", userId));
return;
}
@@ -3309,10 +3309,9 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
* @param forceUpdate whether to force an update of the app Clients.
*/
private void onUserStateChangedLocked(AccessibilityUserState userState, boolean forceUpdate) {
- if (DEBUG) {
- Slog.v(LOG_TAG, "onUserStateChangedLocked for user " + userState.mUserId + " with "
- + "forceUpdate: " + forceUpdate);
- }
+ Slog.v(LOG_TAG, String.format("onUserStateChangedLocked for userId: %d, forceUpdate: %s",
+ userState.mUserId, forceUpdate));
+
// TODO: Remove this hack
mInitialized = true;
updateLegacyCapabilitiesLocked(userState);
@@ -4361,6 +4360,10 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
private void enableShortcutForTargets(
boolean enable, @UserShortcutType int shortcutType,
@NonNull List<String> shortcutTargets, @UserIdInt int userId) {
+ Slog.d(LOG_TAG, String.format(
+ "enableShortcutForTargets: enable %s, shortcutType: %s, shortcutTargets: %s, "
+ + "userId: %s",
+ enable, shortcutType, shortcutTargets, userId));
if (shortcutType == UserShortcutType.GESTURE
&& !android.provider.Flags.a11yStandaloneGestureEnabled()) {
Slog.w(LOG_TAG,
@@ -4418,6 +4421,11 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
}
if (currentTargets.equals(validNewTargets)) {
+ Slog.d(LOG_TAG,
+ String.format(
+ "shortcutTargets are the same: skip modifying: target: %s, "
+ + "shortcutType: %s",
+ validNewTargets, shortcutType));
return;
}
persistColonDelimitedSetToSettingLocked(
@@ -4491,6 +4499,11 @@ public class AccessibilityManagerService extends IAccessibilityManager.Stub
private void updateA11yTileServicesInQuickSettingsPanel(
Set<String> newQsTargets,
Set<String> currentQsTargets, @UserIdInt int userId) {
+ Slog.d(LOG_TAG,
+ String.format(
+ "updateA11yTileServicesInQuickSettingsPanel: newQsTargets: %s , "
+ + "currentQsTargets: %s, userId: %s",
+ newQsTargets, currentQsTargets, userId));
// Call StatusBarManager to add/remove tiles
final StatusBarManagerInternal statusBarManagerInternal =
LocalServices.getService(StatusBarManagerInternal.class);
diff --git a/services/accessibility/java/com/android/server/accessibility/autoclick/AutoclickController.java b/services/accessibility/java/com/android/server/accessibility/autoclick/AutoclickController.java
index 60343e9e81e5..99febd6de60f 100644
--- a/services/accessibility/java/com/android/server/accessibility/autoclick/AutoclickController.java
+++ b/services/accessibility/java/com/android/server/accessibility/autoclick/AutoclickController.java
@@ -81,10 +81,16 @@ import com.android.server.accessibility.Flags;
public class AutoclickController extends BaseEventStreamTransformation {
private static final String LOG_TAG = AutoclickController.class.getSimpleName();
+ // TODO(b/393559560): Finalize scroll amount.
+ private static final float SCROLL_AMOUNT = 1.0f;
private final AccessibilityTraceManager mTrace;
private final Context mContext;
private final int mUserId;
+ @VisibleForTesting
+ float mLastCursorX;
+ @VisibleForTesting
+ float mLastCursorY;
// Lazily created on the first mouse motion event.
@VisibleForTesting ClickScheduler mClickScheduler;
@@ -315,8 +321,58 @@ public class AutoclickController extends BaseEventStreamTransformation {
/**
* Handles scroll operations in the specified direction.
*/
- public void handleScroll(@AutoclickScrollPanel.ScrollDirection int direction) {
- // TODO(b/388845721): Perform actual scroll.
+ private void handleScroll(@AutoclickScrollPanel.ScrollDirection int direction) {
+ final long now = SystemClock.uptimeMillis();
+
+ // Create pointer properties.
+ PointerProperties[] pointerProps = new PointerProperties[1];
+ pointerProps[0] = new PointerProperties();
+ pointerProps[0].id = 0;
+ pointerProps[0].toolType = MotionEvent.TOOL_TYPE_MOUSE;
+
+ // Create pointer coordinates at the last cursor position.
+ PointerCoords[] pointerCoords = new PointerCoords[1];
+ pointerCoords[0] = new PointerCoords();
+ pointerCoords[0].x = mLastCursorX;
+ pointerCoords[0].y = mLastCursorY;
+
+ // Set scroll values based on direction.
+ switch (direction) {
+ case AutoclickScrollPanel.DIRECTION_UP:
+ pointerCoords[0].setAxisValue(MotionEvent.AXIS_VSCROLL, SCROLL_AMOUNT);
+ break;
+ case AutoclickScrollPanel.DIRECTION_DOWN:
+ pointerCoords[0].setAxisValue(MotionEvent.AXIS_VSCROLL, -SCROLL_AMOUNT);
+ break;
+ case AutoclickScrollPanel.DIRECTION_LEFT:
+ pointerCoords[0].setAxisValue(MotionEvent.AXIS_HSCROLL, SCROLL_AMOUNT);
+ break;
+ case AutoclickScrollPanel.DIRECTION_RIGHT:
+ pointerCoords[0].setAxisValue(MotionEvent.AXIS_HSCROLL, -SCROLL_AMOUNT);
+ break;
+ case AutoclickScrollPanel.DIRECTION_EXIT:
+ case AutoclickScrollPanel.DIRECTION_NONE:
+ default:
+ return;
+ }
+
+ // Get device ID from last motion event if possible.
+ int deviceId = mClickScheduler != null && mClickScheduler.mLastMotionEvent != null
+ ? mClickScheduler.mLastMotionEvent.getDeviceId() : 0;
+
+ // Create a scroll event.
+ MotionEvent scrollEvent = MotionEvent.obtain(
+ /* downTime= */ now, /* eventTime= */ now,
+ MotionEvent.ACTION_SCROLL, /* pointerCount= */ 1, pointerProps,
+ pointerCoords, /* metaState= */ 0, /* actionButton= */ 0, /* xPrecision= */
+ 1.0f, /* yPrecision= */ 1.0f, deviceId, /* edgeFlags= */ 0,
+ InputDevice.SOURCE_MOUSE, /* flags= */ 0);
+
+ // Send the scroll event.
+ super.onMotionEvent(scrollEvent, scrollEvent, mClickScheduler.mEventPolicyFlags);
+
+ // Clean up.
+ scrollEvent.recycle();
}
/**
@@ -823,13 +879,19 @@ public class AutoclickController extends BaseEventStreamTransformation {
// If exit button is hovered, exit scroll mode after countdown and return early.
if (mHoveredDirection == AutoclickScrollPanel.DIRECTION_EXIT) {
exitScrollMode();
+ return;
}
- return;
}
// Handle scroll type specially, show scroll panel instead of sending click events.
if (mActiveClickType == AutoclickTypePanel.AUTOCLICK_TYPE_SCROLL) {
if (mAutoclickScrollPanel != null) {
+ // Save the last cursor position at the moment when sendClick() is called.
+ if (mClickScheduler != null && mClickScheduler.mLastMotionEvent != null) {
+ final int pointerIndex = mClickScheduler.mLastMotionEvent.getActionIndex();
+ mLastCursorX = mClickScheduler.mLastMotionEvent.getX(pointerIndex);
+ mLastCursorY = mClickScheduler.mLastMotionEvent.getY(pointerIndex);
+ }
mAutoclickScrollPanel.show();
}
return;
diff --git a/services/accessibility/java/com/android/server/accessibility/autoclick/AutoclickScrollPanel.java b/services/accessibility/java/com/android/server/accessibility/autoclick/AutoclickScrollPanel.java
index c71443149687..025423078da1 100644
--- a/services/accessibility/java/com/android/server/accessibility/autoclick/AutoclickScrollPanel.java
+++ b/services/accessibility/java/com/android/server/accessibility/autoclick/AutoclickScrollPanel.java
@@ -179,7 +179,7 @@ public class AutoclickScrollPanel {
private WindowManager.LayoutParams getLayoutParams() {
final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
- layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
+ layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
layoutParams.privateFlags |= WindowManager.LayoutParams.SYSTEM_FLAG_SHOW_FOR_ALL_USERS;
layoutParams.setFitInsetsTypes(WindowInsets.Type.statusBars());
layoutParams.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
diff --git a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
index b39b5b1a7660..9b735d70abb5 100644
--- a/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
+++ b/services/autofill/java/com/android/server/autofill/AutofillManagerServiceImpl.java
@@ -26,6 +26,7 @@ import static android.view.autofill.AutofillManager.FLAG_ADD_CLIENT_ENABLED_FOR_
import static android.view.autofill.AutofillManager.NO_SESSION;
import static android.view.autofill.AutofillManager.RECEIVER_FLAG_SESSION_FOR_AUGMENTED_AUTOFILL_ONLY;
+import static com.android.internal.util.function.pooled.PooledLambda.obtainMessage;
import static com.android.server.autofill.Helper.sDebug;
import static com.android.server.autofill.Helper.sVerbose;
@@ -761,20 +762,16 @@ final class AutofillManagerServiceImpl
return false;
}
- @GuardedBy("mLock")
- void removeSessionLocked(int sessionId) {
- mSessions.remove(sessionId);
- if (Flags.autofillSessionDestroyed()) {
- if (sVerbose) {
- Slog.v(
- TAG,
- "removeSessionLocked(): removed " + sessionId);
- }
+ void callOnSessionDestroyed(int sessionId) {
+ if (sVerbose) {
+ Slog.v(TAG, "removeSessionLocked(): removed " + sessionId);
+ }
+ synchronized (mLock) {
FillEventHistory history = null;
if (AutofillFeatureFlags.isMultipleFillEventHistoryEnabled()
- && mFillHistories != null) {
+ && mFillHistories != null) {
history = mFillHistories.get(sessionId);
mFillHistories.delete(sessionId);
}
@@ -806,6 +803,16 @@ final class AutofillManagerServiceImpl
}
}
+ @GuardedBy("mLock")
+ void removeSessionLocked(int sessionId) {
+ mSessions.remove(sessionId);
+ if (Flags.autofillSessionDestroyed()) {
+ mHandler.sendMessage(
+ obtainMessage(
+ AutofillManagerServiceImpl::callOnSessionDestroyed, this, sessionId));
+ }
+ }
+
/**
* Ges the previous sessions asked to be kept alive in a given activity task.
*
diff --git a/services/companion/java/com/android/server/companion/utils/MetricUtils.java b/services/companion/java/com/android/server/companion/utils/MetricUtils.java
index cfa7cb00dfac..91f7a3f23a1b 100644
--- a/services/companion/java/com/android/server/companion/utils/MetricUtils.java
+++ b/services/companion/java/com/android/server/companion/utils/MetricUtils.java
@@ -21,7 +21,7 @@ import static android.companion.AssociationRequest.DEVICE_PROFILE_AUTOMOTIVE_PRO
import static android.companion.AssociationRequest.DEVICE_PROFILE_COMPUTER;
import static android.companion.AssociationRequest.DEVICE_PROFILE_GLASSES;
import static android.companion.AssociationRequest.DEVICE_PROFILE_NEARBY_DEVICE_STREAMING;
-import static android.companion.AssociationRequest.DEVICE_PROFILE_SENSOR_DEVICE_STREAMING;
+import static android.companion.AssociationRequest.DEVICE_PROFILE_VIRTUAL_DEVICE;
import static android.companion.AssociationRequest.DEVICE_PROFILE_WATCH;
import static android.companion.AssociationRequest.DEVICE_PROFILE_WEARABLE_SENSING;
@@ -33,8 +33,8 @@ import static com.android.internal.util.FrameworkStatsLog.CDM_ASSOCIATION_ACTION
import static com.android.internal.util.FrameworkStatsLog.CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_COMPUTER;
import static com.android.internal.util.FrameworkStatsLog.CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_GLASSES;
import static com.android.internal.util.FrameworkStatsLog.CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_NEARBY_DEVICE_STREAMING;
-import static com.android.internal.util.FrameworkStatsLog.CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_SENSOR_DEVICE_STREAMING;
import static com.android.internal.util.FrameworkStatsLog.CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_NULL;
+import static com.android.internal.util.FrameworkStatsLog.CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_VIRTUAL_DEVICE;
import static com.android.internal.util.FrameworkStatsLog.CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_WATCH;
import static com.android.internal.util.FrameworkStatsLog.CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_WEARABLE_SENSING;
import static com.android.internal.util.FrameworkStatsLog.write;
@@ -76,8 +76,8 @@ public final class MetricUtils {
CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_NEARBY_DEVICE_STREAMING
);
map.put(
- DEVICE_PROFILE_SENSOR_DEVICE_STREAMING,
- CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_SENSOR_DEVICE_STREAMING
+ DEVICE_PROFILE_VIRTUAL_DEVICE,
+ CDM_ASSOCIATION_ACTION__DEVICE_PROFILE__DEVICE_PROFILE_VIRTUAL_DEVICE
);
map.put(
DEVICE_PROFILE_WEARABLE_SENSING,
diff --git a/services/companion/java/com/android/server/companion/utils/PermissionsUtils.java b/services/companion/java/com/android/server/companion/utils/PermissionsUtils.java
index f4128b820d8f..7157795d8998 100644
--- a/services/companion/java/com/android/server/companion/utils/PermissionsUtils.java
+++ b/services/companion/java/com/android/server/companion/utils/PermissionsUtils.java
@@ -28,7 +28,7 @@ import static android.companion.AssociationRequest.DEVICE_PROFILE_AUTOMOTIVE_PRO
import static android.companion.AssociationRequest.DEVICE_PROFILE_COMPUTER;
import static android.companion.AssociationRequest.DEVICE_PROFILE_GLASSES;
import static android.companion.AssociationRequest.DEVICE_PROFILE_NEARBY_DEVICE_STREAMING;
-import static android.companion.AssociationRequest.DEVICE_PROFILE_SENSOR_DEVICE_STREAMING;
+import static android.companion.AssociationRequest.DEVICE_PROFILE_VIRTUAL_DEVICE;
import static android.companion.AssociationRequest.DEVICE_PROFILE_WATCH;
import static android.companion.AssociationRequest.DEVICE_PROFILE_WEARABLE_SENSING;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
@@ -87,8 +87,8 @@ public final class PermissionsUtils {
map.put(DEVICE_PROFILE_GLASSES, Manifest.permission.REQUEST_COMPANION_PROFILE_GLASSES);
map.put(DEVICE_PROFILE_NEARBY_DEVICE_STREAMING,
Manifest.permission.REQUEST_COMPANION_PROFILE_NEARBY_DEVICE_STREAMING);
- map.put(DEVICE_PROFILE_SENSOR_DEVICE_STREAMING,
- Manifest.permission.REQUEST_COMPANION_PROFILE_SENSOR_DEVICE_STREAMING);
+ map.put(DEVICE_PROFILE_VIRTUAL_DEVICE,
+ Manifest.permission.REQUEST_COMPANION_PROFILE_VIRTUAL_DEVICE);
DEVICE_PROFILE_TO_PERMISSION = unmodifiableMap(map);
}
diff --git a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java
index caf535ce7a40..b90f910cf759 100644
--- a/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java
+++ b/services/companion/java/com/android/server/companion/virtual/VirtualDeviceManagerService.java
@@ -105,7 +105,7 @@ public class VirtualDeviceManagerService extends SystemService {
AssociationRequest.DEVICE_PROFILE_AUTOMOTIVE_PROJECTION,
AssociationRequest.DEVICE_PROFILE_APP_STREAMING,
AssociationRequest.DEVICE_PROFILE_NEARBY_DEVICE_STREAMING,
- AssociationRequest.DEVICE_PROFILE_SENSOR_DEVICE_STREAMING);
+ AssociationRequest.DEVICE_PROFILE_VIRTUAL_DEVICE);
/** Enable default device camera access for apps running on virtual devices. */
@ChangeId
diff --git a/services/core/java/com/android/server/BinaryTransparencyService.java b/services/core/java/com/android/server/BinaryTransparencyService.java
index 1d914c89c570..6ac2180176ce 100644
--- a/services/core/java/com/android/server/BinaryTransparencyService.java
+++ b/services/core/java/com/android/server/BinaryTransparencyService.java
@@ -85,6 +85,8 @@ import com.android.internal.os.IBinaryTransparencyService;
import com.android.internal.util.FrameworkStatsLog;
import com.android.modules.expresslog.Histogram;
import com.android.server.pm.ApexManager;
+import com.android.server.pm.BackgroundInstallControlCallbackHelper;
+import com.android.server.pm.BackgroundInstallControlService;
import com.android.server.pm.pkg.AndroidPackage;
import com.android.server.pm.pkg.AndroidPackageSplit;
import com.android.server.pm.pkg.PackageState;
@@ -101,9 +103,6 @@ import java.util.Map;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
-import com.android.server.pm.BackgroundInstallControlService;
-import com.android.server.pm.BackgroundInstallControlCallbackHelper;
-
/**
* @hide
*/
@@ -1577,19 +1576,17 @@ public class BinaryTransparencyService extends SystemService {
Slog.d(TAG, String.format("VBMeta Digest: %s", mVbmetaDigest));
FrameworkStatsLog.write(FrameworkStatsLog.VBMETA_DIGEST_REPORTED, mVbmetaDigest);
- if (android.security.Flags.binaryTransparencySepolicyHash()) {
- IoThread.getExecutor().execute(() -> {
- byte[] sepolicyHash = PackageUtils.computeSha256DigestForLargeFileAsBytes(
- "/sys/fs/selinux/policy", PackageUtils.createLargeFileBuffer());
- String sepolicyHashEncoded = null;
- if (sepolicyHash != null) {
- sepolicyHashEncoded = HexEncoding.encodeToString(sepolicyHash, false);
- Slog.d(TAG, "sepolicy hash: " + sepolicyHashEncoded);
- }
- FrameworkStatsLog.write(FrameworkStatsLog.BOOT_INTEGRITY_INFO_REPORTED,
- sepolicyHashEncoded, mVbmetaDigest);
- });
- }
+ IoThread.getExecutor().execute(() -> {
+ byte[] sepolicyHash = PackageUtils.computeSha256DigestForLargeFileAsBytes(
+ "/sys/fs/selinux/policy", PackageUtils.createLargeFileBuffer());
+ String sepolicyHashEncoded = null;
+ if (sepolicyHash != null) {
+ sepolicyHashEncoded = HexEncoding.encodeToString(sepolicyHash, false);
+ Slog.d(TAG, "sepolicy hash: " + sepolicyHashEncoded);
+ }
+ FrameworkStatsLog.write(FrameworkStatsLog.BOOT_INTEGRITY_INFO_REPORTED,
+ sepolicyHashEncoded, mVbmetaDigest);
+ });
}
/**
diff --git a/services/core/java/com/android/server/am/BatteryStatsService.java b/services/core/java/com/android/server/am/BatteryStatsService.java
index 6b4a99cc4fae..d1225d4e6eed 100644
--- a/services/core/java/com/android/server/am/BatteryStatsService.java
+++ b/services/core/java/com/android/server/am/BatteryStatsService.java
@@ -3368,6 +3368,14 @@ public final class BatteryStatsService extends IBatteryStats.Stub
return;
} else if ("-a".equals(arg)) {
flags |= BatteryStats.DUMP_VERBOSE;
+ } else if ("--debug".equals(arg)) {
+ i++;
+ if (i >= args.length) {
+ pw.println("Missing time argument for --flags HEX");
+ dumpHelp(pw);
+ return;
+ }
+ flags |= ParseUtils.parseIntWithBase(args[i], 16, 0);
} else if (arg.length() > 0 && arg.charAt(0) == '-'){
pw.println("Unknown option: " + arg);
dumpHelp(pw);
diff --git a/services/core/java/com/android/server/am/BroadcastHistory.java b/services/core/java/com/android/server/am/BroadcastHistory.java
index 700cf9c8deb8..99fdf9c8d229 100644
--- a/services/core/java/com/android/server/am/BroadcastHistory.java
+++ b/services/core/java/com/android/server/am/BroadcastHistory.java
@@ -20,6 +20,7 @@ import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Intent;
import android.os.Bundle;
+import android.os.Trace;
import android.util.TimeUtils;
import android.util.proto.ProtoOutputStream;
@@ -85,16 +86,26 @@ public class BroadcastHistory {
void onBroadcastFrozenLocked(@NonNull BroadcastRecord r) {
mFrozenBroadcasts.add(r);
+ updateTraceCounters();
}
void onBroadcastEnqueuedLocked(@NonNull BroadcastRecord r) {
mFrozenBroadcasts.remove(r);
mPendingBroadcasts.add(r);
+ updateTraceCounters();
}
void onBroadcastFinishedLocked(@NonNull BroadcastRecord r) {
mPendingBroadcasts.remove(r);
addBroadcastToHistoryLocked(r);
+ updateTraceCounters();
+ }
+
+ private void updateTraceCounters() {
+ Trace.traceCounter(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Broadcasts pending",
+ mPendingBroadcasts.size());
+ Trace.traceCounter(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Broadcasts frozen",
+ mFrozenBroadcasts.size());
}
public void addBroadcastToHistoryLocked(@NonNull BroadcastRecord original) {
diff --git a/services/core/java/com/android/server/inputmethod/IInputMethodClientInvoker.java b/services/core/java/com/android/server/inputmethod/IInputMethodClientInvoker.java
index 9d889839879b..c2873e8ee28e 100644
--- a/services/core/java/com/android/server/inputmethod/IInputMethodClientInvoker.java
+++ b/services/core/java/com/android/server/inputmethod/IInputMethodClientInvoker.java
@@ -256,9 +256,11 @@ final class IInputMethodClientInvoker {
@AnyThread
private void setImeVisibilityInternal(boolean visible, @Nullable ImeTracker.Token statsToken) {
try {
+ ImeTracker.forLogging().onProgress(statsToken, ImeTracker.PHASE_SERVER_CLIENT_INVOKER);
mTarget.setImeVisibility(visible, statsToken);
} catch (RemoteException e) {
logRemoteException(e);
+ ImeTracker.forLogging().onFailed(statsToken, ImeTracker.PHASE_SERVER_CLIENT_INVOKER);
}
}
diff --git a/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java b/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java
index 0047ec20d691..3fcb6ce271e3 100644
--- a/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java
+++ b/services/core/java/com/android/server/inputmethod/IInputMethodInvoker.java
@@ -205,9 +205,11 @@ final class IInputMethodInvoker {
boolean showSoftInput(IBinder showInputToken, @NonNull ImeTracker.Token statsToken,
@InputMethod.ShowFlags int flags, ResultReceiver resultReceiver) {
try {
+ ImeTracker.forLogging().onProgress(statsToken, ImeTracker.PHASE_SERVER_IME_INVOKER);
mTarget.showSoftInput(showInputToken, statsToken, flags, resultReceiver);
} catch (RemoteException e) {
logRemoteException(e);
+ ImeTracker.forLogging().onFailed(statsToken, ImeTracker.PHASE_SERVER_IME_INVOKER);
return false;
}
return true;
@@ -218,9 +220,11 @@ final class IInputMethodInvoker {
boolean hideSoftInput(IBinder hideInputToken, @NonNull ImeTracker.Token statsToken,
int flags, ResultReceiver resultReceiver) {
try {
+ ImeTracker.forLogging().onProgress(statsToken, ImeTracker.PHASE_SERVER_IME_INVOKER);
mTarget.hideSoftInput(hideInputToken, statsToken, flags, resultReceiver);
} catch (RemoteException e) {
logRemoteException(e);
+ ImeTracker.forLogging().onFailed(statsToken, ImeTracker.PHASE_SERVER_IME_INVOKER);
return false;
}
return true;
diff --git a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
index 7ff41e309c55..87259d80554f 100644
--- a/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
+++ b/services/core/java/com/android/server/inputmethod/InputMethodManagerService.java
@@ -3206,7 +3206,7 @@ public final class InputMethodManagerService implements IInputMethodManagerImpl.
}
// TODO(b/353463205) check callers to see if we can make statsToken @NonNull
- boolean showCurrentInputInternal(IBinder windowToken, @Nullable ImeTracker.Token statsToken) {
+ boolean showCurrentInputInternal(IBinder windowToken, @NonNull ImeTracker.Token statsToken) {
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "IMMS.showCurrentInputInternal");
ImeTracing.getInstance().triggerManagerServiceDump(
"InputMethodManagerService#showSoftInput", mDumper);
@@ -3226,7 +3226,7 @@ public final class InputMethodManagerService implements IInputMethodManagerImpl.
}
// TODO(b/353463205) check callers to see if we can make statsToken @NonNull
- boolean hideCurrentInputInternal(IBinder windowToken, @Nullable ImeTracker.Token statsToken) {
+ boolean hideCurrentInputInternal(IBinder windowToken, @NonNull ImeTracker.Token statsToken) {
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "IMMS.hideCurrentInputInternal");
ImeTracing.getInstance().triggerManagerServiceDump(
"InputMethodManagerService#hideSoftInput", mDumper);
diff --git a/services/core/java/com/android/server/location/injector/SystemEmergencyHelper.java b/services/core/java/com/android/server/location/injector/SystemEmergencyHelper.java
index 3f75b11befc2..ea4b3d426346 100644
--- a/services/core/java/com/android/server/location/injector/SystemEmergencyHelper.java
+++ b/services/core/java/com/android/server/location/injector/SystemEmergencyHelper.java
@@ -23,6 +23,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
+import android.location.flags.Flags;
import android.os.SystemClock;
import android.telephony.TelephonyCallback;
import android.telephony.TelephonyManager;
@@ -71,13 +72,25 @@ public class SystemEmergencyHelper extends EmergencyHelper {
return;
}
- synchronized (SystemEmergencyHelper.this) {
+ if (Flags.fixIsInEmergencyAnr()) {
try {
- mIsInEmergencyCall = mTelephonyManager.isEmergencyNumber(
+ boolean isInEmergency = mTelephonyManager.isEmergencyNumber(
intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));
+ synchronized (SystemEmergencyHelper.this) {
+ mIsInEmergencyCall = isInEmergency;
+ }
} catch (IllegalStateException | UnsupportedOperationException e) {
Log.w(TAG, "Failed to call TelephonyManager.isEmergencyNumber().", e);
}
+ } else {
+ synchronized (SystemEmergencyHelper.this) {
+ try {
+ mIsInEmergencyCall = mTelephonyManager.isEmergencyNumber(
+ intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER));
+ } catch (IllegalStateException | UnsupportedOperationException e) {
+ Log.w(TAG, "Failed to call TelephonyManager.isEmergencyNumber().", e);
+ }
+ }
}
dispatchEmergencyStateChanged();
@@ -98,27 +111,55 @@ public class SystemEmergencyHelper extends EmergencyHelper {
}
@Override
- public synchronized boolean isInEmergency(long extensionTimeMs) {
- if (mTelephonyManager == null) {
- return false;
- }
+ public boolean isInEmergency(long extensionTimeMs) {
+ if (Flags.fixIsInEmergencyAnr()) {
+ if (mTelephonyManager == null) {
+ return false;
+ }
+ boolean emergencyCallbackMode = false;
+ boolean emergencySmsMode = false;
+ PackageManager pm = mContext.getPackageManager();
+ if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CALLING)) {
+ emergencyCallbackMode = mTelephonyManager.getEmergencyCallbackMode();
+ }
+ if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)) {
+ emergencySmsMode = mTelephonyManager.isInEmergencySmsMode();
+ }
+ boolean isInExtensionTime;
+ synchronized (this) {
+ isInExtensionTime = mEmergencyCallEndRealtimeMs != Long.MIN_VALUE
+ && (SystemClock.elapsedRealtime() - mEmergencyCallEndRealtimeMs)
+ < extensionTimeMs;
+ return mIsInEmergencyCall
+ || isInExtensionTime
+ || emergencyCallbackMode
+ || emergencySmsMode;
+ }
+ } else {
+ synchronized (this) {
+ if (mTelephonyManager == null) {
+ return false;
+ }
- boolean isInExtensionTime = mEmergencyCallEndRealtimeMs != Long.MIN_VALUE
- && (SystemClock.elapsedRealtime() - mEmergencyCallEndRealtimeMs) < extensionTimeMs;
+ boolean isInExtensionTime = mEmergencyCallEndRealtimeMs != Long.MIN_VALUE
+ && (SystemClock.elapsedRealtime() - mEmergencyCallEndRealtimeMs)
+ < extensionTimeMs;
- boolean emergencyCallbackMode = false;
- boolean emergencySmsMode = false;
- PackageManager pm = mContext.getPackageManager();
- if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CALLING)) {
- emergencyCallbackMode = mTelephonyManager.getEmergencyCallbackMode();
- }
- if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)) {
- emergencySmsMode = mTelephonyManager.isInEmergencySmsMode();
+ boolean emergencyCallbackMode = false;
+ boolean emergencySmsMode = false;
+ PackageManager pm = mContext.getPackageManager();
+ if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_CALLING)) {
+ emergencyCallbackMode = mTelephonyManager.getEmergencyCallbackMode();
+ }
+ if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY_MESSAGING)) {
+ emergencySmsMode = mTelephonyManager.isInEmergencySmsMode();
+ }
+ return mIsInEmergencyCall
+ || isInExtensionTime
+ || emergencyCallbackMode
+ || emergencySmsMode;
+ }
}
- return mIsInEmergencyCall
- || isInExtensionTime
- || emergencyCallbackMode
- || emergencySmsMode;
}
private class EmergencyCallTelephonyCallback extends TelephonyCallback implements
diff --git a/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java b/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java
index 85dc811a7811..80cb5480fec1 100644
--- a/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java
+++ b/services/core/java/com/android/server/locksettings/recoverablekeystore/KeySyncTask.java
@@ -168,6 +168,11 @@ public class KeySyncTask implements Runnable {
}
private void syncKeys() throws RemoteException {
+ if (mCredential != null && mCredential.length >= 80) {
+ // The value is likely a randomly generated profile password
+ // It doesn't match string typed by the user.
+ Log.e(TAG, "Unexpected credential length for user " + mUserId);
+ }
if (mCredentialUpdated && mRecoverableKeyStoreDb.getBadRemoteGuessCounter(mUserId) != 0) {
mRecoverableKeyStoreDb.setBadRemoteGuessCounter(mUserId, 0);
}
diff --git a/services/core/java/com/android/server/media/LegacyDeviceRouteController.java b/services/core/java/com/android/server/media/LegacyDeviceRouteController.java
index 65b0ad0d61a0..1e8ebca7f336 100644
--- a/services/core/java/com/android/server/media/LegacyDeviceRouteController.java
+++ b/services/core/java/com/android/server/media/LegacyDeviceRouteController.java
@@ -39,6 +39,7 @@ import android.os.UserHandle;
import android.util.Slog;
import com.android.internal.R;
+import com.android.media.flags.Flags;
import java.util.Collections;
import java.util.List;
@@ -123,7 +124,9 @@ import java.util.Objects;
@Override
public synchronized List<MediaRoute2Info> getAvailableRoutes() {
- return Collections.emptyList();
+ return Flags.enableFixForEmptySystemRoutesCrash()
+ ? List.of(mDeviceRoute)
+ : Collections.emptyList();
}
@Override
diff --git a/services/core/java/com/android/server/media/MediaSessionService.java b/services/core/java/com/android/server/media/MediaSessionService.java
index c174451e8f5b..5d571de2ce54 100644
--- a/services/core/java/com/android/server/media/MediaSessionService.java
+++ b/services/core/java/com/android/server/media/MediaSessionService.java
@@ -3269,13 +3269,21 @@ public class MediaSessionService extends SystemService implements Monitor {
if (!postedNotification.isMediaNotification()) {
return;
}
+ if ((postedNotification.flags & Notification.FLAG_FOREGROUND_SERVICE) == 0) {
+ // Ignore notifications posted without a foreground service.
+ return;
+ }
synchronized (mLock) {
Map<String, StatusBarNotification> notifications = mMediaNotifications.get(uid);
if (notifications == null) {
notifications = new HashMap<>();
mMediaNotifications.put(uid, notifications);
}
- notifications.put(sbn.getKey(), sbn);
+ StatusBarNotification previousSbn = notifications.put(sbn.getKey(), sbn);
+ if (previousSbn != null) {
+ // Only act on the first notification update.
+ return;
+ }
MediaSessionRecordImpl userEngagedRecord =
getUserEngagedMediaSessionRecordForNotification(uid, postedNotification);
if (userEngagedRecord != null) {
diff --git a/services/core/java/com/android/server/notification/NotificationManagerService.java b/services/core/java/com/android/server/notification/NotificationManagerService.java
index c1e46a68b733..de20b82f505c 100644
--- a/services/core/java/com/android/server/notification/NotificationManagerService.java
+++ b/services/core/java/com/android/server/notification/NotificationManagerService.java
@@ -7410,6 +7410,10 @@ public class NotificationManagerService extends SystemService {
adjustments);
if (newChannel == null || newChannel.getId().equals(r.getChannel().getId())) {
adjustments.remove(KEY_TYPE);
+ } else if (android.app.Flags.apiRichOngoing() && hasFlag(r.getNotification().flags,
+ FLAG_PROMOTED_ONGOING)) {
+ // Don't bundle any promoted ongoing notifications
+ adjustments.remove(KEY_TYPE);
} else {
// Save the app-provided type for logging.
int classification = adjustments.getInt(KEY_TYPE);
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
index ac19ea12c6a4..fbf81b9accad 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -1541,8 +1541,19 @@ public class PermissionManagerService extends IPermissionManager.Stub {
}
final AttributionSource resolvedAttributionSource =
accessorSource.withPackageName(resolvedAccessorPackageName);
- final int opMode = appOpsManager.unsafeCheckOpRawNoThrow(op,
- resolvedAttributionSource);
+ // Avoid checking the first attr in the chain in some cases for consistency with
+ // checks for data delivery.
+ // In particular, for chains of 2 or more, when skipProxyOperation is true, the
+ // for data delivery implementation does not actually check the first link in the
+ // chain. If the attribution is just a singleReceiverFromDatasource, this
+ // exemption does not apply, since it does not go through proxyOp flow, and the top
+ // of the chain is actually removed above.
+ // Skipping the check avoids situations where preflight checks fail since the data
+ // source itself does not have the op (e.g. audioserver).
+ final int opMode = (skipProxyOperation && !singleReceiverFromDatasource) ?
+ AppOpsManager.MODE_ALLOWED :
+ appOpsManager.unsafeCheckOpRawNoThrow(op, resolvedAttributionSource);
+
final AttributionSource next = accessorSource.getNext();
if (!selfAccess && opMode == AppOpsManager.MODE_ALLOWED && next != null) {
final String resolvedNextPackageName = resolvePackageName(context, next);
diff --git a/services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionService.java b/services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionService.java
index 3ece07c84080..0735770f9c3c 100644
--- a/services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionService.java
+++ b/services/core/java/com/android/server/security/advancedprotection/AdvancedProtectionService.java
@@ -27,6 +27,7 @@ import android.annotation.Nullable;
import android.app.StatsManager;
import android.content.Context;
import android.content.SharedPreferences;
+import android.content.pm.UserInfo;
import android.os.Binder;
import android.os.Environment;
import android.os.Handler;
@@ -73,7 +74,7 @@ import java.util.List;
import java.util.Set;
/** @hide */
-public class AdvancedProtectionService extends IAdvancedProtectionService.Stub {
+public class AdvancedProtectionService extends IAdvancedProtectionService.Stub {
private static final String TAG = "AdvancedProtectionService";
private static final int MODE_CHANGED = 0;
private static final int CALLBACK_ADDED = 1;
@@ -90,6 +91,7 @@ public class AdvancedProtectionService extends IAdvancedProtectionService.Stub
private final Context mContext;
private final Handler mHandler;
private final AdvancedProtectionStore mStore;
+ private final UserManagerInternal mUserManager;
// Features living with the service - their code will be executed when state changes
private final ArrayList<AdvancedProtectionHook> mHooks = new ArrayList<>();
@@ -106,7 +108,8 @@ public class AdvancedProtectionService extends IAdvancedProtectionService.Stub
super(PermissionEnforcer.fromContext(context));
mContext = context;
mHandler = new AdvancedProtectionHandler(FgThread.get().getLooper());
- mStore = new AdvancedProtectionStore(context);
+ mStore = new AdvancedProtectionStore(mContext);
+ mUserManager = LocalServices.getService(UserManagerInternal.class);
}
private void initFeatures(boolean enabled) {
@@ -156,12 +159,18 @@ public class AdvancedProtectionService extends IAdvancedProtectionService.Stub
// Only for tests
@VisibleForTesting
- AdvancedProtectionService(@NonNull Context context, @NonNull AdvancedProtectionStore store,
- @NonNull Looper looper, @NonNull PermissionEnforcer permissionEnforcer,
- @Nullable AdvancedProtectionHook hook, @Nullable AdvancedProtectionProvider provider) {
+ AdvancedProtectionService(
+ @NonNull Context context,
+ @NonNull AdvancedProtectionStore store,
+ @NonNull UserManagerInternal userManager,
+ @NonNull Looper looper,
+ @NonNull PermissionEnforcer permissionEnforcer,
+ @Nullable AdvancedProtectionHook hook,
+ @Nullable AdvancedProtectionProvider provider) {
super(permissionEnforcer);
mContext = context;
mStore = store;
+ mUserManager = userManager;
mHandler = new AdvancedProtectionHandler(looper);
if (hook != null) {
mHooks.add(hook);
@@ -218,8 +227,10 @@ public class AdvancedProtectionService extends IAdvancedProtectionService.Stub
@EnforcePermission(Manifest.permission.MANAGE_ADVANCED_PROTECTION_MODE)
public void setAdvancedProtectionEnabled(boolean enabled) {
setAdvancedProtectionEnabled_enforcePermission();
+ final UserHandle user = Binder.getCallingUserHandle();
final long identity = Binder.clearCallingIdentity();
try {
+ enforceAdminUser(user);
synchronized (mCallbacks) {
if (enabled != isAdvancedProtectionEnabledInternal()) {
mStore.storeAdvancedProtectionModeEnabled(enabled);
@@ -364,6 +375,13 @@ public class AdvancedProtectionService extends IAdvancedProtectionService.Stub
return features;
}
+ private void enforceAdminUser(UserHandle user) {
+ UserInfo info = mUserManager.getUserInfo(user.getIdentifier());
+ if (!info.isAdmin()) {
+ throw new SecurityException("Only an admin user can manage advanced protection mode");
+ }
+ }
+
@Override
public void onShellCommand(FileDescriptor in, FileDescriptor out,
FileDescriptor err, @NonNull String[] args, ShellCallback callback,
@@ -451,36 +469,34 @@ public class AdvancedProtectionService extends IAdvancedProtectionService.Stub
@VisibleForTesting
static class AdvancedProtectionStore {
- private final Context mContext;
static final int ON = 1;
static final int OFF = 0;
- private final UserManagerInternal mUserManager;
+ private final Context mContext;
AdvancedProtectionStore(@NonNull Context context) {
mContext = context;
- mUserManager = LocalServices.getService(UserManagerInternal.class);
}
void storeAdvancedProtectionModeEnabled(boolean enabled) {
Settings.Secure.putIntForUser(mContext.getContentResolver(),
ADVANCED_PROTECTION_MODE, enabled ? ON : OFF,
- mUserManager.getMainUserId());
+ UserHandle.USER_SYSTEM);
}
boolean retrieveAdvancedProtectionModeEnabled() {
return Settings.Secure.getIntForUser(mContext.getContentResolver(),
- ADVANCED_PROTECTION_MODE, OFF, mUserManager.getMainUserId()) == ON;
+ ADVANCED_PROTECTION_MODE, OFF, UserHandle.USER_SYSTEM) == ON;
}
void storeInt(String key, int value) {
Settings.Secure.putIntForUser(mContext.getContentResolver(),
key, value,
- mUserManager.getMainUserId());
+ UserHandle.USER_SYSTEM);
}
int retrieveInt(String key, int defaultValue) {
return Settings.Secure.getIntForUser(mContext.getContentResolver(),
- key, defaultValue, mUserManager.getMainUserId());
+ key, defaultValue, UserHandle.USER_SYSTEM);
}
}
@@ -492,12 +508,12 @@ public class AdvancedProtectionService extends IAdvancedProtectionService.Stub
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
- //arg1 == enabled
+ // arg1 == enabled
case MODE_CHANGED:
handleAllCallbacks(msg.arg1 == 1);
break;
- //arg1 == enabled
- //obj == callback
+ // arg1 == enabled
+ // obj == callback
case CALLBACK_ADDED:
handleSingleCallback(msg.arg1 == 1, (IAdvancedProtectionCallback) msg.obj);
break;
@@ -546,7 +562,7 @@ public class AdvancedProtectionService extends IAdvancedProtectionService.Stub
private final class DeathRecipient implements IBinder.DeathRecipient {
private final IBinder mBinder;
- DeathRecipient(IBinder binder) {
+ DeathRecipient(IBinder binder) {
mBinder = binder;
}
diff --git a/services/core/java/com/android/server/theming/ThemeSettingsManager.java b/services/core/java/com/android/server/theming/ThemeSettingsManager.java
new file mode 100644
index 000000000000..94094a6f9603
--- /dev/null
+++ b/services/core/java/com/android/server/theming/ThemeSettingsManager.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.theming;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.UserIdInt;
+import android.content.ContentResolver;
+import android.content.theming.ThemeSettings;
+import android.content.theming.ThemeSettingsField;
+import android.content.theming.ThemeSettingsUpdater;
+import android.provider.Settings;
+import android.telecom.Log;
+
+import com.android.internal.util.Preconditions;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.Iterator;
+
+/**
+ * Manages the loading and saving of theme settings. This class handles the persistence of theme
+ * settings to and from the system settings. It utilizes a collection of {@link ThemeSettingsField}
+ * objects to represent individual theme setting fields.
+ *
+ * @hide
+ */
+@FlaggedApi(android.server.Flags.FLAG_ENABLE_THEME_SERVICE)
+class ThemeSettingsManager {
+ private static final String TAG = ThemeSettingsManager.class.getSimpleName();
+ static final String TIMESTAMP_FIELD = "_applied_timestamp";
+ private final ThemeSettingsField<?, ?>[] mFields;
+ private final ThemeSettings mDefaults;
+
+ /**
+ * Constructs a new {@code ThemeSettingsManager} with the specified default settings.
+ *
+ * @param defaults The default theme settings to use.
+ */
+ ThemeSettingsManager(ThemeSettings defaults) {
+ mDefaults = defaults;
+ mFields = ThemeSettingsField.getFields(defaults);
+ }
+
+ /**
+ * Loads the theme settings for the specified user.
+ *
+ * @param userId The ID of the user.
+ * @param contentResolver The content resolver to use.
+ * @return The loaded {@link ThemeSettings}.
+ */
+ @NonNull
+ ThemeSettings loadSettings(@UserIdInt int userId, ContentResolver contentResolver) {
+ String jsonString = Settings.Secure.getStringForUser(contentResolver,
+ Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES, userId);
+
+ JSONObject userSettings;
+
+ try {
+ userSettings = new JSONObject(jsonString == null ? "" : jsonString);
+ } catch (JSONException e) {
+ userSettings = new JSONObject();
+ }
+
+ ThemeSettingsUpdater updater = ThemeSettings.updater();
+
+ for (ThemeSettingsField<?, ?> field : mFields) {
+ field.fromJSON(userSettings, updater);
+ }
+
+ return updater.toThemeSettings(mDefaults);
+ }
+
+ /**
+ * Saves the specified theme settings for the given user.
+ *
+ * @param userId The ID of the user.
+ * @param contentResolver The content resolver to use.
+ * @param newSettings The {@link ThemeSettings} to save.
+ */
+ void replaceSettings(@UserIdInt int userId, ContentResolver contentResolver,
+ ThemeSettings newSettings) throws RuntimeException {
+ Preconditions.checkArgument(newSettings != null, "Impossible to write empty settings");
+
+ JSONObject jsonSettings = new JSONObject();
+
+
+ for (ThemeSettingsField<?, ?> field : mFields) {
+ field.toJSON(newSettings, jsonSettings);
+ }
+
+ // user defined timestamp should be ignored. Storing new timestamp.
+ try {
+ jsonSettings.put(TIMESTAMP_FIELD, System.currentTimeMillis());
+ } catch (JSONException e) {
+ Log.w(TAG, "Error saving timestamp: " + e.getMessage());
+ }
+
+ String jsonString = jsonSettings.toString();
+
+ Settings.Secure.putStringForUser(contentResolver,
+ Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES, jsonString, userId);
+ }
+
+ /**
+ * Saves the specified theme settings for the given user, while preserving unrelated existing
+ * properties.
+ *
+ * @param userId The ID of the user.
+ * @param contentResolver The content resolver to use.
+ * @param newSettings The {@link ThemeSettings} to save.
+ */
+ void updateSettings(@UserIdInt int userId, ContentResolver contentResolver,
+ ThemeSettings newSettings) throws JSONException, RuntimeException {
+ Preconditions.checkArgument(newSettings != null, "Impossible to write empty settings");
+
+ String existingJsonString = Settings.Secure.getStringForUser(contentResolver,
+ Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES, userId);
+
+ JSONObject existingJson;
+ try {
+ existingJson = new JSONObject(existingJsonString == null ? "{}" : existingJsonString);
+ } catch (JSONException e) {
+ existingJson = new JSONObject();
+ }
+
+ JSONObject newJson = new JSONObject();
+ for (ThemeSettingsField<?, ?> field : mFields) {
+ field.toJSON(newSettings, newJson);
+ }
+
+ // user defined timestamp should be ignored. Storing new timestamp.
+ try {
+ newJson.put(TIMESTAMP_FIELD, System.currentTimeMillis());
+ } catch (JSONException e) {
+ Log.w(TAG, "Error saving timestamp: " + e.getMessage());
+ }
+
+ // Merge the new settings with the existing settings
+ Iterator<String> keys = newJson.keys();
+ while (keys.hasNext()) {
+ String key = keys.next();
+ existingJson.put(key, newJson.get(key));
+ }
+
+ String mergedJsonString = existingJson.toString();
+
+ Settings.Secure.putStringForUser(contentResolver,
+ Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES, mergedJsonString, userId);
+ }
+}
diff --git a/services/core/java/com/android/server/updates/CertPinInstallReceiver.java b/services/core/java/com/android/server/updates/CertPinInstallReceiver.java
index 250e99b47b1a..c8e7a8dea5c3 100644
--- a/services/core/java/com/android/server/updates/CertPinInstallReceiver.java
+++ b/services/core/java/com/android/server/updates/CertPinInstallReceiver.java
@@ -19,7 +19,10 @@ package com.android.server.updates;
import android.content.Context;
import android.content.Intent;
+import java.io.File;
+
public class CertPinInstallReceiver extends ConfigUpdateInstallReceiver {
+ private static final String KEYCHAIN_DIR = "/data/misc/keychain/";
public CertPinInstallReceiver() {
super("/data/misc/keychain/", "pins", "metadata/", "version");
@@ -27,7 +30,22 @@ public class CertPinInstallReceiver extends ConfigUpdateInstallReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
- if (!com.android.server.flags.Flags.certpininstallerRemoval()) {
+ if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
+ if (com.android.server.flags.Flags.certpininstallerRemoval()) {
+ File pins = new File(KEYCHAIN_DIR + "pins");
+ if (pins.exists()) {
+ pins.delete();
+ }
+ File version = new File(KEYCHAIN_DIR + "metadata/version");
+ if (version.exists()) {
+ version.delete();
+ }
+ File metadata = new File(KEYCHAIN_DIR + "metadata");
+ if (metadata.exists()) {
+ metadata.delete();
+ }
+ }
+ } else if (!com.android.server.flags.Flags.certpininstallerRemoval()) {
super.onReceive(context, intent);
}
}
diff --git a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
index 274175aa71ba..a0979fa5ee7e 100644
--- a/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
+++ b/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
@@ -747,13 +747,22 @@ public class WallpaperManagerService extends IWallpaperManager.Stub
if (connection == null) {
return false;
}
+ boolean isWallpaperDesktopExperienceEnabled = isDeviceEligibleForDesktopExperienceWallpaper(
+ mContext);
+ boolean isLiveWallpaperSupportedInDesktopExperience =
+ mContext.getResources().getBoolean(
+ R.bool.config_isLiveWallpaperSupportedInDesktopExperience);
// Non image wallpaper.
if (connection.mInfo != null) {
+ if (isWallpaperDesktopExperienceEnabled
+ && !isLiveWallpaperSupportedInDesktopExperience) {
+ return false;
+ }
return connection.mInfo.supportsMultipleDisplays();
}
// Image wallpaper
- if (isDeviceEligibleForDesktopExperienceWallpaper(mContext)) {
+ if (isWallpaperDesktopExperienceEnabled) {
return mWallpaperCropper.isWallpaperCompatibleForDisplay(displayId,
connection.mWallpaper);
}
diff --git a/services/core/java/com/android/server/wm/ActivityClientController.java b/services/core/java/com/android/server/wm/ActivityClientController.java
index 7da4beb95114..5eceb6490256 100644
--- a/services/core/java/com/android/server/wm/ActivityClientController.java
+++ b/services/core/java/com/android/server/wm/ActivityClientController.java
@@ -95,6 +95,7 @@ import android.os.UserHandle;
import android.service.voice.VoiceInteractionManagerInternal;
import android.util.Slog;
import android.view.RemoteAnimationDefinition;
+import android.window.DesktopModeFlags;
import android.window.SizeConfigurationBuckets;
import android.window.TransitionInfo;
@@ -1281,7 +1282,7 @@ class ActivityClientController extends IActivityClientController.Stub {
}
}
- private static void executeMultiWindowFullscreenRequest(int fullscreenRequest, Task requester) {
+ private void executeMultiWindowFullscreenRequest(int fullscreenRequest, Task requester) {
final int targetWindowingMode;
if (fullscreenRequest == FULLSCREEN_MODE_REQUEST_ENTER) {
final int restoreWindowingMode = requester.getRequestedOverrideWindowingMode();
@@ -1294,7 +1295,13 @@ class ActivityClientController extends IActivityClientController.Stub {
requester.getParent().mRemoteToken.toWindowContainerToken();
} else {
targetWindowingMode = requester.mMultiWindowRestoreWindowingMode;
- requester.restoreWindowingMode();
+ if (DesktopModeFlags.ENABLE_REQUEST_FULLSCREEN_BUGFIX.isTrue()
+ && targetWindowingMode == WINDOWING_MODE_PINNED) {
+ final ActivityRecord r = requester.topRunningActivity();
+ enterPictureInPictureMode(r.token, r.pictureInPictureArgs);
+ } else {
+ requester.restoreWindowingMode();
+ }
}
if (targetWindowingMode == WINDOWING_MODE_FULLSCREEN) {
requester.setBounds(null);
diff --git a/services/core/java/com/android/server/wm/DisplayAreaPolicy.java b/services/core/java/com/android/server/wm/DisplayAreaPolicy.java
index 9d9c5ceb57d6..11fb229bb93d 100644
--- a/services/core/java/com/android/server/wm/DisplayAreaPolicy.java
+++ b/services/core/java/com/android/server/wm/DisplayAreaPolicy.java
@@ -26,6 +26,7 @@ import static android.view.WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL;
import static android.view.WindowManager.LayoutParams.TYPE_NOTIFICATION_SHADE;
import static android.view.WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_STATUS_BAR;
+import static android.view.WindowManager.LayoutParams.TYPE_VOLUME_OVERLAY;
import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
import static android.window.DisplayAreaOrganizer.FEATURE_APP_ZOOM_OUT;
import static android.window.DisplayAreaOrganizer.FEATURE_DEFAULT_TASK_CONTAINER;
@@ -166,7 +167,7 @@ public abstract class DisplayAreaPolicy {
.all()
.except(TYPE_NAVIGATION_BAR, TYPE_NAVIGATION_BAR_PANEL,
TYPE_STATUS_BAR, TYPE_NOTIFICATION_SHADE,
- TYPE_KEYGUARD_DIALOG, TYPE_WALLPAPER)
+ TYPE_KEYGUARD_DIALOG, TYPE_WALLPAPER, TYPE_VOLUME_OVERLAY)
.build());
}
if (USE_DISPLAY_AREA_FOR_FULLSCREEN_MAGNIFICATION) {
diff --git a/services/core/java/com/android/server/wm/ImeInsetsSourceProvider.java b/services/core/java/com/android/server/wm/ImeInsetsSourceProvider.java
index 53681f950c8e..f2bc909bd64b 100644
--- a/services/core/java/com/android/server/wm/ImeInsetsSourceProvider.java
+++ b/services/core/java/com/android/server/wm/ImeInsetsSourceProvider.java
@@ -445,14 +445,21 @@ final class ImeInsetsSourceProvider extends InsetsSourceProvider {
if (controlTarget != null) {
final boolean imeAnimating = Flags.reportAnimatingInsetsTypes()
&& (controlTarget.getAnimatingTypes() & WindowInsets.Type.ime()) != 0;
- ImeTracker.forLogging().onProgress(statsToken,
+ final boolean imeVisible =
+ controlTarget.isRequestedVisible(WindowInsets.Type.ime()) || imeAnimating;
+ final var finalStatsToken = statsToken != null ? statsToken
+ : ImeTracker.forLogging().onStart(
+ imeVisible ? ImeTracker.TYPE_SHOW : ImeTracker.TYPE_HIDE,
+ ImeTracker.ORIGIN_SERVER,
+ SoftInputShowHideReason.IME_REQUESTED_CHANGED_LISTENER,
+ false /* fromUser */);
+ ImeTracker.forLogging().onProgress(finalStatsToken,
ImeTracker.PHASE_WM_POSTING_CHANGED_IME_VISIBILITY);
mDisplayContent.mWmService.mH.post(() -> {
- ImeTracker.forLogging().onProgress(statsToken,
+ ImeTracker.forLogging().onProgress(finalStatsToken,
ImeTracker.PHASE_WM_INVOKING_IME_REQUESTED_LISTENER);
- imeListener.onImeRequestedChanged(controlTarget.getWindowToken(),
- controlTarget.isRequestedVisible(WindowInsets.Type.ime())
- || imeAnimating, statsToken);
+ imeListener.onImeRequestedChanged(controlTarget.getWindowToken(), imeVisible,
+ finalStatsToken);
});
} else {
ImeTracker.forLogging().onFailed(statsToken,
diff --git a/services/core/java/com/android/server/wm/TaskChangeNotificationController.java b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
index c3649fe98056..709f491a3bdc 100644
--- a/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
+++ b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
@@ -72,7 +72,6 @@ class TaskChangeNotificationController {
private final Handler mHandler;
// Task stack change listeners in a remote process.
- @GuardedBy("mRemoteTaskStackListeners")
private final RemoteCallbackList<ITaskStackListener> mRemoteTaskStackListeners =
new RemoteCallbackList<>();
@@ -311,9 +310,7 @@ class TaskChangeNotificationController {
}
}
} else if (listener != null) {
- synchronized (mRemoteTaskStackListeners) {
- mRemoteTaskStackListeners.register(listener);
- }
+ mRemoteTaskStackListeners.register(listener);
}
}
@@ -323,24 +320,20 @@ class TaskChangeNotificationController {
mLocalTaskStackListeners.remove(listener);
}
} else if (listener != null) {
- synchronized (mRemoteTaskStackListeners) {
- mRemoteTaskStackListeners.unregister(listener);
- }
+ mRemoteTaskStackListeners.unregister(listener);
}
}
private void forAllRemoteListeners(TaskStackConsumer callback, Message message) {
- synchronized (mRemoteTaskStackListeners) {
- for (int i = mRemoteTaskStackListeners.beginBroadcast() - 1; i >= 0; i--) {
- try {
- // Make a one-way callback to the listener
- callback.accept(mRemoteTaskStackListeners.getBroadcastItem(i), message);
- } catch (RemoteException e) {
- // Handled by the RemoteCallbackList.
- }
+ for (int i = mRemoteTaskStackListeners.beginBroadcast() - 1; i >= 0; i--) {
+ try {
+ // Make a one-way callback to the listener
+ callback.accept(mRemoteTaskStackListeners.getBroadcastItem(i), message);
+ } catch (RemoteException e) {
+ // Handled by the RemoteCallbackList.
}
- mRemoteTaskStackListeners.finishBroadcast();
}
+ mRemoteTaskStackListeners.finishBroadcast();
}
private void forAllLocalListeners(TaskStackConsumer callback, Message message) {
diff --git a/services/core/java/com/android/server/wm/TrustedPresentationListenerController.java b/services/core/java/com/android/server/wm/TrustedPresentationListenerController.java
index e612d8ec0ce6..98c143a866d0 100644
--- a/services/core/java/com/android/server/wm/TrustedPresentationListenerController.java
+++ b/services/core/java/com/android/server/wm/TrustedPresentationListenerController.java
@@ -31,6 +31,7 @@ import android.graphics.Region;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
+import android.os.InputConfig;
import android.os.RemoteException;
import android.util.ArrayMap;
import android.util.IntArray;
@@ -260,8 +261,9 @@ public class TrustedPresentationListenerController {
ArrayMap<ITrustedPresentationListener, Pair<IntArray, IntArray>> listenerUpdates =
new ArrayMap<>();
for (var windowHandle : mLastWindowHandles.first) {
- if (!windowHandle.canOccludePresentation) {
- ProtoLog.v(WM_DEBUG_TPL, "Skipping %s", windowHandle.name);
+ var isInvisible = ((windowHandle.inputConfig & InputConfig.NOT_VISIBLE)
+ == InputConfig.NOT_VISIBLE);
+ if (!windowHandle.canOccludePresentation || isInvisible) {
continue;
}
int displayId = INVALID_DISPLAY;
diff --git a/services/core/java/com/android/server/wm/WindowManagerInternal.java b/services/core/java/com/android/server/wm/WindowManagerInternal.java
index 5f2a2ad7f0eb..8ed93276d646 100644
--- a/services/core/java/com/android/server/wm/WindowManagerInternal.java
+++ b/services/core/java/com/android/server/wm/WindowManagerInternal.java
@@ -371,7 +371,7 @@ public abstract class WindowManagerInternal {
* @param statsToken the token tracking the current IME request.
*/
void onImeRequestedChanged(IBinder windowToken, boolean imeVisible,
- @Nullable ImeTracker.Token statsToken);
+ @NonNull ImeTracker.Token statsToken);
}
/**
diff --git a/services/credentials/java/com/android/server/credentials/CreateRequestSession.java b/services/credentials/java/com/android/server/credentials/CreateRequestSession.java
index 9781fb9a1830..e4c214fd93e6 100644
--- a/services/credentials/java/com/android/server/credentials/CreateRequestSession.java
+++ b/services/credentials/java/com/android/server/credentials/CreateRequestSession.java
@@ -27,6 +27,7 @@ import android.credentials.CreateCredentialResponse;
import android.credentials.CredentialManager;
import android.credentials.CredentialProviderInfo;
import android.credentials.ICreateCredentialCallback;
+import android.credentials.flags.Flags;
import android.credentials.selection.ProviderData;
import android.credentials.selection.RequestInfo;
import android.os.CancellationSignal;
@@ -145,6 +146,9 @@ public final class CreateRequestSession extends RequestSession<CreateCredentialR
if (response != null) {
mRequestSessionMetric.collectChosenProviderStatus(
ProviderStatusForMetrics.FINAL_SUCCESS.getMetricCode());
+ if (Flags.fixMetricDuplicationEmits()) {
+ mRequestSessionMetric.collectChosenClassType(mClientRequest.getType());
+ }
respondToClientWithResponseAndFinish(response);
} else {
mRequestSessionMetric.collectChosenProviderStatus(
diff --git a/services/credentials/java/com/android/server/credentials/GetRequestSession.java b/services/credentials/java/com/android/server/credentials/GetRequestSession.java
index be36b6c5690b..fd00f6dde815 100644
--- a/services/credentials/java/com/android/server/credentials/GetRequestSession.java
+++ b/services/credentials/java/com/android/server/credentials/GetRequestSession.java
@@ -27,6 +27,7 @@ import android.credentials.GetCredentialException;
import android.credentials.GetCredentialRequest;
import android.credentials.GetCredentialResponse;
import android.credentials.IGetCredentialCallback;
+import android.credentials.flags.Flags;
import android.credentials.selection.ProviderData;
import android.credentials.selection.RequestInfo;
import android.os.Binder;
@@ -146,6 +147,12 @@ public class GetRequestSession extends RequestSession<GetCredentialRequest,
if (response != null) {
mRequestSessionMetric.collectChosenProviderStatus(
ProviderStatusForMetrics.FINAL_SUCCESS.getMetricCode());
+ if (Flags.fixMetricDuplicationEmits()) {
+ if (response.getCredential() != null) {
+ mRequestSessionMetric.collectChosenClassType(response.getCredential()
+ .getType());
+ }
+ }
respondToClientWithResponseAndFinish(response);
} else {
mRequestSessionMetric.collectChosenProviderStatus(
diff --git a/services/credentials/java/com/android/server/credentials/MetricUtilities.java b/services/credentials/java/com/android/server/credentials/MetricUtilities.java
index 11edb93dffea..9c89f4c31fc6 100644
--- a/services/credentials/java/com/android/server/credentials/MetricUtilities.java
+++ b/services/credentials/java/com/android/server/credentials/MetricUtilities.java
@@ -201,7 +201,8 @@ public class MetricUtilities {
finalPhaseMetric.getResponseCollective().getUniqueResponseCounts(),
/* framework_exception_unique_classtype */
finalPhaseMetric.getFrameworkException(),
- /* primary_indicated */ finalPhaseMetric.isPrimary()
+ /* primary_indicated */ finalPhaseMetric.isPrimary(),
+ /* chosen_classtype */ finalPhaseMetric.getChosenClassType()
);
} catch (Exception e) {
Slog.w(TAG, "Unexpected error during final provider uid emit: " + e);
@@ -587,7 +588,8 @@ public class MetricUtilities {
/* primary_indicated */ finalPhaseMetric.isPrimary(),
/* oem_credential_manager_ui_uid */ finalPhaseMetric.getOemUiUid(),
/* fallback_credential_manager_ui_uid */ finalPhaseMetric.getFallbackUiUid(),
- /* oem_ui_usage_status */ finalPhaseMetric.getOemUiUsageStatus()
+ /* oem_ui_usage_status */ finalPhaseMetric.getOemUiUsageStatus(),
+ /* chosen_classtype */ finalPhaseMetric.getChosenClassType()
);
} catch (Exception e) {
Slog.w(TAG, "Unexpected error during final no uid metric logging: " + e);
diff --git a/services/credentials/java/com/android/server/credentials/metrics/ChosenProviderFinalPhaseMetric.java b/services/credentials/java/com/android/server/credentials/metrics/ChosenProviderFinalPhaseMetric.java
index 9dd6db6f9d6a..c8f6ba06d020 100644
--- a/services/credentials/java/com/android/server/credentials/metrics/ChosenProviderFinalPhaseMetric.java
+++ b/services/credentials/java/com/android/server/credentials/metrics/ChosenProviderFinalPhaseMetric.java
@@ -83,12 +83,24 @@ public class ChosenProviderFinalPhaseMetric {
// Indicates if this chosen provider was the primary provider, false by default
private boolean mIsPrimary = false;
+ private String mChosenClassType = "";
+
public ChosenProviderFinalPhaseMetric(int sessionIdCaller, int sessionIdProvider) {
mSessionIdCaller = sessionIdCaller;
mSessionIdProvider = sessionIdProvider;
}
+ /* ------------------- Chosen Credential ------------------- */
+
+ public void setChosenClassType(String clickedClassType) {
+ mChosenClassType = clickedClassType;
+ }
+
+ public String getChosenClassType() {
+ return mChosenClassType;
+ }
+
/* ------------------- UID ------------------- */
public int getChosenUid() {
diff --git a/services/credentials/java/com/android/server/credentials/metrics/RequestSessionMetric.java b/services/credentials/java/com/android/server/credentials/metrics/RequestSessionMetric.java
index dc1747f803ea..3d740e531e14 100644
--- a/services/credentials/java/com/android/server/credentials/metrics/RequestSessionMetric.java
+++ b/services/credentials/java/com/android/server/credentials/metrics/RequestSessionMetric.java
@@ -262,6 +262,21 @@ public class RequestSessionMetric {
}
/**
+ * This collects the final chosen class type. While it is possible to collect this during
+ * browsing, note this only collects the final tapped bit.
+ *
+ * @param createOrCredentialType the string type to collect when an entry is tapped by the user
+ */
+ public void collectChosenClassType(String createOrCredentialType) {
+ String truncatedType = generateMetricKey(createOrCredentialType, DELTA_EXCEPTION_CUT);
+ try {
+ mChosenProviderFinalPhaseMetric.setChosenClassType(truncatedType);
+ } catch (Exception e) {
+ Slog.i(TAG, "Unexpected error collecting chosen class type metadata: " + e);
+ }
+ }
+
+ /**
* Updates the final phase metric with the designated bit.
*
* @param exceptionBitFinalPhase represents if the final phase provider had an exception
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
index d984fcc599cb..964826d1ee73 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/DevicePolicyManagerService.java
@@ -23903,10 +23903,9 @@ public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
UserHandle.USER_ALL);
synchronized (getLockObject()) {
- final EnforcingAdmin admin = enforcePermissionAndGetEnforcingAdmin(null,
- MANAGE_DEVICE_POLICY_MTE, callerPackageName, caller.getUserId());
- final Integer policyFromAdmin = mDevicePolicyEngine.getGlobalPolicySetByAdmin(
- PolicyDefinition.MEMORY_TAGGING, admin);
+ final Integer policyFromAdmin = mDevicePolicyEngine.getResolvedPolicy(
+ PolicyDefinition.MEMORY_TAGGING, UserHandle.USER_ALL);
+
return (policyFromAdmin != null ? policyFromAdmin
: DevicePolicyManager.MTE_NOT_CONTROLLED_BY_POLICY);
}
diff --git a/services/java/com/android/server/flags.aconfig b/services/java/com/android/server/flags.aconfig
index 7a6bd75e5893..f864b6b8c768 100644
--- a/services/java/com/android/server/flags.aconfig
+++ b/services/java/com/android/server/flags.aconfig
@@ -31,6 +31,13 @@ flag {
}
flag {
+ namespace: "system_performance"
+ name: "enable_theme_service"
+ description: "Switches from SystemUi's ThemeOverlayController to Server's ThemeService."
+ bug: "333694176"
+}
+
+flag {
name: "allow_removing_vpn_service"
namespace: "wear_frameworks"
description: "Allow removing VpnManagerService"
diff --git a/services/permission/java/com/android/server/permission/access/AccessPolicy.kt b/services/permission/java/com/android/server/permission/access/AccessPolicy.kt
index 1bb395441587..410539c8c5d0 100644
--- a/services/permission/java/com/android/server/permission/access/AccessPolicy.kt
+++ b/services/permission/java/com/android/server/permission/access/AccessPolicy.kt
@@ -431,7 +431,7 @@ private constructor(
companion object {
private val LOG_TAG = AccessPolicy::class.java.simpleName
- internal const val VERSION_LATEST = 16
+ internal const val VERSION_LATEST = 17
private const val TAG_ACCESS = "access"
private const val TAG_DEFAULT_PERMISSION_GRANT = "default-permission-grant"
diff --git a/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionPolicy.kt b/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionPolicy.kt
index 5a140d53a4d8..662e0c06f261 100644
--- a/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionPolicy.kt
+++ b/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionPolicy.kt
@@ -100,7 +100,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
override fun MutateStateScope.onStorageVolumeMounted(
volumeUuid: String?,
packageNames: List<String>,
- isSystemUpdated: Boolean
+ isSystemUpdated: Boolean,
) {
val changedPermissionNames = MutableIndexedSet<String>()
packageNames.forEachIndexed { _, packageName ->
@@ -173,7 +173,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.clearRestrictedPermissionImplicitExemption(
packageState: PackageState,
- userId: Int
+ userId: Int,
) {
// System apps can always retain their UPGRADE_EXEMPT.
if (packageState.isSystem) {
@@ -198,7 +198,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
userId,
permission,
PermissionFlags.UPGRADE_EXEMPT,
- 0
+ 0,
)
}
}
@@ -208,7 +208,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
userId: Int,
permission: Permission,
exemptFlagMask: Int,
- exemptFlagValues: Int
+ exemptFlagValues: Int,
) {
val permissionName = permission.name
val oldFlags = getPermissionFlags(appId, userId, permissionName)
@@ -236,7 +236,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
isSoftRestrictedPermissionExemptForPackage(
it,
targetSdkVersion,
- permissionName
+ permissionName,
)
}
} else {
@@ -257,7 +257,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
override fun MutateStateScope.onPackageUninstalled(
packageName: String,
appId: Int,
- userId: Int
+ userId: Int,
) {
resetRuntimePermissions(packageName, userId)
}
@@ -290,17 +290,16 @@ class AppIdPermissionPolicy : SchemePolicy() {
packageState.isSystem || packageState.getUserStateOrDefault(userId).isInstalled
newFlags =
if (
- isSystemOrInstalled && (
- newFlags.hasBits(PermissionFlags.ROLE) ||
- newFlags.hasBits(PermissionFlags.PREGRANT)
- )
+ isSystemOrInstalled &&
+ (newFlags.hasBits(PermissionFlags.ROLE) ||
+ newFlags.hasBits(PermissionFlags.PREGRANT))
) {
newFlags or PermissionFlags.RUNTIME_GRANTED
} else {
- newFlags andInv (
- PermissionFlags.RUNTIME_GRANTED or PermissionFlags.ROLE or
- PermissionFlags.PREGRANT
- )
+ newFlags andInv
+ (PermissionFlags.RUNTIME_GRANTED or
+ PermissionFlags.ROLE or
+ PermissionFlags.PREGRANT)
}
newFlags = newFlags andInv USER_SETTABLE_MASK
if (newFlags.hasBits(PermissionFlags.LEGACY_GRANTED)) {
@@ -312,7 +311,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.adoptPermissions(
packageState: PackageState,
- changedPermissionNames: MutableIndexedSet<String>
+ changedPermissionNames: MutableIndexedSet<String>,
) {
val `package` = packageState.androidPackage!!
`package`.adoptPermissions.forEachIndexed { _, originalPackageName ->
@@ -341,7 +340,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
oldPermission.copy(
permissionInfo = newPermissionInfo,
isReconciled = false,
- appId = 0
+ appId = 0,
)
newState
.mutateSystemState()
@@ -354,7 +353,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.canAdoptPermissions(
packageName: String,
- originalPackageName: String
+ originalPackageName: String,
): Boolean {
val originalPackageState =
newState.externalState.packageStates[originalPackageName] ?: return false
@@ -362,7 +361,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
Slog.w(
LOG_TAG,
"Unable to adopt permissions from $originalPackageName to $packageName:" +
- " original package not in system partition"
+ " original package not in system partition",
)
return false
}
@@ -370,7 +369,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
Slog.w(
LOG_TAG,
"Unable to adopt permissions from $originalPackageName to $packageName:" +
- " original package still exists"
+ " original package still exists",
)
return false
}
@@ -386,7 +385,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
Slog.w(
LOG_TAG,
"Ignoring permission groups declared in package" +
- " ${packageState.packageName}: instant apps cannot declare permission groups"
+ " ${packageState.packageName}: instant apps cannot declare permission groups",
)
return
}
@@ -394,7 +393,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
val newPermissionGroup =
PackageInfoUtils.generatePermissionGroupInfo(
parsedPermissionGroup,
- PackageManager.GET_META_DATA.toLong()
+ PackageManager.GET_META_DATA.toLong(),
)!!
// TODO: Clear permission state on group take-over?
val permissionGroupName = newPermissionGroup.name
@@ -414,7 +413,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Ignoring permission group $permissionGroupName declared in" +
" package $newPackageName: already declared in another" +
- " package $oldPackageName"
+ " package $oldPackageName",
)
return@forEachIndexed
}
@@ -423,7 +422,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Ignoring permission group $permissionGroupName declared in" +
" system package $newPackageName: already declared in another" +
- " system package $oldPackageName"
+ " system package $oldPackageName",
)
return@forEachIndexed
}
@@ -431,7 +430,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Overriding permission group $permissionGroupName with" +
" new declaration in system package $newPackageName: originally" +
- " declared in another package $oldPackageName"
+ " declared in another package $oldPackageName",
)
}
newState.mutateSystemState().mutatePermissionGroups()[permissionGroupName] =
@@ -441,7 +440,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.addPermissions(
packageState: PackageState,
- changedPermissionNames: MutableIndexedSet<String>
+ changedPermissionNames: MutableIndexedSet<String>,
) {
val androidPackage = packageState.androidPackage!!
// This may not be the same package as the old permission because the old permission owner
@@ -454,7 +453,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
val newPermissionInfo =
PackageInfoUtils.generatePermissionInfo(
parsedPermission,
- PackageManager.GET_META_DATA.toLong()
+ PackageManager.GET_META_DATA.toLong(),
)!!
val permissionName = newPermissionInfo.name
val oldPermission =
@@ -474,7 +473,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Ignoring permission $permissionName declared in package" +
" $newPackageName: base permission tree ${permissionTree.name} is" +
- " declared in another package ${permissionTree.packageName}"
+ " declared in another package ${permissionTree.packageName}",
)
return@forEachIndexed
}
@@ -488,7 +487,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Ignoring permission $permissionName declared in package" +
" $newPackageName: already declared in another package" +
- " $oldPackageName"
+ " $oldPackageName",
)
return@forEachIndexed
}
@@ -497,7 +496,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Ignoring permission $permissionName declared in system package" +
" $newPackageName: already declared in another system package" +
- " $oldPackageName"
+ " $oldPackageName",
)
return@forEachIndexed
}
@@ -505,7 +504,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Overriding permission $permissionName with new declaration in" +
" system package $newPackageName: originally declared in another" +
- " package $oldPackageName"
+ " package $oldPackageName",
)
// Remove permission state on owner change.
newState.externalState.userIds.forEachIndexed { _, userId ->
@@ -534,7 +533,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
"Revoking runtime permission $permissionName for" +
" appId $appId and userId $userId as the permission" +
" group changed from ${oldPermission.groupName}" +
- " to ${newPermissionInfo.group}"
+ " to ${newPermissionInfo.group}",
)
}
if (isPermissionProtectionChanged) {
@@ -542,7 +541,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Revoking permission $permissionName for" +
" appId $appId and userId $userId as the permission" +
- " protection changed."
+ " protection changed.",
)
}
setPermissionFlags(appId, userId, permissionName, 0)
@@ -572,7 +571,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
Permission.TYPE_MANIFEST,
packageState.appId,
gids,
- areGidsPerUser
+ areGidsPerUser,
)
if (parsedPermission.isTree) {
@@ -599,7 +598,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.trimPermissions(
packageName: String,
- changedPermissionNames: MutableIndexedSet<String>
+ changedPermissionNames: MutableIndexedSet<String>,
) {
val packageState = newState.externalState.packageStates[packageName]
val androidPackage = packageState?.androidPackage
@@ -675,7 +674,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
packageName = permissionTree.packageName
},
appId = permissionTree.appId,
- isReconciled = true
+ isReconciled = true,
)
}
@@ -754,7 +753,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
Slog.v(
LOG_TAG,
"Revoking storage permission: $permissionName for appId: " +
- " $appId and user: $userId"
+ " $appId and user: $userId",
)
val newFlags =
oldFlags andInv (PermissionFlags.RUNTIME_GRANTED or USER_SETTABLE_MASK)
@@ -767,7 +766,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.evaluatePermissionStateForAllPackages(
permissionName: String,
- installedPackageState: PackageState?
+ installedPackageState: PackageState?,
) {
val externalState = newState.externalState
externalState.userIds.forEachIndexed { _, userId ->
@@ -785,13 +784,13 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.evaluateAllPermissionStatesForPackage(
packageState: PackageState,
- installedPackageState: PackageState?
+ installedPackageState: PackageState?,
) {
newState.externalState.userIds.forEachIndexed { _, userId ->
evaluateAllPermissionStatesForPackageAndUser(
packageState,
userId,
- installedPackageState
+ installedPackageState,
)
}
}
@@ -799,14 +798,14 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.evaluateAllPermissionStatesForPackageAndUser(
packageState: PackageState,
userId: Int,
- installedPackageState: PackageState?
+ installedPackageState: PackageState?,
) {
packageState.androidPackage?.requestedPermissions?.forEach { permissionName ->
evaluatePermissionState(
packageState.appId,
userId,
permissionName,
- installedPackageState
+ installedPackageState,
)
}
}
@@ -815,7 +814,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
appId: Int,
userId: Int,
permissionName: String,
- installedPackageState: PackageState?
+ installedPackageState: PackageState?,
) {
val packageNames = newState.externalState.appIdPackageNames[appId]!!
// Repeatedly checking whether a permission is requested can actually be costly, so we cache
@@ -989,8 +988,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
"Unknown source permission $sourcePermissionName in split permissions"
}
!sourcePermission.isRuntime
- }
- ?: false
+ } ?: false
val shouldGrantByImplicit =
isLeanbackNotificationsPermission ||
(isImplicitPermission && isAnySourcePermissionNonRuntime)
@@ -1024,7 +1022,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
getPermissionFlags(
appId,
userId,
- Manifest.permission.ACCESS_BACKGROUND_LOCATION
+ Manifest.permission.ACCESS_BACKGROUND_LOCATION,
)
shouldRetainAsNearbyDevices =
PermissionFlags.isAppOpGranted(accessBackgroundLocationFlags) &&
@@ -1081,7 +1079,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
isSoftRestrictedPermissionExemptForPackage(
it,
targetSdkVersion,
- permissionName
+ permissionName,
)
}
) {
@@ -1095,7 +1093,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Unknown protection level ${permission.protectionLevel}" +
"for permission ${permission.name} while evaluating permission state" +
- "for appId $appId and userId $userId"
+ "for appId $appId and userId $userId",
)
}
}
@@ -1154,7 +1152,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun isCompatibilityPermissionForPackage(
androidPackage: AndroidPackage,
- permissionName: String
+ permissionName: String,
): Boolean {
for (compatibilityPermission in CompatibilityPermissionInfo.COMPAT_PERMS) {
if (
@@ -1164,7 +1162,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
Slog.i(
LOG_TAG,
"Auto-granting $permissionName to old package" +
- " ${androidPackage.packageName}"
+ " ${androidPackage.packageName}",
)
return true
}
@@ -1174,7 +1172,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.shouldGrantPermissionBySignature(
packageState: PackageState,
- permission: Permission
+ permission: Permission,
): Boolean {
// Check if the package is allowed to use this signature permission. A package is allowed
// to use a signature permission if:
@@ -1197,12 +1195,12 @@ class AppIdPermissionPolicy : SchemePolicy() {
val hasCommonSigner =
sourceSigningDetails?.hasCommonSignerWithCapability(
packageSigningDetails,
- SigningDetails.CertCapabilities.PERMISSION
+ SigningDetails.CertCapabilities.PERMISSION,
) == true ||
packageSigningDetails.hasAncestorOrSelf(platformSigningDetails) ||
platformSigningDetails.checkCapability(
packageSigningDetails,
- SigningDetails.CertCapabilities.PERMISSION
+ SigningDetails.CertCapabilities.PERMISSION,
)
if (!Flags.signaturePermissionAllowlistEnabled()) {
return hasCommonSigner
@@ -1237,7 +1235,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Signature permission ${permission.name} for package" +
" ${packageState.packageName} (${packageState.path}) not in" +
- " signature permission allowlist"
+ " signature permission allowlist",
)
if (!Build.isDebuggable() || isSignaturePermissionAllowlistForceEnforced) {
return false
@@ -1249,7 +1247,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.getSignaturePermissionAllowlistState(
packageState: PackageState,
- permissionName: String
+ permissionName: String,
): Boolean? {
val permissionAllowlist = newState.externalState.permissionAllowlist
val packageName = packageState.packageName
@@ -1259,30 +1257,30 @@ class AppIdPermissionPolicy : SchemePolicy() {
packageState.isProduct ->
permissionAllowlist.getProductSignatureAppAllowlistState(
packageName,
- permissionName
+ permissionName,
)
packageState.isSystemExt ->
permissionAllowlist.getSystemExtSignatureAppAllowlistState(
packageName,
- permissionName
+ permissionName,
)
else ->
permissionAllowlist.getApexSignatureAppAllowlistState(packageName, permissionName)
?: permissionAllowlist.getProductSignatureAppAllowlistState(
packageName,
- permissionName
+ permissionName,
)
?: permissionAllowlist.getVendorSignatureAppAllowlistState(
packageName,
- permissionName
+ permissionName,
)
?: permissionAllowlist.getSystemExtSignatureAppAllowlistState(
packageName,
- permissionName
+ permissionName,
)
?: permissionAllowlist.getSignatureAppAllowlistState(
packageName,
- permissionName
+ permissionName,
)
}
}
@@ -1292,13 +1290,13 @@ class AppIdPermissionPolicy : SchemePolicy() {
* or for normal apps, we return true to indicate that we don't need to check the allowlist and
* will let follow-up checks to decide whether we should grant the permission.
*
- * @return `true`, if the permission is allowlisted for system privileged apps, or if we
- * don't need to check the allowlist (for platform or for normal apps).
- * `false`, if the permission is not allowlisted for system privileged apps.
+ * @return `true`, if the permission is allowlisted for system privileged apps, or if we don't
+ * need to check the allowlist (for platform or for normal apps). `false`, if the permission
+ * is not allowlisted for system privileged apps.
*/
private fun MutateStateScope.checkPrivilegedPermissionAllowlistIfNeeded(
packageState: PackageState,
- permission: Permission
+ permission: Permission,
): Boolean {
if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE) {
return true
@@ -1330,7 +1328,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Privileged permission ${permission.name} for package" +
" ${packageState.packageName} (${packageState.path}) not in" +
- " privileged permission allowlist"
+ " privileged permission allowlist",
)
if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
privilegedPermissionAllowlistViolations +=
@@ -1348,7 +1346,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
*/
private fun MutateStateScope.getPrivilegedPermissionAllowlistState(
packageState: PackageState,
- permissionName: String
+ permissionName: String,
): Boolean? {
val permissionAllowlist = newState.externalState.permissionAllowlist
val apexModuleName = packageState.apexModuleName
@@ -1357,17 +1355,17 @@ class AppIdPermissionPolicy : SchemePolicy() {
packageState.isVendor || packageState.isOdm ->
permissionAllowlist.getVendorPrivilegedAppAllowlistState(
packageName,
- permissionName
+ permissionName,
)
packageState.isProduct ->
permissionAllowlist.getProductPrivilegedAppAllowlistState(
packageName,
- permissionName
+ permissionName,
)
packageState.isSystemExt ->
permissionAllowlist.getSystemExtPrivilegedAppAllowlistState(
packageName,
- permissionName
+ permissionName,
)
apexModuleName != null -> {
val nonApexAllowlistState =
@@ -1379,14 +1377,14 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Package $packageName is an APK in APEX but has permission" +
" allowlist on the system image, please bundle the allowlist in the" +
- " $apexModuleName APEX instead"
+ " $apexModuleName APEX instead",
)
}
val apexAllowlistState =
permissionAllowlist.getApexPrivilegedAppAllowlistState(
apexModuleName,
packageName,
- permissionName
+ permissionName,
)
apexAllowlistState ?: nonApexAllowlistState
}
@@ -1403,7 +1401,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun isSoftRestrictedPermissionExemptForPackage(
packageState: PackageState,
appIdTargetSdkVersion: Int,
- permissionName: String
+ permissionName: String,
): Boolean =
when (permissionName) {
Manifest.permission.READ_EXTERNAL_STORAGE,
@@ -1415,7 +1413,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.getAppIdTargetSdkVersion(
appId: Int,
permissionName: String?,
- state: AccessState = newState
+ state: AccessState = newState,
): Int =
reducePackageInAppId(appId, Build.VERSION_CODES.CUR_DEVELOPMENT, state) {
targetSdkVersion,
@@ -1431,7 +1429,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private inline fun MutateStateScope.anyPackageInAppId(
appId: Int,
state: AccessState = newState,
- predicate: (PackageState) -> Boolean
+ predicate: (PackageState) -> Boolean,
): Boolean {
val packageNames = state.externalState.appIdPackageNames[appId]!!
return packageNames.anyIndexed { _, packageName ->
@@ -1443,7 +1441,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private inline fun MutateStateScope.forEachPackageInAppId(
appId: Int,
state: AccessState = newState,
- action: (PackageState) -> Unit
+ action: (PackageState) -> Unit,
) {
val packageNames = state.externalState.appIdPackageNames[appId]!!
packageNames.forEachIndexed { _, packageName ->
@@ -1459,7 +1457,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
appId: Int,
initialValue: Int,
state: AccessState = newState,
- accumulator: (Int, PackageState) -> Int
+ accumulator: (Int, PackageState) -> Int,
): Int {
val packageNames = state.externalState.appIdPackageNames[appId]!!
return packageNames.reduceIndexed(initialValue) { value, _, packageName ->
@@ -1474,7 +1472,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.shouldGrantPermissionByProtectionFlags(
packageState: PackageState,
- permission: Permission
+ permission: Permission,
): Boolean {
val androidPackage = packageState.androidPackage!!
val knownPackages = newState.externalState.knownPackages
@@ -1587,7 +1585,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.shouldGrantPrivilegedOrOemPermission(
packageState: PackageState,
- permission: Permission
+ permission: Permission,
): Boolean {
val permissionName = permission.name
val packageName = packageState.packageName
@@ -1605,7 +1603,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
LOG_TAG,
"Permission $permissionName cannot be granted to privileged" +
" vendor (or odm) app $packageName because it isn't a" +
- " vendorPrivileged permission"
+ " vendorPrivileged permission",
)
return false
}
@@ -1617,7 +1615,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
val allowlistState =
newState.externalState.permissionAllowlist.getOemAppAllowlistState(
packageName,
- permissionName
+ permissionName,
)
checkNotNull(allowlistState) {
"OEM permission $permissionName requested by package" +
@@ -1688,7 +1686,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
fun MutateStateScope.addPermission(
permission: Permission,
- isSynchronousWrite: Boolean = false
+ isSynchronousWrite: Boolean = false,
) {
val writeMode = if (isSynchronousWrite) WriteMode.SYNCHRONOUS else WriteMode.ASYNCHRONOUS
newState.mutateSystemState(writeMode).mutatePermissions()[permission.name] = permission
@@ -1707,14 +1705,14 @@ class AppIdPermissionPolicy : SchemePolicy() {
private fun MutateStateScope.getOldStatePermissionFlags(
appId: Int,
userId: Int,
- permissionName: String
+ permissionName: String,
): Int = getPermissionFlags(oldState, appId, userId, permissionName)
private fun getPermissionFlags(
state: AccessState,
appId: Int,
userId: Int,
- permissionName: String
+ permissionName: String,
): Int =
state.userStates[userId]?.appIdPermissionFlags?.get(appId).getWithDefault(permissionName, 0)
@@ -1725,7 +1723,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
appId: Int,
userId: Int,
permissionName: String,
- flags: Int
+ flags: Int,
): Boolean =
updatePermissionFlags(appId, userId, permissionName, PermissionFlags.MASK_ALL, flags)
@@ -1734,7 +1732,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
userId: Int,
permissionName: String,
flagMask: Int,
- flagValues: Int
+ flagValues: Int,
): Boolean {
if (userId !in newState.userStates) {
// Despite that we check UserManagerInternal.exists() in PermissionService, we may still
@@ -1793,7 +1791,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
override fun MutateStateScope.upgradePackageState(
packageState: PackageState,
userId: Int,
- version: Int
+ version: Int,
) {
with(upgrade) { upgradePackageState(packageState, userId, version) }
}
@@ -1819,7 +1817,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
Manifest.permission.BLUETOOTH_ADVERTISE,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN,
- Manifest.permission.NEARBY_WIFI_DEVICES
+ Manifest.permission.NEARBY_WIFI_DEVICES,
)
private val NOTIFICATIONS_PERMISSIONS = indexedSetOf(Manifest.permission.POST_NOTIFICATIONS)
@@ -1832,7 +1830,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
Manifest.permission.READ_MEDIA_VIDEO,
Manifest.permission.READ_MEDIA_IMAGES,
Manifest.permission.ACCESS_MEDIA_LOCATION,
- Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED
+ Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED,
)
/** Mask for all permission flags that can be set by the user */
@@ -1866,7 +1864,7 @@ class AppIdPermissionPolicy : SchemePolicy() {
userId: Int,
permissionName: String,
oldFlags: Int,
- newFlags: Int
+ newFlags: Int,
)
/**
diff --git a/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionUpgrade.kt b/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionUpgrade.kt
index a4546aebef21..022b811d9ac8 100644
--- a/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionUpgrade.kt
+++ b/services/permission/java/com/android/server/permission/access/permission/AppIdPermissionUpgrade.kt
@@ -17,8 +17,10 @@
package com.android.server.permission.access.permission
import android.Manifest
+import android.health.connect.HealthPermissions
import android.os.Build
import android.util.Slog
+import com.android.server.permission.access.GetStateScope
import com.android.server.permission.access.MutateStateScope
import com.android.server.permission.access.immutable.* // ktlint-disable no-wildcard-imports
import com.android.server.permission.access.util.andInv
@@ -36,14 +38,14 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
fun MutateStateScope.upgradePackageState(
packageState: PackageState,
userId: Int,
- version: Int
+ version: Int,
) {
val packageName = packageState.packageName
if (version <= 3) {
Slog.v(
LOG_TAG,
"Allowlisting and upgrading background location permission for " +
- "package: $packageName, version: $version, user:$userId"
+ "package: $packageName, version: $version, user:$userId",
)
allowlistRestrictedPermissions(packageState, userId)
upgradeBackgroundLocationPermission(packageState, userId)
@@ -52,7 +54,7 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
Slog.v(
LOG_TAG,
"Upgrading access media location permission for package: $packageName" +
- ", version: $version, user: $userId"
+ ", version: $version, user: $userId",
)
upgradeAccessMediaLocationPermission(packageState, userId)
}
@@ -61,27 +63,37 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
Slog.v(
LOG_TAG,
"Upgrading scoped media and body sensor permissions for package: $packageName" +
- ", version: $version, user: $userId"
+ ", version: $version, user: $userId",
)
upgradeAuralVisualMediaPermissions(packageState, userId)
- upgradeBodySensorPermissions(packageState, userId)
+ upgradeBodySensorBackgroundPermissions(packageState, userId)
}
// TODO Enable isAtLeastU check, when moving subsystem to mainline.
if (version <= 14 /*&& SdkLevel.isAtLeastU()*/) {
Slog.v(
LOG_TAG,
"Upgrading visual media permission for package: $packageName" +
- ", version: $version, user: $userId"
+ ", version: $version, user: $userId",
)
upgradeUserSelectedVisualMediaPermission(packageState, userId)
}
+ // TODO Enable isAtLeastB check, when moving subsystem to mainline.
+ if (version <= 16 /*&& SdkLevel.isAtLeastB()*/) {
+ Slog.v(
+ LOG_TAG,
+ "Upgrading body sensor / read heart rate permissions for package: $packageName" +
+ ", version: $version, user: $userId",
+ )
+ upgradeBodySensorReadHeartRatePermissions(packageState, userId)
+ }
+
// Add a new upgrade step: if (packageVersion <= LATEST_VERSION) { .... }
// Also increase LATEST_VERSION
}
private fun MutateStateScope.allowlistRestrictedPermissions(
packageState: PackageState,
- userId: Int
+ userId: Int,
) {
packageState.androidPackage!!.requestedPermissions.forEach { permissionName ->
if (permissionName in LEGACY_RESTRICTED_PERMISSIONS) {
@@ -91,7 +103,7 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
userId,
permissionName,
PermissionFlags.UPGRADE_EXEMPT,
- PermissionFlags.UPGRADE_EXEMPT
+ PermissionFlags.UPGRADE_EXEMPT,
)
}
}
@@ -100,7 +112,7 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
private fun MutateStateScope.upgradeBackgroundLocationPermission(
packageState: PackageState,
- userId: Int
+ userId: Int,
) {
if (
Manifest.permission.ACCESS_BACKGROUND_LOCATION in
@@ -122,7 +134,7 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
grantRuntimePermission(
packageState,
userId,
- Manifest.permission.ACCESS_BACKGROUND_LOCATION
+ Manifest.permission.ACCESS_BACKGROUND_LOCATION,
)
}
}
@@ -130,7 +142,7 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
private fun MutateStateScope.upgradeAccessMediaLocationPermission(
packageState: PackageState,
- userId: Int
+ userId: Int,
) {
if (
Manifest.permission.ACCESS_MEDIA_LOCATION in
@@ -141,14 +153,14 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
getPermissionFlags(
packageState.appId,
userId,
- Manifest.permission.READ_EXTERNAL_STORAGE
+ Manifest.permission.READ_EXTERNAL_STORAGE,
)
}
if (PermissionFlags.isAppOpGranted(flags)) {
grantRuntimePermission(
packageState,
userId,
- Manifest.permission.ACCESS_MEDIA_LOCATION
+ Manifest.permission.ACCESS_MEDIA_LOCATION,
)
}
}
@@ -157,7 +169,7 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
/** Upgrade permissions based on storage permissions grant */
private fun MutateStateScope.upgradeAuralVisualMediaPermissions(
packageState: PackageState,
- userId: Int
+ userId: Int,
) {
val androidPackage = packageState.androidPackage!!
if (androidPackage.targetSdkVersion < Build.VERSION_CODES.TIRAMISU) {
@@ -182,9 +194,9 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
}
}
- private fun MutateStateScope.upgradeBodySensorPermissions(
+ private fun MutateStateScope.upgradeBodySensorBackgroundPermissions(
packageState: PackageState,
- userId: Int
+ userId: Int,
) {
if (
Manifest.permission.BODY_SENSORS_BACKGROUND !in
@@ -221,7 +233,7 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
grantRuntimePermission(
packageState,
userId,
- Manifest.permission.BODY_SENSORS_BACKGROUND
+ Manifest.permission.BODY_SENSORS_BACKGROUND,
)
}
}
@@ -229,7 +241,7 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
/** Upgrade permission based on the grant in [Manifest.permission_group.READ_MEDIA_VISUAL] */
private fun MutateStateScope.upgradeUserSelectedVisualMediaPermission(
packageState: PackageState,
- userId: Int
+ userId: Int,
) {
val androidPackage = packageState.androidPackage!!
if (androidPackage.targetSdkVersion < Build.VERSION_CODES.TIRAMISU) {
@@ -250,21 +262,127 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
grantRuntimePermission(
packageState,
userId,
- Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED
+ Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED,
+ )
+ }
+ }
+ }
+
+ /**
+ * Upgrade permissions based on the body sensors and health permissions status.
+ *
+ * Starting in BAKLAVA, the BODY_SENSORS and BODY_SENSORS_BACKGROUND permissions are being
+ * replaced by the READ_HEART_RATE and READ_HEALTH_DATA_IN_BACKGROUND permissions respectively.
+ * To ensure that older apps can continue using BODY_SENSORS without breaking we need to keep
+ * their permission state in sync with the new health permissions.
+ *
+ * The approach we take is to be as conservative as possible. This means if either permission is
+ * not granted, then we want to ensure that both end up not granted to force the user to
+ * re-grant with the expanded scope.
+ */
+ private fun MutateStateScope.upgradeBodySensorReadHeartRatePermissions(
+ packageState: PackageState,
+ userId: Int,
+ ) {
+ val androidPackage = packageState.androidPackage!!
+ if (androidPackage.targetSdkVersion >= Build.VERSION_CODES.BAKLAVA) {
+ return
+ }
+
+ // First sync BODY_SENSORS and READ_HEART_RATE, if required.
+ val isBodySensorsRequested =
+ Manifest.permission.BODY_SENSORS in androidPackage.requestedPermissions
+ val isReadHeartRateRequested =
+ HealthPermissions.READ_HEART_RATE in androidPackage.requestedPermissions
+ var isBodySensorsGranted =
+ isPermissionGranted(packageState, userId, Manifest.permission.BODY_SENSORS)
+ if (isBodySensorsRequested && isReadHeartRateRequested) {
+ val isReadHeartRateGranted =
+ isPermissionGranted(packageState, userId, HealthPermissions.READ_HEART_RATE)
+ if (isBodySensorsGranted != isReadHeartRateGranted) {
+ if (isBodySensorsGranted) {
+ if (
+ revokeRuntimePermission(
+ packageState,
+ userId,
+ Manifest.permission.BODY_SENSORS,
+ )
+ ) {
+ isBodySensorsGranted = false
+ }
+ }
+ if (isReadHeartRateGranted) {
+ revokeRuntimePermission(packageState, userId, HealthPermissions.READ_HEART_RATE)
+ }
+ }
+ }
+
+ // Then check to ensure we haven't put the background/foreground permissions out of sync.
+ var isBodySensorsBackgroundGranted =
+ isPermissionGranted(packageState, userId, Manifest.permission.BODY_SENSORS_BACKGROUND)
+ // Background permission should not be granted without the foreground permission.
+ if (!isBodySensorsGranted && isBodySensorsBackgroundGranted) {
+ if (
+ revokeRuntimePermission(
+ packageState,
+ userId,
+ Manifest.permission.BODY_SENSORS_BACKGROUND,
+ )
+ ) {
+ isBodySensorsBackgroundGranted = false
+ }
+ }
+
+ // Finally sync BODY_SENSORS_BACKGROUND and READ_HEALTH_DATA_IN_BACKGROUND, if required.
+ val isBodySensorsBackgroundRequested =
+ Manifest.permission.BODY_SENSORS_BACKGROUND in androidPackage.requestedPermissions
+ val isReadHealthDataInBackgroundRequested =
+ HealthPermissions.READ_HEALTH_DATA_IN_BACKGROUND in androidPackage.requestedPermissions
+ if (isBodySensorsBackgroundRequested && isReadHealthDataInBackgroundRequested) {
+ val isReadHealthDataInBackgroundGranted =
+ isPermissionGranted(
+ packageState,
+ userId,
+ HealthPermissions.READ_HEALTH_DATA_IN_BACKGROUND,
)
+ if (isBodySensorsBackgroundGranted != isReadHealthDataInBackgroundGranted) {
+ if (isBodySensorsBackgroundGranted) {
+ revokeRuntimePermission(
+ packageState,
+ userId,
+ Manifest.permission.BODY_SENSORS_BACKGROUND,
+ )
+ }
+ if (isReadHealthDataInBackgroundGranted) {
+ revokeRuntimePermission(
+ packageState,
+ userId,
+ HealthPermissions.READ_HEALTH_DATA_IN_BACKGROUND,
+ )
+ }
}
}
}
+ private fun GetStateScope.isPermissionGranted(
+ packageState: PackageState,
+ userId: Int,
+ permissionName: String,
+ ): Boolean {
+ val permissionFlags =
+ with(policy) { getPermissionFlags(packageState.appId, userId, permissionName) }
+ return PermissionFlags.isAppOpGranted(permissionFlags)
+ }
+
private fun MutateStateScope.grantRuntimePermission(
packageState: PackageState,
userId: Int,
- permissionName: String
+ permissionName: String,
) {
Slog.v(
LOG_TAG,
"Granting runtime permission for package: ${packageState.packageName}, " +
- "permission: $permissionName, userId: $userId"
+ "permission: $permissionName, userId: $userId",
)
val permission = newState.systemState.permissions[permissionName]!!
if (packageState.getUserStateOrDefault(userId).isInstantApp && !permission.isInstant) {
@@ -276,7 +394,7 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
if (flags.hasAnyBit(MASK_ANY_FIXED)) {
Slog.v(
LOG_TAG,
- "Not allowed to grant $permissionName to package ${packageState.packageName}"
+ "Not allowed to grant $permissionName to package ${packageState.packageName}",
)
return
}
@@ -292,6 +410,47 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
with(policy) { setPermissionFlags(appId, userId, permissionName, flags) }
}
+ /**
+ * Revoke a runtime permission for a given user from a given package.
+ *
+ * @return true if the permission was revoked, false otherwise.
+ */
+ private fun MutateStateScope.revokeRuntimePermission(
+ packageState: PackageState,
+ userId: Int,
+ permissionName: String,
+ ): Boolean {
+ Slog.v(
+ LOG_TAG,
+ "Revoking runtime permission for package: ${packageState.packageName}, " +
+ "permission: $permissionName, userId: $userId",
+ )
+ val permission = newState.systemState.permissions[permissionName]!!
+ if (packageState.getUserStateOrDefault(userId).isInstantApp && !permission.isInstant) {
+ return false
+ }
+
+ val appId = packageState.appId
+ var flags = with(policy) { getPermissionFlags(appId, userId, permissionName) }
+ if (flags.hasAnyBit(MASK_SYSTEM_OR_POLICY_FIXED)) {
+ Slog.v(
+ LOG_TAG,
+ "Not allowed to revoke $permissionName to package ${packageState.packageName} " +
+ "for user $userId",
+ )
+ return false
+ }
+
+ val newFlags =
+ flags andInv
+ (PermissionFlags.RUNTIME_GRANTED or
+ MASK_USER_SETTABLE or
+ PermissionFlags.PREGRANT or
+ PermissionFlags.ROLE)
+ with(policy) { setPermissionFlags(appId, userId, permissionName, flags) }
+ return true
+ }
+
companion object {
private val LOG_TAG = AppIdPermissionUpgrade::class.java.simpleName
@@ -302,6 +461,17 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
PermissionFlags.POLICY_FIXED or
PermissionFlags.SYSTEM_FIXED
+ private const val MASK_SYSTEM_OR_POLICY_FIXED =
+ PermissionFlags.SYSTEM_FIXED or PermissionFlags.POLICY_FIXED
+
+ private const val MASK_USER_SETTABLE =
+ PermissionFlags.USER_SET or
+ PermissionFlags.USER_FIXED or
+ PermissionFlags.APP_OP_REVOKED or
+ PermissionFlags.ONE_TIME or
+ PermissionFlags.HIBERNATION or
+ PermissionFlags.USER_SELECTED
+
private val LEGACY_RESTRICTED_PERMISSIONS =
indexedSetOf(
Manifest.permission.ACCESS_BACKGROUND_LOCATION,
@@ -314,13 +484,13 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
Manifest.permission.READ_CELL_BROADCASTS,
Manifest.permission.READ_CALL_LOG,
Manifest.permission.WRITE_CALL_LOG,
- Manifest.permission.PROCESS_OUTGOING_CALLS
+ Manifest.permission.PROCESS_OUTGOING_CALLS,
)
private val STORAGE_PERMISSIONS =
indexedSetOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
- Manifest.permission.WRITE_EXTERNAL_STORAGE
+ Manifest.permission.WRITE_EXTERNAL_STORAGE,
)
private val AURAL_VISUAL_MEDIA_PERMISSIONS =
indexedSetOf(
@@ -328,14 +498,14 @@ class AppIdPermissionUpgrade(private val policy: AppIdPermissionPolicy) {
Manifest.permission.READ_MEDIA_IMAGES,
Manifest.permission.READ_MEDIA_VIDEO,
Manifest.permission.ACCESS_MEDIA_LOCATION,
- Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED
+ Manifest.permission.READ_MEDIA_VISUAL_USER_SELECTED,
)
// Visual media permissions in T
private val VISUAL_MEDIA_PERMISSIONS =
indexedSetOf(
Manifest.permission.READ_MEDIA_IMAGES,
Manifest.permission.READ_MEDIA_VIDEO,
- Manifest.permission.ACCESS_MEDIA_LOCATION
+ Manifest.permission.ACCESS_MEDIA_LOCATION,
)
}
}
diff --git a/services/tests/PermissionServiceMockingTests/src/com/android/server/permission/test/AppIdPermissionPolicyPermissionStatesTest.kt b/services/tests/PermissionServiceMockingTests/src/com/android/server/permission/test/AppIdPermissionPolicyPermissionStatesTest.kt
index 6b9c9c2b4abc..bf9033981442 100644
--- a/services/tests/PermissionServiceMockingTests/src/com/android/server/permission/test/AppIdPermissionPolicyPermissionStatesTest.kt
+++ b/services/tests/PermissionServiceMockingTests/src/com/android/server/permission/test/AppIdPermissionPolicyPermissionStatesTest.kt
@@ -57,10 +57,10 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = oldFlags
assertWithMessage(
- "After $action is called for a package that requests a normal permission" +
- " with an existing INSTALL_GRANTED flag, the actual permission flags $actualFlags" +
- " should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a normal permission" +
+ " with an existing INSTALL_GRANTED flag, the actual permission flags $actualFlags" +
+ " should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -71,16 +71,16 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
testEvaluatePermissionState(
oldFlags,
PermissionInfo.PROTECTION_NORMAL,
- isNewInstall = true
+ isNewInstall = true,
) {}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.INSTALL_GRANTED
assertWithMessage(
- "After $action is called for a package that requests a normal permission" +
- " with no existing flags, the actual permission flags $actualFlags" +
- " should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a normal permission" +
+ " with no existing flags, the actual permission flags $actualFlags" +
+ " should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -90,16 +90,16 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val oldFlags = PermissionFlags.ROLE or PermissionFlags.USER_SET
testEvaluatePermissionState(
oldFlags,
- PermissionInfo.PROTECTION_NORMAL or PermissionInfo.PROTECTION_FLAG_APPOP
+ PermissionInfo.PROTECTION_NORMAL or PermissionInfo.PROTECTION_FLAG_APPOP,
) {}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.INSTALL_GRANTED or oldFlags
assertWithMessage(
- "After $action is called for a package that requests a normal app op" +
- " permission with existing ROLE and USER_SET flags, the actual permission flags" +
- " $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a normal app op" +
+ " permission with existing ROLE and USER_SET flags, the actual permission flags" +
+ " $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -115,21 +115,21 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = oldFlags
assertWithMessage(
- "After $action is called for a package that requests an internal permission" +
- " with missing android package and $oldFlags flag, the actual permission flags" +
- " $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests an internal permission" +
+ " with missing android package and $oldFlags flag, the actual permission flags" +
+ " $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@Test
fun testEvaluatePermissionState_internalAppOpPermission_getsRoleAndUserSetFlagsPreserved() {
- val oldFlags = PermissionFlags.PROTECTION_GRANTED or PermissionFlags.ROLE or
- PermissionFlags.USER_SET
+ val oldFlags =
+ PermissionFlags.PROTECTION_GRANTED or PermissionFlags.ROLE or PermissionFlags.USER_SET
testEvaluatePermissionState(
oldFlags,
- PermissionInfo.PROTECTION_INTERNAL or PermissionInfo.PROTECTION_FLAG_APPOP
+ PermissionInfo.PROTECTION_INTERNAL or PermissionInfo.PROTECTION_FLAG_APPOP,
) {
val packageStateWithMissingPackage = mockPackageState(APP_ID_1, MISSING_ANDROID_PACKAGE)
addPackageState(packageStateWithMissingPackage)
@@ -138,11 +138,11 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = oldFlags
assertWithMessage(
- "After $action is called for a package that requests an internal permission" +
- " with missing android package and $oldFlags flag and the permission isAppOp," +
- " the actual permission flags $actualFlags should match the expected" +
- " flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests an internal permission" +
+ " with missing android package and $oldFlags flag and the permission isAppOp," +
+ " the actual permission flags $actualFlags should match the expected" +
+ " flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -152,7 +152,7 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val oldFlags = PermissionFlags.PROTECTION_GRANTED or PermissionFlags.RUNTIME_GRANTED
testEvaluatePermissionState(
oldFlags,
- PermissionInfo.PROTECTION_INTERNAL or PermissionInfo.PROTECTION_FLAG_DEVELOPMENT
+ PermissionInfo.PROTECTION_INTERNAL or PermissionInfo.PROTECTION_FLAG_DEVELOPMENT,
) {
val packageStateWithMissingPackage = mockPackageState(APP_ID_1, MISSING_ANDROID_PACKAGE)
addPackageState(packageStateWithMissingPackage)
@@ -161,22 +161,24 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = oldFlags
assertWithMessage(
- "After $action is called for a package that requests an internal permission" +
- " with missing android package and $oldFlags flag and permission isDevelopment," +
- " the actual permission flags $actualFlags should match the expected" +
- " flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests an internal permission" +
+ " with missing android package and $oldFlags flag and permission isDevelopment," +
+ " the actual permission flags $actualFlags should match the expected" +
+ " flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@Test
fun testEvaluatePermissionState_internalRolePermission_getsRoleAndRuntimeGrantedPreserved() {
- val oldFlags = PermissionFlags.PROTECTION_GRANTED or PermissionFlags.ROLE or
- PermissionFlags.RUNTIME_GRANTED
+ val oldFlags =
+ PermissionFlags.PROTECTION_GRANTED or
+ PermissionFlags.ROLE or
+ PermissionFlags.RUNTIME_GRANTED
testEvaluatePermissionState(
oldFlags,
- PermissionInfo.PROTECTION_INTERNAL or PermissionInfo.PROTECTION_FLAG_ROLE
+ PermissionInfo.PROTECTION_INTERNAL or PermissionInfo.PROTECTION_FLAG_ROLE,
) {
val packageStateWithMissingPackage = mockPackageState(APP_ID_1, MISSING_ANDROID_PACKAGE)
addPackageState(packageStateWithMissingPackage)
@@ -185,11 +187,11 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = oldFlags
assertWithMessage(
- "After $action is called for a package that requests an internal permission" +
- " with missing android package and $oldFlags flag and the permission isRole," +
- " the actual permission flags $actualFlags should match the expected" +
- " flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests an internal permission" +
+ " with missing android package and $oldFlags flag and the permission isRole," +
+ " the actual permission flags $actualFlags should match the expected" +
+ " flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -205,12 +207,10 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
isInstalledPackageProduct = true,
// To mock the return value of shouldGrantPrivilegedOrOemPermission()
isInstalledPackageVendor = true,
- isNewInstall = true
+ isNewInstall = true,
) {
- val platformPackage = mockPackageState(
- PLATFORM_APP_ID,
- mockAndroidPackage(PLATFORM_PACKAGE_NAME)
- )
+ val platformPackage =
+ mockPackageState(PLATFORM_APP_ID, mockAndroidPackage(PLATFORM_PACKAGE_NAME))
setupAllowlist(PACKAGE_NAME_1, false)
addPackageState(platformPackage)
}
@@ -218,10 +218,10 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = oldFlags
assertWithMessage(
- "After $action is called for a package that requests a signature privileged" +
- " permission that's not allowlisted, the actual permission" +
- " flags $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a signature privileged" +
+ " permission that's not allowlisted, the actual permission" +
+ " flags $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -237,12 +237,13 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
isInstalledPackageProduct = true,
isInstalledPackageSignatureMatching = true,
isInstalledPackageVendor = true,
- isNewInstall = true
+ isNewInstall = true,
) {
- val platformPackage = mockPackageState(
- PLATFORM_APP_ID,
- mockAndroidPackage(PLATFORM_PACKAGE_NAME, isSignatureMatching = true)
- )
+ val platformPackage =
+ mockPackageState(
+ PLATFORM_APP_ID,
+ mockAndroidPackage(PLATFORM_PACKAGE_NAME, isSignatureMatching = true),
+ )
setupAllowlist(PACKAGE_NAME_1, false)
addPackageState(platformPackage)
}
@@ -250,10 +251,10 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.PROTECTION_GRANTED
assertWithMessage(
- "After $action is called for a package that requests a signature" +
- " non-privileged permission, the actual permission" +
- " flags $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a signature" +
+ " non-privileged permission, the actual permission" +
+ " flags $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -267,12 +268,10 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
isInstalledPackageSystem = true,
isInstalledPackagePrivileged = true,
isInstalledPackageProduct = true,
- isNewInstall = true
+ isNewInstall = true,
) {
- val platformPackage = mockPackageState(
- PLATFORM_APP_ID,
- mockAndroidPackage(PLATFORM_PACKAGE_NAME)
- )
+ val platformPackage =
+ mockPackageState(PLATFORM_APP_ID, mockAndroidPackage(PLATFORM_PACKAGE_NAME))
setupAllowlist(PACKAGE_NAME_1, true)
addPackageState(platformPackage)
}
@@ -280,10 +279,10 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.PROTECTION_GRANTED
assertWithMessage(
- "After $action is called for a package that requests a signature privileged" +
- " permission that's allowlisted and should grant by protection flags, the actual" +
- " permission flags $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a signature privileged" +
+ " permission that's allowlisted and should grant by protection flags, the actual" +
+ " permission flags $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -291,32 +290,36 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
private fun setupAllowlist(
packageName: String,
allowlistState: Boolean,
- state: MutableAccessState = oldState
+ state: MutableAccessState = oldState,
) {
- state.mutateExternalState().setPrivilegedPermissionAllowlistPackages(
- MutableIndexedListSet<String>().apply { add(packageName) }
- )
- val mockAllowlist = mock<PermissionAllowlist> {
- whenever(
- getProductPrivilegedAppAllowlistState(packageName, PERMISSION_NAME_0)
- ).thenReturn(allowlistState)
- }
+ state
+ .mutateExternalState()
+ .setPrivilegedPermissionAllowlistPackages(
+ MutableIndexedListSet<String>().apply { add(packageName) }
+ )
+ val mockAllowlist =
+ mock<PermissionAllowlist> {
+ whenever(getProductPrivilegedAppAllowlistState(packageName, PERMISSION_NAME_0))
+ .thenReturn(allowlistState)
+ }
state.mutateExternalState().setPermissionAllowlist(mockAllowlist)
}
@Test
fun testEvaluatePermissionState_nonRuntimeFlagsOnRuntimePermissions_getsCleared() {
- val oldFlags = PermissionFlags.INSTALL_GRANTED or PermissionFlags.PREGRANT or
- PermissionFlags.RUNTIME_GRANTED
+ val oldFlags =
+ PermissionFlags.INSTALL_GRANTED or
+ PermissionFlags.PREGRANT or
+ PermissionFlags.RUNTIME_GRANTED
testEvaluatePermissionState(oldFlags, PermissionInfo.PROTECTION_DANGEROUS) {}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.PREGRANT or PermissionFlags.RUNTIME_GRANTED
assertWithMessage(
- "After $action is called for a package that requests a runtime permission" +
- " with existing $oldFlags flags, the actual permission flags $actualFlags should" +
- " match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime permission" +
+ " with existing $oldFlags flags, the actual permission flags $actualFlags should" +
+ " match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -328,16 +331,16 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
oldFlags,
PermissionInfo.PROTECTION_DANGEROUS,
installedPackageTargetSdkVersion = Build.VERSION_CODES.LOLLIPOP,
- isNewInstall = true
+ isNewInstall = true,
) {}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.LEGACY_GRANTED or PermissionFlags.IMPLICIT
assertWithMessage(
- "After $action is called for a package that requests a runtime permission" +
- " with no existing flags in pre M, actual permission flags $actualFlags should" +
- " match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime permission" +
+ " with no existing flags in pre M, actual permission flags $actualFlags should" +
+ " match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -348,20 +351,22 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
testEvaluatePermissionState(
oldFlags,
PermissionInfo.PROTECTION_DANGEROUS,
- installedPackageTargetSdkVersion = Build.VERSION_CODES.LOLLIPOP
+ installedPackageTargetSdkVersion = Build.VERSION_CODES.LOLLIPOP,
) {
setPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0, oldFlags)
}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
- val expectedNewFlags = PermissionFlags.LEGACY_GRANTED or PermissionFlags.USER_FIXED or
- PermissionFlags.APP_OP_REVOKED
+ val expectedNewFlags =
+ PermissionFlags.LEGACY_GRANTED or
+ PermissionFlags.USER_FIXED or
+ PermissionFlags.APP_OP_REVOKED
assertWithMessage(
- "After $action is called for a package that requests a runtime permission" +
- " that should be LEGACY_GRANTED or IMPLICIT_GRANTED that was previously revoked," +
- " the actual permission flags $actualFlags should" +
- " match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime permission" +
+ " that should be LEGACY_GRANTED or IMPLICIT_GRANTED that was previously revoked," +
+ " the actual permission flags $actualFlags should" +
+ " match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -374,11 +379,11 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = 0
assertWithMessage(
- "After $action is called for a package that requests a runtime permission" +
- " that used to require user review, the user review requirement should be removed" +
- " if it's upgraded to post M. The actual permission flags $actualFlags should" +
- " match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime permission" +
+ " that used to require user review, the user review requirement should be removed" +
+ " if it's upgraded to post M. The actual permission flags $actualFlags should" +
+ " match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -391,11 +396,11 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.RUNTIME_GRANTED
assertWithMessage(
- "After $action is called for a package that requests a runtime permission" +
- " that was already reviewed by the user, the permission should be RUNTIME_GRANTED" +
- " if it's upgraded to post M. The actual permission flags $actualFlags should" +
- " match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime permission" +
+ " that was already reviewed by the user, the permission should be RUNTIME_GRANTED" +
+ " if it's upgraded to post M. The actual permission flags $actualFlags should" +
+ " match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -407,22 +412,19 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
oldFlags,
PermissionInfo.PROTECTION_DANGEROUS,
permissionName = PERMISSION_POST_NOTIFICATIONS,
- isNewInstall = true
+ isNewInstall = true,
) {
oldState.mutateExternalState().setLeanback(true)
}
- val actualFlags = getPermissionFlags(
- APP_ID_1,
- getUserIdEvaluated(),
- PERMISSION_POST_NOTIFICATIONS
- )
+ val actualFlags =
+ getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_POST_NOTIFICATIONS)
val expectedNewFlags = PermissionFlags.IMPLICIT_GRANTED
assertWithMessage(
- "After $action is called for a package that requests a runtime notification" +
- " permission when isLeanback, the actual permission flags $actualFlags should" +
- " match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime notification" +
+ " permission when isLeanback, the actual permission flags $actualFlags should" +
+ " match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -434,65 +436,73 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
oldFlags,
PermissionInfo.PROTECTION_DANGEROUS,
implicitPermissions = setOf(PERMISSION_NAME_0),
- isNewInstall = true
+ isNewInstall = true,
) {
- oldState.mutateExternalState().setImplicitToSourcePermissions(
- MutableIndexedMap<String, IndexedListSet<String>>().apply {
- put(PERMISSION_NAME_0, MutableIndexedListSet<String>().apply {
- add(PERMISSION_NAME_1)
- })
- }
- )
+ oldState
+ .mutateExternalState()
+ .setImplicitToSourcePermissions(
+ MutableIndexedMap<String, IndexedListSet<String>>().apply {
+ put(
+ PERMISSION_NAME_0,
+ MutableIndexedListSet<String>().apply { add(PERMISSION_NAME_1) },
+ )
+ }
+ )
addPermission(mockParsedPermission(PERMISSION_NAME_1, PACKAGE_NAME_0))
}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.IMPLICIT_GRANTED or PermissionFlags.IMPLICIT
assertWithMessage(
- "After $action is called for a package that requests a runtime implicit" +
- " permission that's source from a non-runtime permission, the actual permission" +
- " flags $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime implicit" +
+ " permission that's source from a non-runtime permission, the actual permission" +
+ " flags $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
/**
* For a legacy granted or implicit permission during the app upgrade, when the permission
- * should no longer be legacy or implicit granted, we want to remove the APP_OP_REVOKED flag
- * so that the app can request the permission.
+ * should no longer be legacy or implicit granted, we want to remove the APP_OP_REVOKED flag so
+ * that the app can request the permission.
*/
@Test
fun testEvaluatePermissionState_noLongerLegacyOrImplicitGranted_canBeRequested() {
- val oldFlags = PermissionFlags.LEGACY_GRANTED or PermissionFlags.APP_OP_REVOKED or
- PermissionFlags.RUNTIME_GRANTED
+ val oldFlags =
+ PermissionFlags.LEGACY_GRANTED or
+ PermissionFlags.APP_OP_REVOKED or
+ PermissionFlags.RUNTIME_GRANTED
testEvaluatePermissionState(oldFlags, PermissionInfo.PROTECTION_DANGEROUS) {}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = 0
assertWithMessage(
- "After $action is called for a package that requests a runtime permission" +
- " that is no longer LEGACY_GRANTED or IMPLICIT_GRANTED, the actual permission" +
- " flags $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime permission" +
+ " that is no longer LEGACY_GRANTED or IMPLICIT_GRANTED, the actual permission" +
+ " flags $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@Test
fun testEvaluatePermissionState_noLongerImplicit_getsRuntimeAndImplicitFlagsRemoved() {
- val oldFlags = PermissionFlags.IMPLICIT or PermissionFlags.RUNTIME_GRANTED or
- PermissionFlags.USER_SET or PermissionFlags.USER_FIXED
+ val oldFlags =
+ PermissionFlags.IMPLICIT or
+ PermissionFlags.RUNTIME_GRANTED or
+ PermissionFlags.USER_SET or
+ PermissionFlags.USER_FIXED
testEvaluatePermissionState(oldFlags, PermissionInfo.PROTECTION_DANGEROUS) {}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = 0
assertWithMessage(
- "After $action is called for a package that requests a runtime permission" +
- " that is no longer implicit and we shouldn't retain as nearby device" +
- " permissions, the actual permission flags $actualFlags should match the expected" +
- " flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime permission" +
+ " that is no longer implicit and we shouldn't retain as nearby device" +
+ " permissions, the actual permission flags $actualFlags should match the expected" +
+ " flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -504,48 +514,45 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
oldFlags,
PermissionInfo.PROTECTION_DANGEROUS,
permissionName = PERMISSION_BLUETOOTH_CONNECT,
- requestedPermissions = setOf(
- PERMISSION_BLUETOOTH_CONNECT,
- PERMISSION_ACCESS_BACKGROUND_LOCATION
- )
+ requestedPermissions =
+ setOf(PERMISSION_BLUETOOTH_CONNECT, PERMISSION_ACCESS_BACKGROUND_LOCATION),
) {
setPermissionFlags(
APP_ID_1,
getUserIdEvaluated(),
PERMISSION_ACCESS_BACKGROUND_LOCATION,
- PermissionFlags.RUNTIME_GRANTED
+ PermissionFlags.RUNTIME_GRANTED,
)
}
- val actualFlags = getPermissionFlags(
- APP_ID_1,
- getUserIdEvaluated(),
- PERMISSION_BLUETOOTH_CONNECT
- )
+ val actualFlags =
+ getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_BLUETOOTH_CONNECT)
val expectedNewFlags = PermissionFlags.RUNTIME_GRANTED
assertWithMessage(
- "After $action is called for a package that requests a runtime nearby device" +
- " permission that was granted by implicit, the actual permission flags" +
- " $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime nearby device" +
+ " permission that was granted by implicit, the actual permission flags" +
+ " $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@Test
fun testEvaluatePermissionState_noLongerImplicitSystemOrPolicyFixedWasGranted_runtimeGranted() {
- val oldFlags = PermissionFlags.IMPLICIT_GRANTED or PermissionFlags.IMPLICIT or
- PermissionFlags.SYSTEM_FIXED
+ val oldFlags =
+ PermissionFlags.IMPLICIT_GRANTED or
+ PermissionFlags.IMPLICIT or
+ PermissionFlags.SYSTEM_FIXED
testEvaluatePermissionState(oldFlags, PermissionInfo.PROTECTION_DANGEROUS) {}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.RUNTIME_GRANTED or PermissionFlags.SYSTEM_FIXED
assertWithMessage(
- "After $action is called for a package that requests a runtime permission" +
- " that was granted and is no longer implicit and is SYSTEM_FIXED or POLICY_FIXED," +
- " the actual permission flags $actualFlags should match the expected" +
- " flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime permission" +
+ " that was granted and is no longer implicit and is SYSTEM_FIXED or POLICY_FIXED," +
+ " the actual permission flags $actualFlags should match the expected" +
+ " flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -556,16 +563,16 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
testEvaluatePermissionState(
oldFlags,
PermissionInfo.PROTECTION_DANGEROUS,
- permissionInfoFlags = PermissionInfo.FLAG_HARD_RESTRICTED
+ permissionInfoFlags = PermissionInfo.FLAG_HARD_RESTRICTED,
) {}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = oldFlags
assertWithMessage(
- "After $action is called for a package that requests a runtime hard" +
- " restricted permission that is not exempted, the actual permission flags" +
- " $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime hard" +
+ " restricted permission that is not exempted, the actual permission flags" +
+ " $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -576,16 +583,16 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
testEvaluatePermissionState(
oldFlags,
PermissionInfo.PROTECTION_DANGEROUS,
- permissionInfoFlags = PermissionInfo.FLAG_SOFT_RESTRICTED
+ permissionInfoFlags = PermissionInfo.FLAG_SOFT_RESTRICTED,
) {}
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.UPGRADE_EXEMPT
assertWithMessage(
- "After $action is called for a package that requests a runtime soft" +
- " restricted permission that is exempted, the actual permission flags" +
- " $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a runtime soft" +
+ " restricted permission that is exempted, the actual permission flags" +
+ " $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -595,18 +602,20 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val oldImplicitPermissionFlags = PermissionFlags.USER_FIXED
testInheritImplicitPermissionStates(
implicitPermissionFlags = oldImplicitPermissionFlags,
- isNewInstallAndNewPermission = false
+ isNewInstallAndNewPermission = false,
)
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
- val expectedNewFlags = oldImplicitPermissionFlags or PermissionFlags.IMPLICIT_GRANTED or
- PermissionFlags.APP_OP_REVOKED
+ val expectedNewFlags =
+ oldImplicitPermissionFlags or
+ PermissionFlags.IMPLICIT_GRANTED or
+ PermissionFlags.APP_OP_REVOKED
assertWithMessage(
- "After $action is called for a package that requests a permission that is" +
- " implicit, existing and runtime, it should not inherit the runtime flags from" +
- " the source permission. Hence the actual permission flags $actualFlags should" +
- " match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a permission that is" +
+ " implicit, existing and runtime, it should not inherit the runtime flags from" +
+ " the source permission. Hence the actual permission flags $actualFlags should" +
+ " match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -620,11 +629,11 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = PermissionFlags.INSTALL_GRANTED
assertWithMessage(
- "After $action is called for a package that requests a permission that is" +
- " implicit, new and non-runtime, it should not inherit the runtime flags from" +
- " the source permission. Hence the actual permission flags $actualFlags should" +
- " match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a permission that is" +
+ " implicit, new and non-runtime, it should not inherit the runtime flags from" +
+ " the source permission. Hence the actual permission flags $actualFlags should" +
+ " match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -635,14 +644,14 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
testInheritImplicitPermissionStates(sourceRuntimeFlags = sourceRuntimeFlags)
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
- val expectedNewFlags = sourceRuntimeFlags or PermissionFlags.IMPLICIT_GRANTED or
- PermissionFlags.IMPLICIT
+ val expectedNewFlags =
+ sourceRuntimeFlags or PermissionFlags.IMPLICIT_GRANTED or PermissionFlags.IMPLICIT
assertWithMessage(
- "After $action is called for a package that requests a permission that is" +
- " implicit, new and runtime, it should inherit the runtime flags from" +
- " the source permission. Hence the actual permission flags $actualFlags should" +
- " match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a permission that is" +
+ " implicit, new and runtime, it should inherit the runtime flags from" +
+ " the source permission. Hence the actual permission flags $actualFlags should" +
+ " match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -653,17 +662,17 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
testInheritImplicitPermissionStates(
implicitPermissionFlags = PermissionFlags.POLICY_FIXED,
sourceRuntimeFlags = sourceRuntimeFlags,
- isAnySourcePermissionNonRuntime = false
+ isAnySourcePermissionNonRuntime = false,
)
val actualFlags = getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_NAME_0)
val expectedNewFlags = sourceRuntimeFlags or PermissionFlags.IMPLICIT
assertWithMessage(
- "After $action is called for a package that requests a permission that is" +
- " implicit, existing, runtime and revoked, it should only inherit runtime flags" +
- " from source permission. Hence the actual permission flags $actualFlags should" +
- " match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a permission that is" +
+ " implicit, existing, runtime and revoked, it should only inherit runtime flags" +
+ " from source permission. Hence the actual permission flags $actualFlags should" +
+ " match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -678,21 +687,18 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
val sourceRuntimeFlags = PermissionFlags.RUNTIME_GRANTED or PermissionFlags.USER_SET
testInheritImplicitPermissionStates(
implicitPermissionName = PERMISSION_ACCESS_MEDIA_LOCATION,
- sourceRuntimeFlags = sourceRuntimeFlags
+ sourceRuntimeFlags = sourceRuntimeFlags,
)
- val actualFlags = getPermissionFlags(
- APP_ID_1,
- getUserIdEvaluated(),
- PERMISSION_ACCESS_MEDIA_LOCATION
- )
+ val actualFlags =
+ getPermissionFlags(APP_ID_1, getUserIdEvaluated(), PERMISSION_ACCESS_MEDIA_LOCATION)
val expectedNewFlags = sourceRuntimeFlags or PermissionFlags.IMPLICIT_GRANTED
assertWithMessage(
- "After $action is called for a package that requests a media permission that" +
- " is implicit, new and runtime, it should inherit the runtime flags from" +
- " the source permission and have the IMPLICIT flag removed. Hence the actual" +
- " permission flags $actualFlags should match the expected flags $expectedNewFlags"
- )
+ "After $action is called for a package that requests a media permission that" +
+ " is implicit, new and runtime, it should inherit the runtime flags from" +
+ " the source permission and have the IMPLICIT flag removed. Hence the actual" +
+ " permission flags $actualFlags should match the expected flags $expectedNewFlags"
+ )
.that(actualFlags)
.isEqualTo(expectedNewFlags)
}
@@ -703,57 +709,65 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
implicitPermissionProtectionLevel: Int = PermissionInfo.PROTECTION_DANGEROUS,
sourceRuntimeFlags: Int = PermissionFlags.RUNTIME_GRANTED or PermissionFlags.USER_SET,
isAnySourcePermissionNonRuntime: Boolean = true,
- isNewInstallAndNewPermission: Boolean = true
+ isNewInstallAndNewPermission: Boolean = true,
) {
val userId = getUserIdEvaluated()
- val implicitPermission = mockParsedPermission(
- implicitPermissionName,
- PACKAGE_NAME_0,
- protectionLevel = implicitPermissionProtectionLevel,
- )
+ val implicitPermission =
+ mockParsedPermission(
+ implicitPermissionName,
+ PACKAGE_NAME_0,
+ protectionLevel = implicitPermissionProtectionLevel,
+ )
// For source from non-runtime in order to grant by implicit
- val sourcePermission1 = mockParsedPermission(
- PERMISSION_NAME_1,
- PACKAGE_NAME_0,
- protectionLevel = if (isAnySourcePermissionNonRuntime) {
- PermissionInfo.PROTECTION_NORMAL
- } else {
- PermissionInfo.PROTECTION_DANGEROUS
- }
- )
+ val sourcePermission1 =
+ mockParsedPermission(
+ PERMISSION_NAME_1,
+ PACKAGE_NAME_0,
+ protectionLevel =
+ if (isAnySourcePermissionNonRuntime) {
+ PermissionInfo.PROTECTION_NORMAL
+ } else {
+ PermissionInfo.PROTECTION_DANGEROUS
+ },
+ )
// For inheriting runtime flags
- val sourcePermission2 = mockParsedPermission(
- PERMISSION_NAME_2,
- PACKAGE_NAME_0,
- protectionLevel = PermissionInfo.PROTECTION_DANGEROUS,
- )
- val permissionOwnerPackageState = mockPackageState(
- APP_ID_0,
- mockAndroidPackage(
+ val sourcePermission2 =
+ mockParsedPermission(
+ PERMISSION_NAME_2,
PACKAGE_NAME_0,
- permissions = listOf(implicitPermission, sourcePermission1, sourcePermission2)
+ protectionLevel = PermissionInfo.PROTECTION_DANGEROUS,
)
- )
- val installedPackageState = mockPackageState(
- APP_ID_1,
- mockAndroidPackage(
- PACKAGE_NAME_1,
- requestedPermissions = setOf(
- implicitPermissionName,
- PERMISSION_NAME_1,
- PERMISSION_NAME_2
+ val permissionOwnerPackageState =
+ mockPackageState(
+ APP_ID_0,
+ mockAndroidPackage(
+ PACKAGE_NAME_0,
+ permissions = listOf(implicitPermission, sourcePermission1, sourcePermission2),
),
- implicitPermissions = setOf(implicitPermissionName)
)
- )
- oldState.mutateExternalState().setImplicitToSourcePermissions(
- MutableIndexedMap<String, IndexedListSet<String>>().apply {
- put(implicitPermissionName, MutableIndexedListSet<String>().apply {
- add(PERMISSION_NAME_1)
- add(PERMISSION_NAME_2)
- })
- }
- )
+ val installedPackageState =
+ mockPackageState(
+ APP_ID_1,
+ mockAndroidPackage(
+ PACKAGE_NAME_1,
+ requestedPermissions =
+ setOf(implicitPermissionName, PERMISSION_NAME_1, PERMISSION_NAME_2),
+ implicitPermissions = setOf(implicitPermissionName),
+ ),
+ )
+ oldState
+ .mutateExternalState()
+ .setImplicitToSourcePermissions(
+ MutableIndexedMap<String, IndexedListSet<String>>().apply {
+ put(
+ implicitPermissionName,
+ MutableIndexedListSet<String>().apply {
+ add(PERMISSION_NAME_1)
+ add(PERMISSION_NAME_2)
+ },
+ )
+ }
+ )
addPackageState(permissionOwnerPackageState)
addPermission(implicitPermission)
addPermission(sourcePermission1)
@@ -772,7 +786,7 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
userId,
implicitPermissionName,
implicitPermissionFlags,
- newState
+ newState,
)
}
testAction(installedPackageState)
@@ -781,18 +795,17 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
/**
* Setup simple package states for testing evaluatePermissionState().
- * permissionOwnerPackageState is definer of permissionName with APP_ID_0.
- * installedPackageState is the installed package that requests permissionName with APP_ID_1.
+ * permissionOwnerPackageState is definer of permissionName with APP_ID_0. installedPackageState
+ * is the installed package that requests permissionName with APP_ID_1.
*
* @param oldFlags the existing permission flags for APP_ID_1, userId, permissionName
* @param protectionLevel the protectionLevel for the permission
* @param permissionName the name of the permission (1) being defined (2) of the oldFlags, and
- * (3) requested by installedPackageState
+ * (3) requested by installedPackageState
* @param requestedPermissions the permissions requested by installedPackageState
* @param implicitPermissions the implicit permissions of installedPackageState
* @param permissionInfoFlags the flags for the permission itself
* @param isInstalledPackageSystem whether installedPackageState is a system package
- *
* @return installedPackageState
*/
private fun testEvaluatePermissionState(
@@ -809,33 +822,36 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
isInstalledPackageVendor: Boolean = false,
installedPackageTargetSdkVersion: Int = Build.VERSION_CODES.UPSIDE_DOWN_CAKE,
isNewInstall: Boolean = false,
- additionalSetup: () -> Unit
+ additionalSetup: () -> Unit,
) {
val userId = getUserIdEvaluated()
- val parsedPermission = mockParsedPermission(
- permissionName,
- PACKAGE_NAME_0,
- protectionLevel = protectionLevel,
- flags = permissionInfoFlags
- )
- val permissionOwnerPackageState = mockPackageState(
- APP_ID_0,
- mockAndroidPackage(PACKAGE_NAME_0, permissions = listOf(parsedPermission))
- )
- val installedPackageState = mockPackageState(
- APP_ID_1,
- mockAndroidPackage(
- PACKAGE_NAME_1,
- requestedPermissions = requestedPermissions,
- implicitPermissions = implicitPermissions,
- targetSdkVersion = installedPackageTargetSdkVersion,
- isSignatureMatching = isInstalledPackageSignatureMatching
- ),
- isSystem = isInstalledPackageSystem,
- isPrivileged = isInstalledPackagePrivileged,
- isProduct = isInstalledPackageProduct,
- isVendor = isInstalledPackageVendor
- )
+ val parsedPermission =
+ mockParsedPermission(
+ permissionName,
+ PACKAGE_NAME_0,
+ protectionLevel = protectionLevel,
+ flags = permissionInfoFlags,
+ )
+ val permissionOwnerPackageState =
+ mockPackageState(
+ APP_ID_0,
+ mockAndroidPackage(PACKAGE_NAME_0, permissions = listOf(parsedPermission)),
+ )
+ val installedPackageState =
+ mockPackageState(
+ APP_ID_1,
+ mockAndroidPackage(
+ PACKAGE_NAME_1,
+ requestedPermissions = requestedPermissions,
+ implicitPermissions = implicitPermissions,
+ targetSdkVersion = installedPackageTargetSdkVersion,
+ isSignatureMatching = isInstalledPackageSignatureMatching,
+ ),
+ isSystem = isInstalledPackageSystem,
+ isPrivileged = isInstalledPackagePrivileged,
+ isProduct = isInstalledPackageProduct,
+ isVendor = isInstalledPackageVendor,
+ )
addPackageState(permissionOwnerPackageState)
if (!isNewInstall) {
addPackageState(installedPackageState)
@@ -854,26 +870,29 @@ class AppIdPermissionPolicyPermissionStatesTest : BasePermissionPolicyTest() {
}
}
- private fun getUserIdEvaluated(): Int = when (action) {
- Action.ON_USER_ADDED -> USER_ID_NEW
- Action.ON_STORAGE_VOLUME_ADDED, Action.ON_PACKAGE_ADDED -> USER_ID_0
- }
+ private fun getUserIdEvaluated(): Int =
+ when (action) {
+ Action.ON_USER_ADDED -> USER_ID_NEW
+ Action.ON_STORAGE_VOLUME_ADDED,
+ Action.ON_PACKAGE_ADDED -> USER_ID_0
+ }
private fun MutateStateScope.testAction(packageState: PackageState) {
with(appIdPermissionPolicy) {
when (action) {
Action.ON_USER_ADDED -> onUserAdded(getUserIdEvaluated())
- Action.ON_STORAGE_VOLUME_ADDED -> onStorageVolumeMounted(
- null,
- listOf(packageState.packageName),
- true
- )
+ Action.ON_STORAGE_VOLUME_ADDED ->
+ onStorageVolumeMounted(null, listOf(packageState.packageName), true)
Action.ON_PACKAGE_ADDED -> onPackageAdded(packageState)
}
}
}
- enum class Action { ON_USER_ADDED, ON_STORAGE_VOLUME_ADDED, ON_PACKAGE_ADDED }
+ enum class Action {
+ ON_USER_ADDED,
+ ON_STORAGE_VOLUME_ADDED,
+ ON_PACKAGE_ADDED,
+ }
companion object {
@Parameterized.Parameters(name = "{0}")
diff --git a/services/tests/PermissionServiceMockingTests/src/com/android/server/permission/test/BasePermissionPolicyTest.kt b/services/tests/PermissionServiceMockingTests/src/com/android/server/permission/test/BasePermissionPolicyTest.kt
index 7b3f21603c0a..207820cc3135 100644
--- a/services/tests/PermissionServiceMockingTests/src/com/android/server/permission/test/BasePermissionPolicyTest.kt
+++ b/services/tests/PermissionServiceMockingTests/src/com/android/server/permission/test/BasePermissionPolicyTest.kt
@@ -49,32 +49,24 @@ import org.junit.Rule
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.anyLong
-/**
- * Mocking unit test for AppIdPermissionPolicy.
- */
+/** Mocking unit test for AppIdPermissionPolicy. */
@RunWith(AndroidJUnit4::class)
abstract class BasePermissionPolicyTest {
protected lateinit var oldState: MutableAccessState
protected lateinit var newState: MutableAccessState
- protected val defaultPermissionGroup = mockParsedPermissionGroup(
- PERMISSION_GROUP_NAME_0,
- PACKAGE_NAME_0
- )
- protected val defaultPermissionTree = mockParsedPermission(
- PERMISSION_TREE_NAME,
- PACKAGE_NAME_0,
- isTree = true
- )
+ protected val defaultPermissionGroup =
+ mockParsedPermissionGroup(PERMISSION_GROUP_NAME_0, PACKAGE_NAME_0)
+ protected val defaultPermissionTree =
+ mockParsedPermission(PERMISSION_TREE_NAME, PACKAGE_NAME_0, isTree = true)
protected val defaultPermission = mockParsedPermission(PERMISSION_NAME_0, PACKAGE_NAME_0)
protected val appIdPermissionPolicy = AppIdPermissionPolicy()
@Rule
@JvmField
- val extendedMockitoRule = ExtendedMockitoRule.Builder(this)
- .spyStatic(PackageInfoUtils::class.java)
- .build()
+ val extendedMockitoRule =
+ ExtendedMockitoRule.Builder(this).spyStatic(PackageInfoUtils::class.java).build()
@Before
fun baseSetUp() {
@@ -93,65 +85,76 @@ abstract class BasePermissionPolicyTest {
private fun mockPackageInfoUtilsGeneratePermissionInfo() {
wheneverStatic {
- PackageInfoUtils.generatePermissionInfo(any(ParsedPermission::class.java), anyLong())
- }.thenAnswer { invocation ->
- val parsedPermission = invocation.getArgument<ParsedPermission>(0)
- val generateFlags = invocation.getArgument<Long>(1)
- PermissionInfo(parsedPermission.backgroundPermission).apply {
- name = parsedPermission.name
- packageName = parsedPermission.packageName
- metaData = if (generateFlags.toInt().hasBits(PackageManager.GET_META_DATA)) {
- parsedPermission.metaData
- } else {
- null
+ PackageInfoUtils.generatePermissionInfo(
+ any(ParsedPermission::class.java),
+ anyLong(),
+ )
+ }
+ .thenAnswer { invocation ->
+ val parsedPermission = invocation.getArgument<ParsedPermission>(0)
+ val generateFlags = invocation.getArgument<Long>(1)
+ PermissionInfo(parsedPermission.backgroundPermission).apply {
+ name = parsedPermission.name
+ packageName = parsedPermission.packageName
+ metaData =
+ if (generateFlags.toInt().hasBits(PackageManager.GET_META_DATA)) {
+ parsedPermission.metaData
+ } else {
+ null
+ }
+ @Suppress("DEPRECATION")
+ protectionLevel = parsedPermission.protectionLevel
+ group = parsedPermission.group
+ flags = parsedPermission.flags
}
- @Suppress("DEPRECATION")
- protectionLevel = parsedPermission.protectionLevel
- group = parsedPermission.group
- flags = parsedPermission.flags
}
- }
}
private fun mockPackageInfoUtilsGeneratePermissionGroupInfo() {
wheneverStatic {
- PackageInfoUtils.generatePermissionGroupInfo(
- any(ParsedPermissionGroup::class.java),
- anyLong()
- )
- }.thenAnswer { invocation ->
- val parsedPermissionGroup = invocation.getArgument<ParsedPermissionGroup>(0)
- val generateFlags = invocation.getArgument<Long>(1)
- @Suppress("DEPRECATION")
- PermissionGroupInfo().apply {
- name = parsedPermissionGroup.name
- packageName = parsedPermissionGroup.packageName
- metaData = if (generateFlags.toInt().hasBits(PackageManager.GET_META_DATA)) {
- parsedPermissionGroup.metaData
- } else {
- null
+ PackageInfoUtils.generatePermissionGroupInfo(
+ any(ParsedPermissionGroup::class.java),
+ anyLong(),
+ )
+ }
+ .thenAnswer { invocation ->
+ val parsedPermissionGroup = invocation.getArgument<ParsedPermissionGroup>(0)
+ val generateFlags = invocation.getArgument<Long>(1)
+ @Suppress("DEPRECATION")
+ PermissionGroupInfo().apply {
+ name = parsedPermissionGroup.name
+ packageName = parsedPermissionGroup.packageName
+ metaData =
+ if (generateFlags.toInt().hasBits(PackageManager.GET_META_DATA)) {
+ parsedPermissionGroup.metaData
+ } else {
+ null
+ }
+ flags = parsedPermissionGroup.flags
}
- flags = parsedPermissionGroup.flags
}
- }
}
- /**
- * Mock an AndroidPackage with PACKAGE_NAME_0, PERMISSION_NAME_0 and PERMISSION_GROUP_NAME_0
- */
+ /** Mock an AndroidPackage with PACKAGE_NAME_0, PERMISSION_NAME_0 and PERMISSION_GROUP_NAME_0 */
protected fun mockSimpleAndroidPackage(): AndroidPackage =
mockAndroidPackage(
PACKAGE_NAME_0,
permissionGroups = listOf(defaultPermissionGroup),
- permissions = listOf(defaultPermissionTree, defaultPermission)
+ permissions = listOf(defaultPermissionTree, defaultPermission),
)
protected fun createSimplePermission(isTree: Boolean = false): Permission {
- val parsedPermission = if (isTree) { defaultPermissionTree } else { defaultPermission }
- val permissionInfo = PackageInfoUtils.generatePermissionInfo(
- parsedPermission,
- PackageManager.GET_META_DATA.toLong()
- )!!
+ val parsedPermission =
+ if (isTree) {
+ defaultPermissionTree
+ } else {
+ defaultPermission
+ }
+ val permissionInfo =
+ PackageInfoUtils.generatePermissionInfo(
+ parsedPermission,
+ PackageManager.GET_META_DATA.toLong(),
+ )!!
return Permission(permissionInfo, true, Permission.TYPE_MANIFEST, APP_ID_0)
}
@@ -164,13 +167,12 @@ abstract class BasePermissionPolicyTest {
appId: Int,
packageName: String,
isSystem: Boolean = false,
- ): PackageState =
- mock {
- whenever(this.appId).thenReturn(appId)
- whenever(this.packageName).thenReturn(packageName)
- whenever(androidPackage).thenReturn(null)
- whenever(this.isSystem).thenReturn(isSystem)
- }
+ ): PackageState = mock {
+ whenever(this.appId).thenReturn(appId)
+ whenever(this.packageName).thenReturn(packageName)
+ whenever(androidPackage).thenReturn(null)
+ whenever(this.isSystem).thenReturn(isSystem)
+ }
protected fun mockPackageState(
appId: Int,
@@ -179,22 +181,22 @@ abstract class BasePermissionPolicyTest {
isPrivileged: Boolean = false,
isProduct: Boolean = false,
isInstantApp: Boolean = false,
- isVendor: Boolean = false
- ): PackageState =
- mock {
- whenever(this.appId).thenReturn(appId)
- whenever(this.androidPackage).thenReturn(androidPackage)
- val packageName = androidPackage.packageName
- whenever(this.packageName).thenReturn(packageName)
- whenever(this.isSystem).thenReturn(isSystem)
- whenever(this.isPrivileged).thenReturn(isPrivileged)
- whenever(this.isProduct).thenReturn(isProduct)
- whenever(this.isVendor).thenReturn(isVendor)
- val userStates = SparseArray<PackageUserState>().apply {
+ isVendor: Boolean = false,
+ ): PackageState = mock {
+ whenever(this.appId).thenReturn(appId)
+ whenever(this.androidPackage).thenReturn(androidPackage)
+ val packageName = androidPackage.packageName
+ whenever(this.packageName).thenReturn(packageName)
+ whenever(this.isSystem).thenReturn(isSystem)
+ whenever(this.isPrivileged).thenReturn(isPrivileged)
+ whenever(this.isProduct).thenReturn(isProduct)
+ whenever(this.isVendor).thenReturn(isVendor)
+ val userStates =
+ SparseArray<PackageUserState>().apply {
put(USER_ID_0, mock { whenever(this.isInstantApp).thenReturn(isInstantApp) })
}
- whenever(this.userStates).thenReturn(userStates)
- }
+ whenever(this.userStates).thenReturn(userStates)
+ }
protected fun mockAndroidPackage(
packageName: String,
@@ -205,28 +207,26 @@ abstract class BasePermissionPolicyTest {
requestedPermissions: Set<String> = emptySet(),
permissionGroups: List<ParsedPermissionGroup> = emptyList(),
permissions: List<ParsedPermission> = emptyList(),
- isSignatureMatching: Boolean = false
- ): AndroidPackage =
- mock {
- whenever(this.packageName).thenReturn(packageName)
- whenever(this.targetSdkVersion).thenReturn(targetSdkVersion)
- whenever(this.isRequestLegacyExternalStorage).thenReturn(isRequestLegacyExternalStorage)
- whenever(this.adoptPermissions).thenReturn(adoptPermissions)
- whenever(this.implicitPermissions).thenReturn(implicitPermissions)
- whenever(this.requestedPermissions).thenReturn(requestedPermissions)
- whenever(this.permissionGroups).thenReturn(permissionGroups)
- whenever(this.permissions).thenReturn(permissions)
- val signingDetails = mock<SigningDetails> {
- whenever(
- hasCommonSignerWithCapability(any(), any())
- ).thenReturn(isSignatureMatching)
+ isSignatureMatching: Boolean = false,
+ ): AndroidPackage = mock {
+ whenever(this.packageName).thenReturn(packageName)
+ whenever(this.targetSdkVersion).thenReturn(targetSdkVersion)
+ whenever(this.isRequestLegacyExternalStorage).thenReturn(isRequestLegacyExternalStorage)
+ whenever(this.adoptPermissions).thenReturn(adoptPermissions)
+ whenever(this.implicitPermissions).thenReturn(implicitPermissions)
+ whenever(this.requestedPermissions).thenReturn(requestedPermissions)
+ whenever(this.permissionGroups).thenReturn(permissionGroups)
+ whenever(this.permissions).thenReturn(permissions)
+ val signingDetails =
+ mock<SigningDetails> {
+ whenever(hasCommonSignerWithCapability(any(), any()))
+ .thenReturn(isSignatureMatching)
whenever(hasAncestorOrSelf(any())).thenReturn(isSignatureMatching)
- whenever(
- checkCapability(any<SigningDetails>(), any())
- ).thenReturn(isSignatureMatching)
+ whenever(checkCapability(any<SigningDetails>(), any()))
+ .thenReturn(isSignatureMatching)
}
- whenever(this.signingDetails).thenReturn(signingDetails)
- }
+ whenever(this.signingDetails).thenReturn(signingDetails)
+ }
protected fun mockParsedPermission(
permissionName: String,
@@ -235,72 +235,74 @@ abstract class BasePermissionPolicyTest {
group: String? = null,
protectionLevel: Int = PermissionInfo.PROTECTION_NORMAL,
flags: Int = 0,
- isTree: Boolean = false
- ): ParsedPermission =
- mock {
- whenever(name).thenReturn(permissionName)
- whenever(this.packageName).thenReturn(packageName)
- whenever(metaData).thenReturn(Bundle())
- whenever(this.backgroundPermission).thenReturn(backgroundPermission)
- whenever(this.group).thenReturn(group)
- whenever(this.protectionLevel).thenReturn(protectionLevel)
- whenever(this.flags).thenReturn(flags)
- whenever(this.isTree).thenReturn(isTree)
- }
+ isTree: Boolean = false,
+ ): ParsedPermission = mock {
+ whenever(name).thenReturn(permissionName)
+ whenever(this.packageName).thenReturn(packageName)
+ whenever(metaData).thenReturn(Bundle())
+ whenever(this.backgroundPermission).thenReturn(backgroundPermission)
+ whenever(this.group).thenReturn(group)
+ whenever(this.protectionLevel).thenReturn(protectionLevel)
+ whenever(this.flags).thenReturn(flags)
+ whenever(this.isTree).thenReturn(isTree)
+ }
protected fun mockParsedPermissionGroup(
permissionGroupName: String,
packageName: String,
- ): ParsedPermissionGroup =
- mock {
- whenever(name).thenReturn(permissionGroupName)
- whenever(this.packageName).thenReturn(packageName)
- whenever(metaData).thenReturn(Bundle())
- }
+ ): ParsedPermissionGroup = mock {
+ whenever(name).thenReturn(permissionGroupName)
+ whenever(this.packageName).thenReturn(packageName)
+ whenever(metaData).thenReturn(Bundle())
+ }
protected fun addPackageState(
packageState: PackageState,
- state: MutableAccessState = oldState
+ state: MutableAccessState = oldState,
) {
state.mutateExternalState().apply {
setPackageStates(
packageStates.toMutableMap().apply { put(packageState.packageName, packageState) }
)
- mutateAppIdPackageNames().mutateOrPut(packageState.appId) { MutableIndexedListSet() }
+ mutateAppIdPackageNames()
+ .mutateOrPut(packageState.appId) { MutableIndexedListSet() }
.add(packageState.packageName)
}
}
protected fun removePackageState(
packageState: PackageState,
- state: MutableAccessState = oldState
+ state: MutableAccessState = oldState,
) {
state.mutateExternalState().apply {
setPackageStates(
packageStates.toMutableMap().apply { remove(packageState.packageName) }
)
- mutateAppIdPackageNames().mutateOrPut(packageState.appId) { MutableIndexedListSet() }
+ mutateAppIdPackageNames()
+ .mutateOrPut(packageState.appId) { MutableIndexedListSet() }
.remove(packageState.packageName)
}
}
protected fun addDisabledSystemPackageState(
packageState: PackageState,
- state: MutableAccessState = oldState
- ) = state.mutateExternalState().apply {
- (disabledSystemPackageStates as ArrayMap)[packageState.packageName] = packageState
- }
+ state: MutableAccessState = oldState,
+ ) =
+ state.mutateExternalState().apply {
+ (disabledSystemPackageStates as ArrayMap)[packageState.packageName] = packageState
+ }
protected fun addPermission(
parsedPermission: ParsedPermission,
type: Int = Permission.TYPE_MANIFEST,
isReconciled: Boolean = true,
- state: MutableAccessState = oldState
+ state: MutableAccessState = oldState,
) {
- val permissionInfo = PackageInfoUtils.generatePermissionInfo(
- parsedPermission,
- PackageManager.GET_META_DATA.toLong()
- )!!
+ val permissionInfo =
+ PackageInfoUtils.generatePermissionInfo(
+ parsedPermission,
+ PackageManager.GET_META_DATA.toLong(),
+ )!!
val appId = state.externalState.packageStates[permissionInfo.packageName]!!.appId
val permission = Permission(permissionInfo, isReconciled, type, appId)
if (parsedPermission.isTree) {
@@ -312,35 +314,35 @@ abstract class BasePermissionPolicyTest {
protected fun addPermissionGroup(
parsedPermissionGroup: ParsedPermissionGroup,
- state: MutableAccessState = oldState
+ state: MutableAccessState = oldState,
) {
state.mutateSystemState().mutatePermissionGroups()[parsedPermissionGroup.name] =
PackageInfoUtils.generatePermissionGroupInfo(
parsedPermissionGroup,
- PackageManager.GET_META_DATA.toLong()
+ PackageManager.GET_META_DATA.toLong(),
)!!
}
protected fun getPermission(
permissionName: String,
- state: MutableAccessState = newState
+ state: MutableAccessState = newState,
): Permission? = state.systemState.permissions[permissionName]
protected fun getPermissionTree(
permissionTreeName: String,
- state: MutableAccessState = newState
+ state: MutableAccessState = newState,
): Permission? = state.systemState.permissionTrees[permissionTreeName]
protected fun getPermissionGroup(
permissionGroupName: String,
- state: MutableAccessState = newState
+ state: MutableAccessState = newState,
): PermissionGroupInfo? = state.systemState.permissionGroups[permissionGroupName]
protected fun getPermissionFlags(
appId: Int,
userId: Int,
permissionName: String,
- state: MutableAccessState = newState
+ state: MutableAccessState = newState,
): Int =
state.userStates[userId]?.appIdPermissionFlags?.get(appId).getWithDefault(permissionName, 0)
@@ -349,11 +351,13 @@ abstract class BasePermissionPolicyTest {
userId: Int,
permissionName: String,
flags: Int,
- state: MutableAccessState = oldState
+ state: MutableAccessState = oldState,
) =
- state.mutateUserState(userId)!!.mutateAppIdPermissionFlags().mutateOrPut(appId) {
- MutableIndexedMap()
- }.put(permissionName, flags)
+ state
+ .mutateUserState(userId)!!
+ .mutateAppIdPermissionFlags()
+ .mutateOrPut(appId) { MutableIndexedMap() }
+ .put(permissionName, flags)
companion object {
@JvmStatic protected val PACKAGE_NAME_0 = "packageName0"
@@ -375,16 +379,17 @@ abstract class BasePermissionPolicyTest {
@JvmStatic protected val PERMISSION_NAME_1 = "permissionName1"
@JvmStatic protected val PERMISSION_NAME_2 = "permissionName2"
@JvmStatic protected val PERMISSION_BELONGS_TO_A_TREE = "permissionTree.permission"
- @JvmStatic protected val PERMISSION_READ_EXTERNAL_STORAGE =
- Manifest.permission.READ_EXTERNAL_STORAGE
- @JvmStatic protected val PERMISSION_POST_NOTIFICATIONS =
- Manifest.permission.POST_NOTIFICATIONS
- @JvmStatic protected val PERMISSION_BLUETOOTH_CONNECT =
- Manifest.permission.BLUETOOTH_CONNECT
- @JvmStatic protected val PERMISSION_ACCESS_BACKGROUND_LOCATION =
+ @JvmStatic
+ protected val PERMISSION_READ_EXTERNAL_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE
+ @JvmStatic
+ protected val PERMISSION_POST_NOTIFICATIONS = Manifest.permission.POST_NOTIFICATIONS
+ @JvmStatic
+ protected val PERMISSION_BLUETOOTH_CONNECT = Manifest.permission.BLUETOOTH_CONNECT
+ @JvmStatic
+ protected val PERMISSION_ACCESS_BACKGROUND_LOCATION =
Manifest.permission.ACCESS_BACKGROUND_LOCATION
- @JvmStatic protected val PERMISSION_ACCESS_MEDIA_LOCATION =
- Manifest.permission.ACCESS_MEDIA_LOCATION
+ @JvmStatic
+ protected val PERMISSION_ACCESS_MEDIA_LOCATION = Manifest.permission.ACCESS_MEDIA_LOCATION
@JvmStatic protected val USER_ID_0 = 0
@JvmStatic protected val USER_ID_NEW = 1
diff --git a/services/tests/mockingservicestests/src/com/android/server/wallpaper/WallpaperManagerServiceTests.java b/services/tests/mockingservicestests/src/com/android/server/wallpaper/WallpaperManagerServiceTests.java
index 6b8ef88c556c..f8f08a51b375 100644
--- a/services/tests/mockingservicestests/src/com/android/server/wallpaper/WallpaperManagerServiceTests.java
+++ b/services/tests/mockingservicestests/src/com/android/server/wallpaper/WallpaperManagerServiceTests.java
@@ -64,6 +64,7 @@ import android.content.pm.IPackageManager;
import android.content.pm.PackageManager;
import android.content.pm.ParceledListSlice;
import android.content.pm.ServiceInfo;
+import android.content.res.Resources;
import android.graphics.Color;
import android.hardware.display.DisplayManager;
import android.hardware.display.DisplayManager.DisplayListener;
@@ -94,6 +95,7 @@ import com.android.internal.R;
import com.android.modules.utils.TypedXmlPullParser;
import com.android.modules.utils.TypedXmlSerializer;
import com.android.server.LocalServices;
+import com.android.server.wm.ActivityTaskManagerInternal;
import com.android.server.wm.DesktopModeHelper;
import com.android.server.wm.WindowManagerInternal;
@@ -169,6 +171,8 @@ public class WallpaperManagerServiceTests {
private static WindowManagerInternal sWindowManagerInternal;
+ private static ActivityTaskManagerInternal sActivityTaskManagerInternal;
+
@BeforeClass
public static void setUpClass() {
sMockitoSession = mockitoSession()
@@ -181,6 +185,9 @@ public class WallpaperManagerServiceTests {
sWindowManagerInternal = mock(WindowManagerInternal.class);
LocalServices.addService(WindowManagerInternal.class, sWindowManagerInternal);
+ sActivityTaskManagerInternal = mock(ActivityTaskManagerInternal.class);
+ LocalServices.addService(ActivityTaskManagerInternal.class,
+ sActivityTaskManagerInternal);
sContext.addMockSystemService(Context.APP_OPS_SERVICE, mock(AppOpsManager.class));
@@ -232,6 +239,7 @@ public class WallpaperManagerServiceTests {
sMockitoSession = null;
}
LocalServices.removeServiceForTest(WindowManagerInternal.class);
+ LocalServices.removeServiceForTest(ActivityTaskManagerInternal.class);
sImageWallpaperComponentName = null;
sDefaultWallpaperComponent = null;
sFallbackWallpaperComponentName = null;
@@ -1181,6 +1189,10 @@ public class WallpaperManagerServiceTests {
@Test
@EnableFlags(Flags.FLAG_ENABLE_CONNECTED_DISPLAYS_WALLPAPER)
public void setWallpaperComponent_systemAndLockWallpapers_multiDisplays_shouldHaveExpectedConnections() {
+ Resources resources = sContext.getResources();
+ spyOn(resources);
+ doReturn(true).when(resources).getBoolean(
+ R.bool.config_isLiveWallpaperSupportedInDesktopExperience);
final int incompatibleDisplayId = 2;
final int compatibleDisplayId = 3;
setUpDisplays(Map.of(
@@ -1220,6 +1232,71 @@ public class WallpaperManagerServiceTests {
.isTrue();
}
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_CONNECTED_DISPLAYS_WALLPAPER)
+ public void isWallpaperCompatibleForDisplay_liveWallpaperSupported_desktopExperienceEnabled_shouldReturnTrue() {
+ Resources resources = sContext.getResources();
+ spyOn(resources);
+ doReturn(true).when(resources).getBoolean(
+ R.bool.config_isLiveWallpaperSupportedInDesktopExperience);
+
+ final int displayId = 2;
+ setUpDisplays(Map.of(
+ DEFAULT_DISPLAY, true,
+ displayId, true));
+ final int testUserId = USER_SYSTEM;
+ mService.switchUser(testUserId, null);
+ mService.setWallpaperComponent(TEST_WALLPAPER_COMPONENT, sContext.getOpPackageName(),
+ FLAG_SYSTEM | FLAG_LOCK, testUserId);
+
+ assertThat(mService.isWallpaperCompatibleForDisplay(displayId,
+ mService.mLastWallpaper.connection)).isTrue();
+ }
+
+ @Test
+ @EnableFlags(Flags.FLAG_ENABLE_CONNECTED_DISPLAYS_WALLPAPER)
+ public void isWallpaperCompatibleForDisplay_liveWallpaperUnsupported_desktopExperienceEnabled_shouldReturnFalse() {
+ Resources resources = sContext.getResources();
+ spyOn(resources);
+ doReturn(false).when(resources).getBoolean(
+ R.bool.config_isLiveWallpaperSupportedInDesktopExperience);
+
+ final int displayId = 2;
+ setUpDisplays(Map.of(
+ DEFAULT_DISPLAY, true,
+ displayId, true));
+ final int testUserId = USER_SYSTEM;
+ mService.switchUser(testUserId, null);
+ mService.setWallpaperComponent(TEST_WALLPAPER_COMPONENT, sContext.getOpPackageName(),
+ FLAG_SYSTEM | FLAG_LOCK, testUserId);
+
+ assertThat(mService.isWallpaperCompatibleForDisplay(displayId,
+ mService.mLastWallpaper.connection)).isFalse();
+ }
+
+ @Test
+ @DisableFlags(Flags.FLAG_ENABLE_CONNECTED_DISPLAYS_WALLPAPER)
+ public void isWallpaperCompatibleForDisplay_liveWallpaperUnsupported_desktopExperienceDisabled_shouldReturnTrue() {
+ Resources resources = sContext.getResources();
+ spyOn(resources);
+ doReturn(false).when(resources).getBoolean(
+ R.bool.config_isLiveWallpaperSupportedInDesktopExperience);
+
+ final int displayId = 2;
+ setUpDisplays(Map.of(
+ DEFAULT_DISPLAY, true,
+ displayId, true));
+ final int testUserId = USER_SYSTEM;
+ mService.switchUser(testUserId, null);
+ mService.setWallpaperComponent(TEST_WALLPAPER_COMPONENT, sContext.getOpPackageName(),
+ FLAG_SYSTEM | FLAG_LOCK, testUserId);
+
+ // config_isLiveWallpaperSupportedInDesktopExperience is not used if the desktop experience
+ // flag for wallpaper is disabled.
+ assertThat(mService.isWallpaperCompatibleForDisplay(displayId,
+ mService.mLastWallpaper.connection)).isTrue();
+ }
+
// Verify that after continue switch user from userId 0 to lastUserId, the wallpaper data for
// non-current user must not bind to wallpaper service.
private void verifyNoConnectionBeforeLastUser(int lastUserId) {
diff --git a/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java
index 7acb93c0641e..3f937331b52e 100644
--- a/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryStatsHistoryTest.java
@@ -67,10 +67,14 @@ import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
+import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Date;
import java.util.List;
+import java.util.Locale;
import java.util.TimeZone;
+import java.util.concurrent.TimeUnit;
/**
* Test BatteryStatsHistory.
@@ -141,7 +145,7 @@ public class BatteryStatsHistoryTest {
mEventLogger);
mHistory.forceRecordAllHistory();
mHistory.startRecordingHistory(mClock.realtime, mClock.uptime, false);
- mHistoryPrinter = new BatteryStats.HistoryPrinter(TimeZone.getTimeZone("GMT"));
+ mHistoryPrinter = new BatteryStats.HistoryPrinter(TimeZone.getTimeZone("GMT"), 0);
}
@Test
@@ -865,6 +869,39 @@ public class BatteryStatsHistoryTest {
return events;
}
+
+ @Test
+ public void historyLogTimeFormatter() {
+ historyLogTimeFormatting("GMT");
+ historyLogTimeFormatting("PST");
+ historyLogTimeFormatting("NST"); // UTC−03:30
+ historyLogTimeFormatting("NPT"); // UTC+05:45
+ }
+
+ private void historyLogTimeFormatting(String timeZoneId) {
+ TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
+ BatteryStats.HistoryPrinter printer = new BatteryStats.HistoryPrinter(timeZone, 0);
+ SimpleDateFormat simpleDateFormat =
+ new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.US);
+ simpleDateFormat.getCalendar().setTimeZone(timeZone);
+ Date date = new Date();
+
+ HistoryItem item = new HistoryItem();
+ long base = 1738746000000L;
+ for (long offset = 1; offset < TimeUnit.DAYS.toMillis(365 * 100); offset *= 7) {
+ item.currentTime = base + offset;
+ date.setTime(item.currentTime);
+ String expected = simpleDateFormat.format(date);
+ StringWriter sw = new StringWriter();
+ PrintWriter writer = new PrintWriter(sw);
+ printer.printNextItem(writer, item, 0, false, false);
+ writer.flush();
+ String actual = sw.toString().trim().substring(0, "MM-dd HH:mm:ss.SSS".length());
+
+ assertThat(actual).isEqualTo(expected);
+ }
+ }
+
private static void awaitCompletion() {
ConditionVariable done = new ConditionVariable();
BackgroundThread.getHandler().post(done::open);
diff --git a/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsRule.java b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsRule.java
index 53a2522d299e..f29708496940 100644
--- a/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsRule.java
+++ b/services/tests/powerstatstests/src/com/android/server/power/stats/BatteryUsageStatsRule.java
@@ -340,7 +340,7 @@ public class BatteryUsageStatsRule implements TestRule {
}
private void before() {
- BatteryUsageStats.DEBUG_INSTANCE_COUNT = true;
+ BatteryUsageStats.enableInstanceLeakDetection();
HandlerThread bgThread = new HandlerThread("bg thread");
bgThread.setUncaughtExceptionHandler((thread, throwable)-> {
mThrowable = throwable;
diff --git a/services/tests/servicestests/Android.bp b/services/tests/servicestests/Android.bp
index 64e6d323bdfd..d3c3178f3513 100644
--- a/services/tests/servicestests/Android.bp
+++ b/services/tests/servicestests/Android.bp
@@ -347,6 +347,17 @@ test_module_config {
include_filters: ["com.android.server.om."],
}
+test_module_config {
+ name: "FrameworksServicesTests_theme",
+ base: "FrameworksServicesTests",
+ test_suites: [
+ "device-tests",
+ "automotive-tests",
+ ],
+
+ include_filters: ["com.android.server.theming."],
+}
+
// Used by contexthub TEST_MAPPING
test_module_config {
name: "FrameworksServicesTests_contexthub_presubmit",
diff --git a/services/tests/servicestests/src/com/android/server/accessibility/autoclick/AutoclickControllerTest.java b/services/tests/servicestests/src/com/android/server/accessibility/autoclick/AutoclickControllerTest.java
index df77866b5e7f..0f418ab5d19c 100644
--- a/services/tests/servicestests/src/com/android/server/accessibility/autoclick/AutoclickControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/accessibility/autoclick/AutoclickControllerTest.java
@@ -88,6 +88,23 @@ public class AutoclickControllerTest {
}
}
+ public static class ScrollEventCaptor extends BaseEventStreamTransformation {
+ public MotionEvent scrollEvent;
+ public int eventCount = 0;
+
+ @Override
+ public void onMotionEvent(MotionEvent event, MotionEvent rawEvent, int policyFlags) {
+ if (event.getAction() == MotionEvent.ACTION_SCROLL) {
+ if (scrollEvent != null) {
+ scrollEvent.recycle();
+ }
+ scrollEvent = MotionEvent.obtain(event);
+ eventCount++;
+ }
+ super.onMotionEvent(event, rawEvent, policyFlags);
+ }
+ }
+
@Before
public void setUp() {
mTestableLooper = TestableLooper.get(this);
@@ -918,6 +935,110 @@ public class AutoclickControllerTest {
MotionEvent.BUTTON_PRIMARY);
}
+ @Test
+ @EnableFlags(com.android.server.accessibility.Flags.FLAG_ENABLE_AUTOCLICK_INDICATOR)
+ public void sendClick_updateLastCursorAndScrollAtThatLocation() {
+ // Set up event capturer to track scroll events.
+ ScrollEventCaptor scrollCaptor = new ScrollEventCaptor();
+ mController.setNext(scrollCaptor);
+
+ // Initialize controller with mouse event.
+ injectFakeMouseActionHoverMoveEvent();
+
+ // Mock the scroll panel.
+ AutoclickScrollPanel mockScrollPanel = mock(AutoclickScrollPanel.class);
+ mController.mAutoclickScrollPanel = mockScrollPanel;
+
+ // Set click type to scroll.
+ mController.clickPanelController.handleAutoclickTypeChange(
+ AutoclickTypePanel.AUTOCLICK_TYPE_SCROLL);
+
+ // Set cursor position.
+ float expectedX = 75f;
+ float expectedY = 125f;
+ mController.mLastCursorX = expectedX;
+ mController.mLastCursorY = expectedY;
+
+ // Trigger scroll action in up direction.
+ mController.mScrollPanelController.onHoverButtonChange(
+ AutoclickScrollPanel.DIRECTION_UP, true);
+
+ // Verify scroll event happens at last cursor location.
+ assertThat(scrollCaptor.scrollEvent).isNotNull();
+ assertThat(scrollCaptor.scrollEvent.getX()).isEqualTo(expectedX);
+ assertThat(scrollCaptor.scrollEvent.getY()).isEqualTo(expectedY);
+ }
+
+ @Test
+ @EnableFlags(com.android.server.accessibility.Flags.FLAG_ENABLE_AUTOCLICK_INDICATOR)
+ public void handleScroll_generatesCorrectScrollEvents() {
+ ScrollEventCaptor scrollCaptor = new ScrollEventCaptor();
+ mController.setNext(scrollCaptor);
+
+ // Initialize controller.
+ injectFakeMouseActionHoverMoveEvent();
+
+ // Set cursor position.
+ final float expectedX = 100f;
+ final float expectedY = 200f;
+ mController.mLastCursorX = expectedX;
+ mController.mLastCursorY = expectedY;
+
+ // Test UP direction.
+ mController.mScrollPanelController.onHoverButtonChange(
+ AutoclickScrollPanel.DIRECTION_UP, true);
+
+ // Verify basic event properties.
+ assertThat(scrollCaptor.eventCount).isEqualTo(1);
+ assertThat(scrollCaptor.scrollEvent).isNotNull();
+ assertThat(scrollCaptor.scrollEvent.getAction()).isEqualTo(MotionEvent.ACTION_SCROLL);
+ assertThat(scrollCaptor.scrollEvent.getX()).isEqualTo(expectedX);
+ assertThat(scrollCaptor.scrollEvent.getY()).isEqualTo(expectedY);
+
+ // Verify UP direction uses correct axis values.
+ float vScrollUp = scrollCaptor.scrollEvent.getAxisValue(MotionEvent.AXIS_VSCROLL);
+ float hScrollUp = scrollCaptor.scrollEvent.getAxisValue(MotionEvent.AXIS_HSCROLL);
+ assertThat(vScrollUp).isGreaterThan(0);
+ assertThat(hScrollUp).isEqualTo(0);
+
+ // Test DOWN direction.
+ mController.mScrollPanelController.onHoverButtonChange(
+ AutoclickScrollPanel.DIRECTION_DOWN, true);
+
+ // Verify DOWN direction uses correct axis values.
+ assertThat(scrollCaptor.eventCount).isEqualTo(2);
+ float vScrollDown = scrollCaptor.scrollEvent.getAxisValue(MotionEvent.AXIS_VSCROLL);
+ float hScrollDown = scrollCaptor.scrollEvent.getAxisValue(MotionEvent.AXIS_HSCROLL);
+ assertThat(vScrollDown).isLessThan(0);
+ assertThat(hScrollDown).isEqualTo(0);
+
+ // Test LEFT direction.
+ mController.mScrollPanelController.onHoverButtonChange(
+ AutoclickScrollPanel.DIRECTION_LEFT, true);
+
+ // Verify LEFT direction uses correct axis values.
+ assertThat(scrollCaptor.eventCount).isEqualTo(3);
+ float vScrollLeft = scrollCaptor.scrollEvent.getAxisValue(MotionEvent.AXIS_VSCROLL);
+ float hScrollLeft = scrollCaptor.scrollEvent.getAxisValue(MotionEvent.AXIS_HSCROLL);
+ assertThat(hScrollLeft).isGreaterThan(0);
+ assertThat(vScrollLeft).isEqualTo(0);
+
+ // Test RIGHT direction.
+ mController.mScrollPanelController.onHoverButtonChange(
+ AutoclickScrollPanel.DIRECTION_RIGHT, true);
+
+ // Verify RIGHT direction uses correct axis values.
+ assertThat(scrollCaptor.eventCount).isEqualTo(4);
+ float vScrollRight = scrollCaptor.scrollEvent.getAxisValue(MotionEvent.AXIS_VSCROLL);
+ float hScrollRight = scrollCaptor.scrollEvent.getAxisValue(MotionEvent.AXIS_HSCROLL);
+ assertThat(hScrollRight).isLessThan(0);
+ assertThat(vScrollRight).isEqualTo(0);
+
+ // Verify scroll cursor position is preserved.
+ assertThat(scrollCaptor.scrollEvent.getX()).isEqualTo(expectedX);
+ assertThat(scrollCaptor.scrollEvent.getY()).isEqualTo(expectedY);
+ }
+
private void injectFakeMouseActionHoverMoveEvent() {
MotionEvent event = getFakeMotionHoverMoveEvent();
event.setSource(InputDevice.SOURCE_MOUSE);
diff --git a/services/tests/servicestests/src/com/android/server/media/LegacyDeviceRouteControllerTest.java b/services/tests/servicestests/src/com/android/server/media/LegacyDeviceRouteControllerTest.java
index aed68a5dc7b5..113e039d9a43 100644
--- a/services/tests/servicestests/src/com/android/server/media/LegacyDeviceRouteControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/media/LegacyDeviceRouteControllerTest.java
@@ -30,12 +30,17 @@ import android.media.AudioRoutesInfo;
import android.media.IAudioRoutesObserver;
import android.media.MediaRoute2Info;
import android.os.RemoteException;
+import android.platform.test.annotations.RequiresFlagsEnabled;
+import android.platform.test.flag.junit.CheckFlagsRule;
+import android.platform.test.flag.junit.DeviceFlagsValueProvider;
import android.text.TextUtils;
import com.android.internal.R;
+import com.android.media.flags.Flags;
import com.android.server.audio.AudioService;
import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
@@ -48,6 +53,7 @@ import org.mockito.MockitoAnnotations;
import java.util.Arrays;
import java.util.Collection;
+import java.util.List;
@RunWith(Enclosed.class)
public class LegacyDeviceRouteControllerTest {
@@ -70,6 +76,11 @@ public class LegacyDeviceRouteControllerTest {
@RunWith(JUnit4.class)
public static class DefaultDeviceRouteValueTest {
+
+ @Rule
+ public final CheckFlagsRule mCheckFlagsRule =
+ DeviceFlagsValueProvider.createCheckFlagsRule();
+
@Mock
private Context mContext;
@Mock
@@ -136,6 +147,23 @@ public class LegacyDeviceRouteControllerTest {
.isTrue();
assertThat(actualMediaRoute.getVolume()).isEqualTo(VOLUME_DEFAULT_VALUE);
}
+
+ @RequiresFlagsEnabled(Flags.FLAG_ENABLE_FIX_FOR_EMPTY_SYSTEM_ROUTES_CRASH)
+ @Test
+ public void getAvailableRoutes_matchesSelectedRoute() {
+ when(mResources.getText(R.string.default_audio_route_name))
+ .thenReturn(DEFAULT_ROUTE_NAME);
+
+ when(mAudioService.startWatchingRoutes(any())).thenReturn(null);
+
+ LegacyDeviceRouteController deviceRouteController =
+ new LegacyDeviceRouteController(
+ mContext, mAudioManager, mAudioService, mOnDeviceRouteChangedListener);
+
+ MediaRoute2Info selectedRoute = deviceRouteController.getSelectedRoute();
+ assertThat(deviceRouteController.getAvailableRoutes())
+ .isEqualTo(List.of(selectedRoute));
+ }
}
@RunWith(Parameterized.class)
diff --git a/services/tests/servicestests/src/com/android/server/security/advancedprotection/AdvancedProtectionServiceTest.java b/services/tests/servicestests/src/com/android/server/security/advancedprotection/AdvancedProtectionServiceTest.java
index d6b3fecb487c..ca71ed6a4130 100644
--- a/services/tests/servicestests/src/com/android/server/security/advancedprotection/AdvancedProtectionServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/security/advancedprotection/AdvancedProtectionServiceTest.java
@@ -26,6 +26,7 @@ import static org.mockito.Mockito.mock;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
+import android.content.pm.UserInfo;
import android.os.RemoteException;
import android.os.test.FakePermissionEnforcer;
import android.os.test.TestLooper;
@@ -36,6 +37,7 @@ import android.security.advancedprotection.IAdvancedProtectionCallback;
import androidx.annotation.NonNull;
+import com.android.server.pm.UserManagerInternal;
import com.android.server.security.advancedprotection.features.AdvancedProtectionHook;
import com.android.server.security.advancedprotection.features.AdvancedProtectionProvider;
@@ -48,26 +50,37 @@ import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;
+import org.mockito.ArgumentMatchers;
+import org.mockito.Mockito;
@SuppressLint("VisibleForTests")
@RunWith(JUnit4.class)
public class AdvancedProtectionServiceTest {
- private AdvancedProtectionService mService;
private FakePermissionEnforcer mPermissionEnforcer;
+ private UserManagerInternal mUserManager;
private Context mContext;
- private AdvancedProtectionService.AdvancedProtectionStore mStore;
private TestLooper mLooper;
- AdvancedProtectionFeature mTestFeature2g = new AdvancedProtectionFeature(
- AdvancedProtectionManager.FEATURE_ID_DISALLOW_CELLULAR_2G);
+ AdvancedProtectionFeature mTestFeature2g =
+ new AdvancedProtectionFeature(
+ AdvancedProtectionManager.FEATURE_ID_DISALLOW_CELLULAR_2G);
@Before
public void setup() throws Settings.SettingNotFoundException {
mContext = mock(Context.class);
+ mUserManager = mock(UserManagerInternal.class);
+ mLooper = new TestLooper();
mPermissionEnforcer = new FakePermissionEnforcer();
mPermissionEnforcer.grant(Manifest.permission.MANAGE_ADVANCED_PROTECTION_MODE);
mPermissionEnforcer.grant(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE);
+ Mockito.when(mUserManager.getUserInfo(ArgumentMatchers.anyInt()))
+ .thenReturn(new UserInfo(0, "user", UserInfo.FLAG_ADMIN));
+ }
+
+ private AdvancedProtectionService createService(
+ AdvancedProtectionHook hook, AdvancedProtectionProvider provider) {
- mStore = new AdvancedProtectionService.AdvancedProtectionStore(mContext) {
+ AdvancedProtectionService.AdvancedProtectionStore
+ store = new AdvancedProtectionService.AdvancedProtectionStore(mContext) {
private Map<String, Integer> mStoredValues = new HashMap<>();
private boolean mEnabled = false;
@@ -92,24 +105,38 @@ public class AdvancedProtectionServiceTest {
}
};
- mLooper = new TestLooper();
-
- mService = new AdvancedProtectionService(mContext, mStore, mLooper.getLooper(),
- mPermissionEnforcer, null, null);
+ return new AdvancedProtectionService(
+ mContext,
+ store,
+ mUserManager,
+ mLooper.getLooper(),
+ mPermissionEnforcer,
+ hook,
+ provider);
}
@Test
public void testToggleProtection() {
- mService.setAdvancedProtectionEnabled(true);
- assertTrue(mService.isAdvancedProtectionEnabled());
+ AdvancedProtectionService service = createService(null, null);
+ service.setAdvancedProtectionEnabled(true);
+ assertTrue(service.isAdvancedProtectionEnabled());
- mService.setAdvancedProtectionEnabled(false);
- assertFalse(mService.isAdvancedProtectionEnabled());
+ service.setAdvancedProtectionEnabled(false);
+ assertFalse(service.isAdvancedProtectionEnabled());
}
@Test
public void testDisableProtection_byDefault() {
- assertFalse(mService.isAdvancedProtectionEnabled());
+ AdvancedProtectionService service = createService(null, null);
+ assertFalse(service.isAdvancedProtectionEnabled());
+ }
+
+ @Test
+ public void testSetProtection_nonAdminUser() {
+ Mockito.when(mUserManager.getUserInfo(ArgumentMatchers.anyInt()))
+ .thenReturn(new UserInfo(1, "user2", UserInfo.FLAG_FULL));
+ AdvancedProtectionService service = createService(null, null);
+ assertThrows(SecurityException.class, () -> service.setAdvancedProtectionEnabled(true));
}
@Test
@@ -134,9 +161,8 @@ public class AdvancedProtectionServiceTest {
}
};
- mService = new AdvancedProtectionService(mContext, mStore, mLooper.getLooper(),
- mPermissionEnforcer, hook, null);
- mService.setAdvancedProtectionEnabled(true);
+ AdvancedProtectionService service = createService(hook, null);
+ service.setAdvancedProtectionEnabled(true);
mLooper.dispatchNext();
assertTrue(callbackCaptor.get());
@@ -164,10 +190,8 @@ public class AdvancedProtectionServiceTest {
}
};
- mService = new AdvancedProtectionService(mContext, mStore, mLooper.getLooper(),
- mPermissionEnforcer, hook, null);
-
- mService.setAdvancedProtectionEnabled(true);
+ AdvancedProtectionService service = createService(hook, null);
+ service.setAdvancedProtectionEnabled(true);
mLooper.dispatchNext();
assertFalse(callbackCalledCaptor.get());
}
@@ -194,14 +218,13 @@ public class AdvancedProtectionServiceTest {
}
};
- mService = new AdvancedProtectionService(mContext, mStore, mLooper.getLooper(),
- mPermissionEnforcer, hook, null);
- mService.setAdvancedProtectionEnabled(true);
+ AdvancedProtectionService service = createService(hook, null);
+ service.setAdvancedProtectionEnabled(true);
mLooper.dispatchNext();
assertTrue(callbackCalledCaptor.get());
callbackCalledCaptor.set(false);
- mService.setAdvancedProtectionEnabled(true);
+ service.setAdvancedProtectionEnabled(true);
mLooper.dispatchAll();
assertFalse(callbackCalledCaptor.get());
}
@@ -209,21 +232,24 @@ public class AdvancedProtectionServiceTest {
@Test
public void testRegisterCallback() throws RemoteException {
AtomicBoolean callbackCaptor = new AtomicBoolean(false);
- IAdvancedProtectionCallback callback = new IAdvancedProtectionCallback.Stub() {
- @Override
- public void onAdvancedProtectionChanged(boolean enabled) {
- callbackCaptor.set(enabled);
- }
- };
+ IAdvancedProtectionCallback callback =
+ new IAdvancedProtectionCallback.Stub() {
+ @Override
+ public void onAdvancedProtectionChanged(boolean enabled) {
+ callbackCaptor.set(enabled);
+ }
+ };
+
+ AdvancedProtectionService service = createService(null, null);
- mService.setAdvancedProtectionEnabled(true);
+ service.setAdvancedProtectionEnabled(true);
mLooper.dispatchAll();
- mService.registerAdvancedProtectionCallback(callback);
+ service.registerAdvancedProtectionCallback(callback);
mLooper.dispatchNext();
assertTrue(callbackCaptor.get());
- mService.setAdvancedProtectionEnabled(false);
+ service.setAdvancedProtectionEnabled(false);
mLooper.dispatchNext();
assertFalse(callbackCaptor.get());
@@ -232,20 +258,23 @@ public class AdvancedProtectionServiceTest {
@Test
public void testUnregisterCallback() throws RemoteException {
AtomicBoolean callbackCalledCaptor = new AtomicBoolean(false);
- IAdvancedProtectionCallback callback = new IAdvancedProtectionCallback.Stub() {
- @Override
- public void onAdvancedProtectionChanged(boolean enabled) {
- callbackCalledCaptor.set(true);
- }
- };
+ IAdvancedProtectionCallback callback =
+ new IAdvancedProtectionCallback.Stub() {
+ @Override
+ public void onAdvancedProtectionChanged(boolean enabled) {
+ callbackCalledCaptor.set(true);
+ }
+ };
+
+ AdvancedProtectionService service = createService(null, null);
- mService.setAdvancedProtectionEnabled(true);
- mService.registerAdvancedProtectionCallback(callback);
+ service.setAdvancedProtectionEnabled(true);
+ service.registerAdvancedProtectionCallback(callback);
mLooper.dispatchAll();
callbackCalledCaptor.set(false);
- mService.unregisterAdvancedProtectionCallback(callback);
- mService.setAdvancedProtectionEnabled(false);
+ service.unregisterAdvancedProtectionCallback(callback);
+ service.setAdvancedProtectionEnabled(false);
mLooper.dispatchNext();
assertFalse(callbackCalledCaptor.get());
@@ -253,104 +282,107 @@ public class AdvancedProtectionServiceTest {
@Test
public void testGetFeatures() {
- AdvancedProtectionFeature feature1 = new AdvancedProtectionFeature(
- AdvancedProtectionManager.FEATURE_ID_DISALLOW_CELLULAR_2G);
- AdvancedProtectionFeature feature2 = new AdvancedProtectionFeature(
- AdvancedProtectionManager.FEATURE_ID_DISALLOW_INSTALL_UNKNOWN_SOURCES);
- AdvancedProtectionHook hook = new AdvancedProtectionHook(mContext, true) {
- @NonNull
- @Override
- public AdvancedProtectionFeature getFeature() {
- return feature1;
- }
+ AdvancedProtectionFeature feature1 =
+ new AdvancedProtectionFeature(
+ AdvancedProtectionManager.FEATURE_ID_DISALLOW_CELLULAR_2G);
+ AdvancedProtectionFeature feature2 =
+ new AdvancedProtectionFeature(
+ AdvancedProtectionManager.FEATURE_ID_DISALLOW_INSTALL_UNKNOWN_SOURCES);
+ AdvancedProtectionHook hook =
+ new AdvancedProtectionHook(mContext, true) {
+ @NonNull
+ @Override
+ public AdvancedProtectionFeature getFeature() {
+ return feature1;
+ }
- @Override
- public boolean isAvailable() {
- return true;
- }
- };
+ @Override
+ public boolean isAvailable() {
+ return true;
+ }
+ };
- AdvancedProtectionProvider provider = new AdvancedProtectionProvider() {
- @Override
- public List<AdvancedProtectionFeature> getFeatures(Context context) {
- return List.of(feature2);
- }
- };
+ AdvancedProtectionProvider provider =
+ new AdvancedProtectionProvider() {
+ @Override
+ public List<AdvancedProtectionFeature> getFeatures(Context context) {
+ return List.of(feature2);
+ }
+ };
- mService = new AdvancedProtectionService(mContext, mStore, mLooper.getLooper(),
- mPermissionEnforcer, hook, provider);
- List<AdvancedProtectionFeature> features = mService.getAdvancedProtectionFeatures();
+ AdvancedProtectionService service = createService(hook, provider);
+ List<AdvancedProtectionFeature> features = service.getAdvancedProtectionFeatures();
assertThat(features, containsInAnyOrder(feature1, feature2));
}
@Test
public void testGetFeatures_featureNotAvailable() {
- AdvancedProtectionFeature feature1 = new AdvancedProtectionFeature(
- AdvancedProtectionManager.FEATURE_ID_DISALLOW_CELLULAR_2G);
- AdvancedProtectionFeature feature2 = new AdvancedProtectionFeature(
- AdvancedProtectionManager.FEATURE_ID_DISALLOW_INSTALL_UNKNOWN_SOURCES);
- AdvancedProtectionHook hook = new AdvancedProtectionHook(mContext, true) {
- @NonNull
- @Override
- public AdvancedProtectionFeature getFeature() {
- return feature1;
- }
+ AdvancedProtectionFeature feature1 =
+ new AdvancedProtectionFeature(
+ AdvancedProtectionManager.FEATURE_ID_DISALLOW_CELLULAR_2G);
+ AdvancedProtectionFeature feature2 =
+ new AdvancedProtectionFeature(
+ AdvancedProtectionManager.FEATURE_ID_DISALLOW_INSTALL_UNKNOWN_SOURCES);
+ AdvancedProtectionHook hook =
+ new AdvancedProtectionHook(mContext, true) {
+ @NonNull
+ @Override
+ public AdvancedProtectionFeature getFeature() {
+ return feature1;
+ }
- @Override
- public boolean isAvailable() {
- return false;
- }
- };
+ @Override
+ public boolean isAvailable() {
+ return false;
+ }
+ };
- AdvancedProtectionProvider provider = new AdvancedProtectionProvider() {
- @Override
- public List<AdvancedProtectionFeature> getFeatures(Context context) {
- return List.of(feature2);
- }
- };
+ AdvancedProtectionProvider provider =
+ new AdvancedProtectionProvider() {
+ @Override
+ public List<AdvancedProtectionFeature> getFeatures(Context context) {
+ return List.of(feature2);
+ }
+ };
- mService = new AdvancedProtectionService(mContext, mStore, mLooper.getLooper(),
- mPermissionEnforcer, hook, provider);
- List<AdvancedProtectionFeature> features = mService.getAdvancedProtectionFeatures();
+ AdvancedProtectionService service = createService(hook, provider);
+ List<AdvancedProtectionFeature> features = service.getAdvancedProtectionFeatures();
assertThat(features, containsInAnyOrder(feature2));
}
-
@Test
public void testSetProtection_withoutPermission() {
+ AdvancedProtectionService service = createService(null, null);
mPermissionEnforcer.revoke(Manifest.permission.MANAGE_ADVANCED_PROTECTION_MODE);
- assertThrows(SecurityException.class, () -> mService.setAdvancedProtectionEnabled(true));
+ assertThrows(SecurityException.class, () -> service.setAdvancedProtectionEnabled(true));
}
@Test
public void testGetProtection_withoutPermission() {
+ AdvancedProtectionService service = createService(null, null);
mPermissionEnforcer.revoke(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE);
- assertThrows(SecurityException.class, () -> mService.isAdvancedProtectionEnabled());
- }
-
- @Test
- public void testUsbDataProtection_withoutPermission() {
- mPermissionEnforcer.revoke(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE);
- assertThrows(SecurityException.class, () -> mService.isUsbDataProtectionEnabled());
- }
-
- @Test
- public void testSetUsbDataProtection_withoutPermission() {
- mPermissionEnforcer.revoke(Manifest.permission.MANAGE_ADVANCED_PROTECTION_MODE);
- assertThrows(SecurityException.class, () -> mService.setUsbDataProtectionEnabled(true));
+ assertThrows(SecurityException.class, () -> service.isAdvancedProtectionEnabled());
}
@Test
public void testRegisterCallback_withoutPermission() {
+ AdvancedProtectionService service = createService(null, null);
mPermissionEnforcer.revoke(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE);
- assertThrows(SecurityException.class, () -> mService.registerAdvancedProtectionCallback(
- new IAdvancedProtectionCallback.Default()));
+ assertThrows(
+ SecurityException.class,
+ () ->
+ service.registerAdvancedProtectionCallback(
+ new IAdvancedProtectionCallback.Default()));
}
@Test
public void testUnregisterCallback_withoutPermission() {
+ AdvancedProtectionService service = createService(null, null);
mPermissionEnforcer.revoke(Manifest.permission.QUERY_ADVANCED_PROTECTION_MODE);
- assertThrows(SecurityException.class, () -> mService.unregisterAdvancedProtectionCallback(
- new IAdvancedProtectionCallback.Default()));
+ assertThrows(
+ SecurityException.class,
+ () ->
+ service.unregisterAdvancedProtectionCallback(
+ new IAdvancedProtectionCallback.Default()));
}
}
diff --git a/services/tests/servicestests/src/com/android/server/theming/FieldColorBothTests.java b/services/tests/servicestests/src/com/android/server/theming/FieldColorBothTests.java
new file mode 100644
index 000000000000..38cbcf37f88c
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/theming/FieldColorBothTests.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.theming;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.theming.FieldColorBoth;
+import android.content.theming.ThemeSettings;
+import android.content.theming.ThemeSettingsUpdater;
+import android.content.theming.ThemeStyle;
+
+import com.google.common.truth.Truth;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class FieldColorBothTests {
+ static final ThemeSettings DEFAULTS = new ThemeSettings(1, 0xFF123456, 0xFF654321,
+ "home_wallpaper", ThemeStyle.VIBRANT, true);
+ private FieldColorBoth mFieldColorBoth;
+
+ @Before
+ public void setup() {
+ mFieldColorBoth = new FieldColorBoth("colorBoth", ThemeSettingsUpdater::colorBoth,
+ ThemeSettings::colorBoth, DEFAULTS);
+ }
+
+ @Test
+ public void parse_validColorBoth_returnsTrue() {
+ Boolean parsedValue = mFieldColorBoth.parse("1");
+ assertThat(parsedValue).isTrue();
+ }
+
+ @Test
+ public void parse_validColorBoth_returnsFalse() {
+ Boolean parsedValue = mFieldColorBoth.parse("0");
+ assertThat(parsedValue).isFalse();
+ }
+
+ @Test
+ public void parse_invalidColorBoth_returnsNull() {
+ Boolean parsedValue = mFieldColorBoth.parse("invalid");
+ assertThat(parsedValue).isNull();
+ }
+
+ @Test
+ public void serialize_true_returnsTrueString() {
+ String serializedValue = mFieldColorBoth.serialize(true);
+ assertThat(serializedValue).isEqualTo("1");
+ }
+
+ @Test
+ public void serialize_false_returnsFalseString() {
+ String serializedValue = mFieldColorBoth.serialize(false);
+ assertThat(serializedValue).isEqualTo("0");
+ }
+
+ @Test
+ public void validate_true_returnsTrue() {
+ assertThat(mFieldColorBoth.validate(true)).isTrue();
+ }
+
+ @Test
+ public void validate_false_returnsTrue() {
+ assertThat(mFieldColorBoth.validate(false)).isTrue();
+ }
+
+ @Test
+ public void getFieldType_returnsBooleanClass() {
+ Truth.assertThat(mFieldColorBoth.getFieldType()).isEqualTo(Boolean.class);
+ }
+
+ @Test
+ public void getJsonType_returnsStringClass() {
+ Truth.assertThat(mFieldColorBoth.getJsonType()).isEqualTo(String.class);
+ }
+
+ @Test
+ public void get_returnsDefaultValue() {
+ Truth.assertThat(mFieldColorBoth.getDefaultValue()).isEqualTo(DEFAULTS.colorBoth());
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/theming/FieldColorIndexTests.java b/services/tests/servicestests/src/com/android/server/theming/FieldColorIndexTests.java
new file mode 100644
index 000000000000..32df3684a81d
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/theming/FieldColorIndexTests.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.theming;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.theming.FieldColorIndex;
+import android.content.theming.ThemeSettings;
+import android.content.theming.ThemeSettingsUpdater;
+import android.content.theming.ThemeStyle;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class FieldColorIndexTests {
+ static final ThemeSettings DEFAULTS = new ThemeSettings(1, 0xFF123456, 0xFF654321,
+ "home_wallpaper", ThemeStyle.VIBRANT, true);
+
+ private FieldColorIndex mFieldColorIndex;
+
+ @Before
+ public void setup() {
+ mFieldColorIndex = new FieldColorIndex("colorIndex", ThemeSettingsUpdater::colorIndex,
+ ThemeSettings::colorIndex, DEFAULTS);
+ }
+
+ @Test
+ public void parse_validColorIndex_returnsCorrectInteger() {
+ Integer parsedValue = mFieldColorIndex.parse("10");
+ assertThat(parsedValue).isEqualTo(10);
+ }
+
+ @Test
+ public void parse_negativeColorIndex_returnsCorrectInteger() {
+ Integer parsedValue = mFieldColorIndex.parse("-1");
+ assertThat(parsedValue).isEqualTo(-1);
+ }
+
+ @Test
+ public void parse_invalidColorIndex_returnsNull() {
+ Integer parsedValue = mFieldColorIndex.parse("invalid");
+ assertThat(parsedValue).isNull();
+ }
+
+ @Test
+ public void serialize_validColorIndex_returnsCorrectString() {
+ String serializedValue = mFieldColorIndex.serialize(15);
+ assertThat(serializedValue).isEqualTo("15");
+ }
+
+ @Test
+ public void serialize_negativeColorIndex_returnsCorrectString() {
+ String serializedValue = mFieldColorIndex.serialize(-1);
+ assertThat(serializedValue).isEqualTo("-1");
+ }
+
+ @Test
+ public void validate_validColorIndex_returnsTrue() {
+ assertThat(mFieldColorIndex.validate(5)).isTrue();
+ }
+
+ @Test
+ public void validate_negativeColorIndex_returnsTrue() {
+ assertThat(mFieldColorIndex.validate(-1)).isTrue();
+ }
+
+ @Test
+ public void validate_invalidColorIndex_returnsFalse() {
+ assertThat(mFieldColorIndex.validate(-2)).isFalse();
+ }
+
+ @Test
+ public void getFieldType_returnsIntegerClass() {
+ assertThat(mFieldColorIndex.getFieldType()).isEqualTo(Integer.class);
+ }
+
+ @Test
+ public void getJsonType_returnsStringClass() {
+ assertThat(mFieldColorIndex.getJsonType()).isEqualTo(String.class);
+ }
+
+ @Test
+ public void get_returnsDefaultValue() {
+ assertThat(mFieldColorIndex.getDefaultValue()).isEqualTo(DEFAULTS.colorIndex());
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/theming/FieldColorSourceTests.java b/services/tests/servicestests/src/com/android/server/theming/FieldColorSourceTests.java
new file mode 100644
index 000000000000..06edfa862d9c
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/theming/FieldColorSourceTests.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.theming;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.theming.FieldColorSource;
+import android.content.theming.ThemeSettings;
+import android.content.theming.ThemeSettingsUpdater;
+import android.content.theming.ThemeStyle;
+
+import com.google.common.truth.Truth;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+
+@RunWith(JUnit4.class)
+public class FieldColorSourceTests {
+ static final ThemeSettings DEFAULTS = new ThemeSettings(1, 0xFF123456, 0xFF654321,
+ "home_wallpaper", ThemeStyle.VIBRANT, true);
+ private FieldColorSource mFieldColorSource;
+
+ @Before
+ public void setup() {
+ mFieldColorSource = new FieldColorSource("colorSource", ThemeSettingsUpdater::colorSource,
+ ThemeSettings::colorSource, DEFAULTS);
+ }
+
+ @Test
+ public void parse_validColorSource_returnsSameString() {
+ String validColorSource = "home_wallpaper";
+ String parsedValue = mFieldColorSource.parse(validColorSource);
+ assertThat(parsedValue).isEqualTo(validColorSource);
+ }
+
+ @Test
+ public void serialize_validColorSource_returnsSameString() {
+ String validColorSource = "lock_wallpaper";
+ String serializedValue = mFieldColorSource.serialize(validColorSource);
+ assertThat(serializedValue).isEqualTo(validColorSource);
+ }
+
+ @Test
+ public void validate_preset_returnsTrue() {
+ assertThat(mFieldColorSource.validate("preset")).isTrue();
+ }
+
+ @Test
+ public void validate_homeWallpaper_returnsTrue() {
+ assertThat(mFieldColorSource.validate("home_wallpaper")).isTrue();
+ }
+
+ @Test
+ public void validate_lockWallpaper_returnsTrue() {
+ assertThat(mFieldColorSource.validate("lock_wallpaper")).isTrue();
+ }
+
+ @Test
+ public void validate_invalidColorSource_returnsFalse() {
+ assertThat(mFieldColorSource.validate("invalid")).isFalse();
+ }
+
+ @Test
+ public void getFieldType_returnsStringClass() {
+ Truth.assertThat(mFieldColorSource.getFieldType()).isEqualTo(String.class);
+ }
+
+ @Test
+ public void getJsonType_returnsStringClass() {
+ Truth.assertThat(mFieldColorSource.getJsonType()).isEqualTo(String.class);
+ }
+
+ @Test
+ public void get_returnsDefaultValue() {
+ Truth.assertThat(mFieldColorSource.getDefaultValue()).isEqualTo(DEFAULTS.colorSource());
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/theming/FieldColorTests.java b/services/tests/servicestests/src/com/android/server/theming/FieldColorTests.java
new file mode 100644
index 000000000000..54c4b29a5063
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/theming/FieldColorTests.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.theming;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.theming.FieldColor;
+import android.content.theming.ThemeSettings;
+import android.content.theming.ThemeSettingsUpdater;
+import android.content.theming.ThemeStyle;
+
+import com.google.common.truth.Truth;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class FieldColorTests {
+ static final ThemeSettings DEFAULTS = new ThemeSettings(1, 0xFF123456, 0xFF654321,
+ "home_wallpaper", ThemeStyle.VIBRANT, true);
+
+ private FieldColor mFieldColor;
+
+ @Before
+ public void setup() {
+ // Default to blue
+ mFieldColor = new FieldColor("accentColor", ThemeSettingsUpdater::accentColor,
+ ThemeSettings::accentColor, DEFAULTS);
+ }
+
+ @Test
+ public void parse_validColor_returnsCorrectColor() {
+ Integer parsedValue = mFieldColor.parse("FF0000FF");
+ assertThat(parsedValue).isEqualTo(0xFF0000FF);
+ } @Test
+ public void parse_validColorLowercase_returnsCorrectColor() {
+ Integer parsedValue = mFieldColor.parse("ff0000ff");
+ assertThat(parsedValue).isEqualTo(0xFF0000FF);
+ }
+
+ @Test
+ public void parse_validColorNoAlpha_returnsCorrectColor() {
+ Integer parsedValue = mFieldColor.parse("0000ff");
+ assertThat(parsedValue).isEqualTo(0xFF0000FF);
+ }
+
+
+ @Test
+ public void parse_invalidColor_returnsNull() {
+ Integer parsedValue = mFieldColor.parse("invalid");
+ assertThat(parsedValue).isNull();
+ }
+
+ @Test
+ public void parse_nullColor_returnsNull() {
+ Integer parsedValue = mFieldColor.parse(null);
+ assertThat(parsedValue).isNull();
+ }
+
+ @Test
+ public void serialize_validColor_returnsCorrectString() {
+ String serializedValue = mFieldColor.serialize(0xFFFF0000); // Red
+ assertThat(serializedValue).isEqualTo("ffff0000");
+ }
+
+ @Test
+ public void serialize_zeroColor_returnsZeroString() {
+ String serializedValue = mFieldColor.serialize(0);
+ assertThat(serializedValue).isEqualTo("0");
+ }
+
+ @Test
+ public void validate_validColor_returnsTrue() {
+ assertThat(mFieldColor.validate(0xFF00FF00)).isTrue(); // Green
+ }
+
+ @Test
+ public void getFieldType_returnsIntegerClass() {
+ Truth.assertThat(mFieldColor.getFieldType()).isEqualTo(Integer.class);
+ }
+
+ @Test
+ public void getJsonType_returnsStringClass() {
+ Truth.assertThat(mFieldColor.getJsonType()).isEqualTo(String.class);
+ }
+
+ @Test
+ public void get_returnsDefaultValue() {
+ Truth.assertThat(mFieldColor.getDefaultValue()).isEqualTo(DEFAULTS.accentColor());
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/theming/FieldThemeStyleTests.java b/services/tests/servicestests/src/com/android/server/theming/FieldThemeStyleTests.java
new file mode 100644
index 000000000000..09d71292fcf6
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/theming/FieldThemeStyleTests.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.theming;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.theming.FieldThemeStyle;
+import android.content.theming.ThemeSettings;
+import android.content.theming.ThemeSettingsUpdater;
+import android.content.theming.ThemeStyle;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class FieldThemeStyleTests {
+ static final ThemeSettings DEFAULTS = new ThemeSettings(1, 0xFF123456, 0xFF654321,
+ "home_wallpaper", ThemeStyle.VIBRANT, true);
+
+ private FieldThemeStyle mFieldThemeStyle;
+
+ @Before
+ public void setup() {
+ mFieldThemeStyle = new FieldThemeStyle("themeStyle", ThemeSettingsUpdater::themeStyle,
+ ThemeSettings::themeStyle, DEFAULTS);
+ }
+
+ @Test
+ public void parse_validThemeStyle_returnsCorrectStyle() {
+ Integer parsedValue = mFieldThemeStyle.parse("EXPRESSIVE");
+ assertThat(parsedValue).isEqualTo(ThemeStyle.EXPRESSIVE);
+ }
+
+ @Test
+ public void parse_invalidThemeStyle_returnsNull() {
+ Integer parsedValue = mFieldThemeStyle.parse("INVALID");
+ assertThat(parsedValue).isNull();
+ }
+
+ @Test
+ public void serialize_validThemeStyle_returnsCorrectString() {
+ String serializedValue = mFieldThemeStyle.serialize(ThemeStyle.SPRITZ);
+ assertThat(serializedValue).isEqualTo("SPRITZ");
+ }
+
+ @Test
+ public void validate_validThemeStyle_returnsTrue() {
+ assertThat(mFieldThemeStyle.validate(ThemeStyle.TONAL_SPOT)).isTrue();
+ }
+
+ @Test
+ public void validate_invalidThemeStyle_returnsFalse() {
+ assertThat(mFieldThemeStyle.validate(-1)).isFalse();
+ }
+
+ @Test
+ public void getFieldType_returnsIntegerClass() {
+ assertThat(mFieldThemeStyle.getFieldType()).isEqualTo(Integer.class);
+ }
+
+ @Test
+ public void getJsonType_returnsStringClass() {
+ assertThat(mFieldThemeStyle.getJsonType()).isEqualTo(String.class);
+ }
+
+ @Test
+ public void get_returnsDefaultValue() {
+ assertThat(mFieldThemeStyle.getDefaultValue()).isEqualTo(DEFAULTS.themeStyle());
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/theming/TEST_MAPPING b/services/tests/servicestests/src/com/android/server/theming/TEST_MAPPING
new file mode 100644
index 000000000000..d8d73444f6ce
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/theming/TEST_MAPPING
@@ -0,0 +1,7 @@
+{
+ "presubmit": [
+ {
+ "name": "FrameworksServicesTests_theme"
+ }
+ ]
+} \ No newline at end of file
diff --git a/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsFieldTests.java b/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsFieldTests.java
new file mode 100644
index 000000000000..0dc267a8059f
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsFieldTests.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.theming;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.theming.ThemeSettings;
+import android.content.theming.ThemeSettingsField;
+import android.content.theming.ThemeSettingsUpdater;
+import android.content.theming.ThemeStyle;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+
+@RunWith(JUnit4.class)
+public class ThemeSettingsFieldTests {
+ static final ThemeSettings DEFAULTS = new ThemeSettings(1, 0xFF123456, 0xFF654321,
+ "home_wallpaper", ThemeStyle.VIBRANT, true);
+ private ThemeSettingsUpdater mUpdater;
+
+ @Before
+ public void setup() {
+ mUpdater = ThemeSettings.updater();
+ }
+
+ @Test
+ public void testFromJSON_validValue_setsValue() throws Exception {
+ TestThemeSettingsFieldInteger field = getSampleField();
+
+ JSONObject json = new JSONObject();
+ json.put("testKey", "5");
+
+ field.fromJSON(json, mUpdater);
+
+ assertThat(mUpdater.getColorIndex()).isEqualTo(5);
+ }
+
+ @Test
+ public void testFromJSON_nullValue_setsDefault() throws Exception {
+ TestThemeSettingsFieldInteger field = getSampleField();
+
+ JSONObject json = new JSONObject();
+ json.put("testKey",
+ JSONObject.NULL); // Using JSONObject.NULL is how you should indicate null in JSON
+
+ field.fromJSON(json, mUpdater);
+
+ assertThat(mUpdater.getColorIndex()).isEqualTo(DEFAULTS.colorIndex());
+ }
+
+ @Test
+ public void testFromJSON_invalidValue_setsDefault() throws Exception {
+ TestThemeSettingsFieldInteger field = getSampleField();
+
+ JSONObject json = new JSONObject();
+ json.put("testKey", "abc"); // Invalid value
+
+ field.fromJSON(json, mUpdater);
+
+ assertThat(mUpdater.getColorIndex()).isEqualTo(DEFAULTS.colorIndex());
+ }
+
+ @Test
+ public void testToJSON_validValue_writesValue() throws JSONException {
+ TestThemeSettingsFieldInteger field = getSampleField();
+ ThemeSettings settings = new ThemeSettings(10, 0xFF123456, 0xFF654321, "home_wallpaper",
+ 0, true);
+ JSONObject json = new JSONObject();
+
+ field.toJSON(settings, json);
+
+ assertThat(json.getString("testKey")).isEqualTo("10");
+ }
+
+ @Test
+ public void testDefaultValue_returnsGetDefault() {
+ TestThemeSettingsFieldInteger field = getSampleField();
+
+ assertThat(field.getDefaultValue()).isEqualTo(DEFAULTS.colorIndex());
+ }
+
+ @Test
+ public void test_String_validValue_returnsParsedValue() throws JSONException {
+ TestThemeSettingsFieldInteger field = getSampleField();
+
+ JSONObject json = new JSONObject();
+ json.put("testKey", "123");
+
+ field.fromJSON(json, mUpdater);
+
+ assertThat(mUpdater.getColorIndex()).isEqualTo(123);
+ }
+
+ @Test
+ public void test_String_invalidValue_returnsDefaultValue() throws JSONException {
+ TestThemeSettingsFieldInteger field = getSampleField();
+
+ JSONObject json = new JSONObject();
+ // values < 0 are invalid
+ json.put("testKey", "-123");
+ field.fromJSON(json, mUpdater);
+
+ assertThat(mUpdater.getColorIndex()).isEqualTo(DEFAULTS.colorIndex());
+ }
+
+ private TestThemeSettingsFieldInteger getSampleField() {
+ return new TestThemeSettingsFieldInteger("testKey", ThemeSettingsUpdater::colorIndex,
+ ThemeSettings::colorIndex, DEFAULTS);
+ }
+
+
+ // Helper class for testing
+ private static class TestThemeSettingsFieldInteger extends ThemeSettingsField<Integer, String> {
+ TestThemeSettingsFieldInteger(String key, BiConsumer<ThemeSettingsUpdater, Integer> setter,
+ Function<ThemeSettings, Integer> getter, ThemeSettings defaults) {
+ super(key, setter, getter, defaults);
+ }
+
+ @Override
+ public Integer parse(String primitive) {
+ try {
+ return Integer.parseInt(primitive);
+ } catch (NumberFormatException e) {
+ return null;
+ }
+ }
+
+ @Override
+ public String serialize(Integer value) throws RuntimeException {
+ return value.toString();
+ }
+
+ @Override
+ public boolean validate(Integer value) {
+ return value > 0;
+ }
+
+ @Override
+ public Class<Integer> getFieldType() {
+ return Integer.class;
+ }
+
+ @Override
+ public Class<String> getJsonType() {
+ return String.class;
+ }
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsManagerTests.java b/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsManagerTests.java
new file mode 100644
index 000000000000..44f8c73dec84
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsManagerTests.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.theming;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.ContentResolver;
+import android.content.theming.ThemeSettings;
+import android.content.theming.ThemeStyle;
+import android.provider.Settings;
+import android.testing.TestableContext;
+
+import org.json.JSONObject;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
+
+@RunWith(JUnit4.class)
+public class ThemeSettingsManagerTests {
+ private final int mUserId = 0;
+ public static final ThemeSettings DEFAULTS = new ThemeSettings(
+ /* colorIndex= */ 1,
+ /* systemPalette= */ 0xFF123456,
+ /* accentColor= */ 0xFF654321,
+ /* colorSource= */ "home_wallpaper",
+ /* themeStyle= */ ThemeStyle.VIBRANT,
+ /* colorBoth= */ true);
+
+ @Rule
+ public final TestableContext mContext = new TestableContext(
+ getInstrumentation().getTargetContext(), null);
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ private ContentResolver mContentResolver;
+
+
+ @Before
+ public void setup() {
+ mContentResolver = mContext.getContentResolver();
+ }
+
+ @Test
+ public void loadSettings_emptyJSON_returnsDefault() {
+ Settings.Secure.putStringForUser(mContentResolver,
+ Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES, "{}", mUserId);
+
+ ThemeSettingsManager manager = new ThemeSettingsManager(DEFAULTS);
+ ThemeSettings settings = manager.loadSettings(mUserId, mContentResolver);
+
+ assertThat(settings.colorIndex()).isEqualTo(DEFAULTS.colorIndex());
+ assertThat(settings.systemPalette()).isEqualTo(DEFAULTS.systemPalette());
+ assertThat(settings.accentColor()).isEqualTo(DEFAULTS.accentColor());
+ assertThat(settings.colorSource()).isEqualTo(DEFAULTS.colorSource());
+ assertThat(settings.themeStyle()).isEqualTo(DEFAULTS.themeStyle());
+ assertThat(settings.colorBoth()).isEqualTo(DEFAULTS.colorBoth());
+ }
+
+ @Test
+ public void replaceSettings_writesSettingsToProvider() throws Exception {
+
+ ThemeSettingsManager manager = new ThemeSettingsManager(DEFAULTS);
+
+ ThemeSettings newSettings = new ThemeSettings(3, 0xFF112233, 0xFF332211, "preset",
+ ThemeStyle.MONOCHROMATIC, false);
+ manager.replaceSettings(mUserId, mContentResolver, newSettings);
+
+ String settingsString = Settings.Secure.getStringForUser(mContentResolver,
+ Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES, mUserId);
+ JSONObject settingsJson = new JSONObject(settingsString);
+ assertThat(settingsJson.getString("android.theme.customization.color_index")).isEqualTo(
+ "3");
+ assertThat(settingsJson.getString("android.theme.customization.system_palette"))
+ .isEqualTo("ff112233");
+ assertThat(settingsJson.getString("android.theme.customization.accent_color"))
+ .isEqualTo("ff332211");
+ assertThat(settingsJson.getString("android.theme.customization.color_source"))
+ .isEqualTo("preset");
+ assertThat(settingsJson.getString("android.theme.customization.theme_style"))
+ .isEqualTo("MONOCHROMATIC");
+ assertThat(settingsJson.getString("android.theme.customization.color_both")).isEqualTo("0");
+ }
+
+ @Test
+ public void updatesSettings_writesSettingsToProvider() throws Exception {
+ ThemeSettingsManager manager = new ThemeSettingsManager(DEFAULTS);
+
+ ThemeSettings newSettings = new ThemeSettings(3, 0xFF112233, 0xFF332211, "preset",
+ ThemeStyle.MONOCHROMATIC, false);
+ manager.updateSettings(mUserId, mContentResolver, newSettings);
+
+ ThemeSettings loadedSettings = manager.loadSettings(mUserId, mContentResolver);
+ assertThat(loadedSettings.equals(newSettings)).isTrue();
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsTests.java b/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsTests.java
new file mode 100644
index 000000000000..c417a4b571cb
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsTests.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.theming;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.assertNull;
+
+import android.content.theming.ThemeSettings;
+import android.content.theming.ThemeSettingsUpdater;
+import android.content.theming.ThemeStyle;
+import android.os.Parcel;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class ThemeSettingsTests {
+ public static final ThemeSettings DEFAULTS = new ThemeSettings(
+ /* colorIndex= */ 1,
+ /* systemPalette= */ 0xFF123456,
+ /* accentColor= */ 0xFF654321,
+ /* colorSource= */ "home_wallpaper",
+ /* themeStyle= */ ThemeStyle.VIBRANT,
+ /* colorBoth= */ true);
+
+ /**
+ * Test that the updater correctly sets all fields when they are provided.
+ */
+ @Test
+ public void testUpdater_allFieldsSet() {
+ ThemeSettingsUpdater updater = ThemeSettings.updater()
+ .colorIndex(2)
+ .systemPalette(0xFFFF0000)
+ .accentColor(0xFF00FF00)
+ .colorSource("preset")
+ .themeStyle(ThemeStyle.MONOCHROMATIC)
+ .colorBoth(false);
+
+ ThemeSettings settings = updater.toThemeSettings(DEFAULTS);
+
+ assertThat(settings.colorIndex()).isEqualTo(2);
+ assertThat(settings.systemPalette()).isEqualTo(0xFFFF0000);
+ assertThat(settings.accentColor()).isEqualTo(0xFF00FF00);
+ assertThat(settings.colorSource()).isEqualTo("preset");
+ assertThat(settings.themeStyle()).isEqualTo(ThemeStyle.MONOCHROMATIC);
+ assertThat(settings.colorBoth()).isEqualTo(false);
+ }
+
+ /**
+ * Test that the updater uses null values when no fields are explicitly set.
+ */
+ @Test
+ public void testUpdater_noFieldsSet() {
+ ThemeSettingsUpdater updater = ThemeSettings.updater();
+
+ assertNull(updater.getColorIndex());
+ assertNull(updater.getSystemPalette());
+ assertNull(updater.getAccentColor());
+ assertNull(updater.getColorSource());
+ assertNull(updater.getThemeStyle());
+ assertNull(updater.getColorBoth());
+ }
+
+ /**
+ * Test that the ThemeSettings object can be correctly parceled and restored.
+ */
+ @Test
+ public void testParcel_roundTrip() {
+ ThemeSettingsUpdater updater = ThemeSettings.updater()
+ .colorIndex(2)
+ .systemPalette(0xFFFF0000)
+ .accentColor(0xFF00FF00)
+ .colorSource("preset")
+ .themeStyle(ThemeStyle.MONOCHROMATIC)
+ .colorBoth(false);
+
+ ThemeSettings settings = updater.toThemeSettings(DEFAULTS);
+
+ Parcel parcel = Parcel.obtain();
+ settings.writeToParcel(parcel, 0);
+ parcel.setDataPosition(0);
+ ThemeSettings fromParcel = ThemeSettings.CREATOR.createFromParcel(parcel);
+
+ assertThat(settings.colorIndex()).isEqualTo(fromParcel.colorIndex());
+ assertThat(settings.systemPalette()).isEqualTo(fromParcel.systemPalette());
+ assertThat(settings.accentColor()).isEqualTo(fromParcel.accentColor());
+ assertThat(settings.colorSource()).isEqualTo(fromParcel.colorSource());
+ assertThat(settings.themeStyle()).isEqualTo(fromParcel.themeStyle());
+ assertThat(settings.colorBoth()).isEqualTo(fromParcel.colorBoth());
+ }
+}
diff --git a/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsUpdaterTests.java b/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsUpdaterTests.java
new file mode 100644
index 000000000000..7ce32da7b713
--- /dev/null
+++ b/services/tests/servicestests/src/com/android/server/theming/ThemeSettingsUpdaterTests.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2025 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.theming;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.theming.ThemeSettings;
+import android.content.theming.ThemeSettingsUpdater;
+import android.content.theming.ThemeStyle;
+import android.os.Parcel;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+public class ThemeSettingsUpdaterTests {
+ public static final ThemeSettings DEFAULTS = new ThemeSettings(
+ /* colorIndex= */ 1,
+ /* systemPalette= */ 0xFF123456,
+ /* accentColor= */ 0xFF654321,
+ /* colorSource= */ "home_wallpaper",
+ /* themeStyle= */ ThemeStyle.VIBRANT,
+ /* colorBoth= */ true);
+ private ThemeSettingsUpdater mUpdater;
+
+ @Before
+ public void setUp() {
+ mUpdater = ThemeSettings.updater();
+ }
+
+ @Test
+ public void testSetAndGetColorIndex() {
+ mUpdater.colorIndex(5);
+ assertThat(mUpdater.getColorIndex()).isEqualTo(5);
+ }
+
+ @Test
+ public void testSetAndGetSystemPalette() {
+ mUpdater.systemPalette(0xFFABCDEF);
+ assertThat(mUpdater.getSystemPalette()).isEqualTo(0xFFABCDEF);
+ }
+
+ @Test
+ public void testSetAndGetAccentColor() {
+ mUpdater.accentColor(0xFFFEDCBA);
+ assertThat(mUpdater.getAccentColor()).isEqualTo(0xFFFEDCBA);
+ }
+
+ @Test
+ public void testSetAndGetColorSource() {
+ mUpdater.colorSource("lock_wallpaper");
+ assertThat(mUpdater.getColorSource()).isEqualTo("lock_wallpaper");
+ }
+
+ @Test
+ public void testSetAndGetThemeStyle() {
+ mUpdater.themeStyle(ThemeStyle.EXPRESSIVE);
+ assertThat(mUpdater.getThemeStyle()).isEqualTo(ThemeStyle.EXPRESSIVE);
+ }
+
+ @Test
+ public void testSetAndGetColorBoth() {
+ mUpdater.colorBoth(false);
+ assertThat(mUpdater.getColorBoth()).isFalse();
+ }
+
+
+ @Test
+ public void testToThemeSettings_allFieldsSet() {
+ mUpdater.colorIndex(5)
+ .systemPalette(0xFFABCDEF)
+ .accentColor(0xFFFEDCBA)
+ .colorSource("lock_wallpaper")
+ .themeStyle(ThemeStyle.EXPRESSIVE)
+ .colorBoth(false);
+ ThemeSettings settings = mUpdater.toThemeSettings(DEFAULTS);
+
+ assertThat(settings.colorIndex()).isEqualTo(5);
+ assertThat(settings.systemPalette()).isEqualTo(0xFFABCDEF);
+ assertThat(settings.accentColor()).isEqualTo(0xFFFEDCBA);
+ assertThat(settings.colorSource()).isEqualTo("lock_wallpaper");
+ assertThat(settings.themeStyle()).isEqualTo(ThemeStyle.EXPRESSIVE);
+ assertThat(settings.colorBoth()).isFalse();
+ }
+
+ @Test
+ public void testToThemeSettings_someFieldsNotSet_usesDefaults() {
+ mUpdater.colorIndex(5)
+ .systemPalette(0xFFABCDEF);
+
+ ThemeSettings settings = mUpdater.toThemeSettings(DEFAULTS);
+
+ assertThat(settings.colorIndex()).isEqualTo(5);
+ assertThat(settings.systemPalette()).isEqualTo(0xFFABCDEF);
+ assertThat(settings.accentColor()).isEqualTo(DEFAULTS.accentColor());
+ assertThat(settings.colorSource()).isEqualTo(DEFAULTS.colorSource());
+ assertThat(settings.themeStyle()).isEqualTo(DEFAULTS.themeStyle());
+ assertThat(settings.colorBoth()).isEqualTo(DEFAULTS.colorBoth());
+ }
+
+ @Test
+ public void testParcel_roundTrip_allFieldsSet() {
+ mUpdater.colorIndex(5)
+ .systemPalette(0xFFABCDEF)
+ .accentColor(0xFFFEDCBA)
+ .colorSource("lock_wallpaper")
+ .themeStyle(ThemeStyle.EXPRESSIVE)
+ .colorBoth(false);
+
+ Parcel parcel = Parcel.obtain();
+ mUpdater.writeToParcel(parcel, 0);
+ parcel.setDataPosition(0);
+ ThemeSettingsUpdater fromParcel = ThemeSettingsUpdater.CREATOR.createFromParcel(parcel);
+
+ assertThat(fromParcel.getColorIndex()).isEqualTo(5);
+ assertThat(fromParcel.getSystemPalette()).isEqualTo(0xFFABCDEF);
+ assertThat(fromParcel.getAccentColor()).isEqualTo(0xFFFEDCBA);
+ assertThat(fromParcel.getColorSource()).isEqualTo("lock_wallpaper");
+ assertThat(fromParcel.getThemeStyle()).isEqualTo(ThemeStyle.EXPRESSIVE);
+ assertThat(fromParcel.getColorBoth()).isFalse();
+ }
+
+ @Test
+ public void testParcel_roundTrip_noFieldsSet() {
+ Parcel parcel = Parcel.obtain();
+ mUpdater.writeToParcel(parcel, 0);
+ parcel.setDataPosition(0);
+ ThemeSettingsUpdater fromParcel = ThemeSettingsUpdater.CREATOR.createFromParcel(parcel);
+
+ assertThat(fromParcel.getColorIndex()).isNull();
+ assertThat(fromParcel.getSystemPalette()).isNull();
+ assertThat(fromParcel.getAccentColor()).isNull();
+ assertThat(fromParcel.getColorSource()).isNull();
+ assertThat(fromParcel.getThemeStyle()).isNull();
+ assertThat(fromParcel.getColorBoth()).isNull();
+ }
+}
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
index 159b3fd7b5c3..b9b4a78df0ca 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/NotificationManagerServiceTest.java
@@ -17682,6 +17682,58 @@ public class NotificationManagerServiceTest extends UiServiceTestCase {
}
@Test
+ @EnableFlags({android.app.Flags.FLAG_API_RICH_ONGOING,
+ android.service.notification.Flags.FLAG_NOTIFICATION_CLASSIFICATION,
+ android.app.Flags.FLAG_NOTIFICATION_CLASSIFICATION_UI})
+ public void testApplyAdjustment_promotedOngoingNotification_doesNotApply() throws Exception {
+ // promoted ongoing notification which should not have the adjustment applied
+ Notification n = new Notification.Builder(mContext, mTestNotificationChannel.getId())
+ .setSmallIcon(android.R.drawable.sym_def_app_icon)
+ .setStyle(new Notification.BigTextStyle().setBigContentTitle("BIG"))
+ .setColor(Color.WHITE)
+ .setColorized(true)
+ .setOngoing(true)
+ .setFlag(FLAG_PROMOTED_ONGOING, true) // add manually since we're skipping post
+ .setFlag(FLAG_CAN_COLORIZE, true) // add manually since we're skipping post
+ .build();
+
+ StatusBarNotification sbn = new StatusBarNotification(mPkg, mPkg, 9, null, mUid, 0,
+ n, UserHandle.getUserHandleForUid(mUid), null, 0);
+ final NotificationRecord r = new NotificationRecord(mContext, sbn,
+ mTestNotificationChannel);
+
+ // regular notification record for contrast
+ final NotificationRecord r2 = generateNotificationRecord(mTestNotificationChannel);
+
+ mService.addNotification(r);
+ mService.addNotification(r2);
+ NotificationManagerService.WorkerHandler handler = mock(
+ NotificationManagerService.WorkerHandler.class);
+ mService.setHandler(handler);
+ when(mAssistants.isAdjustmentKeyTypeAllowed(anyInt())).thenReturn(true);
+ when(mAssistants.isAdjustmentAllowedForPackage(anyString(), anyString())).thenReturn(true);
+
+ Bundle signals = new Bundle();
+ signals.putInt(KEY_TYPE, TYPE_NEWS);
+ Bundle signals2 = new Bundle(signals); // copy for the second adjustment
+ Adjustment adjustment = new Adjustment(
+ r.getSbn().getPackageName(), r.getKey(), signals, "", r.getUser().getIdentifier());
+ Adjustment a2 = new Adjustment(r2.getSbn().getPackageName(), r2.getKey(), signals2, "",
+ r2.getUser().getIdentifier());
+ when(mAssistants.isSameUser(any(), anyInt())).thenReturn(true);
+ mBinderService.applyAdjustmentsFromAssistant(null, List.of(adjustment, a2));
+
+ waitForIdle();
+
+ r.applyAdjustments();
+ r2.applyAdjustments();
+
+ // promoted ongoing notification does not get bundled; regular one does
+ assertThat(r.getChannel().getId()).isEqualTo(mTestNotificationChannel.getId());
+ assertThat(r2.getChannel().getId()).isEqualTo(NEWS_ID);
+ }
+
+ @Test
@EnableFlags({android.app.Flags.FLAG_API_RICH_ONGOING})
public void testSetCanBePromoted_granted_noui() throws Exception {
testSetCanBePromoted_granted();
diff --git a/services/usage/java/com/android/server/usage/StorageStatsService.java b/services/usage/java/com/android/server/usage/StorageStatsService.java
index e9da53a8a899..5097231b468f 100644
--- a/services/usage/java/com/android/server/usage/StorageStatsService.java
+++ b/services/usage/java/com/android/server/usage/StorageStatsService.java
@@ -352,7 +352,53 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
}
@Override
- public StorageStats queryStatsForPackage(String volumeUuid, String packageName, int userId,
+ public StorageStats queryArtManagedStats(String packageName, int userId, int uid) {
+ if (userId != UserHandle.getCallingUserId()) {
+ mContext.enforceCallingOrSelfPermission(
+ android.Manifest.permission.INTERACT_ACROSS_USERS, TAG);
+ }
+
+ ApplicationInfo appInfo;
+ if (!TextUtils.isEmpty(packageName)) {
+ try {
+ appInfo = mPackage.getApplicationInfoAsUser(packageName,
+ PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
+ } catch (NameNotFoundException e) {
+ throw new ParcelableException(e);
+ }
+ uid = appInfo.uid;
+ if (defeatNullable(mPackage.getPackagesForUid(appInfo.uid)).length > 1) {
+ // Multiple packages, skip
+ return translate(new PackageStats(TAG));
+ }
+ }
+
+ int callingUid = Binder.getCallingUid();
+ String callingPackage = mPackage.getNameForUid(callingUid);
+ if (Binder.getCallingUid() != uid) {
+ enforceStatsPermission(Binder.getCallingUid(), callingPackage);
+ }
+
+ final String[] packageNames = defeatNullable(mPackage.getPackagesForUid(uid));
+ final PackageStats stats = new PackageStats(TAG);
+ for (int i = 0; i < packageNames.length; i++) {
+ try {
+ appInfo = mPackage.getApplicationInfoAsUser(packageNames[i],
+ PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
+ if (appInfo.isSystemApp() && !appInfo.isUpdatedSystemApp()) {
+ // We don't count code baked into system image
+ } else {
+ computeAppArtStats(stats, packageNames[i]);
+ }
+ } catch (NameNotFoundException e) {
+ throw new ParcelableException(e);
+ }
+ }
+ return translate(stats);
+ }
+
+ @Override
+ public StorageStats queryStatsForPackage(String volumeUuid, String packageName, int userId,
String callingPackage) {
if (userId != UserHandle.getCallingUserId()) {
mContext.enforceCallingOrSelfPermission(
@@ -378,9 +424,10 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
callerHasStatsPermission = true;
}
+ StorageStats storageStats;
if (defeatNullable(mPackage.getPackagesForUid(appInfo.uid)).length == 1) {
// Only one package inside UID means we can fast-path
- return queryStatsForUid(volumeUuid, appInfo.uid, callingPackage);
+ storageStats = queryStatsForUid(volumeUuid, appInfo.uid, callingPackage);
} else {
// Multiple packages means we need to go manual
final int appId = UserHandle.getAppId(appInfo.uid);
@@ -411,12 +458,16 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
packageName, userHandle, callerHasStatsPermission);
}, "queryStatsForPackage");
}
- return translate(stats);
+ storageStats = translate(stats);
}
+ storageStats.packageName = packageName;
+ storageStats.userHandle = userId;
+ return storageStats;
}
@Override
- public StorageStats queryStatsForUid(String volumeUuid, int uid, String callingPackage) {
+ public StorageStats queryStatsForUid(String volumeUuid, int uid,
+ String callingPackage) {
final int userId = UserHandle.getUserId(uid);
final int appId = UserHandle.getAppId(uid);
@@ -481,7 +532,10 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
storageStatsAugmenter.augmentStatsForUid(stats, uid, callerHasStatsPermission);
}, "queryStatsForUid");
}
- return translate(stats);
+ StorageStats storageStats = translate(stats);
+ storageStats.userHandle = userId;
+ storageStats.uid = uid;
+ return storageStats;
}
@Override
@@ -592,8 +646,9 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
}
}
- private static StorageStats translate(PackageStats stats) {
+ private StorageStats translate(PackageStats stats) {
final StorageStats res = new StorageStats();
+ res.userHandle = stats.userHandle;
res.codeBytes = stats.codeSize + stats.externalCodeSize;
res.dataBytes = stats.dataSize + stats.externalDataSize;
res.cacheBytes = stats.cacheSize + stats.externalCacheSize;
@@ -967,6 +1022,12 @@ public class StorageStatsService extends IStorageStatsManager.Stub {
stats.dmSize += getFileBytesInDir(srcDir, ".dm");
stats.libSize += getDirBytes(new File(sourceDirName + "/lib/"));
+ if (!Flags.getAppArtManagedBytes()) {
+ computeAppArtStats(stats, packageName);
+ }
+ }
+
+ private void computeAppArtStats(PackageStats stats, String packageName) {
// Get dexopt, current profle and reference profile sizes.
ArtManagedFileStats artManagedFileStats;
try (var snapshot = getPackageManagerLocal().withFilteredSnapshot()) {
diff --git a/tests/AppJankTest/src/android/app/jank/tests/IntegrationTests.java b/tests/AppJankTest/src/android/app/jank/tests/IntegrationTests.java
index 229c7bfb53e9..a08b650b4c2f 100644
--- a/tests/AppJankTest/src/android/app/jank/tests/IntegrationTests.java
+++ b/tests/AppJankTest/src/android/app/jank/tests/IntegrationTests.java
@@ -222,4 +222,46 @@ public class IntegrationTests {
assertTrue(jankTracker.shouldTrack());
}
+
+ /*
+ When JankTracker is first instantiated it gets passed the apps UID the same UID should be
+ passed when reporting AppJankStats. To make sure frames and metrics are all associated with
+ the same app these UIDs need to match. This test confirms that mismatched IDs are not
+ counted.
+ */
+ @Test
+ @RequiresFlagsEnabled(Flags.FLAG_DETAILED_APP_JANK_METRICS_API)
+ public void reportJankStats_statNotMerged_onMisMatchedAppIds() {
+ Activity jankTrackerActivity = mJankTrackerActivityRule.launchActivity(null);
+ mDevice.wait(Until.findObject(
+ By.text(jankTrackerActivity.getString(R.string.continue_test))),
+ WAIT_FOR_TIMEOUT_MS);
+
+ EditText editText = jankTrackerActivity.findViewById(R.id.edit_text);
+ JankTracker jankTracker = editText.getJankTracker();
+
+ HashMap<String, JankDataProcessor.PendingJankStat> pendingStats =
+ jankTracker.getPendingJankStats();
+ assertEquals(0, pendingStats.size());
+
+ int mismatchedAppUID = 25;
+ editText.reportAppJankStats(JankUtils.getAppJankStats(mismatchedAppUID));
+
+ // reportAppJankStats performs the work on a background thread, check periodically to see
+ // if the work is complete.
+ for (int i = 0; i < 10; i++) {
+ try {
+ Thread.sleep(100);
+ if (jankTracker.getPendingJankStats().size() > 0) {
+ break;
+ }
+ } catch (InterruptedException exception) {
+ //do nothing and continue
+ }
+ }
+
+ pendingStats = jankTracker.getPendingJankStats();
+
+ assertEquals(0, pendingStats.size());
+ }
}
diff --git a/tests/AppJankTest/src/android/app/jank/tests/JankUtils.java b/tests/AppJankTest/src/android/app/jank/tests/JankUtils.java
index 9640a84eb9ca..7067b873d4b7 100644
--- a/tests/AppJankTest/src/android/app/jank/tests/JankUtils.java
+++ b/tests/AppJankTest/src/android/app/jank/tests/JankUtils.java
@@ -18,16 +18,18 @@ package android.app.jank.tests;
import android.app.jank.AppJankStats;
import android.app.jank.RelativeFrameTimeHistogram;
+import android.os.Process;
+
public class JankUtils {
- private static final int APP_ID = 25;
+ private static final int APP_ID = Process.myUid();
/**
* Returns a mock AppJankStats object to be used in tests.
*/
- public static AppJankStats getAppJankStats() {
+ public static AppJankStats getAppJankStats(int appUID) {
AppJankStats jankStats = new AppJankStats(
- /*App Uid*/APP_ID,
+ /*App Uid*/appUID,
/*Widget Id*/"test widget id",
/*navigationComponent*/null,
/*Widget Category*/AppJankStats.WIDGET_CATEGORY_SCROLL,
@@ -39,6 +41,10 @@ public class JankUtils {
return jankStats;
}
+ public static AppJankStats getAppJankStats() {
+ return getAppJankStats(APP_ID);
+ }
+
/**
* Returns a mock histogram to be used with an AppJankStats object.
*/
diff --git a/tests/Input/src/android/hardware/input/InputDeviceBatteryListenerTest.kt b/tests/Input/src/android/hardware/input/InputDeviceBatteryListenerTest.kt
index a1e165551b5b..c58287760d0e 100644
--- a/tests/Input/src/android/hardware/input/InputDeviceBatteryListenerTest.kt
+++ b/tests/Input/src/android/hardware/input/InputDeviceBatteryListenerTest.kt
@@ -44,14 +44,12 @@ import org.mockito.junit.MockitoJUnitRunner
/**
* Tests for [InputManager.InputDeviceBatteryListener].
*
- * Build/Install/Run:
- * atest InputTests:InputDeviceBatteryListenerTest
+ * Build/Install/Run: atest InputTests:InputDeviceBatteryListenerTest
*/
@Presubmit
@RunWith(MockitoJUnitRunner::class)
class InputDeviceBatteryListenerTest {
- @get:Rule
- val rule = MockitoJUnit.rule()!!
+ @get:Rule val rule = MockitoJUnit.rule()!!
private lateinit var testLooper: TestLooper
private var registeredListener: IInputDeviceBatteryListener? = null
@@ -60,8 +58,7 @@ class InputDeviceBatteryListenerTest {
private lateinit var context: Context
private lateinit var inputManager: InputManager
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
+ @get:Rule val inputManagerRule = MockInputManagerRule()
@Before
fun setUp() {
@@ -71,41 +68,48 @@ class InputDeviceBatteryListenerTest {
registeredListener = null
monitoredDevices.clear()
inputManager = InputManager(context)
- `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE)))
- .thenReturn(inputManager)
+ `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))).thenReturn(inputManager)
// Handle battery listener registration.
doAnswer {
- val deviceId = it.getArgument(0) as Int
- val listener = it.getArgument(1) as IInputDeviceBatteryListener
- if (registeredListener != null &&
- registeredListener!!.asBinder() != listener.asBinder()) {
- // There can only be one registered battery listener per process.
- fail("Trying to register a new listener when one already exists")
+ val deviceId = it.getArgument(0) as Int
+ val listener = it.getArgument(1) as IInputDeviceBatteryListener
+ if (
+ registeredListener != null &&
+ registeredListener!!.asBinder() != listener.asBinder()
+ ) {
+ // There can only be one registered battery listener per process.
+ fail("Trying to register a new listener when one already exists")
+ }
+ if (monitoredDevices.contains(deviceId)) {
+ fail("Trying to start monitoring a device that was already being monitored")
+ }
+ monitoredDevices.add(deviceId)
+ registeredListener = listener
+ null
}
- if (monitoredDevices.contains(deviceId)) {
- fail("Trying to start monitoring a device that was already being monitored")
- }
- monitoredDevices.add(deviceId)
- registeredListener = listener
- null
- }.`when`(inputManagerRule.mock).registerBatteryListener(anyInt(), any())
+ .`when`(inputManagerRule.mock)
+ .registerBatteryListener(anyInt(), any())
// Handle battery listener being unregistered.
doAnswer {
- val deviceId = it.getArgument(0) as Int
- val listener = it.getArgument(1) as IInputDeviceBatteryListener
- if (registeredListener == null ||
- registeredListener!!.asBinder() != listener.asBinder()) {
- fail("Trying to unregister a listener that is not registered")
- }
- if (!monitoredDevices.remove(deviceId)) {
- fail("Trying to stop monitoring a device that is not being monitored")
+ val deviceId = it.getArgument(0) as Int
+ val listener = it.getArgument(1) as IInputDeviceBatteryListener
+ if (
+ registeredListener == null ||
+ registeredListener!!.asBinder() != listener.asBinder()
+ ) {
+ fail("Trying to unregister a listener that is not registered")
+ }
+ if (!monitoredDevices.remove(deviceId)) {
+ fail("Trying to stop monitoring a device that is not being monitored")
+ }
+ if (monitoredDevices.isEmpty()) {
+ registeredListener = null
+ }
}
- if (monitoredDevices.isEmpty()) {
- registeredListener = null
- }
- }.`when`(inputManagerRule.mock).unregisterBatteryListener(anyInt(), any())
+ .`when`(inputManagerRule.mock)
+ .unregisterBatteryListener(anyInt(), any())
}
private fun notifyBatteryStateChanged(
@@ -113,15 +117,17 @@ class InputDeviceBatteryListenerTest {
isPresent: Boolean = true,
status: Int = BatteryState.STATUS_FULL,
capacity: Float = 1.0f,
- eventTime: Long = 12345L
+ eventTime: Long = 12345L,
) {
- registeredListener!!.onBatteryStateChanged(IInputDeviceBatteryState().apply {
- this.deviceId = deviceId
- this.updateTime = eventTime
- this.isPresent = isPresent
- this.status = status
- this.capacity = capacity
- })
+ registeredListener!!.onBatteryStateChanged(
+ IInputDeviceBatteryState().apply {
+ this.deviceId = deviceId
+ this.updateTime = eventTime
+ this.isPresent = isPresent
+ this.status = status
+ this.capacity = capacity
+ }
+ )
}
@Test
@@ -130,7 +136,9 @@ class InputDeviceBatteryListenerTest {
// Add a battery listener to monitor battery changes.
inputManager.addInputDeviceBatteryListener(1 /*deviceId*/, executor) {
- deviceId: Int, eventTime: Long, batteryState: BatteryState ->
+ deviceId: Int,
+ eventTime: Long,
+ batteryState: BatteryState ->
callbackCount++
assertEquals(1, deviceId)
assertEquals(true, batteryState.isPresent)
@@ -149,8 +157,13 @@ class InputDeviceBatteryListenerTest {
assertEquals(0, callbackCount)
// Notifying battery change for the registered device will notify the listener.
- notifyBatteryStateChanged(1 /*deviceId*/, true /*isPresent*/,
- BatteryState.STATUS_DISCHARGING, 0.5f /*capacity*/, 8675309L /*eventTime*/)
+ notifyBatteryStateChanged(
+ 1 /*deviceId*/,
+ true /*isPresent*/,
+ BatteryState.STATUS_DISCHARGING,
+ 0.5f /*capacity*/,
+ 8675309L, /*eventTime*/
+ )
testLooper.dispatchNext()
assertEquals(1, callbackCount)
}
diff --git a/tests/Input/src/android/hardware/input/InputManagerTest.kt b/tests/Input/src/android/hardware/input/InputManagerTest.kt
index 4c6bb849155c..e6bec077d9d4 100644
--- a/tests/Input/src/android/hardware/input/InputManagerTest.kt
+++ b/tests/Input/src/android/hardware/input/InputManagerTest.kt
@@ -38,8 +38,7 @@ import org.mockito.junit.MockitoJUnitRunner
/**
* Tests for [InputManager].
*
- * Build/Install/Run:
- * atest InputTests:InputManagerTest
+ * Build/Install/Run: atest InputTests:InputManagerTest
*/
@Presubmit
@RunWith(MockitoJUnitRunner::class)
@@ -51,8 +50,7 @@ class InputManagerTest {
const val THIRD_DEVICE_ID = 99
}
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
+ @get:Rule val inputManagerRule = MockInputManagerRule()
private lateinit var devicesChangedListener: IInputDevicesChangedListener
private val deviceGenerationMap = mutableMapOf<Int /*deviceId*/, Int /*generation*/>()
@@ -64,9 +62,7 @@ class InputManagerTest {
context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext()))
inputManager = InputManager(context)
`when`(context.getSystemService(eq(Context.INPUT_SERVICE))).thenReturn(inputManager)
- `when`(inputManagerRule.mock.inputDeviceIds).then {
- deviceGenerationMap.keys.toIntArray()
- }
+ `when`(inputManagerRule.mock.inputDeviceIds).then { deviceGenerationMap.keys.toIntArray() }
}
private fun notifyDeviceChanged(
@@ -74,8 +70,9 @@ class InputManagerTest {
associatedDisplayId: Int,
usiVersion: HostUsiVersion?,
) {
- val generation = deviceGenerationMap[deviceId]?.plus(1)
- ?: throw IllegalArgumentException("Device $deviceId was never added!")
+ val generation =
+ deviceGenerationMap[deviceId]?.plus(1)
+ ?: throw IllegalArgumentException("Device $deviceId was never added!")
deviceGenerationMap[deviceId] = generation
`when`(inputManagerRule.mock.getInputDevice(deviceId))
diff --git a/tests/Input/src/android/hardware/input/KeyGestureEventHandlerTest.kt b/tests/Input/src/android/hardware/input/KeyGestureEventHandlerTest.kt
index c62bd0b72584..7f7d4590c322 100644
--- a/tests/Input/src/android/hardware/input/KeyGestureEventHandlerTest.kt
+++ b/tests/Input/src/android/hardware/input/KeyGestureEventHandlerTest.kt
@@ -23,6 +23,11 @@ import android.platform.test.flag.junit.SetFlagsRule
import android.view.KeyEvent
import androidx.test.core.app.ApplicationProvider
import com.android.test.input.MockInputManagerRule
+import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+import kotlin.test.fail
+import org.junit.Assert.assertThrows
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@@ -31,17 +36,11 @@ import org.mockito.Mockito
import org.mockito.Mockito.doAnswer
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner
-import kotlin.test.assertEquals
-import kotlin.test.assertNotNull
-import kotlin.test.assertNull
-import kotlin.test.fail
-import org.junit.Assert.assertThrows
/**
* Tests for [InputManager.KeyGestureEventHandler].
*
- * Build/Install/Run:
- * atest InputTests:KeyGestureEventHandlerTest
+ * Build/Install/Run: atest InputTests:KeyGestureEventHandlerTest
*/
@Presubmit
@RunWith(MockitoJUnitRunner::class)
@@ -49,24 +48,24 @@ class KeyGestureEventHandlerTest {
companion object {
const val DEVICE_ID = 1
- val HOME_GESTURE_EVENT = KeyGestureEvent.Builder()
- .setDeviceId(DEVICE_ID)
- .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H))
- .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON)
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
- val BACK_GESTURE_EVENT = KeyGestureEvent.Builder()
- .setDeviceId(DEVICE_ID)
- .setKeycodes(intArrayOf(KeyEvent.KEYCODE_DEL))
- .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON)
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
- .build()
+ val HOME_GESTURE_EVENT =
+ KeyGestureEvent.Builder()
+ .setDeviceId(DEVICE_ID)
+ .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H))
+ .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON)
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build()
+ val BACK_GESTURE_EVENT =
+ KeyGestureEvent.Builder()
+ .setDeviceId(DEVICE_ID)
+ .setKeycodes(intArrayOf(KeyEvent.KEYCODE_DEL))
+ .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON)
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
+ .build()
}
- @get:Rule
- val rule = SetFlagsRule()
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
+ @get:Rule val rule = SetFlagsRule()
+ @get:Rule val inputManagerRule = MockInputManagerRule()
private var registeredListener: IKeyGestureHandler? = null
private lateinit var context: Context
@@ -76,31 +75,38 @@ class KeyGestureEventHandlerTest {
fun setUp() {
context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext()))
inputManager = InputManager(context)
- `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE)))
- .thenReturn(inputManager)
+ `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))).thenReturn(inputManager)
// Handle key gesture handler registration.
doAnswer {
- val listener = it.getArgument(1) as IKeyGestureHandler
- if (registeredListener != null &&
- registeredListener!!.asBinder() != listener.asBinder()) {
- // There can only be one registered key gesture handler per process.
- fail("Trying to register a new listener when one already exists")
+ val listener = it.getArgument(1) as IKeyGestureHandler
+ if (
+ registeredListener != null &&
+ registeredListener!!.asBinder() != listener.asBinder()
+ ) {
+ // There can only be one registered key gesture handler per process.
+ fail("Trying to register a new listener when one already exists")
+ }
+ registeredListener = listener
+ null
}
- registeredListener = listener
- null
- }.`when`(inputManagerRule.mock).registerKeyGestureHandler(Mockito.any(), Mockito.any())
+ .`when`(inputManagerRule.mock)
+ .registerKeyGestureHandler(Mockito.any(), Mockito.any())
// Handle key gesture handler being unregistered.
doAnswer {
- val listener = it.getArgument(0) as IKeyGestureHandler
- if (registeredListener == null ||
- registeredListener!!.asBinder() != listener.asBinder()) {
- fail("Trying to unregister a listener that is not registered")
+ val listener = it.getArgument(0) as IKeyGestureHandler
+ if (
+ registeredListener == null ||
+ registeredListener!!.asBinder() != listener.asBinder()
+ ) {
+ fail("Trying to unregister a listener that is not registered")
+ }
+ registeredListener = null
+ null
}
- registeredListener = null
- null
- }.`when`(inputManagerRule.mock).unregisterKeyGestureHandler(Mockito.any())
+ .`when`(inputManagerRule.mock)
+ .unregisterKeyGestureHandler(Mockito.any())
}
private fun handleKeyGestureEvent(event: KeyGestureEvent) {
@@ -143,7 +149,7 @@ class KeyGestureEventHandlerTest {
// Adding the handler should register the callback with InputManagerService.
inputManager.registerKeyGestureEventHandler(
listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME),
- callback1
+ callback1,
)
assertNotNull(registeredListener)
@@ -151,7 +157,7 @@ class KeyGestureEventHandlerTest {
val currListener = registeredListener
inputManager.registerKeyGestureEventHandler(
listOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK),
- callback2
+ callback2,
)
assertEquals(currListener, registeredListener)
}
@@ -164,11 +170,11 @@ class KeyGestureEventHandlerTest {
inputManager.registerKeyGestureEventHandler(
listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME),
- callback1
+ callback1,
)
inputManager.registerKeyGestureEventHandler(
listOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK),
- callback2
+ callback2,
)
// Only removing all handlers should remove the internal callback
@@ -184,24 +190,26 @@ class KeyGestureEventHandlerTest {
var callbackCount1 = 0
var callbackCount2 = 0
// Handler 1 captures all home gestures
- val callback1 = InputManager.KeyGestureEventHandler { event, _ ->
- callbackCount1++
- assertEquals(KeyGestureEvent.KEY_GESTURE_TYPE_HOME, event.keyGestureType)
- }
+ val callback1 =
+ InputManager.KeyGestureEventHandler { event, _ ->
+ callbackCount1++
+ assertEquals(KeyGestureEvent.KEY_GESTURE_TYPE_HOME, event.keyGestureType)
+ }
// Handler 2 captures all back gestures
- val callback2 = InputManager.KeyGestureEventHandler { event, _ ->
- callbackCount2++
- assertEquals(KeyGestureEvent.KEY_GESTURE_TYPE_BACK, event.keyGestureType)
- }
+ val callback2 =
+ InputManager.KeyGestureEventHandler { event, _ ->
+ callbackCount2++
+ assertEquals(KeyGestureEvent.KEY_GESTURE_TYPE_BACK, event.keyGestureType)
+ }
// Add both key gesture event handlers
inputManager.registerKeyGestureEventHandler(
listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME),
- callback1
+ callback1,
)
inputManager.registerKeyGestureEventHandler(
listOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK),
- callback2
+ callback2,
)
// Request handling for home key gesture event, should notify only callback1
@@ -228,12 +236,13 @@ class KeyGestureEventHandlerTest {
inputManager.registerKeyGestureEventHandler(
listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME),
- handler
+ handler,
)
assertThrows(IllegalArgumentException::class.java) {
inputManager.registerKeyGestureEventHandler(
- listOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK), handler
+ listOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK),
+ handler,
)
}
}
@@ -245,12 +254,13 @@ class KeyGestureEventHandlerTest {
inputManager.registerKeyGestureEventHandler(
listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME),
- handler1
+ handler1,
)
assertThrows(IllegalArgumentException::class.java) {
inputManager.registerKeyGestureEventHandler(
- listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME), handler2
+ listOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME),
+ handler2,
)
}
}
diff --git a/tests/Input/src/android/hardware/input/KeyGestureEventListenerTest.kt b/tests/Input/src/android/hardware/input/KeyGestureEventListenerTest.kt
index cf0bfcc4f6df..bf3a9c389c7e 100644
--- a/tests/Input/src/android/hardware/input/KeyGestureEventListenerTest.kt
+++ b/tests/Input/src/android/hardware/input/KeyGestureEventListenerTest.kt
@@ -43,8 +43,7 @@ import org.mockito.junit.MockitoJUnitRunner
/**
* Tests for [InputManager.KeyGestureEventListener].
*
- * Build/Install/Run:
- * atest InputTests:KeyGestureEventListenerTest
+ * Build/Install/Run: atest InputTests:KeyGestureEventListenerTest
*/
@Presubmit
@RunWith(MockitoJUnitRunner::class)
@@ -52,18 +51,17 @@ class KeyGestureEventListenerTest {
companion object {
const val DEVICE_ID = 1
- val HOME_GESTURE_EVENT = KeyGestureEvent.Builder()
- .setDeviceId(DEVICE_ID)
- .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H))
- .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON)
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
+ val HOME_GESTURE_EVENT =
+ KeyGestureEvent.Builder()
+ .setDeviceId(DEVICE_ID)
+ .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H))
+ .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON)
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build()
}
- @get:Rule
- val rule = SetFlagsRule()
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
+ @get:Rule val rule = SetFlagsRule()
+ @get:Rule val inputManagerRule = MockInputManagerRule()
private val testLooper = TestLooper()
private val executor = HandlerExecutor(Handler(testLooper.looper))
@@ -75,31 +73,38 @@ class KeyGestureEventListenerTest {
fun setUp() {
context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext()))
inputManager = InputManager(context)
- `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE)))
- .thenReturn(inputManager)
+ `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))).thenReturn(inputManager)
// Handle key gesture event listener registration.
doAnswer {
- val listener = it.getArgument(0) as IKeyGestureEventListener
- if (registeredListener != null &&
- registeredListener!!.asBinder() != listener.asBinder()) {
- // There can only be one registered key gesture event listener per process.
- fail("Trying to register a new listener when one already exists")
+ val listener = it.getArgument(0) as IKeyGestureEventListener
+ if (
+ registeredListener != null &&
+ registeredListener!!.asBinder() != listener.asBinder()
+ ) {
+ // There can only be one registered key gesture event listener per process.
+ fail("Trying to register a new listener when one already exists")
+ }
+ registeredListener = listener
+ null
}
- registeredListener = listener
- null
- }.`when`(inputManagerRule.mock).registerKeyGestureEventListener(any())
+ .`when`(inputManagerRule.mock)
+ .registerKeyGestureEventListener(any())
// Handle key gesture event listener being unregistered.
doAnswer {
- val listener = it.getArgument(0) as IKeyGestureEventListener
- if (registeredListener == null ||
- registeredListener!!.asBinder() != listener.asBinder()) {
- fail("Trying to unregister a listener that is not registered")
+ val listener = it.getArgument(0) as IKeyGestureEventListener
+ if (
+ registeredListener == null ||
+ registeredListener!!.asBinder() != listener.asBinder()
+ ) {
+ fail("Trying to unregister a listener that is not registered")
+ }
+ registeredListener = null
+ null
}
- registeredListener = null
- null
- }.`when`(inputManagerRule.mock).unregisterKeyGestureEventListener(any())
+ .`when`(inputManagerRule.mock)
+ .unregisterKeyGestureEventListener(any())
}
private fun notifyKeyGestureEvent(event: KeyGestureEvent) {
@@ -119,8 +124,7 @@ class KeyGestureEventListenerTest {
var callbackCount = 0
// Add a key gesture event listener
- inputManager.registerKeyGestureEventListener(executor) {
- event: KeyGestureEvent ->
+ inputManager.registerKeyGestureEventListener(executor) { event: KeyGestureEvent ->
assertEquals(HOME_GESTURE_EVENT, event)
callbackCount++
}
diff --git a/tests/Input/src/android/hardware/input/KeyboardBacklightListenerTest.kt b/tests/Input/src/android/hardware/input/KeyboardBacklightListenerTest.kt
index d25dee1d402c..9e419439fba4 100644
--- a/tests/Input/src/android/hardware/input/KeyboardBacklightListenerTest.kt
+++ b/tests/Input/src/android/hardware/input/KeyboardBacklightListenerTest.kt
@@ -42,15 +42,13 @@ import org.mockito.junit.MockitoJUnitRunner
/**
* Tests for [InputManager.KeyboardBacklightListener].
*
- * Build/Install/Run:
- * atest InputTests:KeyboardBacklightListenerTest
+ * Build/Install/Run: atest InputTests:KeyboardBacklightListenerTest
*/
@Presubmit
@RunWith(MockitoJUnitRunner::class)
class KeyboardBacklightListenerTest {
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
+ @get:Rule val inputManagerRule = MockInputManagerRule()
private lateinit var testLooper: TestLooper
private var registeredListener: IKeyboardBacklightListener? = null
@@ -65,43 +63,54 @@ class KeyboardBacklightListenerTest {
executor = HandlerExecutor(Handler(testLooper.looper))
registeredListener = null
inputManager = InputManager(context)
- `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE)))
- .thenReturn(inputManager)
+ `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))).thenReturn(inputManager)
// Handle keyboard backlight listener registration.
doAnswer {
- val listener = it.getArgument(0) as IKeyboardBacklightListener
- if (registeredListener != null &&
- registeredListener!!.asBinder() != listener.asBinder()) {
- // There can only be one registered keyboard backlight listener per process.
- fail("Trying to register a new listener when one already exists")
+ val listener = it.getArgument(0) as IKeyboardBacklightListener
+ if (
+ registeredListener != null &&
+ registeredListener!!.asBinder() != listener.asBinder()
+ ) {
+ // There can only be one registered keyboard backlight listener per process.
+ fail("Trying to register a new listener when one already exists")
+ }
+ registeredListener = listener
+ null
}
- registeredListener = listener
- null
- }.`when`(inputManagerRule.mock).registerKeyboardBacklightListener(any())
+ .`when`(inputManagerRule.mock)
+ .registerKeyboardBacklightListener(any())
// Handle keyboard backlight listener being unregistered.
doAnswer {
- val listener = it.getArgument(0) as IKeyboardBacklightListener
- if (registeredListener == null ||
- registeredListener!!.asBinder() != listener.asBinder()) {
- fail("Trying to unregister a listener that is not registered")
+ val listener = it.getArgument(0) as IKeyboardBacklightListener
+ if (
+ registeredListener == null ||
+ registeredListener!!.asBinder() != listener.asBinder()
+ ) {
+ fail("Trying to unregister a listener that is not registered")
+ }
+ registeredListener = null
+ null
}
- registeredListener = null
- null
- }.`when`(inputManagerRule.mock).unregisterKeyboardBacklightListener(any())
+ .`when`(inputManagerRule.mock)
+ .unregisterKeyboardBacklightListener(any())
}
private fun notifyKeyboardBacklightChanged(
deviceId: Int,
brightnessLevel: Int,
maxBrightnessLevel: Int = 10,
- isTriggeredByKeyPress: Boolean = true
+ isTriggeredByKeyPress: Boolean = true,
) {
- registeredListener!!.onBrightnessChanged(deviceId, IKeyboardBacklightState().apply {
- this.brightnessLevel = brightnessLevel
- this.maxBrightnessLevel = maxBrightnessLevel
- }, isTriggeredByKeyPress)
+ registeredListener!!.onBrightnessChanged(
+ deviceId,
+ IKeyboardBacklightState().apply {
+ this.brightnessLevel = brightnessLevel
+ this.maxBrightnessLevel = maxBrightnessLevel
+ },
+ isTriggeredByKeyPress,
+ )
}
@Test
@@ -110,9 +119,9 @@ class KeyboardBacklightListenerTest {
// Add a keyboard backlight listener
inputManager.registerKeyboardBacklightListener(executor) {
- deviceId: Int,
- keyboardBacklightState: KeyboardBacklightState,
- isTriggeredByKeyPress: Boolean ->
+ deviceId: Int,
+ keyboardBacklightState: KeyboardBacklightState,
+ isTriggeredByKeyPress: Boolean ->
callbackCount++
assertEquals(1, deviceId)
assertEquals(2, keyboardBacklightState.brightnessLevel)
diff --git a/tests/Input/src/android/hardware/input/KeyboardLayoutPreviewTests.kt b/tests/Input/src/android/hardware/input/KeyboardLayoutPreviewTests.kt
index bcff2fcfca93..a59cbaf5fd55 100644
--- a/tests/Input/src/android/hardware/input/KeyboardLayoutPreviewTests.kt
+++ b/tests/Input/src/android/hardware/input/KeyboardLayoutPreviewTests.kt
@@ -28,8 +28,7 @@ import org.mockito.junit.MockitoJUnitRunner
/**
* Tests for Keyboard layout preview
*
- * Build/Install/Run:
- * atest InputTests:KeyboardLayoutPreviewTests
+ * Build/Install/Run: atest InputTests:KeyboardLayoutPreviewTests
*/
@Presubmit
@RunWith(MockitoJUnitRunner::class)
@@ -52,4 +51,4 @@ class KeyboardLayoutPreviewTests {
assertEquals(WIDTH, drawable.intrinsicWidth)
assertEquals(HEIGHT, drawable.intrinsicHeight)
}
-} \ No newline at end of file
+}
diff --git a/tests/Input/src/android/hardware/input/StickyModifierStateListenerTest.kt b/tests/Input/src/android/hardware/input/StickyModifierStateListenerTest.kt
index cc58bbc38e2d..620cb015911e 100644
--- a/tests/Input/src/android/hardware/input/StickyModifierStateListenerTest.kt
+++ b/tests/Input/src/android/hardware/input/StickyModifierStateListenerTest.kt
@@ -43,15 +43,13 @@ import org.mockito.junit.MockitoJUnitRunner
/**
* Tests for [InputManager.StickyModifierStateListener].
*
- * Build/Install/Run:
- * atest InputTests:StickyModifierStateListenerTest
+ * Build/Install/Run: atest InputTests:StickyModifierStateListenerTest
*/
@Presubmit
@RunWith(MockitoJUnitRunner::class)
class StickyModifierStateListenerTest {
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
+ @get:Rule val inputManagerRule = MockInputManagerRule()
private val testLooper = TestLooper()
private val executor = HandlerExecutor(Handler(testLooper.looper))
@@ -63,31 +61,38 @@ class StickyModifierStateListenerTest {
fun setUp() {
context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext()))
inputManager = InputManager(context)
- `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE)))
- .thenReturn(inputManager)
+ `when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE))).thenReturn(inputManager)
// Handle sticky modifier state listener registration.
doAnswer {
- val listener = it.getArgument(0) as IStickyModifierStateListener
- if (registeredListener != null &&
- registeredListener!!.asBinder() != listener.asBinder()) {
- // There can only be one registered sticky modifier state listener per process.
- fail("Trying to register a new listener when one already exists")
+ val listener = it.getArgument(0) as IStickyModifierStateListener
+ if (
+ registeredListener != null &&
+ registeredListener!!.asBinder() != listener.asBinder()
+ ) {
+ // There can only be one registered sticky modifier state listener per process.
+ fail("Trying to register a new listener when one already exists")
+ }
+ registeredListener = listener
+ null
}
- registeredListener = listener
- null
- }.`when`(inputManagerRule.mock).registerStickyModifierStateListener(any())
+ .`when`(inputManagerRule.mock)
+ .registerStickyModifierStateListener(any())
// Handle sticky modifier state listener being unregistered.
doAnswer {
- val listener = it.getArgument(0) as IStickyModifierStateListener
- if (registeredListener == null ||
- registeredListener!!.asBinder() != listener.asBinder()) {
- fail("Trying to unregister a listener that is not registered")
+ val listener = it.getArgument(0) as IStickyModifierStateListener
+ if (
+ registeredListener == null ||
+ registeredListener!!.asBinder() != listener.asBinder()
+ ) {
+ fail("Trying to unregister a listener that is not registered")
+ }
+ registeredListener = null
+ null
}
- registeredListener = null
- null
- }.`when`(inputManagerRule.mock).unregisterStickyModifierStateListener(any())
+ .`when`(inputManagerRule.mock)
+ .unregisterStickyModifierStateListener(any())
}
private fun notifyStickyModifierStateChanged(modifierState: Int, lockedModifierState: Int) {
@@ -99,9 +104,7 @@ class StickyModifierStateListenerTest {
var callbackCount = 0
// Add a sticky modifier state listener
- inputManager.registerStickyModifierStateListener(executor) {
- callbackCount++
- }
+ inputManager.registerStickyModifierStateListener(executor) { callbackCount++ }
// Notifying sticky modifier state change will notify the listener.
notifyStickyModifierStateChanged(0, 0)
@@ -112,8 +115,7 @@ class StickyModifierStateListenerTest {
@Test
fun testListenerHasCorrectModifierStateNotified() {
// Add a sticky modifier state listener
- inputManager.registerStickyModifierStateListener(executor) {
- state: StickyModifierState ->
+ inputManager.registerStickyModifierStateListener(executor) { state: StickyModifierState ->
assertTrue(state.isAltModifierOn)
assertTrue(state.isAltModifierLocked)
assertTrue(state.isShiftModifierOn)
@@ -128,9 +130,11 @@ class StickyModifierStateListenerTest {
// Notifying sticky modifier state change will notify the listener.
notifyStickyModifierStateChanged(
- KeyEvent.META_ALT_ON or KeyEvent.META_ALT_LEFT_ON or
- KeyEvent.META_SHIFT_ON or KeyEvent.META_SHIFT_LEFT_ON,
- KeyEvent.META_ALT_ON or KeyEvent.META_ALT_LEFT_ON
+ KeyEvent.META_ALT_ON or
+ KeyEvent.META_ALT_LEFT_ON or
+ KeyEvent.META_SHIFT_ON or
+ KeyEvent.META_SHIFT_LEFT_ON,
+ KeyEvent.META_ALT_ON or KeyEvent.META_ALT_LEFT_ON,
)
testLooper.dispatchNext()
}
diff --git a/tests/Input/src/com/android/server/input/AmbientKeyboardBacklightControllerTests.kt b/tests/Input/src/com/android/server/input/AmbientKeyboardBacklightControllerTests.kt
index ad481dff810c..075a3ab8cc73 100644
--- a/tests/Input/src/com/android/server/input/AmbientKeyboardBacklightControllerTests.kt
+++ b/tests/Input/src/com/android/server/input/AmbientKeyboardBacklightControllerTests.kt
@@ -54,8 +54,7 @@ import org.mockito.junit.MockitoJUnit
/**
* Tests for {@link AmbientKeyboardBacklightController}.
*
- * Build/Install/Run:
- * atest InputTests:AmbientKeyboardBacklightControllerTests
+ * Build/Install/Run: atest InputTests:AmbientKeyboardBacklightControllerTests
*/
@Presubmit
class AmbientKeyboardBacklightControllerTests {
@@ -66,24 +65,19 @@ class AmbientKeyboardBacklightControllerTests {
const val SENSOR_TYPE = "test_sensor_type"
}
- @get:Rule
- val rule = MockitoJUnit.rule()!!
+ @get:Rule val rule = MockitoJUnit.rule()!!
private lateinit var context: Context
private lateinit var testLooper: TestLooper
private lateinit var ambientController: AmbientKeyboardBacklightController
- @Mock
- private lateinit var resources: Resources
+ @Mock private lateinit var resources: Resources
- @Mock
- private lateinit var lightSensorInfo: InputSensorInfo
+ @Mock private lateinit var lightSensorInfo: InputSensorInfo
- @Mock
- private lateinit var sensorManager: SensorManager
+ @Mock private lateinit var sensorManager: SensorManager
- @Mock
- private lateinit var displayManagerInternal: DisplayManagerInternal
+ @Mock private lateinit var displayManagerInternal: DisplayManagerInternal
private lateinit var lightSensor: Sensor
private var currentDisplayInfo = DisplayInfo()
@@ -114,26 +108,26 @@ class AmbientKeyboardBacklightControllerTests {
`when`(resources.getIntArray(R.array.config_autoKeyboardBacklightIncreaseLuxThreshold))
.thenReturn(increaseThresholds)
`when`(
- resources.getValue(
- eq(R.dimen.config_autoKeyboardBrightnessSmoothingConstant),
- any(TypedValue::class.java),
- anyBoolean()
+ resources.getValue(
+ eq(R.dimen.config_autoKeyboardBrightnessSmoothingConstant),
+ any(TypedValue::class.java),
+ anyBoolean(),
+ )
)
- ).then {
- val args = it.arguments
- val outValue = args[1] as TypedValue
- outValue.data = java.lang.Float.floatToRawIntBits(1.0f)
- Unit
- }
+ .then {
+ val args = it.arguments
+ val outValue = args[1] as TypedValue
+ outValue.data = java.lang.Float.floatToRawIntBits(1.0f)
+ Unit
+ }
}
private fun setupSensor() {
LocalServices.removeServiceForTest(DisplayManagerInternal::class.java)
LocalServices.addService(DisplayManagerInternal::class.java, displayManagerInternal)
currentDisplayInfo.uniqueId = DEFAULT_DISPLAY_UNIQUE_ID
- `when`(displayManagerInternal.getDisplayInfo(Display.DEFAULT_DISPLAY)).thenReturn(
- currentDisplayInfo
- )
+ `when`(displayManagerInternal.getDisplayInfo(Display.DEFAULT_DISPLAY))
+ .thenReturn(currentDisplayInfo)
val sensorData = DisplayManagerInternal.AmbientLightSensorData(SENSOR_NAME, SENSOR_TYPE)
`when`(displayManagerInternal.getAmbientLightSensorData(Display.DEFAULT_DISPLAY))
.thenReturn(sensorData)
@@ -144,26 +138,28 @@ class AmbientKeyboardBacklightControllerTests {
`when`(context.getSystemService(eq(Context.SENSOR_SERVICE))).thenReturn(sensorManager)
`when`(sensorManager.getSensorList(anyInt())).thenReturn(listOf(lightSensor))
`when`(
- sensorManager.registerListener(
- any(),
- eq(lightSensor),
- anyInt(),
- any(Handler::class.java)
+ sensorManager.registerListener(
+ any(),
+ eq(lightSensor),
+ anyInt(),
+ any(Handler::class.java),
+ )
)
- ).then {
- listenerRegistered = true
- listenerRegistrationCount++
- true
- }
+ .then {
+ listenerRegistered = true
+ listenerRegistrationCount++
+ true
+ }
`when`(
- sensorManager.unregisterListener(
- any(SensorEventListener::class.java),
- eq(lightSensor)
+ sensorManager.unregisterListener(
+ any(SensorEventListener::class.java),
+ eq(lightSensor),
+ )
)
- ).then {
- listenerRegistered = false
- Unit
- }
+ .then {
+ listenerRegistered = false
+ Unit
+ }
}
private fun setupSensorWithInitialLux(luxValue: Float) {
@@ -181,7 +177,7 @@ class AmbientKeyboardBacklightControllerTests {
assertEquals(
"Should receive immediate callback for first lux change",
100,
- lastBrightnessCallback
+ lastBrightnessCallback,
)
}
@@ -190,15 +186,13 @@ class AmbientKeyboardBacklightControllerTests {
setupSensorWithInitialLux(500F)
// Current state: Step 1 [value = 100, increaseThreshold = 1000, decreaseThreshold = -1]
- repeat(HYSTERESIS_THRESHOLD) {
- sendAmbientLuxValue(1500F)
- }
+ repeat(HYSTERESIS_THRESHOLD) { sendAmbientLuxValue(1500F) }
testLooper.dispatchAll()
assertEquals(
"Should receive brightness change callback for increasing lux change",
200,
- lastBrightnessCallback
+ lastBrightnessCallback,
)
}
@@ -207,39 +201,31 @@ class AmbientKeyboardBacklightControllerTests {
setupSensorWithInitialLux(1500F)
// Current state: Step 2 [value = 200, increaseThreshold = 2000, decreaseThreshold = 900]
- repeat(HYSTERESIS_THRESHOLD) {
- sendAmbientLuxValue(500F)
- }
+ repeat(HYSTERESIS_THRESHOLD) { sendAmbientLuxValue(500F) }
testLooper.dispatchAll()
assertEquals(
"Should receive brightness change callback for decreasing lux change",
100,
- lastBrightnessCallback
+ lastBrightnessCallback,
)
}
@Test
fun testRegisterAmbientListener_throwsExceptionOnRegisteringDuplicate() {
- val ambientListener =
- AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener { }
+ val ambientListener = AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener {}
ambientController.registerAmbientBacklightListener(ambientListener)
assertThrows(IllegalStateException::class.java) {
- ambientController.registerAmbientBacklightListener(
- ambientListener
- )
+ ambientController.registerAmbientBacklightListener(ambientListener)
}
}
@Test
fun testUnregisterAmbientListener_throwsExceptionOnUnregisteringNonExistent() {
- val ambientListener =
- AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener { }
+ val ambientListener = AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener {}
assertThrows(IllegalStateException::class.java) {
- ambientController.unregisterAmbientBacklightListener(
- ambientListener
- )
+ ambientController.unregisterAmbientBacklightListener(ambientListener)
}
}
@@ -248,25 +234,23 @@ class AmbientKeyboardBacklightControllerTests {
assertEquals(
"Should not have a sensor listener registered at init",
0,
- listenerRegistrationCount
+ listenerRegistrationCount,
)
assertFalse("Should not have a sensor listener registered at init", listenerRegistered)
val ambientListener1 =
- AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener { }
+ AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener {}
ambientController.registerAmbientBacklightListener(ambientListener1)
- assertEquals(
- "Should register a new sensor listener", 1, listenerRegistrationCount
- )
+ assertEquals("Should register a new sensor listener", 1, listenerRegistrationCount)
assertTrue("Should have sensor listener registered", listenerRegistered)
val ambientListener2 =
- AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener { }
+ AmbientKeyboardBacklightController.AmbientKeyboardBacklightListener {}
ambientController.registerAmbientBacklightListener(ambientListener2)
assertEquals(
"Should not register a new sensor listener when adding a second ambient listener",
1,
- listenerRegistrationCount
+ listenerRegistrationCount,
)
assertTrue("Should have sensor listener registered", listenerRegistered)
@@ -276,7 +260,7 @@ class AmbientKeyboardBacklightControllerTests {
ambientController.unregisterAmbientBacklightListener(ambientListener2)
assertFalse(
"Should not have sensor listener registered if there are no ambient listeners",
- listenerRegistered
+ listenerRegistered,
)
}
@@ -291,7 +275,7 @@ class AmbientKeyboardBacklightControllerTests {
assertEquals(
"Should not re-register listener on display change if unique is same",
count,
- listenerRegistrationCount
+ listenerRegistrationCount,
)
}
@@ -307,7 +291,7 @@ class AmbientKeyboardBacklightControllerTests {
assertEquals(
"Should re-register listener on display change if unique id changed",
count + 1,
- listenerRegistrationCount
+ listenerRegistrationCount,
)
}
@@ -318,15 +302,13 @@ class AmbientKeyboardBacklightControllerTests {
// Previous state: Step 1 [value = 100, increaseThreshold = 1000, decreaseThreshold = -1]
// Current state: Step 2 [value = 200, increaseThreshold = 2000, decreaseThreshold = 900]
lastBrightnessCallback = -1
- repeat(HYSTERESIS_THRESHOLD) {
- sendAmbientLuxValue(999F)
- }
+ repeat(HYSTERESIS_THRESHOLD) { sendAmbientLuxValue(999F) }
testLooper.dispatchAll()
assertEquals(
"Should not receive any callback for brightness change",
-1,
- lastBrightnessCallback
+ lastBrightnessCallback,
)
}
@@ -337,15 +319,13 @@ class AmbientKeyboardBacklightControllerTests {
// Previous state: Step 1 [value = 100, increaseThreshold = 1000, decreaseThreshold = -1]
// Current state: Step 2 [value = 200, increaseThreshold = 2000, decreaseThreshold = 900]
lastBrightnessCallback = -1
- repeat(HYSTERESIS_THRESHOLD - 1) {
- sendAmbientLuxValue(2001F)
- }
+ repeat(HYSTERESIS_THRESHOLD - 1) { sendAmbientLuxValue(2001F) }
testLooper.dispatchAll()
assertEquals(
"Should not receive any callback for brightness change",
-1,
- lastBrightnessCallback
+ lastBrightnessCallback,
)
}
diff --git a/tests/Input/src/com/android/server/input/BatteryControllerTests.kt b/tests/Input/src/com/android/server/input/BatteryControllerTests.kt
index 890c346ea015..bcb740652dde 100644
--- a/tests/Input/src/com/android/server/input/BatteryControllerTests.kt
+++ b/tests/Input/src/com/android/server/input/BatteryControllerTests.kt
@@ -92,7 +92,7 @@ private fun createInputDevice(
private fun <T, U> memberMatcher(
member: String,
memberProvider: (T) -> U,
- match: Matcher<U>
+ match: Matcher<U>,
): TypeSafeMatcher<T> =
object : TypeSafeMatcher<T>() {
@@ -115,12 +115,13 @@ private fun matchesState(
isPresent: Boolean = true,
status: Int? = null,
capacity: Float? = null,
- eventTime: Long? = null
+ eventTime: Long? = null,
): Matcher<IInputDeviceBatteryState> {
- val batteryStateMatchers = mutableListOf<Matcher<IInputDeviceBatteryState>>(
- memberMatcher("deviceId", { it.deviceId }, equalTo(deviceId)),
- memberMatcher("isPresent", { it.isPresent }, equalTo(isPresent))
- )
+ val batteryStateMatchers =
+ mutableListOf<Matcher<IInputDeviceBatteryState>>(
+ memberMatcher("deviceId", { it.deviceId }, equalTo(deviceId)),
+ memberMatcher("isPresent", { it.isPresent }, equalTo(isPresent)),
+ )
if (eventTime != null) {
batteryStateMatchers.add(memberMatcher("updateTime", { it.updateTime }, equalTo(eventTime)))
}
@@ -143,14 +144,14 @@ private fun IInputDeviceBatteryListener.verifyNotified(
isPresent: Boolean = true,
status: Int? = null,
capacity: Float? = null,
- eventTime: Long? = null
+ eventTime: Long? = null,
) {
verifyNotified(matchesState(deviceId, isPresent, status, capacity, eventTime), mode)
}
private fun IInputDeviceBatteryListener.verifyNotified(
matcher: Matcher<IInputDeviceBatteryState>,
- mode: VerificationMode = times(1)
+ mode: VerificationMode = times(1),
) {
verify(this, mode).onBatteryStateChanged(MockitoHamcrest.argThat(matcher))
}
@@ -165,8 +166,7 @@ private fun createMockListener(): IInputDeviceBatteryListener {
/**
* Tests for {@link InputDeviceBatteryController}.
*
- * Build/Install/Run:
- * atest InputTests:InputDeviceBatteryControllerTests
+ * Build/Install/Run: atest InputTests:InputDeviceBatteryControllerTests
*/
@Presubmit
class BatteryControllerTests {
@@ -181,19 +181,13 @@ class BatteryControllerTests {
const val TIMESTAMP = 123456789L
}
- @get:Rule
- val rule = MockitoJUnit.rule()!!
- @get:Rule
- val context = TestableContext(ApplicationProvider.getApplicationContext())
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
+ @get:Rule val rule = MockitoJUnit.rule()!!
+ @get:Rule val context = TestableContext(ApplicationProvider.getApplicationContext())
+ @get:Rule val inputManagerRule = MockInputManagerRule()
- @Mock
- private lateinit var native: NativeInputManagerService
- @Mock
- private lateinit var uEventManager: UEventManager
- @Mock
- private lateinit var bluetoothBatteryManager: BluetoothBatteryManager
+ @Mock private lateinit var native: NativeInputManagerService
+ @Mock private lateinit var uEventManager: UEventManager
+ @Mock private lateinit var bluetoothBatteryManager: BluetoothBatteryManager
private lateinit var batteryController: BatteryController
private lateinit var testLooper: TestLooper
@@ -206,14 +200,18 @@ class BatteryControllerTests {
testLooper = TestLooper()
val inputManager = InputManager(context)
context.addMockSystemService(InputManager::class.java, inputManager)
- `when`(inputManagerRule.mock.inputDeviceIds).then {
- deviceGenerationMap.keys.toIntArray()
- }
+ `when`(inputManagerRule.mock.inputDeviceIds).then { deviceGenerationMap.keys.toIntArray() }
addInputDevice(DEVICE_ID)
addInputDevice(SECOND_DEVICE_ID)
- batteryController = BatteryController(context, native, testLooper.looper, uEventManager,
- bluetoothBatteryManager)
+ batteryController =
+ BatteryController(
+ context,
+ native,
+ testLooper.looper,
+ uEventManager,
+ bluetoothBatteryManager,
+ )
batteryController.systemRunning()
val listenerCaptor = ArgumentCaptor.forClass(IInputDevicesChangedListener::class.java)
verify(inputManagerRule.mock).registerInputDevicesChangedListener(listenerCaptor.capture())
@@ -222,12 +220,13 @@ class BatteryControllerTests {
}
private fun notifyDeviceChanged(
- deviceId: Int,
+ deviceId: Int,
hasBattery: Boolean = true,
- supportsUsi: Boolean = false
+ supportsUsi: Boolean = false,
) {
- val generation = deviceGenerationMap[deviceId]?.plus(1)
- ?: throw IllegalArgumentException("Device $deviceId was never added!")
+ val generation =
+ deviceGenerationMap[deviceId]?.plus(1)
+ ?: throw IllegalArgumentException("Device $deviceId was never added!")
deviceGenerationMap[deviceId] = generation
`when`(inputManagerRule.mock.getInputDevice(deviceId))
@@ -239,7 +238,7 @@ class BatteryControllerTests {
}
private fun addInputDevice(
- deviceId: Int,
+ deviceId: Int,
hasBattery: Boolean = true,
supportsUsi: Boolean = false,
) {
@@ -248,8 +247,10 @@ class BatteryControllerTests {
}
private fun createBluetoothDevice(address: String): BluetoothDevice {
- return context.getSystemService(BluetoothManager::class.java)!!
- .adapter.getRemoteDevice(address)
+ return context
+ .getSystemService(BluetoothManager::class.java)!!
+ .adapter
+ .getRemoteDevice(address)
}
@Test
@@ -279,8 +280,7 @@ class BatteryControllerTests {
try {
batteryController.registerBatteryListener(DEVICE_ID, listener2, PID)
fail("Expected security exception when registering more than one listener per process")
- } catch (ignored: SecurityException) {
- }
+ } catch (ignored: SecurityException) {}
}
@Test
@@ -323,15 +323,18 @@ class BatteryControllerTests {
batteryController.registerBatteryListener(DEVICE_ID, listener, PID)
// The device paths for UEvent notifications do not include the "/sys" prefix, so verify
// that the added listener is configured to match the path without that prefix.
- verify(uEventManager)
- .addListener(uEventListener.capture(), eq("DEVPATH=/dev/test/device1"))
+ verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/test/device1"))
listener.verifyNotified(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.78f)
// If the battery state has changed when an UEvent is sent, the listeners are notified.
`when`(native.getBatteryCapacity(DEVICE_ID)).thenReturn(80)
uEventListener.value!!.onBatteryUEvent(TIMESTAMP)
- listener.verifyNotified(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.80f,
- eventTime = TIMESTAMP)
+ listener.verifyNotified(
+ DEVICE_ID,
+ status = STATUS_CHARGING,
+ capacity = 0.80f,
+ eventTime = TIMESTAMP,
+ )
// If the battery state has not changed when an UEvent is sent, the listeners are not
// notified.
@@ -341,8 +344,11 @@ class BatteryControllerTests {
batteryController.unregisterBatteryListener(DEVICE_ID, listener, PID)
verify(uEventManager).removeListener(uEventListener.capture())
- assertEquals("The same observer must be registered and unregistered",
- uEventListener.allValues[0], uEventListener.allValues[1])
+ assertEquals(
+ "The same observer must be registered and unregistered",
+ uEventListener.allValues[0],
+ uEventListener.allValues[1],
+ )
}
@Test
@@ -366,8 +372,12 @@ class BatteryControllerTests {
// If the battery becomes present again, the listener is notified.
notifyDeviceChanged(DEVICE_ID, hasBattery = true)
testLooper.dispatchNext()
- listener.verifyNotified(DEVICE_ID, mode = times(2), status = STATUS_CHARGING,
- capacity = 0.78f)
+ listener.verifyNotified(
+ DEVICE_ID,
+ mode = times(2),
+ status = STATUS_CHARGING,
+ capacity = 0.78f,
+ )
// Ensure that a new UEventListener was added.
verify(uEventManager, times(2))
.addListener(uEventListener.capture(), eq("DEVPATH=/test/device1"))
@@ -437,8 +447,11 @@ class BatteryControllerTests {
`when`(native.getBatteryStatus(DEVICE_ID)).thenReturn(STATUS_CHARGING)
`when`(native.getBatteryCapacity(DEVICE_ID)).thenReturn(78)
val batteryState = batteryController.getBatteryState(DEVICE_ID)
- assertThat("battery state matches", batteryState,
- matchesState(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.78f))
+ assertThat(
+ "battery state matches",
+ batteryState,
+ matchesState(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.78f),
+ )
}
@Test
@@ -453,8 +466,11 @@ class BatteryControllerTests {
// change in the battery state, the listener is also notified.
`when`(native.getBatteryCapacity(DEVICE_ID)).thenReturn(80)
val batteryState = batteryController.getBatteryState(DEVICE_ID)
- assertThat("battery matches state", batteryState,
- matchesState(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.80f))
+ assertThat(
+ "battery matches state",
+ batteryState,
+ matchesState(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.80f),
+ )
listener.verifyNotified(DEVICE_ID, status = STATUS_CHARGING, capacity = 0.80f)
}
@@ -466,8 +482,7 @@ class BatteryControllerTests {
// Even though there is no listener added for this device, it is being monitored.
val uEventListener = ArgumentCaptor.forClass(UEventBatteryListener::class.java)
- verify(uEventManager)
- .addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device"))
+ verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device"))
// Add and remove a listener for the device.
val listener = createMockListener()
@@ -507,8 +522,7 @@ class BatteryControllerTests {
addInputDevice(USI_DEVICE_ID, supportsUsi = true)
testLooper.dispatchNext()
val uEventListener = ArgumentCaptor.forClass(UEventBatteryListener::class.java)
- verify(uEventManager)
- .addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device"))
+ verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device"))
// A USI device's battery state is not valid until the first UEvent notification.
// Add a listener, and ensure it is notified that the battery state is not present.
@@ -517,34 +531,49 @@ class BatteryControllerTests {
listener.verifyNotified(isInvalidBatteryState(USI_DEVICE_ID))
// Ensure that querying for battery state also returns the same invalid result.
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- isInvalidBatteryState(USI_DEVICE_ID))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ isInvalidBatteryState(USI_DEVICE_ID),
+ )
// There is a UEvent signaling a battery change. The battery state is now valid.
uEventListener.value!!.onBatteryUEvent(TIMESTAMP)
listener.verifyNotified(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f)
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f),
+ )
// There is another UEvent notification. The battery state is now updated.
`when`(native.getBatteryCapacity(USI_DEVICE_ID)).thenReturn(64)
uEventListener.value!!.onBatteryUEvent(TIMESTAMP + 1)
listener.verifyNotified(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.64f)
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.64f))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.64f),
+ )
// The battery state is still valid after a millisecond.
testLooper.moveTimeForward(1)
testLooper.dispatchAll()
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.64f))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.64f),
+ )
// The battery is no longer present after the timeout expires.
testLooper.moveTimeForward(USI_BATTERY_VALIDITY_DURATION_MILLIS - 1)
testLooper.dispatchNext()
listener.verifyNotified(isInvalidBatteryState(USI_DEVICE_ID), times(2))
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- isInvalidBatteryState(USI_DEVICE_ID))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ isInvalidBatteryState(USI_DEVICE_ID),
+ )
}
@Test
@@ -556,16 +585,18 @@ class BatteryControllerTests {
addInputDevice(USI_DEVICE_ID, supportsUsi = true)
testLooper.dispatchNext()
val uEventListener = ArgumentCaptor.forClass(UEventBatteryListener::class.java)
- verify(uEventManager)
- .addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device"))
+ verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device"))
// There is a UEvent signaling a battery change. The battery state is now valid.
uEventListener.value!!.onBatteryUEvent(TIMESTAMP)
val listener = createMockListener()
batteryController.registerBatteryListener(USI_DEVICE_ID, listener, PID)
listener.verifyNotified(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f)
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f),
+ )
// Stylus presence is detected before the validity timeout expires.
testLooper.moveTimeForward(100)
@@ -575,15 +606,21 @@ class BatteryControllerTests {
// Ensure that timeout was extended, and the battery state is now valid for longer.
testLooper.moveTimeForward(USI_BATTERY_VALIDITY_DURATION_MILLIS - 100)
testLooper.dispatchAll()
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f),
+ )
// Ensure the validity period expires after the expected amount of time.
testLooper.moveTimeForward(100)
testLooper.dispatchNext()
listener.verifyNotified(isInvalidBatteryState(USI_DEVICE_ID))
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- isInvalidBatteryState(USI_DEVICE_ID))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ isInvalidBatteryState(USI_DEVICE_ID),
+ )
}
@Test
@@ -595,22 +632,27 @@ class BatteryControllerTests {
addInputDevice(USI_DEVICE_ID, supportsUsi = true)
testLooper.dispatchNext()
val uEventListener = ArgumentCaptor.forClass(UEventBatteryListener::class.java)
- verify(uEventManager)
- .addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device"))
+ verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device"))
// The USI battery state is initially invalid.
val listener = createMockListener()
batteryController.registerBatteryListener(USI_DEVICE_ID, listener, PID)
listener.verifyNotified(isInvalidBatteryState(USI_DEVICE_ID))
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- isInvalidBatteryState(USI_DEVICE_ID))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ isInvalidBatteryState(USI_DEVICE_ID),
+ )
// A stylus presence is detected. This validates the battery state.
batteryController.notifyStylusGestureStarted(USI_DEVICE_ID, TIMESTAMP)
listener.verifyNotified(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f)
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ matchesState(USI_DEVICE_ID, status = STATUS_DISCHARGING, capacity = 0.78f),
+ )
}
@Test
@@ -623,27 +665,35 @@ class BatteryControllerTests {
addInputDevice(USI_DEVICE_ID, supportsUsi = true)
testLooper.dispatchNext()
val uEventListener = ArgumentCaptor.forClass(UEventBatteryListener::class.java)
- verify(uEventManager)
- .addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device"))
+ verify(uEventManager).addListener(uEventListener.capture(), eq("DEVPATH=/dev/usi_device"))
// The USI battery state is initially invalid.
val listener = createMockListener()
batteryController.registerBatteryListener(USI_DEVICE_ID, listener, PID)
listener.verifyNotified(isInvalidBatteryState(USI_DEVICE_ID))
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- isInvalidBatteryState(USI_DEVICE_ID))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ isInvalidBatteryState(USI_DEVICE_ID),
+ )
// Since the capacity reported is 0, stylus presence does not validate the battery state.
batteryController.notifyStylusGestureStarted(USI_DEVICE_ID, TIMESTAMP)
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- isInvalidBatteryState(USI_DEVICE_ID))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ isInvalidBatteryState(USI_DEVICE_ID),
+ )
// However, if a UEvent reports a battery capacity of 0, the battery state is now valid.
uEventListener.value!!.onBatteryUEvent(TIMESTAMP)
listener.verifyNotified(USI_DEVICE_ID, status = STATUS_UNKNOWN, capacity = 0f)
- assertThat("battery state matches", batteryController.getBatteryState(USI_DEVICE_ID),
- matchesState(USI_DEVICE_ID, status = STATUS_UNKNOWN, capacity = 0f))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(USI_DEVICE_ID),
+ matchesState(USI_DEVICE_ID, status = STATUS_UNKNOWN, capacity = 0f),
+ )
}
@Test
@@ -722,15 +772,21 @@ class BatteryControllerTests {
verify(bluetoothBatteryManager).addBatteryListener(bluetoothListener.capture())
verify(uEventManager).addListener(uEventListener.capture(), any())
listener.verifyNotified(BT_DEVICE_ID, capacity = 0.21f)
- assertThat("battery state matches", batteryController.getBatteryState(BT_DEVICE_ID),
- matchesState(BT_DEVICE_ID, capacity = 0.21f))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(BT_DEVICE_ID),
+ matchesState(BT_DEVICE_ID, capacity = 0.21f),
+ )
// If only the native battery state changes the listener is not notified.
`when`(native.getBatteryCapacity(BT_DEVICE_ID)).thenReturn(97)
uEventListener.value!!.onBatteryUEvent(TIMESTAMP)
listener.verifyNotified(BT_DEVICE_ID, mode = times(1), capacity = 0.21f)
- assertThat("battery state matches", batteryController.getBatteryState(BT_DEVICE_ID),
- matchesState(BT_DEVICE_ID, capacity = 0.21f))
+ assertThat(
+ "battery state matches",
+ batteryController.getBatteryState(BT_DEVICE_ID),
+ matchesState(BT_DEVICE_ID, capacity = 0.21f),
+ )
}
@Test
@@ -751,8 +807,11 @@ class BatteryControllerTests {
listener.verifyNotified(BT_DEVICE_ID, capacity = 0.21f)
// Fall back to the native state when BT is off.
- bluetoothListener.value!!.onBluetoothBatteryChanged(TIMESTAMP, "AA:BB:CC:DD:EE:FF",
- BluetoothDevice.BATTERY_LEVEL_BLUETOOTH_OFF)
+ bluetoothListener.value!!.onBluetoothBatteryChanged(
+ TIMESTAMP,
+ "AA:BB:CC:DD:EE:FF",
+ BluetoothDevice.BATTERY_LEVEL_BLUETOOTH_OFF,
+ )
listener.verifyNotified(BT_DEVICE_ID, capacity = 0.98f)
bluetoothListener.value!!.onBluetoothBatteryChanged(TIMESTAMP, "AA:BB:CC:DD:EE:FF", 22)
@@ -760,8 +819,11 @@ class BatteryControllerTests {
listener.verifyNotified(BT_DEVICE_ID, capacity = 0.22f)
// Fall back to the native state when BT battery is unknown.
- bluetoothListener.value!!.onBluetoothBatteryChanged(TIMESTAMP, "AA:BB:CC:DD:EE:FF",
- BluetoothDevice.BATTERY_LEVEL_UNKNOWN)
+ bluetoothListener.value!!.onBluetoothBatteryChanged(
+ TIMESTAMP,
+ "AA:BB:CC:DD:EE:FF",
+ BluetoothDevice.BATTERY_LEVEL_UNKNOWN,
+ )
listener.verifyNotified(BT_DEVICE_ID, mode = times(2), capacity = 0.98f)
}
@@ -782,10 +844,10 @@ class BatteryControllerTests {
batteryController.registerBatteryListener(DEVICE_ID, listener, PID)
verify(bluetoothBatteryManager, never()).addMetadataListener(any(), any())
- val metadataListener1 = ArgumentCaptor.forClass(
- BluetoothAdapter.OnMetadataChangedListener::class.java)
- val metadataListener2 = ArgumentCaptor.forClass(
- BluetoothAdapter.OnMetadataChangedListener::class.java)
+ val metadataListener1 =
+ ArgumentCaptor.forClass(BluetoothAdapter.OnMetadataChangedListener::class.java)
+ val metadataListener2 =
+ ArgumentCaptor.forClass(BluetoothAdapter.OnMetadataChangedListener::class.java)
// The metadata listener is added when the first BT input device is monitored.
batteryController.registerBatteryListener(BT_DEVICE_ID, listener, PID)
@@ -814,12 +876,16 @@ class BatteryControllerTests {
fun testNotifiesBluetoothMetadataBatteryChanges() {
`when`(inputManagerRule.mock.getInputDeviceBluetoothAddress(BT_DEVICE_ID))
.thenReturn("AA:BB:CC:DD:EE:FF")
- `when`(bluetoothBatteryManager.getMetadata("AA:BB:CC:DD:EE:FF",
- BluetoothDevice.METADATA_MAIN_BATTERY))
+ `when`(
+ bluetoothBatteryManager.getMetadata(
+ "AA:BB:CC:DD:EE:FF",
+ BluetoothDevice.METADATA_MAIN_BATTERY,
+ )
+ )
.thenReturn("21".toByteArray())
addInputDevice(BT_DEVICE_ID)
- val metadataListener = ArgumentCaptor.forClass(
- BluetoothAdapter.OnMetadataChangedListener::class.java)
+ val metadataListener =
+ ArgumentCaptor.forClass(BluetoothAdapter.OnMetadataChangedListener::class.java)
val listener = createMockListener()
val bluetoothDevice = createBluetoothDevice("AA:BB:CC:DD:EE:FF")
batteryController.registerBatteryListener(BT_DEVICE_ID, listener, PID)
@@ -829,25 +895,44 @@ class BatteryControllerTests {
// When the state has not changed, the listener is not notified again.
metadataListener.value!!.onMetadataChanged(
- bluetoothDevice, BluetoothDevice.METADATA_MAIN_BATTERY, "21".toByteArray())
+ bluetoothDevice,
+ BluetoothDevice.METADATA_MAIN_BATTERY,
+ "21".toByteArray(),
+ )
listener.verifyNotified(BT_DEVICE_ID, mode = times(1), capacity = 0.21f)
metadataListener.value!!.onMetadataChanged(
- bluetoothDevice, BluetoothDevice.METADATA_MAIN_BATTERY, "25".toByteArray())
+ bluetoothDevice,
+ BluetoothDevice.METADATA_MAIN_BATTERY,
+ "25".toByteArray(),
+ )
listener.verifyNotified(BT_DEVICE_ID, capacity = 0.25f, status = STATUS_UNKNOWN)
metadataListener.value!!.onMetadataChanged(
- bluetoothDevice, BluetoothDevice.METADATA_MAIN_CHARGING, "true".toByteArray())
+ bluetoothDevice,
+ BluetoothDevice.METADATA_MAIN_CHARGING,
+ "true".toByteArray(),
+ )
listener.verifyNotified(BT_DEVICE_ID, capacity = 0.25f, status = STATUS_CHARGING)
metadataListener.value!!.onMetadataChanged(
- bluetoothDevice, BluetoothDevice.METADATA_MAIN_CHARGING, "false".toByteArray())
+ bluetoothDevice,
+ BluetoothDevice.METADATA_MAIN_CHARGING,
+ "false".toByteArray(),
+ )
listener.verifyNotified(BT_DEVICE_ID, capacity = 0.25f, status = STATUS_DISCHARGING)
metadataListener.value!!.onMetadataChanged(
- bluetoothDevice, BluetoothDevice.METADATA_MAIN_CHARGING, null)
- listener.verifyNotified(BT_DEVICE_ID, mode = times(2), capacity = 0.25f,
- status = STATUS_UNKNOWN)
+ bluetoothDevice,
+ BluetoothDevice.METADATA_MAIN_CHARGING,
+ null,
+ )
+ listener.verifyNotified(
+ BT_DEVICE_ID,
+ mode = times(2),
+ capacity = 0.25f,
+ status = STATUS_UNKNOWN,
+ )
}
@Test
@@ -855,13 +940,17 @@ class BatteryControllerTests {
`when`(inputManagerRule.mock.getInputDeviceBluetoothAddress(BT_DEVICE_ID))
.thenReturn("AA:BB:CC:DD:EE:FF")
`when`(bluetoothBatteryManager.getBatteryLevel(eq("AA:BB:CC:DD:EE:FF"))).thenReturn(21)
- `when`(bluetoothBatteryManager.getMetadata("AA:BB:CC:DD:EE:FF",
- BluetoothDevice.METADATA_MAIN_BATTERY))
+ `when`(
+ bluetoothBatteryManager.getMetadata(
+ "AA:BB:CC:DD:EE:FF",
+ BluetoothDevice.METADATA_MAIN_BATTERY,
+ )
+ )
.thenReturn("22".toByteArray())
addInputDevice(BT_DEVICE_ID)
val bluetoothListener = ArgumentCaptor.forClass(BluetoothBatteryListener::class.java)
- val metadataListener = ArgumentCaptor.forClass(
- BluetoothAdapter.OnMetadataChangedListener::class.java)
+ val metadataListener =
+ ArgumentCaptor.forClass(BluetoothAdapter.OnMetadataChangedListener::class.java)
val listener = createMockListener()
val bluetoothDevice = createBluetoothDevice("AA:BB:CC:DD:EE:FF")
batteryController.registerBatteryListener(BT_DEVICE_ID, listener, PID)
@@ -877,13 +966,19 @@ class BatteryControllerTests {
listener.verifyNotified(BT_DEVICE_ID, mode = never(), capacity = 0.23f)
metadataListener.value!!.onMetadataChanged(
- bluetoothDevice, BluetoothDevice.METADATA_MAIN_BATTERY, "24".toByteArray())
+ bluetoothDevice,
+ BluetoothDevice.METADATA_MAIN_BATTERY,
+ "24".toByteArray(),
+ )
listener.verifyNotified(BT_DEVICE_ID, capacity = 0.24f)
// When the battery level from the metadata is no longer valid, we fall back to using the
// Bluetooth battery level.
metadataListener.value!!.onMetadataChanged(
- bluetoothDevice, BluetoothDevice.METADATA_MAIN_BATTERY, null)
+ bluetoothDevice,
+ BluetoothDevice.METADATA_MAIN_BATTERY,
+ null,
+ )
listener.verifyNotified(BT_DEVICE_ID, capacity = 0.23f)
}
}
diff --git a/tests/Input/src/com/android/server/input/InputDataStoreTests.kt b/tests/Input/src/com/android/server/input/InputDataStoreTests.kt
index 78c828bafd8f..812bd608ed20 100644
--- a/tests/Input/src/com/android/server/input/InputDataStoreTests.kt
+++ b/tests/Input/src/com/android/server/input/InputDataStoreTests.kt
@@ -41,8 +41,7 @@ import org.mockito.Mockito
/**
* Tests for {@link InputDataStore}.
*
- * Build/Install/Run:
- * atest InputTests:InputDataStoreTests
+ * Build/Install/Run: atest InputTests:InputDataStoreTests
*/
@Presubmit
class InputDataStoreTests {
@@ -63,25 +62,32 @@ class InputDataStoreTests {
private fun setupInputDataStore() {
tempFile = File.createTempFile("input_gestures", ".xml")
- inputDataStore = InputDataStore(object : InputDataStore.FileInjector("input_gestures") {
- private val atomicFile: AtomicFile = AtomicFile(tempFile)
+ inputDataStore =
+ InputDataStore(
+ object : InputDataStore.FileInjector("input_gestures") {
+ private val atomicFile: AtomicFile = AtomicFile(tempFile)
- override fun openRead(userId: Int): InputStream? {
- return atomicFile.openRead()
- }
+ override fun openRead(userId: Int): InputStream? {
+ return atomicFile.openRead()
+ }
- override fun startWrite(userId: Int): FileOutputStream? {
- return atomicFile.startWrite()
- }
+ override fun startWrite(userId: Int): FileOutputStream? {
+ return atomicFile.startWrite()
+ }
- override fun finishWrite(userId: Int, fos: FileOutputStream?, success: Boolean) {
- if (success) {
- atomicFile.finishWrite(fos)
- } else {
- atomicFile.failWrite(fos)
+ override fun finishWrite(
+ userId: Int,
+ fos: FileOutputStream?,
+ success: Boolean,
+ ) {
+ if (success) {
+ atomicFile.finishWrite(fos)
+ } else {
+ atomicFile.failWrite(fos)
+ }
+ }
}
- }
- })
+ )
}
private fun getPrintableXml(inputGestures: List<InputGestureData>): String {
@@ -92,164 +98,157 @@ class InputDataStoreTests {
@Test
fun saveToDiskKeyGesturesOnly() {
- val inputGestures = listOf(
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_H,
- KeyEvent.META_META_ON
+ val inputGestures =
+ listOf(
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_1,
- KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(
+ KeyEvent.KEYCODE_1,
+ KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_2,
- KeyEvent.META_META_ON
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
- .build()
- )
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
+ .build(),
+ )
inputDataStore.saveInputGestures(USER_ID, inputGestures)
assertEquals(
inputGestures,
inputDataStore.loadInputGestures(USER_ID),
- getPrintableXml(inputGestures)
+ getPrintableXml(inputGestures),
)
}
@Test
fun saveToDiskTouchpadGestures() {
- val inputGestures = listOf(
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createTouchpadTrigger(
- InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ val inputGestures =
+ listOf(
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createTouchpadTrigger(
+ InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
- )
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build()
+ )
inputDataStore.saveInputGestures(USER_ID, inputGestures)
assertEquals(
inputGestures,
inputDataStore.loadInputGestures(USER_ID),
- getPrintableXml(inputGestures)
+ getPrintableXml(inputGestures),
)
}
@Test
fun saveToDiskAppLaunchGestures() {
- val inputGestures = listOf(
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createTouchpadTrigger(
- InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ val inputGestures =
+ listOf(
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createTouchpadTrigger(
+ InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION)
- .setAppLaunchData(AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER))
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_2,
- KeyEvent.META_META_ON
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION)
+ .setAppLaunchData(
+ AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION)
- .setAppLaunchData(AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS))
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_1,
- KeyEvent.META_META_ON
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION)
- .setAppLaunchData(
- AppLaunchData.createLaunchDataForComponent(
- "com.test",
- "com.test.BookmarkTest"
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION)
+ .setAppLaunchData(
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)
)
- )
- .build()
- )
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_1, KeyEvent.META_META_ON)
+ )
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION)
+ .setAppLaunchData(
+ AppLaunchData.createLaunchDataForComponent(
+ "com.test",
+ "com.test.BookmarkTest",
+ )
+ )
+ .build(),
+ )
inputDataStore.saveInputGestures(USER_ID, inputGestures)
assertEquals(
inputGestures,
inputDataStore.loadInputGestures(USER_ID),
- getPrintableXml(inputGestures)
+ getPrintableXml(inputGestures),
)
}
@Test
fun saveToDiskCombinedGestures() {
- val inputGestures = listOf(
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_1,
- KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON
+ val inputGestures =
+ listOf(
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(
+ KeyEvent.KEYCODE_1,
+ KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_2,
- KeyEvent.META_META_ON
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createTouchpadTrigger(
- InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createTouchpadTrigger(
+ InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_9,
- KeyEvent.META_META_ON
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_9, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION)
- .setAppLaunchData(AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS))
- .build(),
- )
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION)
+ .setAppLaunchData(
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)
+ )
+ .build(),
+ )
inputDataStore.saveInputGestures(USER_ID, inputGestures)
assertEquals(
inputGestures,
inputDataStore.loadInputGestures(USER_ID),
- getPrintableXml(inputGestures)
+ getPrintableXml(inputGestures),
)
}
@Test
fun validXmlParse() {
- val xmlData = """
+ val xmlData =
+ """
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<root>
<input_gesture_list>
@@ -263,45 +262,42 @@ class InputDataStoreTests {
<touchpad_trigger touchpad_gesture_type="1" />
</input_gesture>
</input_gesture_list>
- </root>""".trimIndent()
- val validInputGestures = listOf(
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_1,
- KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON
+ </root>"""
+ .trimIndent()
+ val validInputGestures =
+ listOf(
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(
+ KeyEvent.KEYCODE_1,
+ KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_2,
- KeyEvent.META_META_ON
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createTouchpadTrigger(
- InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createTouchpadTrigger(
+ InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
- )
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build(),
+ )
val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8))
- assertEquals(
- validInputGestures,
- inputDataStore.readInputGesturesXml(inputStream, true)
- )
+ assertEquals(validInputGestures, inputDataStore.readInputGesturesXml(inputStream, true))
}
@Test
fun missingTriggerData() {
- val xmlData = """
+ val xmlData =
+ """
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<root>
<input_gesture_list>
@@ -314,36 +310,33 @@ class InputDataStoreTests {
<touchpad_trigger touchpad_gesture_type="1" />
</input_gesture>
</input_gesture_list>
- </root>""".trimIndent()
- val validInputGestures = listOf(
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_2,
- KeyEvent.META_META_ON
+ </root>"""
+ .trimIndent()
+ val validInputGestures =
+ listOf(
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createTouchpadTrigger(
- InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createTouchpadTrigger(
+ InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
- )
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build(),
+ )
val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8))
- assertEquals(
- validInputGestures,
- inputDataStore.readInputGesturesXml(inputStream, true)
- )
+ assertEquals(validInputGestures, inputDataStore.readInputGesturesXml(inputStream, true))
}
@Test
fun invalidKeycode() {
- val xmlData = """
+ val xmlData =
+ """
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<root>
<input_gesture_list>
@@ -357,36 +350,36 @@ class InputDataStoreTests {
<touchpad_trigger touchpad_gesture_type="1" />
</input_gesture>
</input_gesture_list>
- </root>""".trimIndent()
- val validInputGestures = listOf(
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_1,
- KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON
+ </root>"""
+ .trimIndent()
+ val validInputGestures =
+ listOf(
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(
+ KeyEvent.KEYCODE_1,
+ KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createTouchpadTrigger(
- InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createTouchpadTrigger(
+ InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
- )
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build(),
+ )
val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8))
- assertEquals(
- validInputGestures,
- inputDataStore.readInputGesturesXml(inputStream, true)
- )
+ assertEquals(validInputGestures, inputDataStore.readInputGesturesXml(inputStream, true))
}
@Test
fun invalidTriggerName() {
- val xmlData = """
+ val xmlData =
+ """
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<root>
<input_gesture_list>
@@ -400,37 +393,34 @@ class InputDataStoreTests {
<invalid_trigger_name touchpad_gesture_type="1" />
</input_gesture>
</input_gesture_list>
- </root>""".trimIndent()
- val validInputGestures = listOf(
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_1,
- KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON
+ </root>"""
+ .trimIndent()
+ val validInputGestures =
+ listOf(
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(
+ KeyEvent.KEYCODE_1,
+ KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_2,
- KeyEvent.META_META_ON
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
- .build(),
- )
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
+ .build(),
+ )
val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8))
- assertEquals(
- validInputGestures,
- inputDataStore.readInputGesturesXml(inputStream, true)
- )
+ assertEquals(validInputGestures, inputDataStore.readInputGesturesXml(inputStream, true))
}
@Test
fun invalidTouchpadGestureType() {
- val xmlData = """
+ val xmlData =
+ """
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<root>
<input_gesture_list>
@@ -444,61 +434,55 @@ class InputDataStoreTests {
<touchpad_trigger touchpad_gesture_type="9999" />
</input_gesture>
</input_gesture_list>
- </root>""".trimIndent()
- val validInputGestures = listOf(
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_1,
- KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON
+ </root>"""
+ .trimIndent()
+ val validInputGestures =
+ listOf(
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(
+ KeyEvent.KEYCODE_1,
+ KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
- .build(),
- InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_2,
- KeyEvent.META_META_ON
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
+ .build(),
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_2, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
- .build(),
- )
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS)
+ .build(),
+ )
val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8))
- assertEquals(
- validInputGestures,
- inputDataStore.readInputGesturesXml(inputStream, true)
- )
+ assertEquals(validInputGestures, inputDataStore.readInputGesturesXml(inputStream, true))
}
@Test
fun emptyInputGestureList() {
- val xmlData = """
+ val xmlData =
+ """
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<root>
<input_gesture_list>
</input_gesture_list>
- </root>""".trimIndent()
+ </root>"""
+ .trimIndent()
val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8))
- assertEquals(
- listOf(),
- inputDataStore.readInputGesturesXml(inputStream, true)
- )
+ assertEquals(listOf(), inputDataStore.readInputGesturesXml(inputStream, true))
}
@Test
fun invalidTag() {
- val xmlData = """
+ val xmlData =
+ """
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<root>
<invalid_tag_name>
</invalid_tag_name>
- </root>""".trimIndent()
+ </root>"""
+ .trimIndent()
val inputStream = ByteArrayInputStream(xmlData.toByteArray(Charsets.UTF_8))
- assertEquals(
- listOf(),
- inputDataStore.readInputGesturesXml(inputStream, true)
- )
+ assertEquals(listOf(), inputDataStore.readInputGesturesXml(inputStream, true))
}
-} \ No newline at end of file
+}
diff --git a/tests/Input/src/com/android/server/input/InputGestureManagerTests.kt b/tests/Input/src/com/android/server/input/InputGestureManagerTests.kt
index e281a3fb1287..5b4a39b49146 100644
--- a/tests/Input/src/com/android/server/input/InputGestureManagerTests.kt
+++ b/tests/Input/src/com/android/server/input/InputGestureManagerTests.kt
@@ -29,8 +29,7 @@ import org.junit.Test
/**
* Tests for custom keyboard glyph map configuration.
*
- * Build/Install/Run:
- * atest InputTests:CustomInputGestureManagerTests
+ * Build/Install/Run: atest InputTests:CustomInputGestureManagerTests
*/
@Presubmit
class InputGestureManagerTests {
@@ -48,163 +47,144 @@ class InputGestureManagerTests {
@Test
fun addRemoveCustomGesture() {
- val customGesture = InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_H,
- KeyEvent.META_META_ON
+ val customGesture =
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build()
val result = inputGestureManager.addCustomInputGesture(USER_ID, customGesture)
assertEquals(InputManager.CUSTOM_INPUT_GESTURE_RESULT_SUCCESS, result)
assertEquals(
listOf(customGesture),
- inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null)
+ inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null),
)
inputGestureManager.removeCustomInputGesture(USER_ID, customGesture)
assertEquals(
listOf<InputGestureData>(),
- inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null)
+ inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null),
)
}
@Test
fun removeNonExistentGesture() {
- val customGesture = InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_H,
- KeyEvent.META_META_ON
+ val customGesture =
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build()
val result = inputGestureManager.removeCustomInputGesture(USER_ID, customGesture)
assertEquals(InputManager.CUSTOM_INPUT_GESTURE_RESULT_ERROR_DOES_NOT_EXIST, result)
assertEquals(
listOf<InputGestureData>(),
- inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null)
+ inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null),
)
}
@Test
fun addAlreadyExistentGesture() {
- val customGesture = InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_H,
- KeyEvent.META_META_ON
+ val customGesture =
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build()
inputGestureManager.addCustomInputGesture(USER_ID, customGesture)
- val customGesture2 = InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_H,
- KeyEvent.META_META_ON
+ val customGesture2 =
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
- .build()
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
+ .build()
val result = inputGestureManager.addCustomInputGesture(USER_ID, customGesture2)
assertEquals(InputManager.CUSTOM_INPUT_GESTURE_RESULT_ERROR_ALREADY_EXISTS, result)
assertEquals(
listOf(customGesture),
- inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null)
+ inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null),
)
}
@Test
fun addRemoveAllExistentGestures() {
- val customGesture = InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_H,
- KeyEvent.META_META_ON
+ val customGesture =
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build()
inputGestureManager.addCustomInputGesture(USER_ID, customGesture)
- val customGesture2 = InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_DEL,
- KeyEvent.META_META_ON
+ val customGesture2 =
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_DEL, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
- .build()
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
+ .build()
inputGestureManager.addCustomInputGesture(USER_ID, customGesture2)
assertEquals(
listOf(customGesture, customGesture2),
- inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null)
+ inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null),
)
- inputGestureManager.removeAllCustomInputGestures(USER_ID, /* filter = */null)
+ inputGestureManager.removeAllCustomInputGestures(USER_ID, /* filter= */ null)
assertEquals(
listOf<InputGestureData>(),
- inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null)
+ inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null),
)
}
@Test
fun filteringBasedOnTouchpadOrKeyGestures() {
- val customKeyGesture = InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createKeyTrigger(
- KeyEvent.KEYCODE_H,
- KeyEvent.META_META_ON
+ val customKeyGesture =
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createKeyTrigger(KeyEvent.KEYCODE_H, KeyEvent.META_META_ON)
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .build()
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .build()
inputGestureManager.addCustomInputGesture(USER_ID, customKeyGesture)
- val customTouchpadGesture = InputGestureData.Builder()
- .setTrigger(
- InputGestureData.createTouchpadTrigger(
- InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ val customTouchpadGesture =
+ InputGestureData.Builder()
+ .setTrigger(
+ InputGestureData.createTouchpadTrigger(
+ InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP
+ )
)
- )
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
- .build()
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_BACK)
+ .build()
inputGestureManager.addCustomInputGesture(USER_ID, customTouchpadGesture)
assertEquals(
listOf(customTouchpadGesture, customKeyGesture),
- inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null)
+ inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null),
)
assertEquals(
listOf(customKeyGesture),
- inputGestureManager.getCustomInputGestures(USER_ID, InputGestureData.Filter.KEY)
+ inputGestureManager.getCustomInputGestures(USER_ID, InputGestureData.Filter.KEY),
)
assertEquals(
listOf(customTouchpadGesture),
- inputGestureManager.getCustomInputGestures(
- USER_ID,
- InputGestureData.Filter.TOUCHPAD
- )
+ inputGestureManager.getCustomInputGestures(USER_ID, InputGestureData.Filter.TOUCHPAD),
)
inputGestureManager.removeAllCustomInputGestures(USER_ID, InputGestureData.Filter.KEY)
assertEquals(
listOf(customTouchpadGesture),
- inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null)
+ inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null),
)
- inputGestureManager.removeAllCustomInputGestures(
- USER_ID,
- InputGestureData.Filter.TOUCHPAD
- )
+ inputGestureManager.removeAllCustomInputGestures(USER_ID, InputGestureData.Filter.TOUCHPAD)
assertEquals(
listOf<InputGestureData>(),
- inputGestureManager.getCustomInputGestures(USER_ID, /* filter = */null)
+ inputGestureManager.getCustomInputGestures(USER_ID, /* filter= */ null),
)
}
-} \ No newline at end of file
+}
diff --git a/tests/Input/src/com/android/server/input/InputManagerServiceTests.kt b/tests/Input/src/com/android/server/input/InputManagerServiceTests.kt
index 71c7a6b1119d..4737d19acde1 100644
--- a/tests/Input/src/com/android/server/input/InputManagerServiceTests.kt
+++ b/tests/Input/src/com/android/server/input/InputManagerServiceTests.kt
@@ -16,7 +16,6 @@
package com.android.server.input
-
import android.Manifest
import android.content.Context
import android.content.ContextWrapper
@@ -39,14 +38,14 @@ import android.platform.test.annotations.EnableFlags
import android.platform.test.annotations.Presubmit
import android.platform.test.flag.junit.SetFlagsRule
import android.provider.Settings
-import android.view.View.OnKeyListener
+import android.test.mock.MockContentResolver
import android.view.InputDevice
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
+import android.view.View.OnKeyListener
import android.view.WindowManager
-import android.test.mock.MockContentResolver
import androidx.test.platform.app.InstrumentationRegistry
import com.android.compatibility.common.util.SystemUtil.runWithShellPermissionIdentity
import com.android.dx.mockito.inline.extended.ExtendedMockito
@@ -75,28 +74,33 @@ import org.mockito.Mockito.never
import org.mockito.Mockito.spy
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
-import org.mockito.Mockito.verifyNoMoreInteractions
import org.mockito.Mockito.verifyNoInteractions
+import org.mockito.Mockito.verifyNoMoreInteractions
import org.mockito.Mockito.`when`
import org.mockito.stubbing.OngoingStubbing
/**
* Tests for {@link InputManagerService}.
*
- * Build/Install/Run:
- * atest InputTests:InputManagerServiceTests
+ * Build/Install/Run: atest InputTests:InputManagerServiceTests
*/
@Presubmit
class InputManagerServiceTests {
companion object {
- val ACTION_KEY_EVENTS = listOf(
- KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_META_LEFT),
- KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_META_RIGHT),
- KeyEvent( /* downTime= */0, /* eventTime= */0, /* action= */0, /* code= */0,
- /* repeat= */0, KeyEvent.META_META_ON
+ val ACTION_KEY_EVENTS =
+ listOf(
+ KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_META_LEFT),
+ KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_META_RIGHT),
+ KeyEvent(
+ /* downTime= */ 0,
+ /* eventTime= */ 0,
+ /* action= */ 0,
+ /* code= */ 0,
+ /* repeat= */ 0,
+ KeyEvent.META_META_ON,
+ ),
)
- )
}
@get:Rule
@@ -108,32 +112,24 @@ class InputManagerServiceTests {
.mockStatic(InputSettings::class.java)
.build()!!
- @get:Rule
- val setFlagsRule = SetFlagsRule()
+ @get:Rule val setFlagsRule = SetFlagsRule()
- @get:Rule
- val fakeSettingsProviderRule = FakeSettingsProvider.rule()!!
+ @get:Rule val fakeSettingsProviderRule = FakeSettingsProvider.rule()!!
- @Mock
- private lateinit var native: NativeInputManagerService
+ @Mock private lateinit var native: NativeInputManagerService
- @Mock
- private lateinit var wmCallbacks: InputManagerService.WindowManagerCallbacks
+ @Mock private lateinit var wmCallbacks: InputManagerService.WindowManagerCallbacks
- @Mock
- private lateinit var windowManagerInternal: WindowManagerInternal
+ @Mock private lateinit var windowManagerInternal: WindowManagerInternal
- @Mock
- private lateinit var packageManagerInternal: PackageManagerInternal
+ @Mock private lateinit var packageManagerInternal: PackageManagerInternal
- @Mock
- private lateinit var uEventManager: UEventManager
+ @Mock private lateinit var uEventManager: UEventManager
@Mock
private lateinit var kbdController: InputManagerService.KeyboardBacklightControllerInterface
- @Mock
- private lateinit var kcm: KeyCharacterMap
+ @Mock private lateinit var kcm: KeyCharacterMap
private lateinit var service: InputManagerService
private lateinit var localService: InputManagerInternal
@@ -147,44 +143,50 @@ class InputManagerServiceTests {
fun setup() {
context = spy(ContextWrapper(InstrumentationRegistry.getInstrumentation().getContext()))
fakePermissionEnforcer = FakePermissionEnforcer()
- doReturn(Context.PERMISSION_ENFORCER_SERVICE).`when`(context).getSystemServiceName(
- eq(PermissionEnforcer::class.java)
- )
- doReturn(fakePermissionEnforcer).`when`(context).getSystemService(
- eq(Context.PERMISSION_ENFORCER_SERVICE)
- )
+ doReturn(Context.PERMISSION_ENFORCER_SERVICE)
+ .`when`(context)
+ .getSystemServiceName(eq(PermissionEnforcer::class.java))
+ doReturn(fakePermissionEnforcer)
+ .`when`(context)
+ .getSystemService(eq(Context.PERMISSION_ENFORCER_SERVICE))
contentResolver = MockContentResolver(context)
contentResolver.addProvider(Settings.AUTHORITY, FakeSettingsProvider())
whenever(context.contentResolver).thenReturn(contentResolver)
testLooper = TestLooper()
service =
- InputManagerService(object : InputManagerService.Injector(
- context, testLooper.looper, testLooper.looper, uEventManager) {
- override fun getNativeService(
- service: InputManagerService?
- ): NativeInputManagerService {
- return native
- }
-
- override fun registerLocalService(service: InputManagerInternal?) {
- localService = service!!
- }
-
- override fun getKeyboardBacklightController(
- nativeService: NativeInputManagerService?
- ): InputManagerService.KeyboardBacklightControllerInterface {
- return kbdController
- }
- }, fakePermissionEnforcer)
+ InputManagerService(
+ object :
+ InputManagerService.Injector(
+ context,
+ testLooper.looper,
+ testLooper.looper,
+ uEventManager,
+ ) {
+ override fun getNativeService(
+ service: InputManagerService?
+ ): NativeInputManagerService {
+ return native
+ }
+
+ override fun registerLocalService(service: InputManagerInternal?) {
+ localService = service!!
+ }
+
+ override fun getKeyboardBacklightController(
+ nativeService: NativeInputManagerService?
+ ): InputManagerService.KeyboardBacklightControllerInterface {
+ return kbdController
+ }
+ },
+ fakePermissionEnforcer,
+ )
inputManagerGlobalSession = InputManagerGlobal.createTestSession(service)
val inputManager = InputManager(context)
whenever(context.getSystemService(InputManager::class.java)).thenReturn(inputManager)
whenever(context.getSystemService(Context.INPUT_SERVICE)).thenReturn(inputManager)
whenever(context.checkCallingOrSelfPermission(Manifest.permission.MANAGE_KEY_GESTURES))
- .thenReturn(
- PackageManager.PERMISSION_GRANTED
- )
+ .thenReturn(PackageManager.PERMISSION_GRANTED)
ExtendedMockito.doReturn(windowManagerInternal).`when` {
LocalServices.getService(eq(WindowManagerInternal::class.java))
@@ -192,9 +194,7 @@ class InputManagerServiceTests {
ExtendedMockito.doReturn(packageManagerInternal).`when` {
LocalServices.getService(eq(PackageManagerInternal::class.java))
}
- ExtendedMockito.doReturn(kcm).`when` {
- KeyCharacterMap.load(anyInt())
- }
+ ExtendedMockito.doReturn(kcm).`when` { KeyCharacterMap.load(anyInt()) }
assertTrue("Local service must be registered", this::localService.isInitialized)
service.setWindowManagerCallbacks(wmCallbacks)
@@ -219,9 +219,7 @@ class InputManagerServiceTests {
fun testInputSettingsUpdatedOnSystemRunning() {
verifyNoInteractions(native)
- runWithShellPermissionIdentity {
- service.systemRunning()
- }
+ runWithShellPermissionIdentity { service.systemRunning() }
verify(native).setPointerSpeed(anyInt())
verify(native).setTouchpadPointerSpeed(anyInt())
@@ -238,8 +236,7 @@ class InputManagerServiceTests {
verify(native).setStylusPointerIconEnabled(anyBoolean())
// Called thrice at boot, since there are individual callbacks to update the
// key repeat timeout, the key repeat delay and whether key repeat enabled.
- verify(native, times(3)).setKeyRepeatConfiguration(anyInt(), anyInt(),
- anyBoolean())
+ verify(native, times(3)).setKeyRepeatConfiguration(anyInt(), anyInt(), anyBoolean())
}
@Test
@@ -259,7 +256,9 @@ class InputManagerServiceTests {
localService.setTypeAssociation(inputPort, type)
- assertThat(service.getDeviceTypeAssociations()).asList().containsExactly(inputPort, type)
+ assertThat(service.getDeviceTypeAssociations())
+ .asList()
+ .containsExactly(inputPort, type)
.inOrder()
}
@@ -290,8 +289,8 @@ class InputManagerServiceTests {
fun testActionKeyEventsForwardedToFocusedWindow_whenCorrectlyRequested() {
service.systemRunning()
overrideSendActionKeyEventsToFocusedWindow(
- /* hasPermission = */true,
- /* hasPrivateFlag = */true
+ /* hasPermission = */ true,
+ /* hasPrivateFlag = */ true,
)
whenever(wmCallbacks.interceptKeyBeforeDispatching(any(), any(), anyInt())).thenReturn(-1)
@@ -304,8 +303,8 @@ class InputManagerServiceTests {
fun testActionKeyEventsNotForwardedToFocusedWindow_whenNoPermissions() {
service.systemRunning()
overrideSendActionKeyEventsToFocusedWindow(
- /* hasPermission = */false,
- /* hasPrivateFlag = */true
+ /* hasPermission = */ false,
+ /* hasPrivateFlag = */ true,
)
whenever(wmCallbacks.interceptKeyBeforeDispatching(any(), any(), anyInt())).thenReturn(-1)
@@ -318,8 +317,8 @@ class InputManagerServiceTests {
fun testActionKeyEventsNotForwardedToFocusedWindow_whenNoPrivateFlag() {
service.systemRunning()
overrideSendActionKeyEventsToFocusedWindow(
- /* hasPermission = */true,
- /* hasPrivateFlag = */false
+ /* hasPermission = */ true,
+ /* hasPrivateFlag = */ false,
)
whenever(wmCallbacks.interceptKeyBeforeDispatching(any(), any(), anyInt())).thenReturn(-1)
@@ -362,13 +361,20 @@ class InputManagerServiceTests {
fun testKeyEventsForwardedToFocusedWindow_whenWmAllows() {
service.systemRunning()
overrideSendActionKeyEventsToFocusedWindow(
- /* hasPermission = */false,
- /* hasPrivateFlag = */false
+ /* hasPermission = */ false,
+ /* hasPrivateFlag = */ false,
)
whenever(wmCallbacks.interceptKeyBeforeDispatching(any(), any(), anyInt())).thenReturn(0)
- val event = KeyEvent( /* downTime= */0, /* eventTime= */0, KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_SPACE, /* repeat= */0, KeyEvent.META_CTRL_ON)
+ val event =
+ KeyEvent(
+ /* downTime= */ 0,
+ /* eventTime= */ 0,
+ KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_SPACE,
+ /* repeat= */ 0,
+ KeyEvent.META_CTRL_ON,
+ )
assertEquals(0, service.interceptKeyBeforeDispatching(null, event, 0))
}
@@ -399,13 +405,20 @@ class InputManagerServiceTests {
fun testKeyEventsNotForwardedToFocusedWindow_whenWmConsumes() {
service.systemRunning()
overrideSendActionKeyEventsToFocusedWindow(
- /* hasPermission = */false,
- /* hasPrivateFlag = */false
+ /* hasPermission = */ false,
+ /* hasPrivateFlag = */ false,
)
whenever(wmCallbacks.interceptKeyBeforeDispatching(any(), any(), anyInt())).thenReturn(-1)
- val event = KeyEvent( /* downTime= */0, /* eventTime= */0, KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_SPACE, /* repeat= */0, KeyEvent.META_CTRL_ON)
+ val event =
+ KeyEvent(
+ /* downTime= */ 0,
+ /* eventTime= */ 0,
+ KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_SPACE,
+ /* repeat= */ 0,
+ KeyEvent.META_CTRL_ON,
+ )
assertEquals(-1, service.interceptKeyBeforeDispatching(null, event, 0))
}
@@ -420,19 +433,20 @@ class InputManagerServiceTests {
}
private fun createVirtualDisplays(count: Int): AutoClosingVirtualDisplays {
- val displayManager: DisplayManager = context.getSystemService(
- DisplayManager::class.java
- ) as DisplayManager
+ val displayManager: DisplayManager =
+ context.getSystemService(DisplayManager::class.java) as DisplayManager
val virtualDisplays = mutableListOf<VirtualDisplay>()
for (i in 0 until count) {
- virtualDisplays.add(displayManager.createVirtualDisplay(
+ virtualDisplays.add(
+ displayManager.createVirtualDisplay(
/* displayName= */ "testVirtualDisplay$i",
/* width= */ 100,
/* height= */ 100,
/* densityDpi= */ 100,
/* surface= */ null,
- /* flags= */ 0
- ))
+ /* flags= */ 0,
+ )
+ )
}
return AutoClosingVirtualDisplays(virtualDisplays)
}
@@ -441,26 +455,26 @@ class InputManagerServiceTests {
private fun createKeycodeAEvent(inputDevice: InputDevice, action: Int): KeyEvent {
val eventTime = SystemClock.uptimeMillis()
return KeyEvent(
- /* downTime= */ eventTime,
- /* eventTime= */ eventTime,
- /* action= */ action,
- /* code= */ KeyEvent.KEYCODE_A,
- /* repeat= */ 0,
- /* metaState= */ 0,
- /* deviceId= */ inputDevice.id,
- /* scanCode= */ 0,
- /* flags= */ KeyEvent.FLAG_FROM_SYSTEM,
- /* source= */ InputDevice.SOURCE_KEYBOARD
+ /* downTime= */ eventTime,
+ /* eventTime= */ eventTime,
+ /* action= */ action,
+ /* code= */ KeyEvent.KEYCODE_A,
+ /* repeat= */ 0,
+ /* metaState= */ 0,
+ /* deviceId= */ inputDevice.id,
+ /* scanCode= */ 0,
+ /* flags= */ KeyEvent.FLAG_FROM_SYSTEM,
+ /* source= */ InputDevice.SOURCE_KEYBOARD,
)
}
private fun createInputDevice(): InputDevice {
return InputDevice.Builder()
- .setId(123)
- .setName("abc")
- .setDescriptor("def")
- .setSources(InputDevice.SOURCE_KEYBOARD)
- .build()
+ .setId(123)
+ .setName("abc")
+ .setDescriptor("def")
+ .setSources(InputDevice.SOURCE_KEYBOARD)
+ .build()
}
@Test
@@ -485,8 +499,8 @@ class InputManagerServiceTests {
// Associate input device with display
service.addUniqueIdAssociationByDescriptor(
- inputDevice.descriptor,
- virtualDisplays[0].display.displayId.toString()
+ inputDevice.descriptor,
+ virtualDisplays[0].display.displayId.toString(),
)
// Simulate 2 different KeyEvents
@@ -513,8 +527,8 @@ class InputManagerServiceTests {
// Associate with Display 2
service.addUniqueIdAssociationByDescriptor(
- inputDevice.descriptor,
- virtualDisplays[1].display.displayId.toString()
+ inputDevice.descriptor,
+ virtualDisplays[1].display.displayId.toString(),
)
// Simulate a KeyEvent
@@ -548,8 +562,8 @@ class InputManagerServiceTests {
// Associate input device with display
service.addUniqueIdAssociationByPort(
- inputDevice.name,
- virtualDisplays[0].display.displayId.toString()
+ inputDevice.name,
+ virtualDisplays[0].display.displayId.toString(),
)
// Simulate 2 different KeyEvents
@@ -576,8 +590,8 @@ class InputManagerServiceTests {
// Associate with Display 2
service.addUniqueIdAssociationByPort(
- inputDevice.name,
- virtualDisplays[1].display.displayId.toString()
+ inputDevice.name,
+ virtualDisplays[1].display.displayId.toString(),
)
// Simulate a KeyEvent
@@ -619,7 +633,7 @@ class InputManagerServiceTests {
ExtendedMockito.verify {
InputSettings.setAccessibilityBounceKeysThreshold(
any(),
- eq(InputSettings.DEFAULT_BOUNCE_KEYS_THRESHOLD_MILLIS)
+ eq(InputSettings.DEFAULT_BOUNCE_KEYS_THRESHOLD_MILLIS),
)
}
}
@@ -635,9 +649,7 @@ class InputManagerServiceTests {
.setAction(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
.build()
service.handleKeyGestureEvent(toggleMouseKeysEvent)
- ExtendedMockito.verify {
- InputSettings.setAccessibilityMouseKeysEnabled(any(), eq(true))
- }
+ ExtendedMockito.verify { InputSettings.setAccessibilityMouseKeysEnabled(any(), eq(true)) }
}
@Test
@@ -648,9 +660,7 @@ class InputManagerServiceTests {
.setAction(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
.build()
service.handleKeyGestureEvent(toggleStickyKeysEvent)
- ExtendedMockito.verify {
- InputSettings.setAccessibilityStickyKeysEnabled(any(), eq(true))
- }
+ ExtendedMockito.verify { InputSettings.setAccessibilityStickyKeysEnabled(any(), eq(true)) }
}
@Test
@@ -664,7 +674,7 @@ class InputManagerServiceTests {
ExtendedMockito.verify {
InputSettings.setAccessibilitySlowKeysThreshold(
any(),
- eq(InputSettings.DEFAULT_SLOW_KEYS_THRESHOLD_MILLIS)
+ eq(InputSettings.DEFAULT_SLOW_KEYS_THRESHOLD_MILLIS),
)
}
}
@@ -683,37 +693,39 @@ class InputManagerServiceTests {
fun overrideSendActionKeyEventsToFocusedWindow(
hasPermission: Boolean,
- hasPrivateFlag: Boolean
+ hasPrivateFlag: Boolean,
) {
ExtendedMockito.doReturn(
- if (hasPermission) {
- PermissionChecker.PERMISSION_GRANTED
- } else {
- PermissionChecker.PERMISSION_HARD_DENIED
- }
- ).`when` {
- PermissionChecker.checkPermissionForDataDelivery(
- any(),
- eq(Manifest.permission.OVERRIDE_SYSTEM_KEY_BEHAVIOR_IN_FOCUSED_WINDOW),
- anyInt(),
- anyInt(),
- any(),
- any(),
- any()
+ if (hasPermission) {
+ PermissionChecker.PERMISSION_GRANTED
+ } else {
+ PermissionChecker.PERMISSION_HARD_DENIED
+ }
)
- }
+ .`when` {
+ PermissionChecker.checkPermissionForDataDelivery(
+ any(),
+ eq(Manifest.permission.OVERRIDE_SYSTEM_KEY_BEHAVIOR_IN_FOCUSED_WINDOW),
+ anyInt(),
+ anyInt(),
+ any(),
+ any(),
+ any(),
+ )
+ }
- val info = KeyInterceptionInfo(
- /* type = */0,
- if (hasPrivateFlag) {
- WindowManager.LayoutParams.PRIVATE_FLAG_ALLOW_ACTION_KEY_EVENTS
- } else {
- 0
- },
- "title",
- /* uid = */0,
- /* inputFeatureFlags = */ 0
- )
+ val info =
+ KeyInterceptionInfo(
+ /* type = */ 0,
+ if (hasPrivateFlag) {
+ WindowManager.LayoutParams.PRIVATE_FLAG_ALLOW_ACTION_KEY_EVENTS
+ } else {
+ 0
+ },
+ "title",
+ /* uid = */ 0,
+ /* inputFeatureFlags = */ 0,
+ )
whenever(windowManagerInternal.getKeyInterceptionInfoFromToken(any())).thenReturn(info)
}
}
diff --git a/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt b/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt
index 163dda84a71c..c64578e4638f 100644
--- a/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt
+++ b/tests/Input/src/com/android/server/input/KeyGestureControllerTests.kt
@@ -77,8 +77,7 @@ import org.mockito.kotlin.times
/**
* Tests for {@link KeyGestureController}.
*
- * Build/Install/Run:
- * atest InputTests:KeyGestureControllerTests
+ * Build/Install/Run: atest InputTests:KeyGestureControllerTests
*/
@Presubmit
@RunWith(JUnitParamsRunner::class)
@@ -86,23 +85,29 @@ class KeyGestureControllerTests {
companion object {
const val DEVICE_ID = 1
- val HOME_GESTURE_COMPLETE_EVENT = KeyGestureEvent.Builder()
- .setDeviceId(DEVICE_ID)
- .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H))
- .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON)
- .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
- .setAction(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
- .build()
- val MODIFIER = mapOf(
- KeyEvent.KEYCODE_CTRL_LEFT to (KeyEvent.META_CTRL_LEFT_ON or KeyEvent.META_CTRL_ON),
- KeyEvent.KEYCODE_CTRL_RIGHT to (KeyEvent.META_CTRL_RIGHT_ON or KeyEvent.META_CTRL_ON),
- KeyEvent.KEYCODE_ALT_LEFT to (KeyEvent.META_ALT_LEFT_ON or KeyEvent.META_ALT_ON),
- KeyEvent.KEYCODE_ALT_RIGHT to (KeyEvent.META_ALT_RIGHT_ON or KeyEvent.META_ALT_ON),
- KeyEvent.KEYCODE_SHIFT_LEFT to (KeyEvent.META_SHIFT_LEFT_ON or KeyEvent.META_SHIFT_ON),
- KeyEvent.KEYCODE_SHIFT_RIGHT to (KeyEvent.META_SHIFT_RIGHT_ON or KeyEvent.META_SHIFT_ON),
- KeyEvent.KEYCODE_META_LEFT to (KeyEvent.META_META_LEFT_ON or KeyEvent.META_META_ON),
- KeyEvent.KEYCODE_META_RIGHT to (KeyEvent.META_META_RIGHT_ON or KeyEvent.META_META_ON),
- )
+ val HOME_GESTURE_COMPLETE_EVENT =
+ KeyGestureEvent.Builder()
+ .setDeviceId(DEVICE_ID)
+ .setKeycodes(intArrayOf(KeyEvent.KEYCODE_H))
+ .setModifierState(KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON)
+ .setKeyGestureType(KeyGestureEvent.KEY_GESTURE_TYPE_HOME)
+ .setAction(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ .build()
+ val MODIFIER =
+ mapOf(
+ KeyEvent.KEYCODE_CTRL_LEFT to (KeyEvent.META_CTRL_LEFT_ON or KeyEvent.META_CTRL_ON),
+ KeyEvent.KEYCODE_CTRL_RIGHT to
+ (KeyEvent.META_CTRL_RIGHT_ON or KeyEvent.META_CTRL_ON),
+ KeyEvent.KEYCODE_ALT_LEFT to (KeyEvent.META_ALT_LEFT_ON or KeyEvent.META_ALT_ON),
+ KeyEvent.KEYCODE_ALT_RIGHT to (KeyEvent.META_ALT_RIGHT_ON or KeyEvent.META_ALT_ON),
+ KeyEvent.KEYCODE_SHIFT_LEFT to
+ (KeyEvent.META_SHIFT_LEFT_ON or KeyEvent.META_SHIFT_ON),
+ KeyEvent.KEYCODE_SHIFT_RIGHT to
+ (KeyEvent.META_SHIFT_RIGHT_ON or KeyEvent.META_SHIFT_ON),
+ KeyEvent.KEYCODE_META_LEFT to (KeyEvent.META_META_LEFT_ON or KeyEvent.META_META_ON),
+ KeyEvent.KEYCODE_META_RIGHT to
+ (KeyEvent.META_META_RIGHT_ON or KeyEvent.META_META_ON),
+ )
const val SEARCH_KEY_BEHAVIOR_DEFAULT_SEARCH = 0
const val SEARCH_KEY_BEHAVIOR_TARGET_ACTIVITY = 1
const val SETTINGS_KEY_BEHAVIOR_SETTINGS_ACTIVITY = 0
@@ -116,15 +121,14 @@ class KeyGestureControllerTests {
@JvmField
@Rule
- val extendedMockitoRule = ExtendedMockitoRule.Builder(this)
- .mockStatic(FrameworkStatsLog::class.java)
- .mockStatic(SystemProperties::class.java)
- .mockStatic(KeyCharacterMap::class.java)
- .build()!!
+ val extendedMockitoRule =
+ ExtendedMockitoRule.Builder(this)
+ .mockStatic(FrameworkStatsLog::class.java)
+ .mockStatic(SystemProperties::class.java)
+ .mockStatic(KeyCharacterMap::class.java)
+ .build()!!
- @JvmField
- @Rule
- val rule = SetFlagsRule()
+ @JvmField @Rule val rule = SetFlagsRule()
@Mock private lateinit var iInputManager: IInputManager
@Mock private lateinit var packageManager: PackageManager
@@ -151,29 +155,35 @@ class KeyGestureControllerTests {
currentPid = Process.myPid()
tempFile = File.createTempFile("input_gestures", ".xml")
inputDataStore =
- InputDataStore(object : InputDataStore.FileInjector("input_gestures.xml") {
- private val atomicFile: AtomicFile = AtomicFile(tempFile)
+ InputDataStore(
+ object : InputDataStore.FileInjector("input_gestures.xml") {
+ private val atomicFile: AtomicFile = AtomicFile(tempFile)
- override fun openRead(userId: Int): InputStream? {
- return atomicFile.openRead()
- }
+ override fun openRead(userId: Int): InputStream? {
+ return atomicFile.openRead()
+ }
- override fun startWrite(userId: Int): FileOutputStream? {
- return atomicFile.startWrite()
- }
+ override fun startWrite(userId: Int): FileOutputStream? {
+ return atomicFile.startWrite()
+ }
- override fun finishWrite(userId: Int, fos: FileOutputStream?, success: Boolean) {
- if (success) {
- atomicFile.finishWrite(fos)
- } else {
- atomicFile.failWrite(fos)
+ override fun finishWrite(
+ userId: Int,
+ fos: FileOutputStream?,
+ success: Boolean,
+ ) {
+ if (success) {
+ atomicFile.finishWrite(fos)
+ } else {
+ atomicFile.failWrite(fos)
+ }
}
- }
- override fun getAtomicFileForUserId(userId: Int): AtomicFile {
- return atomicFile
+ override fun getAtomicFileForUserId(userId: Int): AtomicFile {
+ return atomicFile
+ }
}
- })
+ )
startNewInputGlobalTestSession()
}
@@ -230,11 +240,12 @@ class KeyGestureControllerTests {
object : KeyGestureController.Injector() {
override fun getAccessibilityShortcutController(
context: Context?,
- handler: Handler?
+ handler: Handler?,
): AccessibilityShortcutController {
return accessibilityShortcutController
}
- })
+ },
+ )
Mockito.`when`(iInputManager.registerKeyGestureHandler(Mockito.any(), Mockito.any()))
.thenAnswer {
val args = it.arguments
@@ -242,14 +253,18 @@ class KeyGestureControllerTests {
keyGestureController.registerKeyGestureHandler(
args[0] as IntArray,
args[1] as IKeyGestureHandler,
- SYSTEM_PID
+ SYSTEM_PID,
)
}
- }
+ }
keyGestureController.setWindowManagerCallbacks(wmCallbacks)
Mockito.`when`(wmCallbacks.isKeyguardLocked(Mockito.anyInt())).thenReturn(false)
- Mockito.`when`(accessibilityShortcutController
- .isAccessibilityShortcutAvailable(Mockito.anyBoolean())).thenReturn(true)
+ Mockito.`when`(
+ accessibilityShortcutController.isAccessibilityShortcutAvailable(
+ Mockito.anyBoolean()
+ )
+ )
+ .thenReturn(true)
Mockito.`when`(iInputManager.appLaunchBookmarks)
.thenReturn(keyGestureController.appLaunchBookmarks)
keyGestureController.systemRunning()
@@ -258,9 +273,10 @@ class KeyGestureControllerTests {
private fun notifyHomeGestureCompleted() {
keyGestureController.notifyKeyGestureCompleted(
- DEVICE_ID, intArrayOf(KeyEvent.KEYCODE_H),
+ DEVICE_ID,
+ intArrayOf(KeyEvent.KEYCODE_H),
KeyEvent.META_META_ON or KeyEvent.META_META_LEFT_ON,
- KeyGestureEvent.KEY_GESTURE_TYPE_HOME
+ KeyGestureEvent.KEY_GESTURE_TYPE_HOME,
)
}
@@ -273,15 +289,11 @@ class KeyGestureControllerTests {
keyGestureController.registerKeyGestureEventListener(listener, 0)
notifyHomeGestureCompleted()
testLooper.dispatchAll()
- assertEquals(
- "Listener should get callbacks on key gesture event completed",
- 1,
- events.size
- )
+ assertEquals("Listener should get callbacks on key gesture event completed", 1, events.size)
assertEquals(
"Listener should get callback for key gesture complete event",
HOME_GESTURE_COMPLETE_EVENT,
- events[0]
+ events[0],
)
// Unregister listener
@@ -289,11 +301,7 @@ class KeyGestureControllerTests {
keyGestureController.unregisterKeyGestureEventListener(listener, 0)
notifyHomeGestureCompleted()
testLooper.dispatchAll()
- assertEquals(
- "Listener should not get callback after being unregistered",
- 0,
- events.size
- )
+ assertEquals("Listener should not get callback after being unregistered", 0, events.size)
}
class TestData(
@@ -317,7 +325,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_ASSISTANT,
intArrayOf(KeyEvent.KEYCODE_A),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + H -> Go Home",
@@ -325,7 +333,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_HOME,
intArrayOf(KeyEvent.KEYCODE_H),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + ENTER -> Go Home",
@@ -333,7 +341,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_HOME,
intArrayOf(KeyEvent.KEYCODE_ENTER),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + I -> Launch System Settings",
@@ -341,7 +349,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SYSTEM_SETTINGS,
intArrayOf(KeyEvent.KEYCODE_I),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + L -> Lock",
@@ -349,7 +357,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_LOCK_SCREEN,
intArrayOf(KeyEvent.KEYCODE_L),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + N -> Toggle Notification",
@@ -357,18 +365,15 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_NOTIFICATION_PANEL,
intArrayOf(KeyEvent.KEYCODE_N),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + S -> Take Screenshot",
- intArrayOf(
- KeyEvent.KEYCODE_META_LEFT,
- KeyEvent.KEYCODE_S
- ),
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_S),
KeyGestureEvent.KEY_GESTURE_TYPE_TAKE_SCREENSHOT,
intArrayOf(KeyEvent.KEYCODE_S),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + ESC -> Back",
@@ -376,7 +381,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_BACK,
intArrayOf(KeyEvent.KEYCODE_ESCAPE),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + DPAD_LEFT -> Back",
@@ -384,55 +389,55 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_BACK,
intArrayOf(KeyEvent.KEYCODE_DPAD_LEFT),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + CTRL + DPAD_UP -> Multi Window Navigation",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_CTRL_LEFT,
- KeyEvent.KEYCODE_DPAD_UP
+ KeyEvent.KEYCODE_DPAD_UP,
),
KeyGestureEvent.KEY_GESTURE_TYPE_MULTI_WINDOW_NAVIGATION,
intArrayOf(KeyEvent.KEYCODE_DPAD_UP),
KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + CTRL + DPAD_DOWN -> Desktop Mode",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_CTRL_LEFT,
- KeyEvent.KEYCODE_DPAD_DOWN
+ KeyEvent.KEYCODE_DPAD_DOWN,
),
KeyGestureEvent.KEY_GESTURE_TYPE_DESKTOP_MODE,
intArrayOf(KeyEvent.KEYCODE_DPAD_DOWN),
KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + CTRL + DPAD_LEFT -> Splitscreen Navigation Left",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_CTRL_LEFT,
- KeyEvent.KEYCODE_DPAD_LEFT
+ KeyEvent.KEYCODE_DPAD_LEFT,
),
KeyGestureEvent.KEY_GESTURE_TYPE_SPLIT_SCREEN_NAVIGATION_LEFT,
intArrayOf(KeyEvent.KEYCODE_DPAD_LEFT),
KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + CTRL + DPAD_RIGHT -> Splitscreen Navigation Right",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_CTRL_LEFT,
- KeyEvent.KEYCODE_DPAD_RIGHT
+ KeyEvent.KEYCODE_DPAD_RIGHT,
),
KeyGestureEvent.KEY_GESTURE_TYPE_SPLIT_SCREEN_NAVIGATION_RIGHT,
intArrayOf(KeyEvent.KEYCODE_DPAD_RIGHT),
KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + / -> Open Shortcut Helper",
@@ -440,7 +445,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_OPEN_SHORTCUT_HELPER,
intArrayOf(KeyEvent.KEYCODE_SLASH),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + ALT -> Toggle Caps Lock",
@@ -448,7 +453,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_CAPS_LOCK,
intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"ALT + META -> Toggle Caps Lock",
@@ -456,7 +461,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_CAPS_LOCK,
intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_ALT_LEFT),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + TAB -> Open Overview",
@@ -464,7 +469,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_RECENT_APPS,
intArrayOf(KeyEvent.KEYCODE_TAB),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"ALT + TAB -> Toggle Recent Apps Switcher",
@@ -474,8 +479,8 @@ class KeyGestureControllerTests {
KeyEvent.META_ALT_ON,
intArrayOf(
KeyGestureEvent.ACTION_GESTURE_START,
- KeyGestureEvent.ACTION_GESTURE_COMPLETE
- )
+ KeyGestureEvent.ACTION_GESTURE_COMPLETE,
+ ),
),
TestData(
"CTRL + SPACE -> Switch Language Forward",
@@ -483,31 +488,31 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_LANGUAGE_SWITCH,
intArrayOf(KeyEvent.KEYCODE_SPACE),
KeyEvent.META_CTRL_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"CTRL + SHIFT + SPACE -> Switch Language Backward",
intArrayOf(
KeyEvent.KEYCODE_CTRL_LEFT,
KeyEvent.KEYCODE_SHIFT_LEFT,
- KeyEvent.KEYCODE_SPACE
+ KeyEvent.KEYCODE_SPACE,
),
KeyGestureEvent.KEY_GESTURE_TYPE_LANGUAGE_SWITCH,
intArrayOf(KeyEvent.KEYCODE_SPACE),
KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"CTRL + ALT + Z -> Accessibility Shortcut",
intArrayOf(
KeyEvent.KEYCODE_CTRL_LEFT,
KeyEvent.KEYCODE_ALT_LEFT,
- KeyEvent.KEYCODE_Z
+ KeyEvent.KEYCODE_Z,
),
KeyGestureEvent.KEY_GESTURE_TYPE_ACCESSIBILITY_SHORTCUT,
intArrayOf(KeyEvent.KEYCODE_Z),
KeyEvent.META_CTRL_ON or KeyEvent.META_ALT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + B -> Launch Default Browser",
@@ -516,7 +521,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_B),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER)
+ AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER),
),
TestData(
"META + C -> Launch Default Contacts",
@@ -525,7 +530,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_P),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS),
),
TestData(
"META + E -> Launch Default Email",
@@ -534,7 +539,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_E),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL),
),
TestData(
"META + K -> Launch Default Calendar",
@@ -543,7 +548,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_C),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR),
),
TestData(
"META + M -> Launch Default Maps",
@@ -552,7 +557,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_M),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MAPS)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MAPS),
),
TestData(
"META + U -> Launch Default Calculator",
@@ -561,159 +566,147 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_U),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR),
),
TestData(
"META + CTRL + DEL -> Trigger Bug Report",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_CTRL_LEFT,
- KeyEvent.KEYCODE_DEL
+ KeyEvent.KEYCODE_DEL,
),
KeyGestureEvent.KEY_GESTURE_TYPE_TRIGGER_BUG_REPORT,
intArrayOf(KeyEvent.KEYCODE_DEL),
KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"Meta + Alt + 3 -> Toggle Bounce Keys",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_ALT_LEFT,
- KeyEvent.KEYCODE_3
+ KeyEvent.KEYCODE_3,
),
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_BOUNCE_KEYS,
intArrayOf(KeyEvent.KEYCODE_3),
KeyEvent.META_META_ON or KeyEvent.META_ALT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"Meta + Alt + 4 -> Toggle Mouse Keys",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_ALT_LEFT,
- KeyEvent.KEYCODE_4
+ KeyEvent.KEYCODE_4,
),
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_MOUSE_KEYS,
intArrayOf(KeyEvent.KEYCODE_4),
KeyEvent.META_META_ON or KeyEvent.META_ALT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"Meta + Alt + 5 -> Toggle Sticky Keys",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_ALT_LEFT,
- KeyEvent.KEYCODE_5
+ KeyEvent.KEYCODE_5,
),
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_STICKY_KEYS,
intArrayOf(KeyEvent.KEYCODE_5),
KeyEvent.META_META_ON or KeyEvent.META_ALT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"Meta + Alt + 6 -> Toggle Slow Keys",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_ALT_LEFT,
- KeyEvent.KEYCODE_6
+ KeyEvent.KEYCODE_6,
),
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_SLOW_KEYS,
intArrayOf(KeyEvent.KEYCODE_6),
KeyEvent.META_META_ON or KeyEvent.META_ALT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + CTRL + D -> Move a task to next display",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_CTRL_LEFT,
- KeyEvent.KEYCODE_D
+ KeyEvent.KEYCODE_D,
),
KeyGestureEvent.KEY_GESTURE_TYPE_MOVE_TO_NEXT_DISPLAY,
intArrayOf(KeyEvent.KEYCODE_D),
KeyEvent.META_META_ON or KeyEvent.META_CTRL_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + [ -> Resizes a task to fit the left half of the screen",
- intArrayOf(
- KeyEvent.KEYCODE_META_LEFT,
- KeyEvent.KEYCODE_LEFT_BRACKET
- ),
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_LEFT_BRACKET),
KeyGestureEvent.KEY_GESTURE_TYPE_SNAP_LEFT_FREEFORM_WINDOW,
intArrayOf(KeyEvent.KEYCODE_LEFT_BRACKET),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + ] -> Resizes a task to fit the right half of the screen",
- intArrayOf(
- KeyEvent.KEYCODE_META_LEFT,
- KeyEvent.KEYCODE_RIGHT_BRACKET
- ),
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_RIGHT_BRACKET),
KeyGestureEvent.KEY_GESTURE_TYPE_SNAP_RIGHT_FREEFORM_WINDOW,
intArrayOf(KeyEvent.KEYCODE_RIGHT_BRACKET),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + '=' -> Toggles maximization of a task to maximized and restore its bounds",
- intArrayOf(
- KeyEvent.KEYCODE_META_LEFT,
- KeyEvent.KEYCODE_EQUALS
- ),
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_EQUALS),
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_MAXIMIZE_FREEFORM_WINDOW,
intArrayOf(KeyEvent.KEYCODE_EQUALS),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + '-' -> Minimizes a freeform task",
- intArrayOf(
- KeyEvent.KEYCODE_META_LEFT,
- KeyEvent.KEYCODE_MINUS
- ),
+ intArrayOf(KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_MINUS),
KeyGestureEvent.KEY_GESTURE_TYPE_MINIMIZE_FREEFORM_WINDOW,
intArrayOf(KeyEvent.KEYCODE_MINUS),
KeyEvent.META_META_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + ALT + M -> Toggle Magnification",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_ALT_LEFT,
- KeyEvent.KEYCODE_M
+ KeyEvent.KEYCODE_M,
),
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_MAGNIFICATION,
intArrayOf(KeyEvent.KEYCODE_M),
KeyEvent.META_META_ON or KeyEvent.META_ALT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + ALT + S -> Activate Select to Speak",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_ALT_LEFT,
- KeyEvent.KEYCODE_S
+ KeyEvent.KEYCODE_S,
),
KeyGestureEvent.KEY_GESTURE_TYPE_ACTIVATE_SELECT_TO_SPEAK,
intArrayOf(KeyEvent.KEYCODE_S),
KeyEvent.META_META_ON or KeyEvent.META_ALT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + ALT + 'V' -> Toggle Voice Access",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_ALT_LEFT,
- KeyEvent.KEYCODE_V
+ KeyEvent.KEYCODE_V,
),
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_VOICE_ACCESS,
intArrayOf(KeyEvent.KEYCODE_V),
KeyEvent.META_META_ON or KeyEvent.META_ALT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
)
}
@@ -727,7 +720,7 @@ class KeyGestureControllerTests {
com.android.hardware.input.Flags.FLAG_ENABLE_TALKBACK_AND_MAGNIFIER_KEY_GESTURES,
com.android.hardware.input.Flags.FLAG_ENABLE_VOICE_ACCESS_KEY_GESTURES,
com.android.window.flags.Flags.FLAG_ENABLE_MOVE_TO_NEXT_DISPLAY_SHORTCUT,
- com.android.window.flags.Flags.FLAG_ENABLE_TASK_RESIZING_KEYBOARD_SHORTCUTS
+ com.android.window.flags.Flags.FLAG_ENABLE_TASK_RESIZING_KEYBOARD_SHORTCUTS,
)
fun testKeyGestures(test: TestData) {
setupKeyGestureController()
@@ -743,26 +736,27 @@ class KeyGestureControllerTests {
com.android.hardware.input.Flags.FLAG_ENABLE_TALKBACK_AND_MAGNIFIER_KEY_GESTURES,
com.android.hardware.input.Flags.FLAG_ENABLE_VOICE_ACCESS_KEY_GESTURES,
com.android.window.flags.Flags.FLAG_ENABLE_MOVE_TO_NEXT_DISPLAY_SHORTCUT,
- com.android.window.flags.Flags.FLAG_ENABLE_TASK_RESIZING_KEYBOARD_SHORTCUTS
+ com.android.window.flags.Flags.FLAG_ENABLE_TASK_RESIZING_KEYBOARD_SHORTCUTS,
)
fun testCustomKeyGesturesNotAllowedForSystemGestures(test: TestData) {
setupKeyGestureController()
- val builder = InputGestureData.Builder()
- .setKeyGestureType(test.expectedKeyGestureType)
- .setTrigger(
- InputGestureData.createKeyTrigger(
- test.expectedKeys[0],
- test.expectedModifierState
+ val builder =
+ InputGestureData.Builder()
+ .setKeyGestureType(test.expectedKeyGestureType)
+ .setTrigger(
+ InputGestureData.createKeyTrigger(
+ test.expectedKeys[0],
+ test.expectedModifierState,
+ )
)
- )
if (test.expectedAppLaunchData != null) {
builder.setAppLaunchData(test.expectedAppLaunchData)
}
assertEquals(
test.toString(),
InputManager.CUSTOM_INPUT_GESTURE_RESULT_ERROR_RESERVED_GESTURE,
- keyGestureController.addCustomInputGesture(0, builder.build().aidlData)
+ keyGestureController.addCustomInputGesture(0, builder.build().aidlData),
)
}
@@ -776,7 +770,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_B),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER)
+ AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER),
),
TestData(
"META + P -> Launch Default Contacts",
@@ -785,7 +779,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_P),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS),
),
TestData(
"META + E -> Launch Default Email",
@@ -794,7 +788,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_E),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL),
),
TestData(
"META + C -> Launch Default Calendar",
@@ -803,7 +797,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_C),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR),
),
TestData(
"META + M -> Launch Default Maps",
@@ -812,7 +806,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_M),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MAPS)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MAPS),
),
TestData(
"META + U -> Launch Default Calculator",
@@ -821,47 +815,47 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_U),
KeyEvent.META_META_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR),
),
TestData(
"META + SHIFT + B -> Launch Default Browser",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_SHIFT_LEFT,
- KeyEvent.KEYCODE_B
+ KeyEvent.KEYCODE_B,
),
KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
intArrayOf(KeyEvent.KEYCODE_B),
KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER)
+ AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER),
),
TestData(
"META + SHIFT + P -> Launch Default Contacts",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_SHIFT_LEFT,
- KeyEvent.KEYCODE_P
+ KeyEvent.KEYCODE_P,
),
KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
intArrayOf(KeyEvent.KEYCODE_P),
KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS),
),
TestData(
"META + SHIFT + J -> Launch Target Activity",
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_SHIFT_LEFT,
- KeyEvent.KEYCODE_J
+ KeyEvent.KEYCODE_J,
),
KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
intArrayOf(KeyEvent.KEYCODE_J),
KeyEvent.META_META_ON or KeyEvent.META_SHIFT_ON,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest")
- )
+ AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest"),
+ ),
)
}
@@ -890,7 +884,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_RECENT_APPS,
intArrayOf(KeyEvent.KEYCODE_RECENT_APPS),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"APP_SWITCH -> App Switch",
@@ -900,8 +894,8 @@ class KeyGestureControllerTests {
0,
intArrayOf(
KeyGestureEvent.ACTION_GESTURE_START,
- KeyGestureEvent.ACTION_GESTURE_COMPLETE
- )
+ KeyGestureEvent.ACTION_GESTURE_COMPLETE,
+ ),
),
TestData(
"BRIGHTNESS_UP -> Brightness Up",
@@ -909,7 +903,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_BRIGHTNESS_UP,
intArrayOf(KeyEvent.KEYCODE_BRIGHTNESS_UP),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"BRIGHTNESS_DOWN -> Brightness Down",
@@ -917,7 +911,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_BRIGHTNESS_DOWN,
intArrayOf(KeyEvent.KEYCODE_BRIGHTNESS_DOWN),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"KEYBOARD_BACKLIGHT_UP -> Keyboard Backlight Up",
@@ -925,7 +919,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_KEYBOARD_BACKLIGHT_UP,
intArrayOf(KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_UP),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"KEYBOARD_BACKLIGHT_DOWN -> Keyboard Backlight Down",
@@ -933,7 +927,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_KEYBOARD_BACKLIGHT_DOWN,
intArrayOf(KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_DOWN),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"KEYBOARD_BACKLIGHT_TOGGLE -> Keyboard Backlight Toggle",
@@ -941,7 +935,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_KEYBOARD_BACKLIGHT_TOGGLE,
intArrayOf(KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_TOGGLE),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"ALL_APPS -> Open App Drawer",
@@ -949,7 +943,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_ALL_APPS,
intArrayOf(KeyEvent.KEYCODE_ALL_APPS),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"NOTIFICATION -> Toggle Notification Panel",
@@ -957,7 +951,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_NOTIFICATION_PANEL,
intArrayOf(KeyEvent.KEYCODE_NOTIFICATION),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"LANGUAGE_SWITCH -> Switch Language Forward",
@@ -965,7 +959,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_LANGUAGE_SWITCH,
intArrayOf(KeyEvent.KEYCODE_LANGUAGE_SWITCH),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"SHIFT + LANGUAGE_SWITCH -> Switch Language Backward",
@@ -973,7 +967,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_LANGUAGE_SWITCH,
intArrayOf(KeyEvent.KEYCODE_LANGUAGE_SWITCH),
KeyEvent.META_SHIFT_ON,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"SCREENSHOT -> Take Screenshot",
@@ -981,7 +975,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_TAKE_SCREENSHOT,
intArrayOf(KeyEvent.KEYCODE_SCREENSHOT),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META -> Open Apps Drawer",
@@ -989,7 +983,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_ACCESSIBILITY_ALL_APPS,
intArrayOf(KeyEvent.KEYCODE_META_LEFT),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"SYSRQ -> Take screenshot",
@@ -997,7 +991,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_TAKE_SCREENSHOT,
intArrayOf(KeyEvent.KEYCODE_SYSRQ),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"ESC -> Close All Dialogs",
@@ -1005,7 +999,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_CLOSE_ALL_DIALOGS,
intArrayOf(KeyEvent.KEYCODE_ESCAPE),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"EXPLORER -> Launch Default Browser",
@@ -1014,7 +1008,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_EXPLORER),
0,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER)
+ AppLaunchData.createLaunchDataForRole(RoleManager.ROLE_BROWSER),
),
TestData(
"ENVELOPE -> Launch Default Email",
@@ -1023,7 +1017,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_ENVELOPE),
0,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_EMAIL),
),
TestData(
"CONTACTS -> Launch Default Contacts",
@@ -1032,7 +1026,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_CONTACTS),
0,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CONTACTS),
),
TestData(
"CALENDAR -> Launch Default Calendar",
@@ -1041,7 +1035,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_CALENDAR),
0,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALENDAR),
),
TestData(
"MUSIC -> Launch Default Music",
@@ -1050,7 +1044,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_MUSIC),
0,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MUSIC)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_MUSIC),
),
TestData(
"CALCULATOR -> Launch Default Calculator",
@@ -1059,7 +1053,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_CALCULATOR),
0,
intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
- AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR)
+ AppLaunchData.createLaunchDataForCategory(Intent.CATEGORY_APP_CALCULATOR),
),
TestData(
"LOCK -> Lock Screen",
@@ -1067,7 +1061,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_LOCK_SCREEN,
intArrayOf(KeyEvent.KEYCODE_LOCK),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"FULLSCREEN -> Turns a task into fullscreen",
@@ -1075,7 +1069,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_MULTI_WINDOW_NAVIGATION,
intArrayOf(KeyEvent.KEYCODE_FULLSCREEN),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
)
}
@@ -1091,31 +1085,32 @@ class KeyGestureControllerTests {
@Test
fun testKeycodesFullyConsumed_irrespectiveOfHandlers() {
setupKeyGestureController()
- val testKeys = intArrayOf(
- KeyEvent.KEYCODE_RECENT_APPS,
- KeyEvent.KEYCODE_APP_SWITCH,
- KeyEvent.KEYCODE_BRIGHTNESS_UP,
- KeyEvent.KEYCODE_BRIGHTNESS_DOWN,
- KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_DOWN,
- KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_UP,
- KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_TOGGLE,
- KeyEvent.KEYCODE_ALL_APPS,
- KeyEvent.KEYCODE_NOTIFICATION,
- KeyEvent.KEYCODE_SETTINGS,
- KeyEvent.KEYCODE_LANGUAGE_SWITCH,
- KeyEvent.KEYCODE_SCREENSHOT,
- KeyEvent.KEYCODE_META_LEFT,
- KeyEvent.KEYCODE_META_RIGHT,
- KeyEvent.KEYCODE_ASSIST,
- KeyEvent.KEYCODE_VOICE_ASSIST,
- KeyEvent.KEYCODE_STYLUS_BUTTON_PRIMARY,
- KeyEvent.KEYCODE_STYLUS_BUTTON_SECONDARY,
- KeyEvent.KEYCODE_STYLUS_BUTTON_TERTIARY,
- KeyEvent.KEYCODE_STYLUS_BUTTON_TAIL,
- KeyEvent.KEYCODE_DO_NOT_DISTURB,
- KeyEvent.KEYCODE_LOCK,
- KeyEvent.KEYCODE_FULLSCREEN
- )
+ val testKeys =
+ intArrayOf(
+ KeyEvent.KEYCODE_RECENT_APPS,
+ KeyEvent.KEYCODE_APP_SWITCH,
+ KeyEvent.KEYCODE_BRIGHTNESS_UP,
+ KeyEvent.KEYCODE_BRIGHTNESS_DOWN,
+ KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_DOWN,
+ KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_UP,
+ KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_TOGGLE,
+ KeyEvent.KEYCODE_ALL_APPS,
+ KeyEvent.KEYCODE_NOTIFICATION,
+ KeyEvent.KEYCODE_SETTINGS,
+ KeyEvent.KEYCODE_LANGUAGE_SWITCH,
+ KeyEvent.KEYCODE_SCREENSHOT,
+ KeyEvent.KEYCODE_META_LEFT,
+ KeyEvent.KEYCODE_META_RIGHT,
+ KeyEvent.KEYCODE_ASSIST,
+ KeyEvent.KEYCODE_VOICE_ASSIST,
+ KeyEvent.KEYCODE_STYLUS_BUTTON_PRIMARY,
+ KeyEvent.KEYCODE_STYLUS_BUTTON_SECONDARY,
+ KeyEvent.KEYCODE_STYLUS_BUTTON_TERTIARY,
+ KeyEvent.KEYCODE_STYLUS_BUTTON_TAIL,
+ KeyEvent.KEYCODE_DO_NOT_DISTURB,
+ KeyEvent.KEYCODE_LOCK,
+ KeyEvent.KEYCODE_FULLSCREEN,
+ )
for (key in testKeys) {
sendKeys(intArrayOf(key), assertNotSentToApps = true)
@@ -1130,7 +1125,7 @@ class KeyGestureControllerTests {
testKeyGestureNotProduced(
"SEARCH -> Default Search",
intArrayOf(KeyEvent.KEYCODE_SEARCH),
- intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SEARCH)
+ intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SEARCH),
)
}
@@ -1146,7 +1141,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SEARCH,
intArrayOf(KeyEvent.KEYCODE_SEARCH),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
)
)
}
@@ -1161,8 +1156,8 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_SETTINGS),
intArrayOf(
KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SEARCH,
- KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_NOTIFICATION_PANEL
- )
+ KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_NOTIFICATION_PANEL,
+ ),
)
}
@@ -1178,7 +1173,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_SYSTEM_SETTINGS,
intArrayOf(KeyEvent.KEYCODE_SETTINGS),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
)
)
}
@@ -1195,7 +1190,7 @@ class KeyGestureControllerTests {
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_NOTIFICATION_PANEL,
intArrayOf(KeyEvent.KEYCODE_SETTINGS),
0,
- intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE)
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
)
)
}
@@ -1208,15 +1203,11 @@ class KeyGestureControllerTests {
keyGestureController.registerKeyGestureEventListener(listener, 0)
sendKeys(intArrayOf(KeyEvent.KEYCODE_CAPS_LOCK))
testLooper.dispatchAll()
- assertEquals(
- "Listener should get callbacks on key gesture event completed",
- 1,
- events.size
- )
+ assertEquals("Listener should get callbacks on key gesture event completed", 1, events.size)
assertEquals(
"Listener should get callback for Toggle Caps Lock key gesture complete event",
KeyGestureEvent.KEY_GESTURE_TYPE_TOGGLE_CAPS_LOCK,
- events[0].keyGestureType
+ events[0].keyGestureType,
)
}
@@ -1231,8 +1222,8 @@ class KeyGestureControllerTests {
0,
intArrayOf(
KeyGestureEvent.ACTION_GESTURE_START,
- KeyGestureEvent.ACTION_GESTURE_COMPLETE
- )
+ KeyGestureEvent.ACTION_GESTURE_COMPLETE,
+ ),
),
TestData(
"POWER + STEM_PRIMARY -> Screenshot Chord",
@@ -1242,8 +1233,8 @@ class KeyGestureControllerTests {
0,
intArrayOf(
KeyGestureEvent.ACTION_GESTURE_START,
- KeyGestureEvent.ACTION_GESTURE_COMPLETE
- )
+ KeyGestureEvent.ACTION_GESTURE_COMPLETE,
+ ),
),
TestData(
"BACK + DPAD_CENTER -> TV Trigger Bug Report",
@@ -1253,8 +1244,8 @@ class KeyGestureControllerTests {
0,
intArrayOf(
KeyGestureEvent.ACTION_GESTURE_START,
- KeyGestureEvent.ACTION_GESTURE_COMPLETE
- )
+ KeyGestureEvent.ACTION_GESTURE_COMPLETE,
+ ),
),
)
}
@@ -1263,7 +1254,7 @@ class KeyGestureControllerTests {
@Parameters(method = "systemGesturesTestArguments_forKeyCombinations")
@EnableFlags(
com.android.hardware.input.Flags.FLAG_USE_KEY_GESTURE_EVENT_HANDLER,
- com.android.hardware.input.Flags.FLAG_USE_KEY_GESTURE_EVENT_HANDLER_MULTI_KEY_GESTURES
+ com.android.hardware.input.Flags.FLAG_USE_KEY_GESTURE_EVENT_HANDLER_MULTI_KEY_GESTURES,
)
fun testKeyCombinationGestures(test: TestData) {
setupKeyGestureController()
@@ -1278,29 +1269,25 @@ class KeyGestureControllerTests {
intArrayOf(
KeyEvent.KEYCODE_META_LEFT,
KeyEvent.KEYCODE_ALT_LEFT,
- KeyEvent.KEYCODE_Q
+ KeyEvent.KEYCODE_Q,
),
KeyGestureEvent.KEY_GESTURE_TYPE_HOME,
intArrayOf(KeyEvent.KEYCODE_Q),
KeyEvent.META_META_ON or KeyEvent.META_ALT_ON,
- intArrayOf(
- KeyGestureEvent.ACTION_GESTURE_COMPLETE
- )
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
),
TestData(
"META + ALT + Q -> Launch app",
intArrayOf(
KeyEvent.KEYCODE_CTRL_LEFT,
KeyEvent.KEYCODE_SHIFT_LEFT,
- KeyEvent.KEYCODE_Q
+ KeyEvent.KEYCODE_Q,
),
KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
intArrayOf(KeyEvent.KEYCODE_Q),
KeyEvent.META_CTRL_ON or KeyEvent.META_SHIFT_ON,
- intArrayOf(
- KeyGestureEvent.ACTION_GESTURE_COMPLETE
- ),
- AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest")
+ intArrayOf(KeyGestureEvent.ACTION_GESTURE_COMPLETE),
+ AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest"),
),
)
}
@@ -1309,31 +1296,27 @@ class KeyGestureControllerTests {
@Parameters(method = "customInputGesturesTestArguments")
fun testCustomKeyGestures(test: TestData) {
setupKeyGestureController()
- val trigger = InputGestureData.createKeyTrigger(
- test.expectedKeys[0],
- test.expectedModifierState
- )
- val builder = InputGestureData.Builder()
- .setKeyGestureType(test.expectedKeyGestureType)
- .setTrigger(trigger)
+ val trigger =
+ InputGestureData.createKeyTrigger(test.expectedKeys[0], test.expectedModifierState)
+ val builder =
+ InputGestureData.Builder()
+ .setKeyGestureType(test.expectedKeyGestureType)
+ .setTrigger(trigger)
if (test.expectedAppLaunchData != null) {
builder.setAppLaunchData(test.expectedAppLaunchData)
}
val inputGestureData = builder.build()
- assertNull(
- test.toString(),
- keyGestureController.getInputGesture(0, trigger.aidlTrigger)
- )
+ assertNull(test.toString(), keyGestureController.getInputGesture(0, trigger.aidlTrigger))
assertEquals(
test.toString(),
InputManager.CUSTOM_INPUT_GESTURE_RESULT_SUCCESS,
- keyGestureController.addCustomInputGesture(0, builder.build().aidlData)
+ keyGestureController.addCustomInputGesture(0, builder.build().aidlData),
)
assertEquals(
test.toString(),
inputGestureData.aidlData,
- keyGestureController.getInputGesture(0, trigger.aidlTrigger)
+ keyGestureController.getInputGesture(0, trigger.aidlTrigger),
)
testKeyGestureInternal(test)
}
@@ -1343,14 +1326,15 @@ class KeyGestureControllerTests {
fun testCustomKeyGesturesSavedAndLoadedByController(test: TestData) {
val userId = 10
setupKeyGestureController()
- val builder = InputGestureData.Builder()
- .setKeyGestureType(test.expectedKeyGestureType)
- .setTrigger(
- InputGestureData.createKeyTrigger(
- test.expectedKeys[0],
- test.expectedModifierState
+ val builder =
+ InputGestureData.Builder()
+ .setKeyGestureType(test.expectedKeyGestureType)
+ .setTrigger(
+ InputGestureData.createKeyTrigger(
+ test.expectedKeys[0],
+ test.expectedModifierState,
+ )
)
- )
if (test.expectedAppLaunchData != null) {
builder.setAppLaunchData(test.expectedAppLaunchData)
}
@@ -1371,11 +1355,12 @@ class KeyGestureControllerTests {
assertEquals(
"Test: $test doesn't produce correct number of saved input gestures",
1,
- savedInputGestures.size
+ savedInputGestures.size,
)
assertEquals(
- "Test: $test doesn't produce correct input gesture data", inputGestureData,
- InputGestureData(savedInputGestures[0])
+ "Test: $test doesn't produce correct input gesture data",
+ inputGestureData,
+ InputGestureData(savedInputGestures[0]),
)
}
@@ -1384,14 +1369,15 @@ class KeyGestureControllerTests {
fun testCustomKeyGestureRestoredFromBackup(test: TestData) {
val userId = 10
setupKeyGestureController()
- val builder = InputGestureData.Builder()
- .setKeyGestureType(test.expectedKeyGestureType)
- .setTrigger(
- InputGestureData.createKeyTrigger(
- test.expectedKeys[0],
- test.expectedModifierState
+ val builder =
+ InputGestureData.Builder()
+ .setKeyGestureType(test.expectedKeyGestureType)
+ .setTrigger(
+ InputGestureData.createKeyTrigger(
+ test.expectedKeys[0],
+ test.expectedModifierState,
+ )
)
- )
if (test.expectedAppLaunchData != null) {
builder.setAppLaunchData(test.expectedAppLaunchData)
}
@@ -1415,7 +1401,7 @@ class KeyGestureControllerTests {
assertEquals(
"Test: $test doesn't produce correct number of saved input gestures",
0,
- savedInputGestures.size
+ savedInputGestures.size,
)
// After the restore, there should be the original gesture re-registered.
@@ -1424,11 +1410,12 @@ class KeyGestureControllerTests {
assertEquals(
"Test: $test doesn't produce correct number of saved input gestures",
1,
- savedInputGestures.size
+ savedInputGestures.size,
)
assertEquals(
- "Test: $test doesn't produce correct input gesture data", inputGestureData,
- InputGestureData(savedInputGestures[0])
+ "Test: $test doesn't produce correct input gesture data",
+ inputGestureData,
+ InputGestureData(savedInputGestures[0]),
)
}
@@ -1449,14 +1436,14 @@ class KeyGestureControllerTests {
"3 Finger Tap -> Go Home",
InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP,
KeyGestureEvent.KEY_GESTURE_TYPE_HOME,
- KeyGestureEvent.ACTION_GESTURE_COMPLETE
+ KeyGestureEvent.ACTION_GESTURE_COMPLETE,
),
TouchpadTestData(
"3 Finger Tap -> Launch app",
InputGestureData.TOUCHPAD_GESTURE_TYPE_THREE_FINGER_TAP,
KeyGestureEvent.KEY_GESTURE_TYPE_LAUNCH_APPLICATION,
KeyGestureEvent.ACTION_GESTURE_COMPLETE,
- AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest")
+ AppLaunchData.createLaunchDataForComponent("com.test", "com.test.BookmarkTest"),
),
)
}
@@ -1465,9 +1452,10 @@ class KeyGestureControllerTests {
@Parameters(method = "customTouchpadGesturesTestArguments")
fun testCustomTouchpadGesture(test: TouchpadTestData) {
setupKeyGestureController()
- val builder = InputGestureData.Builder()
- .setKeyGestureType(test.expectedKeyGestureType)
- .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType))
+ val builder =
+ InputGestureData.Builder()
+ .setKeyGestureType(test.expectedKeyGestureType)
+ .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType))
if (test.expectedAppLaunchData != null) {
builder.setAppLaunchData(test.expectedAppLaunchData)
}
@@ -1476,13 +1464,11 @@ class KeyGestureControllerTests {
keyGestureController.addCustomInputGesture(0, inputGestureData.aidlData)
val handledEvents = mutableListOf<KeyGestureEvent>()
- val handler = KeyGestureHandler { event, _ ->
- handledEvents.add(KeyGestureEvent(event))
- }
+ val handler = KeyGestureHandler { event, _ -> handledEvents.add(KeyGestureEvent(event)) }
keyGestureController.registerKeyGestureHandler(
intArrayOf(test.expectedKeyGestureType),
handler,
- TEST_PID
+ TEST_PID,
)
handledEvents.clear()
@@ -1491,23 +1477,23 @@ class KeyGestureControllerTests {
assertEquals(
"Test: $test doesn't produce correct number of key gesture events",
1,
- handledEvents.size
+ handledEvents.size,
)
val event = handledEvents[0]
assertEquals(
"Test: $test doesn't produce correct key gesture type",
test.expectedKeyGestureType,
- event.keyGestureType
+ event.keyGestureType,
)
assertEquals(
"Test: $test doesn't produce correct key gesture action",
test.expectedAction,
- event.action
+ event.action,
)
assertEquals(
"Test: $test doesn't produce correct app launch data",
test.expectedAppLaunchData,
- event.appLaunchData
+ event.appLaunchData,
)
keyGestureController.unregisterKeyGestureHandler(handler, TEST_PID)
@@ -1518,9 +1504,10 @@ class KeyGestureControllerTests {
fun testCustomTouchpadGesturesSavedAndLoadedByController(test: TouchpadTestData) {
val userId = 10
setupKeyGestureController()
- val builder = InputGestureData.Builder()
- .setKeyGestureType(test.expectedKeyGestureType)
- .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType))
+ val builder =
+ InputGestureData.Builder()
+ .setKeyGestureType(test.expectedKeyGestureType)
+ .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType))
if (test.expectedAppLaunchData != null) {
builder.setAppLaunchData(test.expectedAppLaunchData)
}
@@ -1540,23 +1527,24 @@ class KeyGestureControllerTests {
assertEquals(
"Test: $test doesn't produce correct number of saved input gestures",
1,
- savedInputGestures.size
+ savedInputGestures.size,
)
assertEquals(
- "Test: $test doesn't produce correct input gesture data", inputGestureData,
- InputGestureData(savedInputGestures[0])
+ "Test: $test doesn't produce correct input gesture data",
+ inputGestureData,
+ InputGestureData(savedInputGestures[0]),
)
}
-
@Test
@Parameters(method = "customTouchpadGesturesTestArguments")
fun testCustomTouchpadGesturesRestoredFromBackup(test: TouchpadTestData) {
val userId = 10
setupKeyGestureController()
- val builder = InputGestureData.Builder()
- .setKeyGestureType(test.expectedKeyGestureType)
- .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType))
+ val builder =
+ InputGestureData.Builder()
+ .setKeyGestureType(test.expectedKeyGestureType)
+ .setTrigger(InputGestureData.createTouchpadTrigger(test.touchpadGestureType))
if (test.expectedAppLaunchData != null) {
builder.setAppLaunchData(test.expectedAppLaunchData)
}
@@ -1579,7 +1567,7 @@ class KeyGestureControllerTests {
assertEquals(
"Test: $test doesn't produce correct number of saved input gestures",
0,
- savedInputGestures.size
+ savedInputGestures.size,
)
// After the restore, there should be the original gesture re-registered.
@@ -1588,11 +1576,12 @@ class KeyGestureControllerTests {
assertEquals(
"Test: $test doesn't produce correct number of saved input gestures",
1,
- savedInputGestures.size
+ savedInputGestures.size,
)
assertEquals(
- "Test: $test doesn't produce correct input gesture data", inputGestureData,
- InputGestureData(savedInputGestures[0])
+ "Test: $test doesn't produce correct input gesture data",
+ inputGestureData,
+ InputGestureData(savedInputGestures[0]),
)
}
@@ -1604,7 +1593,7 @@ class KeyGestureControllerTests {
intArrayOf(KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN),
// Assuming this value is always greater than the accessibility shortcut timeout, which
// currently defaults to 3000ms
- timeDelayMs = 10000
+ timeDelayMs = 10000,
)
Mockito.verify(accessibilityShortcutController, times(1)).performAccessibilityShortcut()
}
@@ -1613,10 +1602,7 @@ class KeyGestureControllerTests {
fun testAccessibilityTvShortcutChordPressed() {
setupKeyGestureController()
- sendKeys(
- intArrayOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_DPAD_DOWN),
- timeDelayMs = 10000
- )
+ sendKeys(intArrayOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_DPAD_DOWN), timeDelayMs = 10000)
Mockito.verify(accessibilityShortcutController, times(1)).performAccessibilityShortcut()
}
@@ -1626,7 +1612,7 @@ class KeyGestureControllerTests {
sendKeys(
intArrayOf(KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN),
- timeDelayMs = 0
+ timeDelayMs = 0,
)
Mockito.verify(accessibilityShortcutController, never()).performAccessibilityShortcut()
}
@@ -1635,10 +1621,7 @@ class KeyGestureControllerTests {
fun testAccessibilityTvShortcutChordPressedForLessThanTimeout() {
setupKeyGestureController()
- sendKeys(
- intArrayOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_DPAD_DOWN),
- timeDelayMs = 0
- )
+ sendKeys(intArrayOf(KeyEvent.KEYCODE_BACK, KeyEvent.KEYCODE_DPAD_DOWN), timeDelayMs = 0)
Mockito.verify(accessibilityShortcutController, never()).performAccessibilityShortcut()
}
@@ -1651,14 +1634,14 @@ class KeyGestureControllerTests {
keyGestureController.registerKeyGestureHandler(
intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME),
handler1,
- RANDOM_PID1
+ RANDOM_PID1,
)
assertThrows(IllegalStateException::class.java) {
keyGestureController.registerKeyGestureHandler(
intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_BACK),
handler2,
- RANDOM_PID1
+ RANDOM_PID1,
)
}
}
@@ -1672,14 +1655,14 @@ class KeyGestureControllerTests {
keyGestureController.registerKeyGestureHandler(
intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME),
handler1,
- RANDOM_PID1
+ RANDOM_PID1,
)
assertThrows(IllegalArgumentException::class.java) {
keyGestureController.registerKeyGestureHandler(
intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_HOME),
handler2,
- RANDOM_PID2
+ RANDOM_PID2,
)
}
}
@@ -1691,11 +1674,7 @@ class KeyGestureControllerTests {
val handler = KeyGestureHandler { _, _ -> }
assertThrows(IllegalArgumentException::class.java) {
- keyGestureController.registerKeyGestureHandler(
- intArrayOf(),
- handler,
- RANDOM_PID1
- )
+ keyGestureController.registerKeyGestureHandler(intArrayOf(), handler, RANDOM_PID1)
}
}
@@ -1708,15 +1687,12 @@ class KeyGestureControllerTests {
keyGestureController.registerKeyGestureHandler(
intArrayOf(KeyGestureEvent.KEY_GESTURE_TYPE_RECENT_APPS),
handler1,
- TEST_PID
+ TEST_PID,
)
sendKeys(intArrayOf(KeyEvent.KEYCODE_RECENT_APPS))
assertEquals(1, callbackCount)
- keyGestureController.unregisterKeyGestureHandler(
- handler1,
- TEST_PID
- )
+ keyGestureController.unregisterKeyGestureHandler(handler1, TEST_PID)
// Callback should not be sent after unregister
sendKeys(intArrayOf(KeyEvent.KEYCODE_RECENT_APPS))
@@ -1725,13 +1701,11 @@ class KeyGestureControllerTests {
private fun testKeyGestureInternal(test: TestData) {
val handledEvents = mutableListOf<KeyGestureEvent>()
- val handler = KeyGestureHandler { event, _ ->
- handledEvents.add(KeyGestureEvent(event))
- }
+ val handler = KeyGestureHandler { event, _ -> handledEvents.add(KeyGestureEvent(event)) }
keyGestureController.registerKeyGestureHandler(
intArrayOf(test.expectedKeyGestureType),
handler,
- TEST_PID
+ TEST_PID,
)
handledEvents.clear()
@@ -1740,34 +1714,34 @@ class KeyGestureControllerTests {
assertEquals(
"Test: $test doesn't produce correct number of key gesture events",
test.expectedActions.size,
- handledEvents.size
+ handledEvents.size,
)
for (i in handledEvents.indices) {
val event = handledEvents[i]
assertArrayEquals(
"Test: $test doesn't produce correct key gesture keycodes",
test.expectedKeys,
- event.keycodes
+ event.keycodes,
)
assertEquals(
"Test: $test doesn't produce correct key gesture modifier state",
test.expectedModifierState,
- event.modifierState
+ event.modifierState,
)
assertEquals(
"Test: $test doesn't produce correct key gesture type",
test.expectedKeyGestureType,
- event.keyGestureType
+ event.keyGestureType,
)
assertEquals(
"Test: $test doesn't produce correct key gesture action",
test.expectedActions[i],
- event.action
+ event.action,
)
assertEquals(
"Test: $test doesn't produce correct app launch data",
test.expectedAppLaunchData,
- event.appLaunchData
+ event.appLaunchData,
)
}
@@ -1777,12 +1751,10 @@ class KeyGestureControllerTests {
private fun testKeyGestureNotProduced(
testName: String,
testKeys: IntArray,
- possibleGestures: IntArray
+ possibleGestures: IntArray,
) {
var handledEvents = mutableListOf<KeyGestureEvent>()
- val handler = KeyGestureHandler { event, _ ->
- handledEvents.add(KeyGestureEvent(event))
- }
+ val handler = KeyGestureHandler { event, _ -> handledEvents.add(KeyGestureEvent(event)) }
keyGestureController.registerKeyGestureHandler(possibleGestures, handler, TEST_PID)
handledEvents.clear()
@@ -1793,16 +1765,24 @@ class KeyGestureControllerTests {
private fun sendKeys(
testKeys: IntArray,
assertNotSentToApps: Boolean = false,
- timeDelayMs: Long = 0
+ timeDelayMs: Long = 0,
) {
var metaState = 0
val now = SystemClock.uptimeMillis()
for (key in testKeys) {
- val downEvent = KeyEvent(
- now, now, KeyEvent.ACTION_DOWN, key, 0 /*repeat*/, metaState,
- DEVICE_ID, 0 /*scancode*/, 0 /*flags*/,
- InputDevice.SOURCE_KEYBOARD
- )
+ val downEvent =
+ KeyEvent(
+ now,
+ now,
+ KeyEvent.ACTION_DOWN,
+ key,
+ 0 /*repeat*/,
+ metaState,
+ DEVICE_ID,
+ 0 /*scancode*/,
+ 0 /*flags*/,
+ InputDevice.SOURCE_KEYBOARD,
+ )
interceptKey(downEvent, assertNotSentToApps)
metaState = metaState or MODIFIER.getOrDefault(key, 0)
@@ -1816,11 +1796,19 @@ class KeyGestureControllerTests {
}
for (key in testKeys.reversed()) {
- val upEvent = KeyEvent(
- now, now, KeyEvent.ACTION_UP, key, 0 /*repeat*/, metaState,
- DEVICE_ID, 0 /*scancode*/, 0 /*flags*/,
- InputDevice.SOURCE_KEYBOARD
- )
+ val upEvent =
+ KeyEvent(
+ now,
+ now,
+ KeyEvent.ACTION_UP,
+ key,
+ 0 /*repeat*/,
+ metaState,
+ DEVICE_ID,
+ 0 /*scancode*/,
+ 0 /*flags*/,
+ InputDevice.SOURCE_KEYBOARD,
+ )
interceptKey(upEvent, assertNotSentToApps)
metaState = metaState and MODIFIER.getOrDefault(key, 0).inv()
@@ -1833,13 +1821,9 @@ class KeyGestureControllerTests {
keyGestureController.interceptKeyBeforeQueueing(event, FLAG_INTERACTIVE)
testLooper.dispatchAll()
- val consumed =
- keyGestureController.interceptKeyBeforeDispatching(null, event, 0) == -1L
+ val consumed = keyGestureController.interceptKeyBeforeDispatching(null, event, 0) == -1L
if (assertNotSentToApps) {
- assertTrue(
- "interceptKeyBeforeDispatching should consume all events $event",
- consumed
- )
+ assertTrue("interceptKeyBeforeDispatching should consume all events $event", consumed)
}
if (!consumed) {
keyGestureController.interceptUnhandledKey(event, null)
diff --git a/tests/Input/src/com/android/server/input/KeyRemapperTests.kt b/tests/Input/src/com/android/server/input/KeyRemapperTests.kt
index 4f4c97bef4c0..1fa985647513 100644
--- a/tests/Input/src/com/android/server/input/KeyRemapperTests.kt
+++ b/tests/Input/src/com/android/server/input/KeyRemapperTests.kt
@@ -51,31 +51,32 @@ private fun createKeyboard(deviceId: Int): InputDevice =
/**
* Tests for {@link KeyRemapper}.
*
- * Build/Install/Run:
- * atest InputTests:KeyRemapperTests
+ * Build/Install/Run: atest InputTests:KeyRemapperTests
*/
@Presubmit
class KeyRemapperTests {
companion object {
const val DEVICE_ID = 1
- val REMAPPABLE_KEYS = intArrayOf(
- KeyEvent.KEYCODE_CTRL_LEFT, KeyEvent.KEYCODE_CTRL_RIGHT,
- KeyEvent.KEYCODE_META_LEFT, KeyEvent.KEYCODE_META_RIGHT,
- KeyEvent.KEYCODE_ALT_LEFT, KeyEvent.KEYCODE_ALT_RIGHT,
- KeyEvent.KEYCODE_SHIFT_LEFT, KeyEvent.KEYCODE_SHIFT_RIGHT,
- KeyEvent.KEYCODE_CAPS_LOCK
- )
+ val REMAPPABLE_KEYS =
+ intArrayOf(
+ KeyEvent.KEYCODE_CTRL_LEFT,
+ KeyEvent.KEYCODE_CTRL_RIGHT,
+ KeyEvent.KEYCODE_META_LEFT,
+ KeyEvent.KEYCODE_META_RIGHT,
+ KeyEvent.KEYCODE_ALT_LEFT,
+ KeyEvent.KEYCODE_ALT_RIGHT,
+ KeyEvent.KEYCODE_SHIFT_LEFT,
+ KeyEvent.KEYCODE_SHIFT_RIGHT,
+ KeyEvent.KEYCODE_CAPS_LOCK,
+ )
}
- @get:Rule
- val rule = MockitoJUnit.rule()!!
+ @get:Rule val rule = MockitoJUnit.rule()!!
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
+ @get:Rule val inputManagerRule = MockInputManagerRule()
- @Mock
- private lateinit var native: NativeInputManagerService
+ @Mock private lateinit var native: NativeInputManagerService
private lateinit var mKeyRemapper: KeyRemapper
private lateinit var context: Context
private lateinit var dataStore: PersistentDataStore
@@ -84,24 +85,22 @@ class KeyRemapperTests {
@Before
fun setup() {
context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext()))
- dataStore = PersistentDataStore(object : PersistentDataStore.Injector() {
- override fun openRead(): InputStream? {
- throw FileNotFoundException()
- }
-
- override fun startWrite(): FileOutputStream? {
- throw IOException()
- }
-
- override fun finishWrite(fos: FileOutputStream?, success: Boolean) {}
- })
+ dataStore =
+ PersistentDataStore(
+ object : PersistentDataStore.Injector() {
+ override fun openRead(): InputStream? {
+ throw FileNotFoundException()
+ }
+
+ override fun startWrite(): FileOutputStream? {
+ throw IOException()
+ }
+
+ override fun finishWrite(fos: FileOutputStream?, success: Boolean) {}
+ }
+ )
testLooper = TestLooper()
- mKeyRemapper = KeyRemapper(
- context,
- native,
- dataStore,
- testLooper.looper
- )
+ mKeyRemapper = KeyRemapper(context, native, dataStore, testLooper.looper)
val inputManager = InputManager(context)
Mockito.`when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE)))
.thenReturn(inputManager)
@@ -131,7 +130,7 @@ class KeyRemapperTests {
assertEquals(
"Remapping should include mapping from $fromKeyCode to $toKeyCode",
toKeyCode,
- remapping.getOrDefault(fromKeyCode, -1)
+ remapping.getOrDefault(fromKeyCode, -1),
)
}
@@ -141,7 +140,7 @@ class KeyRemapperTests {
assertEquals(
"Remapping size should be 0 after clearAllModifierKeyRemappings",
0,
- mKeyRemapper.keyRemapping.size
+ mKeyRemapper.keyRemapping.size,
)
}
}
@@ -159,7 +158,7 @@ class KeyRemapperTests {
assertEquals(
"Remapping should not be done if modifier key remapping is disabled",
0,
- remapping.size
+ remapping.size,
)
}
}
@@ -168,7 +167,8 @@ class KeyRemapperTests {
init {
Settings.Global.putString(
context.contentResolver,
- "settings_new_keyboard_modifier_key", enabled.toString()
+ "settings_new_keyboard_modifier_key",
+ enabled.toString(),
)
}
@@ -176,8 +176,8 @@ class KeyRemapperTests {
Settings.Global.putString(
context.contentResolver,
"settings_new_keyboard_modifier_key",
- ""
+ "",
)
}
}
-} \ No newline at end of file
+}
diff --git a/tests/Input/src/com/android/server/input/KeyboardBacklightControllerTests.kt b/tests/Input/src/com/android/server/input/KeyboardBacklightControllerTests.kt
index 644d5a0679de..cf09b54753b0 100644
--- a/tests/Input/src/com/android/server/input/KeyboardBacklightControllerTests.kt
+++ b/tests/Input/src/com/android/server/input/KeyboardBacklightControllerTests.kt
@@ -29,8 +29,8 @@ import android.os.SystemProperties
import android.os.UEventObserver
import android.os.test.TestLooper
import android.platform.test.annotations.Presubmit
-import android.view.InputDevice
import android.util.TypedValue
+import android.view.InputDevice
import androidx.test.annotation.UiThreadTest
import androidx.test.core.app.ApplicationProvider
import com.android.dx.mockito.inline.extended.ExtendedMockito
@@ -65,12 +65,7 @@ private fun createKeyboard(deviceId: Int): InputDevice =
.setExternal(true)
.build()
-private fun createLight(lightId: Int, lightType: Int): Light =
- createLight(
- lightId,
- lightType,
- null
- )
+private fun createLight(lightId: Int, lightType: Int): Light = createLight(lightId, lightType, null)
private fun createLight(lightId: Int, lightType: Int, suggestedBrightnessLevels: IntArray?): Light =
Light(
@@ -79,13 +74,13 @@ private fun createLight(lightId: Int, lightType: Int, suggestedBrightnessLevels:
1,
lightType,
Light.LIGHT_CAPABILITY_BRIGHTNESS,
- suggestedBrightnessLevels
+ suggestedBrightnessLevels,
)
+
/**
* Tests for {@link KeyboardBacklightController}.
*
- * Build/Install/Run:
- * atest InputTests:KeyboardBacklightControllerTests
+ * Build/Install/Run: atest InputTests:KeyboardBacklightControllerTests
*/
@Presubmit
class KeyboardBacklightControllerTests {
@@ -100,15 +95,11 @@ class KeyboardBacklightControllerTests {
@get:Rule
val extendedMockitoRule =
ExtendedMockitoRule.Builder(this).mockStatic(SystemProperties::class.java).build()!!
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
-
- @Mock
- private lateinit var native: NativeInputManagerService
- @Mock
- private lateinit var uEventManager: UEventManager
- @Mock
- private lateinit var resources: Resources
+ @get:Rule val inputManagerRule = MockInputManagerRule()
+
+ @Mock private lateinit var native: NativeInputManagerService
+ @Mock private lateinit var uEventManager: UEventManager
+ @Mock private lateinit var resources: Resources
private lateinit var keyboardBacklightController: KeyboardBacklightController
private lateinit var context: Context
private lateinit var testLooper: TestLooper
@@ -135,9 +126,7 @@ class KeyboardBacklightControllerTests {
lightColorMap.getOrDefault(args[1] as Int, 0)
}
lightColorMap.clear()
- `when`(native.sysfsNodeChanged(any())).then {
- sysfsNodeChanges++
- }
+ `when`(native.sysfsNodeChanged(any())).then { sysfsNodeChanges++ }
}
private fun setupConfig() {
@@ -153,22 +142,29 @@ class KeyboardBacklightControllerTests {
`when`(resources.getInteger(R.integer.config_keyboardBacklightTimeoutMs))
.thenReturn(USER_INACTIVITY_THRESHOLD_MILLIS)
`when`(
- resources.getValue(
- eq(R.dimen.config_autoKeyboardBrightnessSmoothingConstant),
- any(TypedValue::class.java),
- anyBoolean()
+ resources.getValue(
+ eq(R.dimen.config_autoKeyboardBrightnessSmoothingConstant),
+ any(TypedValue::class.java),
+ anyBoolean(),
+ )
)
- ).then {
- val args = it.arguments
- val outValue = args[1] as TypedValue
- outValue.data = java.lang.Float.floatToRawIntBits(1.0f)
- Unit
- }
+ .then {
+ val args = it.arguments
+ val outValue = args[1] as TypedValue
+ outValue.data = java.lang.Float.floatToRawIntBits(1.0f)
+ Unit
+ }
}
private fun setupController() {
- keyboardBacklightController = KeyboardBacklightController(context, native,
- testLooper.looper, FakeAnimatorFactory(), uEventManager)
+ keyboardBacklightController =
+ KeyboardBacklightController(
+ context,
+ native,
+ testLooper.looper,
+ FakeAnimatorFactory(),
+ uEventManager,
+ )
}
@Test
@@ -180,8 +176,11 @@ class KeyboardBacklightControllerTests {
`when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight))
keyboardBacklightController.onInputDeviceAdded(DEVICE_ID)
- assertIncrementDecrementForLevels(keyboardWithBacklight, keyboardBacklight,
- DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL)
+ assertIncrementDecrementForLevels(
+ keyboardWithBacklight,
+ keyboardBacklight,
+ DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL,
+ )
}
@Test
@@ -204,12 +203,8 @@ class KeyboardBacklightControllerTests {
val keyboardBacklight = createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT)
val keyboardInputLight = createLight(SECOND_LIGHT_ID, Light.LIGHT_TYPE_INPUT)
`when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight)
- `when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(
- listOf(
- keyboardBacklight,
- keyboardInputLight
- )
- )
+ `when`(inputManagerRule.mock.getLights(DEVICE_ID))
+ .thenReturn(listOf(keyboardBacklight, keyboardInputLight))
keyboardBacklightController.onInputDeviceAdded(DEVICE_ID)
incrementKeyboardBacklight(DEVICE_ID)
@@ -239,22 +234,22 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Backlight state device Id should be $DEVICE_ID",
DEVICE_ID,
- lastBacklightState!!.deviceId
+ lastBacklightState!!.deviceId,
)
assertEquals(
"Backlight state brightnessLevel should be 1",
1,
- lastBacklightState!!.brightnessLevel
+ lastBacklightState!!.brightnessLevel,
)
assertEquals(
"Backlight state maxBrightnessLevel should be $maxLevel",
maxLevel,
- lastBacklightState!!.maxBrightnessLevel
+ lastBacklightState!!.maxBrightnessLevel,
)
assertEquals(
"Backlight state isTriggeredByKeyPress should be true",
true,
- lastBacklightState!!.isTriggeredByKeyPress
+ lastBacklightState!!.isTriggeredByKeyPress,
)
// Unregister listener
@@ -278,7 +273,7 @@ class KeyboardBacklightControllerTests {
assertNotEquals(
"Keyboard backlight level should be incremented to a non-zero value",
0,
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
testLooper.moveTimeForward((USER_INACTIVITY_THRESHOLD_MILLIS + 1000).toLong())
@@ -286,7 +281,7 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Keyboard backlight level should be turned off after inactivity",
0,
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
}
@@ -304,21 +299,21 @@ class KeyboardBacklightControllerTests {
assertNotEquals(
"Keyboard backlight level should be incremented to a non-zero value",
0,
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
keyboardBacklightController.handleInteractiveStateChange(false /* isDisplayOn */)
assertEquals(
"Keyboard backlight level should be turned off after display is turned off",
0,
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
keyboardBacklightController.handleInteractiveStateChange(true /* isDisplayOn */)
assertEquals(
"Keyboard backlight level should be turned on after display is turned on",
currentValue,
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
}
@@ -326,58 +321,70 @@ class KeyboardBacklightControllerTests {
fun testKeyboardBacklightSysfsNodeAdded_AfterInputDeviceAdded() {
setupController()
var counter = sysfsNodeChanges
- keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent(
- "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::no_backlight\u0000"
- ))
+ keyboardBacklightController.onKeyboardBacklightUEvent(
+ UEventObserver.UEvent(
+ "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::no_backlight\u0000"
+ )
+ )
assertEquals(
"Should not reload sysfs node if UEvent path doesn't contain kbd_backlight",
counter,
- sysfsNodeChanges
+ sysfsNodeChanges,
)
- keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent(
- "ACTION=add\u0000SUBSYSTEM=power\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000"
- ))
+ keyboardBacklightController.onKeyboardBacklightUEvent(
+ UEventObserver.UEvent(
+ "ACTION=add\u0000SUBSYSTEM=power\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000"
+ )
+ )
assertEquals(
"Should not reload sysfs node if UEvent doesn't belong to subsystem LED",
counter,
- sysfsNodeChanges
+ sysfsNodeChanges,
)
- keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent(
- "ACTION=remove\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000"
- ))
+ keyboardBacklightController.onKeyboardBacklightUEvent(
+ UEventObserver.UEvent(
+ "ACTION=remove\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000"
+ )
+ )
assertEquals(
"Should not reload sysfs node if UEvent doesn't have ACTION(add)",
counter,
- sysfsNodeChanges
+ sysfsNodeChanges,
)
- keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent(
- "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/pqr/abc::kbd_backlight\u0000"
- ))
+ keyboardBacklightController.onKeyboardBacklightUEvent(
+ UEventObserver.UEvent(
+ "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/pqr/abc::kbd_backlight\u0000"
+ )
+ )
assertEquals(
"Should not reload sysfs node if UEvent path doesn't belong to leds/ directory",
counter,
- sysfsNodeChanges
+ sysfsNodeChanges,
)
- keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent(
- "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000"
- ))
+ keyboardBacklightController.onKeyboardBacklightUEvent(
+ UEventObserver.UEvent(
+ "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc::kbd_backlight\u0000"
+ )
+ )
assertEquals(
"Should reload sysfs node if a valid Keyboard backlight LED UEvent occurs",
++counter,
- sysfsNodeChanges
+ sysfsNodeChanges,
)
- keyboardBacklightController.onKeyboardBacklightUEvent(UEventObserver.UEvent(
- "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc:kbd_backlight:red\u0000"
- ))
+ keyboardBacklightController.onKeyboardBacklightUEvent(
+ UEventObserver.UEvent(
+ "ACTION=add\u0000SUBSYSTEM=leds\u0000DEVPATH=/xyz/leds/abc:kbd_backlight:red\u0000"
+ )
+ )
assertEquals(
"Should reload sysfs node if a valid Keyboard backlight LED UEvent occurs",
++counter,
- sysfsNodeChanges
+ sysfsNodeChanges,
)
}
@@ -398,12 +405,12 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Should start animation from level 0",
DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL[0],
- lastAnimationValues[0]
+ lastAnimationValues[0],
)
assertEquals(
"Should start animation to level 1",
DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL[1],
- lastAnimationValues[1]
+ lastAnimationValues[1],
)
}
@@ -412,8 +419,8 @@ class KeyboardBacklightControllerTests {
setupController()
val keyboardWithBacklight = createKeyboard(DEVICE_ID)
val suggestedLevels = intArrayOf(0, 22, 63, 135, 196, 255)
- val keyboardBacklight = createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT,
- suggestedLevels)
+ val keyboardBacklight =
+ createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, suggestedLevels)
`when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight)
`when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight))
keyboardBacklightController.onInputDeviceAdded(DEVICE_ID)
@@ -426,14 +433,17 @@ class KeyboardBacklightControllerTests {
setupController()
val keyboardWithBacklight = createKeyboard(DEVICE_ID)
val suggestedLevels = IntArray(MAX_BRIGHTNESS_CHANGE_STEPS + 1) { 10 * (it + 1) }
- val keyboardBacklight = createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT,
- suggestedLevels)
+ val keyboardBacklight =
+ createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, suggestedLevels)
`when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight)
`when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight))
keyboardBacklightController.onInputDeviceAdded(DEVICE_ID)
- assertIncrementDecrementForLevels(keyboardWithBacklight, keyboardBacklight,
- DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL)
+ assertIncrementDecrementForLevels(
+ keyboardWithBacklight,
+ keyboardBacklight,
+ DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL,
+ )
}
@Test
@@ -441,15 +451,18 @@ class KeyboardBacklightControllerTests {
setupController()
val keyboardWithBacklight = createKeyboard(DEVICE_ID)
val suggestedLevels = intArrayOf(22, 63, 135, 196)
- val keyboardBacklight = createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT,
- suggestedLevels)
+ val keyboardBacklight =
+ createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, suggestedLevels)
`when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight)
`when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight))
keyboardBacklightController.onInputDeviceAdded(DEVICE_ID)
// Framework will add the lowest and maximum levels if not provided via config
- assertIncrementDecrementForLevels(keyboardWithBacklight, keyboardBacklight,
- intArrayOf(0, 22, 63, 135, 196, 255))
+ assertIncrementDecrementForLevels(
+ keyboardWithBacklight,
+ keyboardBacklight,
+ intArrayOf(0, 22, 63, 135, 196, 255),
+ )
}
@Test
@@ -457,15 +470,18 @@ class KeyboardBacklightControllerTests {
setupController()
val keyboardWithBacklight = createKeyboard(DEVICE_ID)
val suggestedLevels = intArrayOf(22, 63, 135, 400, 196, 1000)
- val keyboardBacklight = createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT,
- suggestedLevels)
+ val keyboardBacklight =
+ createLight(LIGHT_ID, Light.LIGHT_TYPE_KEYBOARD_BACKLIGHT, suggestedLevels)
`when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardWithBacklight)
`when`(inputManagerRule.mock.getLights(DEVICE_ID)).thenReturn(listOf(keyboardBacklight))
keyboardBacklightController.onInputDeviceAdded(DEVICE_ID)
// Framework will drop out of bound levels in the config
- assertIncrementDecrementForLevels(keyboardWithBacklight, keyboardBacklight,
- intArrayOf(0, 22, 63, 135, 196, 255))
+ assertIncrementDecrementForLevels(
+ keyboardWithBacklight,
+ keyboardBacklight,
+ intArrayOf(0, 22, 63, 135, 196, 255),
+ )
}
@Test
@@ -480,7 +496,7 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Light value should be changed to ambient provided value",
Color.argb(1, 0, 0, 0),
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
incrementKeyboardBacklight(DEVICE_ID)
@@ -488,7 +504,7 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Light value for level after increment post Ambient change is mismatched",
Color.argb(DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL[1], 0, 0, 0),
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
}
@@ -504,7 +520,7 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Light value should be changed to ambient provided value",
Color.argb(254, 0, 0, 0),
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
decrementKeyboardBacklight(DEVICE_ID)
@@ -513,7 +529,7 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Light value for level after decrement post Ambient change is mismatched",
Color.argb(DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL[numLevels - 2], 0, 0, 0),
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
}
@@ -529,21 +545,21 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Light value should be changed to the first level",
Color.argb(DEFAULT_BRIGHTNESS_VALUE_FOR_LEVEL[1], 0, 0, 0),
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
sendAmbientBacklightValue(100)
assertNotEquals(
"Light value should not change based on ambient changes after manual changes",
Color.argb(100, 0, 0, 0),
- lightColorMap[LIGHT_ID]
+ lightColorMap[LIGHT_ID],
)
}
private fun assertIncrementDecrementForLevels(
device: InputDevice,
light: Light,
- expectedLevels: IntArray
+ expectedLevels: IntArray,
) {
val deviceId = device.id
val lightId = light.id
@@ -552,7 +568,7 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Light value for level $level mismatched",
Color.argb(expectedLevels[level], 0, 0, 0),
- lightColorMap[lightId]
+ lightColorMap[lightId],
)
}
@@ -561,7 +577,7 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Light value for max level mismatched",
Color.argb(MAX_BRIGHTNESS, 0, 0, 0),
- lightColorMap[lightId]
+ lightColorMap[lightId],
)
for (level in expectedLevels.size - 2 downTo 0) {
@@ -569,7 +585,7 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Light value for level $level mismatched",
Color.argb(expectedLevels[level], 0, 0, 0),
- lightColorMap[lightId]
+ lightColorMap[lightId],
)
}
@@ -578,7 +594,7 @@ class KeyboardBacklightControllerTests {
assertEquals(
"Light value for min level mismatched",
Color.argb(0, 0, 0, 0),
- lightColorMap[lightId]
+ lightColorMap[lightId],
)
}
@@ -586,14 +602,15 @@ class KeyboardBacklightControllerTests {
override fun onBrightnessChanged(
deviceId: Int,
state: IKeyboardBacklightState,
- isTriggeredByKeyPress: Boolean
+ isTriggeredByKeyPress: Boolean,
) {
- lastBacklightState = KeyboardBacklightState(
- deviceId,
- state.brightnessLevel,
- state.maxBrightnessLevel,
- isTriggeredByKeyPress
- )
+ lastBacklightState =
+ KeyboardBacklightState(
+ deviceId,
+ state.brightnessLevel,
+ state.maxBrightnessLevel,
+ isTriggeredByKeyPress,
+ )
}
}
@@ -619,7 +636,7 @@ class KeyboardBacklightControllerTests {
val deviceId: Int,
val brightnessLevel: Int,
val maxBrightnessLevel: Int,
- val isTriggeredByKeyPress: Boolean
+ val isTriggeredByKeyPress: Boolean,
)
private inner class FakeAnimatorFactory : KeyboardBacklightController.AnimatorFactory {
diff --git a/tests/Input/src/com/android/server/input/KeyboardGlyphManagerTests.kt b/tests/Input/src/com/android/server/input/KeyboardGlyphManagerTests.kt
index 5da0beb9cc8a..7c3a6a60d3b6 100644
--- a/tests/Input/src/com/android/server/input/KeyboardGlyphManagerTests.kt
+++ b/tests/Input/src/com/android/server/input/KeyboardGlyphManagerTests.kt
@@ -49,8 +49,7 @@ import org.mockito.junit.MockitoJUnit
/**
* Tests for custom keyboard glyph map configuration.
*
- * Build/Install/Run:
- * atest InputTests:KeyboardGlyphManagerTests
+ * Build/Install/Run: atest InputTests:KeyboardGlyphManagerTests
*/
@Presubmit
class KeyboardGlyphManagerTests {
@@ -66,15 +65,11 @@ class KeyboardGlyphManagerTests {
const val RECEIVER_NAME = "DummyReceiver"
}
- @get:Rule
- val setFlagsRule = SetFlagsRule()
- @get:Rule
- val mockitoRule = MockitoJUnit.rule()!!
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
+ @get:Rule val setFlagsRule = SetFlagsRule()
+ @get:Rule val mockitoRule = MockitoJUnit.rule()!!
+ @get:Rule val inputManagerRule = MockInputManagerRule()
- @Mock
- private lateinit var packageManager: PackageManager
+ @Mock private lateinit var packageManager: PackageManager
private lateinit var keyboardGlyphManager: KeyboardGlyphManager
private lateinit var context: Context
@@ -99,7 +94,8 @@ class KeyboardGlyphManagerTests {
.thenReturn(inputManager)
keyboardDevice = createKeyboard(DEVICE_ID, VENDOR_ID, PRODUCT_ID, 0, "", "")
- Mockito.`when`(inputManagerRule.mock.inputDeviceIds).thenReturn(intArrayOf(DEVICE_ID, DEVICE_ID2))
+ Mockito.`when`(inputManagerRule.mock.inputDeviceIds)
+ .thenReturn(intArrayOf(DEVICE_ID, DEVICE_ID2))
Mockito.`when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardDevice)
val keyboardDevice2 = createKeyboard(DEVICE_ID2, VENDOR_ID2, PRODUCT_ID2, 0, "", "")
@@ -110,19 +106,22 @@ class KeyboardGlyphManagerTests {
Mockito.`when`(context.packageManager).thenReturn(packageManager)
val info = createMockReceiver()
- Mockito.`when`(packageManager.queryBroadcastReceiversAsUser(Mockito.any(), Mockito.anyInt(),
- Mockito.anyInt())).thenReturn(listOf(info))
+ Mockito.`when`(
+ packageManager.queryBroadcastReceiversAsUser(
+ Mockito.any(),
+ Mockito.anyInt(),
+ Mockito.anyInt(),
+ )
+ )
+ .thenReturn(listOf(info))
Mockito.`when`(packageManager.getReceiverInfo(Mockito.any(), Mockito.anyInt()))
.thenReturn(info.activityInfo)
val resources = context.resources
Mockito.`when`(
- packageManager.getResourcesForApplication(
- Mockito.any(
- ApplicationInfo::class.java
- )
+ packageManager.getResourcesForApplication(Mockito.any(ApplicationInfo::class.java))
)
- ).thenReturn(resources)
+ .thenReturn(resources)
}
private fun createMockReceiver(): ResolveInfo {
@@ -134,7 +133,7 @@ class KeyboardGlyphManagerTests {
info.activityInfo.metaData = Bundle()
info.activityInfo.metaData.putInt(
InputManager.META_DATA_KEYBOARD_GLYPH_MAPS,
- R.xml.keyboard_glyph_maps
+ R.xml.keyboard_glyph_maps,
)
info.serviceInfo = ServiceInfo()
info.serviceInfo.packageName = PACKAGE_NAME
@@ -147,15 +146,15 @@ class KeyboardGlyphManagerTests {
fun testGlyphMapsLoaded() {
assertNotNull(
"Glyph map for test keyboard(deviceId=$DEVICE_ID) must exist",
- keyboardGlyphManager.getKeyGlyphMap(DEVICE_ID)
+ keyboardGlyphManager.getKeyGlyphMap(DEVICE_ID),
)
assertNotNull(
"Glyph map for test keyboard(deviceId=$DEVICE_ID2) must exist",
- keyboardGlyphManager.getKeyGlyphMap(DEVICE_ID2)
+ keyboardGlyphManager.getKeyGlyphMap(DEVICE_ID2),
)
assertNull(
"Glyph map for non-existing keyboard must be null",
- keyboardGlyphManager.getKeyGlyphMap(-2)
+ keyboardGlyphManager.getKeyGlyphMap(-2),
)
}
@@ -178,16 +177,15 @@ class KeyboardGlyphManagerTests {
assertEquals(2, hardwareShortcuts.size)
assertEquals(
KeyEvent.KEYCODE_BACK,
- hardwareShortcuts[KeyCombination(KeyEvent.META_FUNCTION_ON, KeyEvent.KEYCODE_1)]
+ hardwareShortcuts[KeyCombination(KeyEvent.META_FUNCTION_ON, KeyEvent.KEYCODE_1)],
)
assertEquals(
KeyEvent.KEYCODE_HOME,
hardwareShortcuts[
KeyCombination(
KeyEvent.META_FUNCTION_ON or KeyEvent.META_META_ON,
- KeyEvent.KEYCODE_2
- )
- ]
+ KeyEvent.KEYCODE_2,
+ )],
)
}
}
diff --git a/tests/Input/src/com/android/server/input/KeyboardLayoutManagerTests.kt b/tests/Input/src/com/android/server/input/KeyboardLayoutManagerTests.kt
index 4440a839caef..c83036ce05ba 100644
--- a/tests/Input/src/com/android/server/input/KeyboardLayoutManagerTests.kt
+++ b/tests/Input/src/com/android/server/input/KeyboardLayoutManagerTests.kt
@@ -65,7 +65,7 @@ fun createKeyboard(
productId: Int,
deviceBus: Int,
languageTag: String,
- layoutType: String
+ layoutType: String,
): InputDevice =
InputDevice.Builder()
.setId(deviceId)
@@ -84,8 +84,7 @@ fun createKeyboard(
/**
* Tests for {@link Default UI} and {@link New UI}.
*
- * Build/Install/Run:
- * atest InputTests:KeyboardLayoutManagerTests
+ * Build/Install/Run: atest InputTests:KeyboardLayoutManagerTests
*/
@Presubmit
class KeyboardLayoutManagerTests {
@@ -118,19 +117,15 @@ class KeyboardLayoutManagerTests {
@JvmField
@Rule
- val extendedMockitoRule = ExtendedMockitoRule.Builder(this)
- .mockStatic(FrameworkStatsLog::class.java).build()!!
+ val extendedMockitoRule =
+ ExtendedMockitoRule.Builder(this).mockStatic(FrameworkStatsLog::class.java).build()!!
- @get:Rule
- val inputManagerRule = MockInputManagerRule()
+ @get:Rule val inputManagerRule = MockInputManagerRule()
- @Mock
- private lateinit var native: NativeInputManagerService
+ @Mock private lateinit var native: NativeInputManagerService
- @Mock
- private lateinit var packageManager: PackageManager
- @Mock
- private lateinit var notificationManager: NotificationManager
+ @Mock private lateinit var packageManager: PackageManager
+ @Mock private lateinit var notificationManager: NotificationManager
private lateinit var keyboardLayoutManager: KeyboardLayoutManager
private lateinit var imeInfo: InputMethodInfo
@@ -149,23 +144,25 @@ class KeyboardLayoutManagerTests {
@Before
fun setup() {
context = Mockito.spy(ContextWrapper(ApplicationProvider.getApplicationContext()))
- dataStore = PersistentDataStore(object : PersistentDataStore.Injector() {
- override fun openRead(): InputStream? {
- throw FileNotFoundException()
- }
-
- override fun startWrite(): FileOutputStream? {
- throw IOException()
- }
-
- override fun finishWrite(fos: FileOutputStream?, success: Boolean) {}
- })
+ dataStore =
+ PersistentDataStore(
+ object : PersistentDataStore.Injector() {
+ override fun openRead(): InputStream? {
+ throw FileNotFoundException()
+ }
+
+ override fun startWrite(): FileOutputStream? {
+ throw IOException()
+ }
+
+ override fun finishWrite(fos: FileOutputStream?, success: Boolean) {}
+ }
+ )
testLooper = TestLooper()
- keyboardLayoutManager = Mockito.spy(
- KeyboardLayoutManager(context, native, dataStore, testLooper.looper)
- )
+ keyboardLayoutManager =
+ Mockito.spy(KeyboardLayoutManager(context, native, dataStore, testLooper.looper))
Mockito.`when`(context.getSystemService(Mockito.eq(Context.NOTIFICATION_SERVICE)))
- .thenReturn(notificationManager)
+ .thenReturn(notificationManager)
setupInputDevices()
setupBroadcastReceiver()
setupIme()
@@ -176,47 +173,72 @@ class KeyboardLayoutManagerTests {
Mockito.`when`(context.getSystemService(Mockito.eq(Context.INPUT_SERVICE)))
.thenReturn(inputManager)
- keyboardDevice = createKeyboard(DEVICE_ID, DEFAULT_VENDOR_ID, DEFAULT_PRODUCT_ID,
- DEFAULT_DEVICE_BUS, "", "")
- vendorSpecificKeyboardDevice = createKeyboard(VENDOR_SPECIFIC_DEVICE_ID, 1, 1,
- 1, "", "")
- englishDvorakKeyboardDevice = createKeyboard(ENGLISH_DVORAK_DEVICE_ID, DEFAULT_VENDOR_ID,
- DEFAULT_PRODUCT_ID, DEFAULT_DEVICE_BUS, "en", "dvorak")
- englishQwertyKeyboardDevice = createKeyboard(ENGLISH_QWERTY_DEVICE_ID, DEFAULT_VENDOR_ID,
- DEFAULT_PRODUCT_ID, DEFAULT_DEVICE_BUS, "en", "qwerty")
- Mockito.`when`(inputManagerRule.mock.inputDeviceIds)
- .thenReturn(intArrayOf(
+ keyboardDevice =
+ createKeyboard(
DEVICE_ID,
- VENDOR_SPECIFIC_DEVICE_ID,
+ DEFAULT_VENDOR_ID,
+ DEFAULT_PRODUCT_ID,
+ DEFAULT_DEVICE_BUS,
+ "",
+ "",
+ )
+ vendorSpecificKeyboardDevice = createKeyboard(VENDOR_SPECIFIC_DEVICE_ID, 1, 1, 1, "", "")
+ englishDvorakKeyboardDevice =
+ createKeyboard(
ENGLISH_DVORAK_DEVICE_ID,
- ENGLISH_QWERTY_DEVICE_ID
- ))
+ DEFAULT_VENDOR_ID,
+ DEFAULT_PRODUCT_ID,
+ DEFAULT_DEVICE_BUS,
+ "en",
+ "dvorak",
+ )
+ englishQwertyKeyboardDevice =
+ createKeyboard(
+ ENGLISH_QWERTY_DEVICE_ID,
+ DEFAULT_VENDOR_ID,
+ DEFAULT_PRODUCT_ID,
+ DEFAULT_DEVICE_BUS,
+ "en",
+ "qwerty",
+ )
+ Mockito.`when`(inputManagerRule.mock.inputDeviceIds)
+ .thenReturn(
+ intArrayOf(
+ DEVICE_ID,
+ VENDOR_SPECIFIC_DEVICE_ID,
+ ENGLISH_DVORAK_DEVICE_ID,
+ ENGLISH_QWERTY_DEVICE_ID,
+ )
+ )
Mockito.`when`(inputManagerRule.mock.getInputDevice(DEVICE_ID)).thenReturn(keyboardDevice)
Mockito.`when`(inputManagerRule.mock.getInputDevice(VENDOR_SPECIFIC_DEVICE_ID))
.thenReturn(vendorSpecificKeyboardDevice)
Mockito.`when`(inputManagerRule.mock.getInputDevice(ENGLISH_DVORAK_DEVICE_ID))
.thenReturn(englishDvorakKeyboardDevice)
Mockito.`when`(inputManagerRule.mock.getInputDevice(ENGLISH_QWERTY_DEVICE_ID))
- .thenReturn(englishQwertyKeyboardDevice)
+ .thenReturn(englishQwertyKeyboardDevice)
}
private fun setupBroadcastReceiver() {
Mockito.`when`(context.packageManager).thenReturn(packageManager)
val info = createMockReceiver()
- Mockito.`when`(packageManager.queryBroadcastReceiversAsUser(Mockito.any(), Mockito.anyInt(),
- Mockito.anyInt())).thenReturn(listOf(info))
+ Mockito.`when`(
+ packageManager.queryBroadcastReceiversAsUser(
+ Mockito.any(),
+ Mockito.anyInt(),
+ Mockito.anyInt(),
+ )
+ )
+ .thenReturn(listOf(info))
Mockito.`when`(packageManager.getReceiverInfo(Mockito.any(), Mockito.anyInt()))
.thenReturn(info.activityInfo)
val resources = context.resources
Mockito.`when`(
- packageManager.getResourcesForApplication(
- Mockito.any(
- ApplicationInfo::class.java
- )
+ packageManager.getResourcesForApplication(Mockito.any(ApplicationInfo::class.java))
)
- ).thenReturn(resources)
+ .thenReturn(resources)
}
private fun setupIme() {
@@ -229,22 +251,21 @@ class KeyboardLayoutManagerTests {
assertNotEquals(
"Keyboard layout API should not return empty array",
0,
- keyboardLayouts.size
+ keyboardLayouts.size,
)
assertTrue(
"Keyboard layout API should provide English(US) layout",
- hasLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR)
+ hasLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR),
)
}
@Test
fun testGetKeyboardLayout() {
- val keyboardLayout =
- keyboardLayoutManager.getKeyboardLayout(ENGLISH_US_LAYOUT_DESCRIPTOR)
- assertEquals("getKeyboardLayout API should return correct Layout from " +
- "available layouts",
+ val keyboardLayout = keyboardLayoutManager.getKeyboardLayout(ENGLISH_US_LAYOUT_DESCRIPTOR)
+ assertEquals(
+ "getKeyboardLayout API should return correct Layout from " + "available layouts",
ENGLISH_US_LAYOUT_DESCRIPTOR,
- keyboardLayout!!.descriptor
+ keyboardLayout!!.descriptor,
)
}
@@ -253,32 +274,44 @@ class KeyboardLayoutManagerTests {
val imeSubtype = createImeSubtype()
keyboardLayoutManager.setKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype,
- ENGLISH_UK_LAYOUT_DESCRIPTOR
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ imeSubtype,
+ ENGLISH_UK_LAYOUT_DESCRIPTOR,
)
var result =
keyboardLayoutManager.getKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ imeSubtype,
)
assertEquals(
"getKeyboardLayoutForInputDevice API should return the set layout",
ENGLISH_UK_LAYOUT_DESCRIPTOR,
- result.layoutDescriptor
+ result.layoutDescriptor,
)
// This should replace previously set layout
keyboardLayoutManager.setKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype,
- ENGLISH_US_LAYOUT_DESCRIPTOR
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ imeSubtype,
+ ENGLISH_US_LAYOUT_DESCRIPTOR,
)
result =
keyboardLayoutManager.getKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ imeSubtype,
)
assertEquals(
"getKeyboardLayoutForInputDevice API should return the last set layout",
ENGLISH_US_LAYOUT_DESCRIPTOR,
- result.layoutDescriptor
+ result.layoutDescriptor,
)
}
@@ -288,32 +321,42 @@ class KeyboardLayoutManagerTests {
keyboardLayoutManager.setKeyboardLayoutOverrideForInputDevice(
keyboardDevice.identifier,
- ENGLISH_UK_LAYOUT_DESCRIPTOR
+ ENGLISH_UK_LAYOUT_DESCRIPTOR,
)
var result =
keyboardLayoutManager.getKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ imeSubtype,
)
assertEquals(LAYOUT_SELECTION_CRITERIA_DEVICE, result.selectionCriteria)
assertEquals(
"getKeyboardLayoutForInputDevice API should return the set layout",
ENGLISH_UK_LAYOUT_DESCRIPTOR,
- result.layoutDescriptor
+ result.layoutDescriptor,
)
// This should replace the overriding layout set above
keyboardLayoutManager.setKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype,
- ENGLISH_US_LAYOUT_DESCRIPTOR
- )
- result = keyboardLayoutManager.getKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ imeSubtype,
+ ENGLISH_US_LAYOUT_DESCRIPTOR,
)
+ result =
+ keyboardLayoutManager.getKeyboardLayoutForInputDevice(
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ imeSubtype,
+ )
assertEquals(LAYOUT_SELECTION_CRITERIA_USER, result.selectionCriteria)
assertEquals(
"getKeyboardLayoutForInputDevice API should return the user set layout",
ENGLISH_US_LAYOUT_DESCRIPTOR,
- result.layoutDescriptor
+ result.layoutDescriptor,
)
}
@@ -322,54 +365,67 @@ class KeyboardLayoutManagerTests {
// Check Layouts for "hi-Latn". It should return all 'Latn' keyboard layouts
var keyboardLayouts =
keyboardLayoutManager.getKeyboardLayoutListForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo,
- createImeSubtypeForLanguageTag("hi-Latn")
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ createImeSubtypeForLanguageTag("hi-Latn"),
)
assertNotEquals(
"getKeyboardLayoutListForInputDevice API should return the list of " +
- "supported layouts with matching script code",
+ "supported layouts with matching script code",
0,
- keyboardLayouts.size
+ keyboardLayouts.size,
)
- assertTrue("getKeyboardLayoutListForInputDevice API should return a list " +
+ assertTrue(
+ "getKeyboardLayoutListForInputDevice API should return a list " +
"containing English(US) layout for hi-Latn",
- containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR)
+ containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR),
)
- assertTrue("getKeyboardLayoutListForInputDevice API should return a list " +
+ assertTrue(
+ "getKeyboardLayoutListForInputDevice API should return a list " +
"containing English(No script code) layout for hi-Latn",
containsLayout(
keyboardLayouts,
- createLayoutDescriptor("keyboard_layout_english_without_script_code")
- )
+ createLayoutDescriptor("keyboard_layout_english_without_script_code"),
+ ),
)
// Check Layouts for "hi" which by default uses 'Deva' script.
keyboardLayouts =
keyboardLayoutManager.getKeyboardLayoutListForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo,
- createImeSubtypeForLanguageTag("hi")
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ createImeSubtypeForLanguageTag("hi"),
)
- assertEquals("getKeyboardLayoutListForInputDevice API should return empty " +
+ assertEquals(
+ "getKeyboardLayoutListForInputDevice API should return empty " +
"list if no supported layouts available",
0,
- keyboardLayouts.size
+ keyboardLayouts.size,
)
// If user manually selected some layout, always provide it in the layout list
val imeSubtype = createImeSubtypeForLanguageTag("hi")
keyboardLayoutManager.setKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo, imeSubtype,
- ENGLISH_US_LAYOUT_DESCRIPTOR
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ imeSubtype,
+ ENGLISH_US_LAYOUT_DESCRIPTOR,
)
keyboardLayouts =
keyboardLayoutManager.getKeyboardLayoutListForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo,
- imeSubtype
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ imeSubtype,
)
- assertEquals("getKeyboardLayoutListForInputDevice API should return user " +
+ assertEquals(
+ "getKeyboardLayoutListForInputDevice API should return user " +
"selected layout even if the script is incompatible with IME",
- 1,
- keyboardLayouts.size
+ 1,
+ keyboardLayouts.size,
)
// Special case Japanese: UScript ignores provided script code for certain language tags
@@ -377,63 +433,71 @@ class KeyboardLayoutManagerTests {
// script from language tags and match those.
keyboardLayouts =
keyboardLayoutManager.getKeyboardLayoutListForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo,
- createImeSubtypeForLanguageTag("ja-Latn-JP")
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ createImeSubtypeForLanguageTag("ja-Latn-JP"),
)
assertNotEquals(
"getKeyboardLayoutListForInputDevice API should return the list of " +
- "supported layouts with matching script code for ja-Latn-JP",
+ "supported layouts with matching script code for ja-Latn-JP",
0,
- keyboardLayouts.size
+ keyboardLayouts.size,
)
- assertTrue("getKeyboardLayoutListForInputDevice API should return a list " +
+ assertTrue(
+ "getKeyboardLayoutListForInputDevice API should return a list " +
"containing English(US) layout for ja-Latn-JP",
- containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR)
+ containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR),
)
- assertTrue("getKeyboardLayoutListForInputDevice API should return a list " +
+ assertTrue(
+ "getKeyboardLayoutListForInputDevice API should return a list " +
"containing English(No script code) layout for ja-Latn-JP",
containsLayout(
keyboardLayouts,
- createLayoutDescriptor("keyboard_layout_english_without_script_code")
- )
+ createLayoutDescriptor("keyboard_layout_english_without_script_code"),
+ ),
)
// If script code not explicitly provided for Japanese should rely on Uscript to find
// derived script code and hence no suitable layout will be found.
keyboardLayouts =
keyboardLayoutManager.getKeyboardLayoutListForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo,
- createImeSubtypeForLanguageTag("ja-JP")
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ createImeSubtypeForLanguageTag("ja-JP"),
)
assertEquals(
"getKeyboardLayoutListForInputDevice API should return empty list of " +
- "supported layouts with matching script code for ja-JP",
+ "supported layouts with matching script code for ja-JP",
0,
- keyboardLayouts.size
+ keyboardLayouts.size,
)
// If IME doesn't have a corresponding language tag, then should show all available
// layouts no matter the script code.
keyboardLayouts =
keyboardLayoutManager.getKeyboardLayoutListForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo, null
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ null,
)
assertNotEquals(
"getKeyboardLayoutListForInputDevice API should return all layouts if" +
"language tag or subtype not provided",
0,
- keyboardLayouts.size
+ keyboardLayouts.size,
)
- assertTrue("getKeyboardLayoutListForInputDevice API should contain Latin " +
- "layouts if language tag or subtype not provided",
- containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR)
+ assertTrue(
+ "getKeyboardLayoutListForInputDevice API should contain Latin " +
+ "layouts if language tag or subtype not provided",
+ containsLayout(keyboardLayouts, ENGLISH_US_LAYOUT_DESCRIPTOR),
)
- assertTrue("getKeyboardLayoutListForInputDevice API should contain Cyrillic " +
- "layouts if language tag or subtype not provided",
- containsLayout(
- keyboardLayouts,
- createLayoutDescriptor("keyboard_layout_russian")
- )
+ assertTrue(
+ "getKeyboardLayoutListForInputDevice API should contain Cyrillic " +
+ "layouts if language tag or subtype not provided",
+ containsLayout(keyboardLayouts, createLayoutDescriptor("keyboard_layout_russian")),
)
}
@@ -442,46 +506,50 @@ class KeyboardLayoutManagerTests {
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTag("en-US"),
- ENGLISH_US_LAYOUT_DESCRIPTOR
+ ENGLISH_US_LAYOUT_DESCRIPTOR,
)
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTag("en-GB"),
- ENGLISH_UK_LAYOUT_DESCRIPTOR
+ ENGLISH_UK_LAYOUT_DESCRIPTOR,
)
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTag("de"),
- GERMAN_LAYOUT_DESCRIPTOR
+ GERMAN_LAYOUT_DESCRIPTOR,
)
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTag("fr-FR"),
- createLayoutDescriptor("keyboard_layout_french")
+ createLayoutDescriptor("keyboard_layout_french"),
)
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTag("ru"),
- createLayoutDescriptor("keyboard_layout_russian")
+ createLayoutDescriptor("keyboard_layout_russian"),
)
assertEquals(
"getDefaultKeyboardLayoutForInputDevice should return " +
- "KeyboardLayoutSelectionResult.FAILED when no layout available",
+ "KeyboardLayoutSelectionResult.FAILED when no layout available",
KeyboardLayoutSelectionResult.FAILED,
keyboardLayoutManager.getKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo,
- createImeSubtypeForLanguageTag("it")
- )
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ createImeSubtypeForLanguageTag("it"),
+ ),
)
assertEquals(
"getDefaultKeyboardLayoutForInputDevice should return " +
- "KeyboardLayoutSelectionResult.FAILED when no layout for script code is" +
- "available",
+ "KeyboardLayoutSelectionResult.FAILED when no layout for script code is" +
+ "available",
KeyboardLayoutSelectionResult.FAILED,
keyboardLayoutManager.getKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo,
- createImeSubtypeForLanguageTag("en-Deva")
- )
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ createImeSubtypeForLanguageTag("en-Deva"),
+ ),
)
}
@@ -490,72 +558,75 @@ class KeyboardLayoutManagerTests {
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("en-US", "qwerty"),
- ENGLISH_US_LAYOUT_DESCRIPTOR
+ ENGLISH_US_LAYOUT_DESCRIPTOR,
)
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("en-US", "dvorak"),
- createLayoutDescriptor("keyboard_layout_english_us_dvorak")
+ createLayoutDescriptor("keyboard_layout_english_us_dvorak"),
)
// Try to match layout type even if country doesn't match
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("en-GB", "dvorak"),
- createLayoutDescriptor("keyboard_layout_english_us_dvorak")
+ createLayoutDescriptor("keyboard_layout_english_us_dvorak"),
)
// Choose layout based on layout type priority, if layout type is not provided by IME
// (Qwerty > Dvorak > Extended)
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("en-US", ""),
- ENGLISH_US_LAYOUT_DESCRIPTOR
+ ENGLISH_US_LAYOUT_DESCRIPTOR,
)
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("en-GB", "qwerty"),
- ENGLISH_UK_LAYOUT_DESCRIPTOR
+ ENGLISH_UK_LAYOUT_DESCRIPTOR,
)
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("de", "qwertz"),
- GERMAN_LAYOUT_DESCRIPTOR
+ GERMAN_LAYOUT_DESCRIPTOR,
)
// Wrong layout type should match with language if provided layout type not available
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("de", "qwerty"),
- GERMAN_LAYOUT_DESCRIPTOR
+ GERMAN_LAYOUT_DESCRIPTOR,
)
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("fr-FR", "azerty"),
- createLayoutDescriptor("keyboard_layout_french")
+ createLayoutDescriptor("keyboard_layout_french"),
)
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("ru", "qwerty"),
- createLayoutDescriptor("keyboard_layout_russian_qwerty")
+ createLayoutDescriptor("keyboard_layout_russian_qwerty"),
)
// If layout type is empty then prioritize KCM with empty layout type
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("ru", ""),
- createLayoutDescriptor("keyboard_layout_russian")
+ createLayoutDescriptor("keyboard_layout_russian"),
)
- assertEquals("getDefaultKeyboardLayoutForInputDevice should return " +
+ assertEquals(
+ "getDefaultKeyboardLayoutForInputDevice should return " +
"KeyboardLayoutSelectionResult.FAILED when no layout for script code is" +
"available",
KeyboardLayoutSelectionResult.FAILED,
keyboardLayoutManager.getKeyboardLayoutForInputDevice(
- keyboardDevice.identifier, USER_ID, imeInfo,
- createImeSubtypeForLanguageTagAndLayoutType("en-Deva-US", "")
- )
+ keyboardDevice.identifier,
+ USER_ID,
+ imeInfo,
+ createImeSubtypeForLanguageTagAndLayoutType("en-Deva-US", ""),
+ ),
)
// If prefer layout with empty country over mismatched country
assertCorrectLayout(
keyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("en-AU", "qwerty"),
- ENGLISH_US_LAYOUT_DESCRIPTOR
+ ENGLISH_US_LAYOUT_DESCRIPTOR,
)
}
@@ -567,7 +638,7 @@ class KeyboardLayoutManagerTests {
assertCorrectLayout(
englishDvorakKeyboardDevice,
frenchSubtype,
- createLayoutDescriptor("keyboard_layout_english_us_dvorak")
+ createLayoutDescriptor("keyboard_layout_english_us_dvorak"),
)
// Back to back changing HW keyboards with same product and vendor ID but different
@@ -575,7 +646,7 @@ class KeyboardLayoutManagerTests {
assertCorrectLayout(
englishQwertyKeyboardDevice,
frenchSubtype,
- createLayoutDescriptor("keyboard_layout_english_us")
+ createLayoutDescriptor("keyboard_layout_english_us"),
)
// Fallback to IME information if the HW provided layout script is incompatible with the
@@ -583,62 +654,72 @@ class KeyboardLayoutManagerTests {
assertCorrectLayout(
englishDvorakKeyboardDevice,
createImeSubtypeForLanguageTagAndLayoutType("ru", ""),
- createLayoutDescriptor("keyboard_layout_russian")
+ createLayoutDescriptor("keyboard_layout_russian"),
)
}
@Test
fun testConfigurationLogged_onInputDeviceAdded_VirtualKeyboardBasedSelection() {
- val imeInfos = listOf(
- KeyboardLayoutManager.ImeInfo(0, imeInfo,
- createImeSubtypeForLanguageTagAndLayoutType("de-Latn", "qwertz")))
+ val imeInfos =
+ listOf(
+ KeyboardLayoutManager.ImeInfo(
+ 0,
+ imeInfo,
+ createImeSubtypeForLanguageTagAndLayoutType("de-Latn", "qwertz"),
+ )
+ )
Mockito.doReturn(imeInfos).`when`(keyboardLayoutManager).imeInfoListForLayoutMapping
keyboardLayoutManager.onInputDeviceAdded(keyboardDevice.id)
ExtendedMockito.verify {
FrameworkStatsLog.write(
- ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED),
- ArgumentMatchers.anyBoolean(),
- ArgumentMatchers.eq(keyboardDevice.vendorId),
- ArgumentMatchers.eq(keyboardDevice.productId),
- ArgumentMatchers.eq(
- createByteArray(
- KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG,
- LAYOUT_TYPE_DEFAULT,
- GERMAN_LAYOUT_NAME,
- KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD,
- "de-Latn",
- LAYOUT_TYPE_QWERTZ
- ),
- ),
- ArgumentMatchers.eq(keyboardDevice.deviceBus),
+ ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED),
+ ArgumentMatchers.anyBoolean(),
+ ArgumentMatchers.eq(keyboardDevice.vendorId),
+ ArgumentMatchers.eq(keyboardDevice.productId),
+ ArgumentMatchers.eq(
+ createByteArray(
+ KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG,
+ LAYOUT_TYPE_DEFAULT,
+ GERMAN_LAYOUT_NAME,
+ KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD,
+ "de-Latn",
+ LAYOUT_TYPE_QWERTZ,
+ )
+ ),
+ ArgumentMatchers.eq(keyboardDevice.deviceBus),
)
}
}
@Test
fun testConfigurationLogged_onInputDeviceAdded_DeviceBasedSelection() {
- val imeInfos = listOf(
- KeyboardLayoutManager.ImeInfo(0, imeInfo,
- createImeSubtypeForLanguageTagAndLayoutType("de-Latn", "qwertz")))
+ val imeInfos =
+ listOf(
+ KeyboardLayoutManager.ImeInfo(
+ 0,
+ imeInfo,
+ createImeSubtypeForLanguageTagAndLayoutType("de-Latn", "qwertz"),
+ )
+ )
Mockito.doReturn(imeInfos).`when`(keyboardLayoutManager).imeInfoListForLayoutMapping
keyboardLayoutManager.onInputDeviceAdded(englishQwertyKeyboardDevice.id)
ExtendedMockito.verify {
FrameworkStatsLog.write(
- ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED),
- ArgumentMatchers.anyBoolean(),
- ArgumentMatchers.eq(englishQwertyKeyboardDevice.vendorId),
- ArgumentMatchers.eq(englishQwertyKeyboardDevice.productId),
- ArgumentMatchers.eq(
- createByteArray(
- "en",
- LAYOUT_TYPE_QWERTY,
- ENGLISH_US_LAYOUT_NAME,
- KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE,
- "de-Latn",
- LAYOUT_TYPE_QWERTZ
- )
- ),
- ArgumentMatchers.eq(keyboardDevice.deviceBus),
+ ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED),
+ ArgumentMatchers.anyBoolean(),
+ ArgumentMatchers.eq(englishQwertyKeyboardDevice.vendorId),
+ ArgumentMatchers.eq(englishQwertyKeyboardDevice.productId),
+ ArgumentMatchers.eq(
+ createByteArray(
+ "en",
+ LAYOUT_TYPE_QWERTY,
+ ENGLISH_US_LAYOUT_NAME,
+ KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE,
+ "de-Latn",
+ LAYOUT_TYPE_QWERTZ,
+ )
+ ),
+ ArgumentMatchers.eq(keyboardDevice.deviceBus),
)
}
}
@@ -650,21 +731,21 @@ class KeyboardLayoutManagerTests {
keyboardLayoutManager.onInputDeviceAdded(keyboardDevice.id)
ExtendedMockito.verify {
FrameworkStatsLog.write(
- ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED),
- ArgumentMatchers.anyBoolean(),
- ArgumentMatchers.eq(keyboardDevice.vendorId),
- ArgumentMatchers.eq(keyboardDevice.productId),
- ArgumentMatchers.eq(
- createByteArray(
- KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG,
- LAYOUT_TYPE_DEFAULT,
- "Default",
- KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEFAULT,
- KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG,
- LAYOUT_TYPE_DEFAULT
- ),
- ),
- ArgumentMatchers.eq(keyboardDevice.deviceBus),
+ ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED),
+ ArgumentMatchers.anyBoolean(),
+ ArgumentMatchers.eq(keyboardDevice.vendorId),
+ ArgumentMatchers.eq(keyboardDevice.productId),
+ ArgumentMatchers.eq(
+ createByteArray(
+ KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG,
+ LAYOUT_TYPE_DEFAULT,
+ "Default",
+ KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEFAULT,
+ KeyboardMetricsCollector.DEFAULT_LANGUAGE_TAG,
+ LAYOUT_TYPE_DEFAULT,
+ )
+ ),
+ ArgumentMatchers.eq(keyboardDevice.deviceBus),
)
}
}
@@ -674,82 +755,86 @@ class KeyboardLayoutManagerTests {
val imeInfos = listOf(KeyboardLayoutManager.ImeInfo(0, imeInfo, createImeSubtype()))
Mockito.doReturn(imeInfos).`when`(keyboardLayoutManager).imeInfoListForLayoutMapping
keyboardLayoutManager.onInputDeviceChanged(keyboardDevice.id)
- ExtendedMockito.verify({
- FrameworkStatsLog.write(
+ ExtendedMockito.verify(
+ {
+ FrameworkStatsLog.write(
ArgumentMatchers.eq(FrameworkStatsLog.KEYBOARD_CONFIGURED),
ArgumentMatchers.anyBoolean(),
ArgumentMatchers.anyInt(),
ArgumentMatchers.anyInt(),
ArgumentMatchers.any(ByteArray::class.java),
ArgumentMatchers.anyInt(),
- )
- }, Mockito.times(0))
+ )
+ },
+ Mockito.times(0),
+ )
}
@Test
fun testNotificationShown_onInputDeviceChanged() {
val imeInfos = listOf(KeyboardLayoutManager.ImeInfo(0, imeInfo, createImeSubtype()))
Mockito.doReturn(imeInfos).`when`(keyboardLayoutManager).imeInfoListForLayoutMapping
- Mockito.doReturn(false).`when`(keyboardLayoutManager).isVirtualDevice(
- ArgumentMatchers.eq(keyboardDevice.id)
- )
+ Mockito.doReturn(false)
+ .`when`(keyboardLayoutManager)
+ .isVirtualDevice(ArgumentMatchers.eq(keyboardDevice.id))
keyboardLayoutManager.onInputDeviceChanged(keyboardDevice.id)
- ExtendedMockito.verify(
- notificationManager,
- Mockito.times(1)
- ).notifyAsUser(
- ArgumentMatchers.isNull(),
- ArgumentMatchers.anyInt(),
- ArgumentMatchers.any(),
- ArgumentMatchers.any()
- )
+ ExtendedMockito.verify(notificationManager, Mockito.times(1))
+ .notifyAsUser(
+ ArgumentMatchers.isNull(),
+ ArgumentMatchers.anyInt(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ )
}
@Test
fun testNotificationNotShown_onInputDeviceChanged_forVirtualDevice() {
val imeInfos = listOf(KeyboardLayoutManager.ImeInfo(0, imeInfo, createImeSubtype()))
Mockito.doReturn(imeInfos).`when`(keyboardLayoutManager).imeInfoListForLayoutMapping
- Mockito.doReturn(true).`when`(keyboardLayoutManager).isVirtualDevice(
- ArgumentMatchers.eq(keyboardDevice.id)
- )
+ Mockito.doReturn(true)
+ .`when`(keyboardLayoutManager)
+ .isVirtualDevice(ArgumentMatchers.eq(keyboardDevice.id))
keyboardLayoutManager.onInputDeviceChanged(keyboardDevice.id)
- ExtendedMockito.verify(
- notificationManager,
- Mockito.never()
- ).notifyAsUser(
- ArgumentMatchers.isNull(),
- ArgumentMatchers.anyInt(),
- ArgumentMatchers.any(),
- ArgumentMatchers.any()
- )
+ ExtendedMockito.verify(notificationManager, Mockito.never())
+ .notifyAsUser(
+ ArgumentMatchers.isNull(),
+ ArgumentMatchers.anyInt(),
+ ArgumentMatchers.any(),
+ ArgumentMatchers.any(),
+ )
}
private fun assertCorrectLayout(
device: InputDevice,
imeSubtype: InputMethodSubtype,
- expectedLayout: String
+ expectedLayout: String,
) {
- val result = keyboardLayoutManager.getKeyboardLayoutForInputDevice(
- device.identifier, USER_ID, imeInfo, imeSubtype
- )
+ val result =
+ keyboardLayoutManager.getKeyboardLayoutForInputDevice(
+ device.identifier,
+ USER_ID,
+ imeInfo,
+ imeSubtype,
+ )
assertEquals(
"getDefaultKeyboardLayoutForInputDevice should return $expectedLayout",
expectedLayout,
- result.layoutDescriptor
+ result.layoutDescriptor,
)
}
private fun createImeSubtype(): InputMethodSubtype =
- createImeSubtypeForLanguageTagAndLayoutType(null, null)
+ createImeSubtypeForLanguageTagAndLayoutType(null, null)
private fun createImeSubtypeForLanguageTag(languageTag: String): InputMethodSubtype =
- createImeSubtypeForLanguageTagAndLayoutType(languageTag, null)
+ createImeSubtypeForLanguageTagAndLayoutType(languageTag, null)
private fun createImeSubtypeForLanguageTagAndLayoutType(
- languageTag: String?,
- layoutType: String?
+ languageTag: String?,
+ layoutType: String?,
): InputMethodSubtype {
- val builder = InputMethodSubtype.InputMethodSubtypeBuilder()
+ val builder =
+ InputMethodSubtype.InputMethodSubtypeBuilder()
.setSubtypeId(nextImeSubtypeId++)
.setIsAuxiliary(false)
.setSubtypeMode("keyboard")
@@ -762,39 +847,39 @@ class KeyboardLayoutManagerTests {
}
private fun createByteArray(
- expectedLanguageTag: String,
- expectedLayoutType: Int,
- expectedLayoutName: String,
- expectedCriteria: Int,
- expectedImeLanguageTag: String,
- expectedImeLayoutType: Int
+ expectedLanguageTag: String,
+ expectedLayoutType: Int,
+ expectedLayoutName: String,
+ expectedCriteria: Int,
+ expectedImeLanguageTag: String,
+ expectedImeLayoutType: Int,
): ByteArray {
val proto = ProtoOutputStream()
- val keyboardLayoutConfigToken = proto.start(
- KeyboardConfiguredProto.RepeatedKeyboardLayoutConfig.KEYBOARD_LAYOUT_CONFIG)
+ val keyboardLayoutConfigToken =
+ proto.start(KeyboardConfiguredProto.RepeatedKeyboardLayoutConfig.KEYBOARD_LAYOUT_CONFIG)
proto.write(
- KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LANGUAGE_TAG,
- expectedLanguageTag
+ KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LANGUAGE_TAG,
+ expectedLanguageTag,
)
proto.write(
- KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LAYOUT_TYPE,
- expectedLayoutType
+ KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LAYOUT_TYPE,
+ expectedLayoutType,
)
proto.write(
- KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LAYOUT_NAME,
- expectedLayoutName
+ KeyboardConfiguredProto.KeyboardLayoutConfig.KEYBOARD_LAYOUT_NAME,
+ expectedLayoutName,
)
proto.write(
- KeyboardConfiguredProto.KeyboardLayoutConfig.LAYOUT_SELECTION_CRITERIA,
- expectedCriteria
+ KeyboardConfiguredProto.KeyboardLayoutConfig.LAYOUT_SELECTION_CRITERIA,
+ expectedCriteria,
)
proto.write(
- KeyboardConfiguredProto.KeyboardLayoutConfig.IME_LANGUAGE_TAG,
- expectedImeLanguageTag
+ KeyboardConfiguredProto.KeyboardLayoutConfig.IME_LANGUAGE_TAG,
+ expectedImeLanguageTag,
)
proto.write(
- KeyboardConfiguredProto.KeyboardLayoutConfig.IME_LAYOUT_TYPE,
- expectedImeLayoutType
+ KeyboardConfiguredProto.KeyboardLayoutConfig.IME_LAYOUT_TYPE,
+ expectedImeLayoutType,
)
proto.end(keyboardLayoutConfigToken)
return proto.bytes
@@ -830,7 +915,7 @@ class KeyboardLayoutManagerTests {
info.activityInfo.metaData = Bundle()
info.activityInfo.metaData.putInt(
InputManager.META_DATA_KEYBOARD_LAYOUTS,
- R.xml.keyboard_layouts
+ R.xml.keyboard_layouts,
)
info.serviceInfo = ServiceInfo()
info.serviceInfo.packageName = PACKAGE_NAME
diff --git a/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt b/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt
index 0615941eda09..5251f3d3f1d3 100644
--- a/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt
+++ b/tests/Input/src/com/android/server/input/KeyboardMetricsCollectorTests.kt
@@ -33,7 +33,7 @@ private fun createKeyboard(
productId: Int,
deviceBus: Int,
languageTag: String?,
- layoutType: String?
+ layoutType: String?,
): InputDevice =
InputDevice.Builder()
.setId(deviceId)
@@ -52,16 +52,17 @@ private fun createKeyboard(
private fun createImeSubtype(
imeSubtypeId: Int,
languageTag: ULocale?,
- layoutType: String
+ layoutType: String,
): InputMethodSubtype =
- InputMethodSubtype.InputMethodSubtypeBuilder().setSubtypeId(imeSubtypeId)
- .setPhysicalKeyboardHint(languageTag, layoutType).build()
+ InputMethodSubtype.InputMethodSubtypeBuilder()
+ .setSubtypeId(imeSubtypeId)
+ .setPhysicalKeyboardHint(languageTag, layoutType)
+ .build()
/**
* Tests for {@link KeyboardMetricsCollector}.
*
- * Build/Install/Run:
- * atest InputTests:KeyboardMetricsCollectorTests
+ * Build/Install/Run: atest InputTests:KeyboardMetricsCollectorTests
*/
@Presubmit
class KeyboardMetricsCollectorTests {
@@ -77,15 +78,16 @@ class KeyboardMetricsCollectorTests {
fun testCreateKeyboardConfigurationEvent_throwsExceptionWithoutAnyLayoutConfiguration() {
assertThrows(IllegalStateException::class.java) {
KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder(
- createKeyboard(
- DEVICE_ID,
- DEFAULT_VENDOR_ID,
- DEFAULT_PRODUCT_ID,
- DEFAULT_DEVICE_BUS,
- null,
- null
+ createKeyboard(
+ DEVICE_ID,
+ DEFAULT_VENDOR_ID,
+ DEFAULT_PRODUCT_ID,
+ DEFAULT_DEVICE_BUS,
+ null,
+ null,
+ )
)
- ).build()
+ .build()
}
}
@@ -93,66 +95,78 @@ class KeyboardMetricsCollectorTests {
fun testCreateKeyboardConfigurationEvent_throwsExceptionWithInvalidLayoutSelectionCriteria() {
assertThrows(IllegalStateException::class.java) {
KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder(
- createKeyboard(
- DEVICE_ID,
- DEFAULT_VENDOR_ID,
- DEFAULT_PRODUCT_ID,
- DEFAULT_DEVICE_BUS,
+ createKeyboard(
+ DEVICE_ID,
+ DEFAULT_VENDOR_ID,
+ DEFAULT_PRODUCT_ID,
+ DEFAULT_DEVICE_BUS,
+ null,
+ null,
+ )
+ )
+ .addLayoutSelection(
+ createImeSubtype(1, ULocale.forLanguageTag("en-US"), "qwerty"),
null,
- null
+ 123,
)
- ).addLayoutSelection(createImeSubtype(1, ULocale.forLanguageTag("en-US"), "qwerty"),
- null, 123).build()
+ .build()
}
}
@Test
fun testCreateKeyboardConfigurationEvent_withMultipleConfigurations() {
- val builder = KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder(
- createKeyboard(
- DEVICE_ID,
- DEFAULT_VENDOR_ID,
- DEFAULT_PRODUCT_ID,
- DEFAULT_DEVICE_BUS,
- "de-CH",
- "qwertz"
+ val builder =
+ KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder(
+ createKeyboard(
+ DEVICE_ID,
+ DEFAULT_VENDOR_ID,
+ DEFAULT_PRODUCT_ID,
+ DEFAULT_DEVICE_BUS,
+ "de-CH",
+ "qwertz",
+ )
)
- )
- val event = builder.addLayoutSelection(
- createImeSubtype(1, ULocale.forLanguageTag("en-US"), "qwerty"),
- "English(US)(Qwerty)",
- KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD
- ).addLayoutSelection(
- createImeSubtype(2, ULocale.forLanguageTag("en-US"), "azerty"),
- null, // Default layout type
- KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_USER
- ).addLayoutSelection(
- createImeSubtype(3, ULocale.forLanguageTag("en-US"), "qwerty"),
- "German",
- KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE
- ).setIsFirstTimeConfiguration(true).build()
+ val event =
+ builder
+ .addLayoutSelection(
+ createImeSubtype(1, ULocale.forLanguageTag("en-US"), "qwerty"),
+ "English(US)(Qwerty)",
+ KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_VIRTUAL_KEYBOARD,
+ )
+ .addLayoutSelection(
+ createImeSubtype(2, ULocale.forLanguageTag("en-US"), "azerty"),
+ null, // Default layout type
+ KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_USER,
+ )
+ .addLayoutSelection(
+ createImeSubtype(3, ULocale.forLanguageTag("en-US"), "qwerty"),
+ "German",
+ KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE,
+ )
+ .setIsFirstTimeConfiguration(true)
+ .build()
assertEquals(
"KeyboardConfigurationEvent should pick vendor ID from provided InputDevice",
DEFAULT_VENDOR_ID,
- event.vendorId
+ event.vendorId,
)
assertEquals(
"KeyboardConfigurationEvent should pick product ID from provided InputDevice",
DEFAULT_PRODUCT_ID,
- event.productId
+ event.productId,
)
assertEquals(
- "KeyboardConfigurationEvent should pick device bus from provided InputDevice",
- DEFAULT_DEVICE_BUS,
- event.deviceBus
+ "KeyboardConfigurationEvent should pick device bus from provided InputDevice",
+ DEFAULT_DEVICE_BUS,
+ event.deviceBus,
)
assertTrue(event.isFirstConfiguration)
assertEquals(
"KeyboardConfigurationEvent should contain 3 configurations provided",
3,
- event.layoutConfigurations.size
+ event.layoutConfigurations.size,
)
assertExpectedLayoutConfiguration(
event.layoutConfigurations[0],
@@ -185,21 +199,25 @@ class KeyboardMetricsCollectorTests {
@Test
fun testCreateKeyboardConfigurationEvent_withDefaultLanguageTag() {
- val builder = KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder(
- createKeyboard(
- DEVICE_ID,
- DEFAULT_VENDOR_ID,
- DEFAULT_PRODUCT_ID,
- DEFAULT_DEVICE_BUS,
- "und", // Undefined language tag
- "azerty"
+ val builder =
+ KeyboardMetricsCollector.KeyboardConfigurationEvent.Builder(
+ createKeyboard(
+ DEVICE_ID,
+ DEFAULT_VENDOR_ID,
+ DEFAULT_PRODUCT_ID,
+ DEFAULT_DEVICE_BUS,
+ "und", // Undefined language tag
+ "azerty",
+ )
)
- )
- val event = builder.addLayoutSelection(
- createImeSubtype(4, null, "qwerty"), // Default language tag
- "German",
- KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE
- ).build()
+ val event =
+ builder
+ .addLayoutSelection(
+ createImeSubtype(4, null, "qwerty"), // Default language tag
+ "German",
+ KeyboardLayoutSelectionResult.LAYOUT_SELECTION_CRITERIA_DEVICE,
+ )
+ .build()
assertExpectedLayoutConfiguration(
event.layoutConfigurations[0],
@@ -219,7 +237,7 @@ class KeyboardMetricsCollectorTests {
expectedSelectedLayout: String,
expectedLayoutSelectionCriteria: Int,
expectedImeLanguageTag: String,
- expectedImeLayoutType: Int
+ expectedImeLayoutType: Int,
) {
assertEquals(expectedKeyboardLanguageTag, configuration.keyboardLanguageTag)
assertEquals(expectedKeyboardLayoutType, configuration.keyboardLayoutType)
diff --git a/tests/Input/src/com/android/server/input/PointerIconCacheTest.kt b/tests/Input/src/com/android/server/input/PointerIconCacheTest.kt
index 47e7ac720a08..d9ae7f339ed9 100644
--- a/tests/Input/src/com/android/server/input/PointerIconCacheTest.kt
+++ b/tests/Input/src/com/android/server/input/PointerIconCacheTest.kt
@@ -34,19 +34,14 @@ import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
-/**
- * Tests for {@link PointerIconCache}.
- */
+/** Tests for {@link PointerIconCache}. */
@Presubmit
class PointerIconCacheTest {
- @get:Rule
- val rule = MockitoJUnit.rule()!!
+ @get:Rule val rule = MockitoJUnit.rule()!!
- @Mock
- private lateinit var native: NativeInputManagerService
- @Mock
- private lateinit var defaultDisplay: Display
+ @Mock private lateinit var native: NativeInputManagerService
+ @Mock private lateinit var defaultDisplay: Display
private lateinit var context: Context
private lateinit var testLooper: TestLooper
@@ -56,9 +51,10 @@ class PointerIconCacheTest {
fun setup() {
whenever(defaultDisplay.displayId).thenReturn(Display.DEFAULT_DISPLAY)
- context = object : ContextWrapper(InstrumentationRegistry.getInstrumentation().context) {
- override fun getDisplay() = defaultDisplay
- }
+ context =
+ object : ContextWrapper(InstrumentationRegistry.getInstrumentation().context) {
+ override fun getDisplay() = defaultDisplay
+ }
testLooper = TestLooper()
cache = PointerIconCache(context, native, Handler(testLooper.looper))
diff --git a/tests/Input/src/com/android/test/input/InputEventAssignerTest.kt b/tests/Input/src/com/android/test/input/InputEventAssignerTest.kt
index 015e188fc98e..faa68bd484f6 100644
--- a/tests/Input/src/com/android/test/input/InputEventAssignerTest.kt
+++ b/tests/Input/src/com/android/test/input/InputEventAssignerTest.kt
@@ -17,10 +17,9 @@
package com.android.test.input
import android.view.InputDevice.SOURCE_MOUSE
-import android.view.InputDevice.SOURCE_TOUCHSCREEN
import android.view.InputDevice.SOURCE_STYLUS
import android.view.InputDevice.SOURCE_TOUCHPAD
-
+import android.view.InputDevice.SOURCE_TOUCHSCREEN
import android.view.InputEventAssigner
import android.view.KeyEvent
import android.view.MotionEvent
@@ -28,13 +27,13 @@ import org.junit.Assert.assertEquals
import org.junit.Test
sealed class StreamEvent
+
private data object Vsync : StreamEvent()
+
data class MotionEventData(val action: Int, val source: Int, val id: Int, val expectedId: Int) :
StreamEvent()
-/**
- * Create a MotionEvent with the provided action, eventTime, and source
- */
+/** Create a MotionEvent with the provided action, eventTime, and source */
fun createMotionEvent(action: Int, eventTime: Long, source: Int): MotionEvent {
val downTime: Long = 10
val x = 1f
@@ -47,8 +46,22 @@ fun createMotionEvent(action: Int, eventTime: Long, source: Int): MotionEvent {
val deviceId = 1
val edgeFlags = 0
val displayId = 0
- return MotionEvent.obtain(downTime, eventTime, action, x, y, pressure, size, metaState,
- xPrecision, yPrecision, deviceId, edgeFlags, source, displayId)
+ return MotionEvent.obtain(
+ downTime,
+ eventTime,
+ action,
+ x,
+ y,
+ pressure,
+ size,
+ metaState,
+ xPrecision,
+ yPrecision,
+ deviceId,
+ edgeFlags,
+ source,
+ displayId,
+ )
}
private fun createKeyEvent(action: Int, eventTime: Long): KeyEvent {
@@ -58,11 +71,10 @@ private fun createKeyEvent(action: Int, eventTime: Long): KeyEvent {
}
/**
- * Check that the correct eventIds are assigned in a stream. The stream consists of motion
- * events or vsync (processed frame)
- * Each streamEvent should have unique ids when writing tests
- * The test passes even if two events get assigned the same eventId, since the mapping is
- * streamEventId -> motionEventId and streamEvents have unique ids
+ * Check that the correct eventIds are assigned in a stream. The stream consists of motion events or
+ * vsync (processed frame) Each streamEvent should have unique ids when writing tests The test
+ * passes even if two events get assigned the same eventId, since the mapping is streamEventId ->
+ * motionEventId and streamEvents have unique ids
*/
private fun checkEventStream(vararg streamEvents: StreamEvent) {
val assigner = InputEventAssigner()
@@ -90,9 +102,7 @@ class InputEventAssignerTest {
private const val TAG = "InputEventAssignerTest"
}
- /**
- * A single event should be assigned to the next available frame.
- */
+ /** A single event should be assigned to the next available frame. */
@Test
fun testTouchMove() {
checkEventStream(
@@ -145,7 +155,7 @@ class InputEventAssignerTest {
MotionEventData(MotionEvent.ACTION_DOWN, source, id = 1, expectedId = 1),
MotionEventData(MotionEvent.ACTION_MOVE, source, id = 2, expectedId = 1),
Vsync,
- MotionEventData(MotionEvent.ACTION_MOVE, source, id = 4, expectedId = 4)
+ MotionEventData(MotionEvent.ACTION_MOVE, source, id = 4, expectedId = 4),
)
}
@@ -169,57 +179,47 @@ class InputEventAssignerTest {
testDownAndMove(SOURCE_TOUCHPAD)
}
- /**
- * After an up event, motion events should be assigned their own event id
- */
+ /** After an up event, motion events should be assigned their own event id */
@Test
fun testMouseDownUpAndScroll() {
checkEventStream(
MotionEventData(MotionEvent.ACTION_DOWN, SOURCE_MOUSE, id = 1, expectedId = 1),
MotionEventData(MotionEvent.ACTION_UP, SOURCE_MOUSE, id = 2, expectedId = 2),
- MotionEventData(MotionEvent.ACTION_SCROLL, SOURCE_MOUSE, id = 3, expectedId = 3)
+ MotionEventData(MotionEvent.ACTION_SCROLL, SOURCE_MOUSE, id = 3, expectedId = 3),
)
}
- /**
- * After an up event, motion events should be assigned their own event id
- */
+ /** After an up event, motion events should be assigned their own event id */
@Test
fun testStylusDownUpAndHover() {
checkEventStream(
MotionEventData(MotionEvent.ACTION_DOWN, SOURCE_STYLUS, id = 1, expectedId = 1),
MotionEventData(MotionEvent.ACTION_UP, SOURCE_STYLUS, id = 2, expectedId = 2),
- MotionEventData(MotionEvent.ACTION_HOVER_ENTER, SOURCE_STYLUS, id = 3, expectedId = 3)
+ MotionEventData(MotionEvent.ACTION_HOVER_ENTER, SOURCE_STYLUS, id = 3, expectedId = 3),
)
}
- /**
- * After a cancel event, motion events should be assigned their own event id
- */
+ /** After a cancel event, motion events should be assigned their own event id */
@Test
fun testMouseDownCancelAndScroll() {
checkEventStream(
MotionEventData(MotionEvent.ACTION_DOWN, SOURCE_MOUSE, id = 1, expectedId = 1),
MotionEventData(MotionEvent.ACTION_CANCEL, SOURCE_MOUSE, id = 2, expectedId = 2),
- MotionEventData(MotionEvent.ACTION_SCROLL, SOURCE_MOUSE, id = 3, expectedId = 3)
+ MotionEventData(MotionEvent.ACTION_SCROLL, SOURCE_MOUSE, id = 3, expectedId = 3),
)
}
- /**
- * After a cancel event, motion events should be assigned their own event id
- */
+ /** After a cancel event, motion events should be assigned their own event id */
@Test
fun testStylusDownCancelAndHover() {
checkEventStream(
MotionEventData(MotionEvent.ACTION_DOWN, SOURCE_STYLUS, id = 1, expectedId = 1),
MotionEventData(MotionEvent.ACTION_CANCEL, SOURCE_STYLUS, id = 2, expectedId = 2),
- MotionEventData(MotionEvent.ACTION_HOVER_ENTER, SOURCE_STYLUS, id = 3, expectedId = 3)
+ MotionEventData(MotionEvent.ACTION_HOVER_ENTER, SOURCE_STYLUS, id = 3, expectedId = 3),
)
}
- /**
- * KeyEvents are processed immediately, so the latest event should be returned.
- */
+ /** KeyEvents are processed immediately, so the latest event should be returned. */
@Test
fun testKeyEvent() {
val assigner = InputEventAssigner()
diff --git a/tests/Input/src/com/android/test/input/InputEventSenderAndReceiverTest.kt b/tests/Input/src/com/android/test/input/InputEventSenderAndReceiverTest.kt
index 075cf0cc5a45..acd5a7d3f9e2 100644
--- a/tests/Input/src/com/android/test/input/InputEventSenderAndReceiverTest.kt
+++ b/tests/Input/src/com/android/test/input/InputEventSenderAndReceiverTest.kt
@@ -22,8 +22,8 @@ import android.view.InputChannel
import android.view.InputEvent
import android.view.InputEventReceiver
import android.view.KeyEvent
-import org.junit.Assert.assertEquals
import org.junit.After
+import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
@@ -42,12 +42,17 @@ private fun assertKeyEvent(expected: KeyEvent, received: KeyEvent) {
}
private fun getTestKeyEvent(): KeyEvent {
- return KeyEvent(1 /*downTime*/, 1 /*eventTime*/, KeyEvent.ACTION_DOWN,
- KeyEvent.KEYCODE_A, 0 /*repeat*/)
+ return KeyEvent(
+ 1 /*downTime*/,
+ 1 /*eventTime*/,
+ KeyEvent.ACTION_DOWN,
+ KeyEvent.KEYCODE_A,
+ 0, /*repeat*/
+ )
}
private class CrashingInputEventReceiver(channel: InputChannel, looper: Looper) :
- InputEventReceiver(channel, looper) {
+ InputEventReceiver(channel, looper) {
override fun onInputEvent(event: InputEvent) {
try {
throw IllegalArgumentException("This receiver crashes when it receives input event")
@@ -61,6 +66,7 @@ class InputEventSenderAndReceiverTest {
companion object {
private const val TAG = "InputEventSenderAndReceiverTest"
}
+
private val mHandlerThread = HandlerThread("Process input events")
private lateinit var mReceiver: SpyInputEventReceiver
private lateinit var mSender: SpyInputEventSender
@@ -98,8 +104,8 @@ class InputEventSenderAndReceiverTest {
// The timeline case is slightly unusual because it goes from InputConsumer to InputPublisher.
@Test
fun testSendAndReceiveTimeline() {
- val sent = SpyInputEventSender.Timeline(
- inputEventId = 1, gpuCompletedTime = 2, presentTime = 3)
+ val sent =
+ SpyInputEventSender.Timeline(inputEventId = 1, gpuCompletedTime = 2, presentTime = 3)
mReceiver.reportTimeline(sent.inputEventId, sent.gpuCompletedTime, sent.presentTime)
val received = mSender.getTimeline()
assertEquals(sent, received)
@@ -110,8 +116,8 @@ class InputEventSenderAndReceiverTest {
// event processing.
@Test
fun testSendAndReceiveInvalidTimeline() {
- val sent = SpyInputEventSender.Timeline(
- inputEventId = 1, gpuCompletedTime = 3, presentTime = 2)
+ val sent =
+ SpyInputEventSender.Timeline(inputEventId = 1, gpuCompletedTime = 3, presentTime = 2)
mReceiver.reportTimeline(sent.inputEventId, sent.gpuCompletedTime, sent.presentTime)
mSender.assertNoEvents()
// Sender will no longer receive callbacks for this fd, even if receiver sends a valid
@@ -123,9 +129,8 @@ class InputEventSenderAndReceiverTest {
/**
* If a receiver throws an exception during 'onInputEvent' execution, the 'finally' block still
* completes, and therefore, finishInputEvent is called. Make sure that there's no crash in the
- * native layer in these circumstances.
- * In this test, we are reusing the 'mHandlerThread', but we are creating new sender and
- * receiver.
+ * native layer in these circumstances. In this test, we are reusing the 'mHandlerThread', but
+ * we are creating new sender and receiver.
*/
@Test
fun testCrashingReceiverDoesNotCrash() {
diff --git a/tests/Input/src/com/android/test/input/KeyCharacterMapTest.kt b/tests/Input/src/com/android/test/input/KeyCharacterMapTest.kt
index 860d9f680c4c..4ca08d839c54 100644
--- a/tests/Input/src/com/android/test/input/KeyCharacterMapTest.kt
+++ b/tests/Input/src/com/android/test/input/KeyCharacterMapTest.kt
@@ -18,12 +18,9 @@ package com.android.test.input
import android.platform.test.annotations.EnableFlags
import android.platform.test.flag.junit.SetFlagsRule
-
import android.view.KeyCharacterMap
import android.view.KeyEvent
-
import com.android.hardware.input.Flags
-
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Rule
@@ -32,13 +29,10 @@ import org.junit.Test
/**
* Tests for {@link KeyCharacterMap}.
*
- * <p>Build/Install/Run:
- * atest KeyCharacterMapTest
- *
+ * <p>Build/Install/Run: atest KeyCharacterMapTest
*/
class KeyCharacterMapTest {
- @get:Rule
- val setFlagsRule = SetFlagsRule()
+ @get:Rule val setFlagsRule = SetFlagsRule()
@Test
@EnableFlags(Flags.FLAG_REMOVE_FALLBACK_MODIFIERS)
@@ -47,28 +41,33 @@ class KeyCharacterMapTest {
val keyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)
// One modifier fallback.
- val oneModifierFallback = keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_SPACE,
- KeyEvent.META_CTRL_ON)
+ val oneModifierFallback =
+ keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_SPACE, KeyEvent.META_CTRL_ON)
assertEquals(KeyEvent.KEYCODE_LANGUAGE_SWITCH, oneModifierFallback.keyCode)
assertEquals(0, oneModifierFallback.metaState)
// Multiple modifier fallback.
- val twoModifierFallback = keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_DEL,
- KeyEvent.META_CTRL_ON or KeyEvent.META_ALT_ON)
+ val twoModifierFallback =
+ keyCharacterMap.getFallbackAction(
+ KeyEvent.KEYCODE_DEL,
+ KeyEvent.META_CTRL_ON or KeyEvent.META_ALT_ON,
+ )
assertEquals(KeyEvent.KEYCODE_BACK, twoModifierFallback.keyCode)
assertEquals(0, twoModifierFallback.metaState)
// No default button, fallback only.
- val keyOnlyFallback =
- keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_BUTTON_A, 0)
+ val keyOnlyFallback = keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_BUTTON_A, 0)
assertEquals(KeyEvent.KEYCODE_DPAD_CENTER, keyOnlyFallback.keyCode)
assertEquals(0, keyOnlyFallback.metaState)
// A key event that is not an exact match for a fallback. Expect a null return.
// E.g. Ctrl + Space -> LanguageSwitch
// Ctrl + Alt + Space -> Ctrl + Alt + Space (No fallback).
- val noMatchFallback = keyCharacterMap.getFallbackAction(KeyEvent.KEYCODE_SPACE,
- KeyEvent.META_CTRL_ON or KeyEvent.META_ALT_ON)
+ val noMatchFallback =
+ keyCharacterMap.getFallbackAction(
+ KeyEvent.KEYCODE_SPACE,
+ KeyEvent.META_CTRL_ON or KeyEvent.META_ALT_ON,
+ )
assertNull(noMatchFallback)
}
}
diff --git a/tests/Input/src/com/android/test/input/MockInputManagerRule.kt b/tests/Input/src/com/android/test/input/MockInputManagerRule.kt
index cef985600c40..8fa5f4a03749 100644
--- a/tests/Input/src/com/android/test/input/MockInputManagerRule.kt
+++ b/tests/Input/src/com/android/test/input/MockInputManagerRule.kt
@@ -21,8 +21,8 @@ import org.junit.rules.ExternalResource
import org.mockito.Mockito
/**
- * A test rule that temporarily replaces the [IInputManager] connection to the server with a mock
- * to be used for testing.
+ * A test rule that temporarily replaces the [IInputManager] connection to the server with a mock to
+ * be used for testing.
*/
class MockInputManagerRule : ExternalResource() {
diff --git a/tests/Input/src/com/android/test/input/MotionPredictorTest.kt b/tests/Input/src/com/android/test/input/MotionPredictorTest.kt
index d3eeac147c2a..784eb1b37765 100644
--- a/tests/Input/src/com/android/test/input/MotionPredictorTest.kt
+++ b/tests/Input/src/com/android/test/input/MotionPredictorTest.kt
@@ -26,11 +26,10 @@ import android.view.MotionEvent.ACTION_MOVE
import android.view.MotionEvent.PointerCoords
import android.view.MotionEvent.PointerProperties
import android.view.MotionPredictor
-
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
-
+import java.time.Duration
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
@@ -40,14 +39,12 @@ import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.mockito.Mockito.`when`
-import java.time.Duration
-
private fun getStylusMotionEvent(
- eventTime: Duration,
- action: Int,
- x: Float,
- y: Float,
- ): MotionEvent{
+ eventTime: Duration,
+ action: Int,
+ x: Float,
+ y: Float,
+): MotionEvent {
val pointerCount = 1
val properties = arrayOfNulls<MotionEvent.PointerProperties>(pointerCount)
val coords = arrayOfNulls<MotionEvent.PointerCoords>(pointerCount)
@@ -61,21 +58,32 @@ private fun getStylusMotionEvent(
coords[i]!!.y = y
}
- return MotionEvent.obtain(/*downTime=*/0, eventTime.toMillis(), action, properties.size,
- properties, coords, /*metaState=*/0, /*buttonState=*/0,
- /*xPrecision=*/0f, /*yPrecision=*/0f, /*deviceId=*/0, /*edgeFlags=*/0,
- InputDevice.SOURCE_STYLUS, /*flags=*/0)
+ return MotionEvent.obtain(
+ /*downTime=*/ 0,
+ eventTime.toMillis(),
+ action,
+ properties.size,
+ properties,
+ coords,
+ /*metaState=*/ 0,
+ /*buttonState=*/ 0,
+ /*xPrecision=*/ 0f,
+ /*yPrecision=*/ 0f,
+ /*deviceId=*/ 0,
+ /*edgeFlags=*/ 0,
+ InputDevice.SOURCE_STYLUS,
+ /*flags=*/ 0,
+ )
}
private fun getPredictionContext(offset: Duration, enablePrediction: Boolean): Context {
val context = mock(Context::class.java)
val resources: Resources = mock(Resources::class.java)
`when`(context.getResources()).thenReturn(resources)
- `when`(resources.getInteger(
- com.android.internal.R.integer.config_motionPredictionOffsetNanos)).thenReturn(
- offset.toNanos().toInt())
- `when`(resources.getBoolean(
- com.android.internal.R.bool.config_enableMotionPrediction)).thenReturn(enablePrediction)
+ `when`(resources.getInteger(com.android.internal.R.integer.config_motionPredictionOffsetNanos))
+ .thenReturn(offset.toNanos().toInt())
+ `when`(resources.getBoolean(com.android.internal.R.bool.config_enableMotionPrediction))
+ .thenReturn(enablePrediction)
return context
}
@@ -88,38 +96,36 @@ class MotionPredictorTest {
@Before
fun setUp() {
instrumentation.uiAutomation.executeShellCommand(
- "setprop persist.input.enable_motion_prediction true")
+ "setprop persist.input.enable_motion_prediction true"
+ )
}
@After
fun tearDown() {
instrumentation.uiAutomation.executeShellCommand(
- "setprop persist.input.enable_motion_prediction $initialPropertyValue")
+ "setprop persist.input.enable_motion_prediction $initialPropertyValue"
+ )
}
/**
- * In a typical usage, app will send the event to the predictor and then call .predict to draw
- * a prediction. Here, we send 2 events to the predictor and check the returned event.
- * Input:
- * t = 0 x = 0 y = 0
- * t = 4 x = 10 y = 20
- * Output (expected):
- * t = 12 x = 30 y = 60 ± error
+ * In a typical usage, app will send the event to the predictor and then call .predict to draw a
+ * prediction. Here, we send 2 events to the predictor and check the returned event. Input: t =
+ * 0 x = 0 y = 0 t = 4 x = 10 y = 20 Output (expected): t = 12 x = 30 y = 60 ± error
*
* Historical data is ignored for simplicity.
*/
@Test
fun testPredictedCoordinatesAndTime() {
- val context = getPredictionContext(
- /*offset=*/Duration.ofMillis(1), /*enablePrediction=*/true)
+ val context =
+ getPredictionContext(/* offset= */ Duration.ofMillis(1), /* enablePrediction= */ true)
val predictor = MotionPredictor(context)
var eventTime = Duration.ofMillis(0)
- val downEvent = getStylusMotionEvent(eventTime, ACTION_DOWN, /*x=*/0f, /*y=*/0f)
+ val downEvent = getStylusMotionEvent(eventTime, ACTION_DOWN, /* x= */ 0f, /* y= */ 0f)
// ACTION_DOWN t=0 x=0 y=0
predictor.record(downEvent)
eventTime += Duration.ofMillis(4)
- val moveEvent = getStylusMotionEvent(eventTime, ACTION_MOVE, /*x=*/10f, /*y=*/20f)
+ val moveEvent = getStylusMotionEvent(eventTime, ACTION_MOVE, /* x= */ 10f, /* y= */ 20f)
// ACTION_MOVE t=1 x=1 y=2
predictor.record(moveEvent)
@@ -129,7 +135,7 @@ class MotionPredictorTest {
// Prediction will happen for t=12 (since it is the next input interval after the requested
// time, 8, plus the model offset, 1).
assertEquals(12, predicted!!.eventTime)
- assertEquals(30f, predicted.x, /*delta=*/10f)
- assertEquals(60f, predicted.y, /*delta=*/15f)
+ assertEquals(30f, predicted.x, /* delta= */ 10f)
+ assertEquals(60f, predicted.y, /* delta= */ 15f)
}
}
diff --git a/tests/Input/src/com/android/test/input/PointerEventDispatcherTest.kt b/tests/Input/src/com/android/test/input/PointerEventDispatcherTest.kt
index f311bc222d22..3c4ba5a3cd09 100644
--- a/tests/Input/src/com/android/test/input/PointerEventDispatcherTest.kt
+++ b/tests/Input/src/com/android/test/input/PointerEventDispatcherTest.kt
@@ -21,11 +21,10 @@ import android.view.InputChannel
import android.view.InputDevice
import android.view.MotionEvent
import android.view.WindowManagerPolicyConstants.PointerEventListener
-
import com.android.server.UiThread
import com.android.server.wm.PointerEventDispatcher
-import org.junit.Assert.assertEquals
import org.junit.After
+import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
@@ -39,6 +38,7 @@ class PointerEventDispatcherTest {
companion object {
private const val TAG = "PointerEventDispatcherTest"
}
+
private val mHandlerThread = HandlerThread("Process input events")
private lateinit var mSender: SpyInputEventSender
private lateinit var mPointerEventDispatcher: PointerEventDispatcher
@@ -75,8 +75,15 @@ class PointerEventDispatcherTest {
// The MotionEvent properties aren't important for this test, as long as the event
// is a pointer event, so that it gets processed by CrashingPointerEventListener
val downTime = 0L
- val motionEvent = MotionEvent.obtain(downTime, downTime,
- MotionEvent.ACTION_DOWN, 0f /* x */, 0f /* y */, 0 /* metaState */)
+ val motionEvent =
+ MotionEvent.obtain(
+ downTime,
+ downTime,
+ MotionEvent.ACTION_DOWN,
+ 0f /* x */,
+ 0f /* y */,
+ 0, /* metaState */
+ )
motionEvent.source = InputDevice.SOURCE_TOUCHSCREEN
val seq = 10
mSender.sendInputEvent(seq, motionEvent)
diff --git a/tests/Input/src/com/android/test/input/PointerIconLoadingTest.kt b/tests/Input/src/com/android/test/input/PointerIconLoadingTest.kt
index abfe549f3d22..443ef6937c53 100644
--- a/tests/Input/src/com/android/test/input/PointerIconLoadingTest.kt
+++ b/tests/Input/src/com/android/test/input/PointerIconLoadingTest.kt
@@ -42,8 +42,7 @@ import platform.test.screenshot.matchers.PixelPerfectMatcher
/**
* Unit tests for PointerIcon.
*
- * Run with:
- * atest InputTests:com.android.test.input.PointerIconLoadingTest
+ * Run with: atest InputTests:com.android.test.input.PointerIconLoadingTest
*/
@SmallTest
@RunWith(AndroidJUnit4::class)
@@ -51,16 +50,19 @@ class PointerIconLoadingTest {
private lateinit var context: Context
private lateinit var exactScreenshotMatcher: BitmapMatcher
- @get:Rule
- val testName = TestName()
+ @get:Rule val testName = TestName()
@get:Rule
- val screenshotRule = ScreenshotTestRule(GoldenPathManager(
- InstrumentationRegistry.getInstrumentation().getContext(),
- ASSETS_PATH,
- TEST_OUTPUT_PATH,
- PathConfig()
- ), disableIconPool = false)
+ val screenshotRule =
+ ScreenshotTestRule(
+ GoldenPathManager(
+ InstrumentationRegistry.getInstrumentation().getContext(),
+ ASSETS_PATH,
+ TEST_OUTPUT_PATH,
+ PathConfig(),
+ ),
+ disableIconPool = false,
+ )
@Before
fun setUp() {
@@ -86,22 +88,26 @@ class PointerIconLoadingTest {
theme.setTo(context.getTheme())
theme.applyStyle(
PointerIcon.vectorFillStyleToResource(PointerIcon.POINTER_ICON_VECTOR_STYLE_FILL_GREEN),
- /* force= */ true)
- theme.applyStyle(PointerIcon.vectorStrokeStyleToResource(
- PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_WHITE), /* force= */ true)
+ /* force= */ true,
+ )
+ theme.applyStyle(
+ PointerIcon.vectorStrokeStyleToResource(
+ PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_WHITE
+ ),
+ /* force= */ true,
+ )
val pointerIcon =
PointerIcon.getLoadedSystemIcon(
ContextThemeWrapper(context, theme),
PointerIcon.TYPE_ARROW,
/* useLargeIcons= */ false,
- /* pointerScale= */ 1f)
+ /* pointerScale= */ 1f,
+ )
- pointerIcon.getBitmap().assertAgainstGolden(
- screenshotRule,
- testName.methodName,
- exactScreenshotMatcher
- )
+ pointerIcon
+ .getBitmap()
+ .assertAgainstGolden(screenshotRule, testName.methodName, exactScreenshotMatcher)
}
@Test
@@ -113,22 +119,26 @@ class PointerIconLoadingTest {
theme.setTo(context.getTheme())
theme.applyStyle(
PointerIcon.vectorFillStyleToResource(PointerIcon.POINTER_ICON_VECTOR_STYLE_FILL_BLACK),
- /* force= */ true)
- theme.applyStyle(PointerIcon.vectorStrokeStyleToResource(
- PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_BLACK), /* force= */ true)
+ /* force= */ true,
+ )
+ theme.applyStyle(
+ PointerIcon.vectorStrokeStyleToResource(
+ PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_BLACK
+ ),
+ /* force= */ true,
+ )
val pointerIcon =
PointerIcon.getLoadedSystemIcon(
ContextThemeWrapper(context, theme),
PointerIcon.TYPE_ARROW,
/* useLargeIcons= */ false,
- /* pointerScale= */ 1f)
+ /* pointerScale= */ 1f,
+ )
- pointerIcon.getBitmap().assertAgainstGolden(
- screenshotRule,
- testName.methodName,
- exactScreenshotMatcher
- )
+ pointerIcon
+ .getBitmap()
+ .assertAgainstGolden(screenshotRule, testName.methodName, exactScreenshotMatcher)
}
@Test
@@ -140,11 +150,14 @@ class PointerIconLoadingTest {
theme.setTo(context.getTheme())
theme.applyStyle(
PointerIcon.vectorFillStyleToResource(PointerIcon.POINTER_ICON_VECTOR_STYLE_FILL_BLACK),
- /* force= */ true)
+ /* force= */ true,
+ )
theme.applyStyle(
PointerIcon.vectorStrokeStyleToResource(
- PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_WHITE),
- /* force= */ true)
+ PointerIcon.POINTER_ICON_VECTOR_STYLE_STROKE_WHITE
+ ),
+ /* force= */ true,
+ )
val pointerScale = 2f
val pointerIcon =
@@ -152,13 +165,12 @@ class PointerIconLoadingTest {
ContextThemeWrapper(context, theme),
PointerIcon.TYPE_ARROW,
/* useLargeIcons= */ false,
- pointerScale)
+ pointerScale,
+ )
- pointerIcon.getBitmap().assertAgainstGolden(
- screenshotRule,
- testName.methodName,
- exactScreenshotMatcher
- )
+ pointerIcon
+ .getBitmap()
+ .assertAgainstGolden(screenshotRule, testName.methodName, exactScreenshotMatcher)
}
companion object {
diff --git a/tests/Input/src/com/android/test/input/SpyInputEventSenderAndReceiver.kt b/tests/Input/src/com/android/test/input/SpyInputEventSenderAndReceiver.kt
index 5cbfce534b15..05aa5e91132b 100644
--- a/tests/Input/src/com/android/test/input/SpyInputEventSenderAndReceiver.kt
+++ b/tests/Input/src/com/android/test/input/SpyInputEventSenderAndReceiver.kt
@@ -26,7 +26,6 @@ import android.view.KeyEvent
import android.view.MotionEvent
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
-
import org.junit.Assert.assertNull
private fun <T> getEvent(queue: LinkedBlockingQueue<T>): T? {
@@ -39,7 +38,7 @@ private fun <T> assertNoEvents(queue: LinkedBlockingQueue<T>) {
}
class SpyInputEventReceiver(channel: InputChannel, looper: Looper) :
- InputEventReceiver(channel, looper) {
+ InputEventReceiver(channel, looper) {
private val mInputEvents = LinkedBlockingQueue<InputEvent>()
override fun onInputEvent(event: InputEvent) {
@@ -57,8 +56,9 @@ class SpyInputEventReceiver(channel: InputChannel, looper: Looper) :
}
class SpyInputEventSender(channel: InputChannel, looper: Looper) :
- InputEventSender(channel, looper) {
+ InputEventSender(channel, looper) {
data class FinishedSignal(val seq: Int, val handled: Boolean)
+
data class Timeline(val inputEventId: Int, val gpuCompletedTime: Long, val presentTime: Long)
private val mFinishedSignals = LinkedBlockingQueue<FinishedSignal>()
diff --git a/tests/Input/src/com/android/test/input/UinputRecordingIntegrationTests.kt b/tests/Input/src/com/android/test/input/UinputRecordingIntegrationTests.kt
index 1a0837b6d3d7..49b224a751b6 100644
--- a/tests/Input/src/com/android/test/input/UinputRecordingIntegrationTests.kt
+++ b/tests/Input/src/com/android/test/input/UinputRecordingIntegrationTests.kt
@@ -59,9 +59,7 @@ import org.junit.runners.Parameterized
class UinputRecordingIntegrationTests {
companion object {
- /**
- * Add new test cases by adding a new [TestData] to the following list.
- */
+ /** Add new test cases by adding a new [TestData] to the following list. */
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun data(): Iterable<Any> =
@@ -74,12 +72,10 @@ class UinputRecordingIntegrationTests {
vendorId = 0x0603,
productId = 0x7806,
deviceSources = InputDevice.SOURCE_TOUCHSCREEN,
- ),
+ )
)
- /**
- * Use the debug mode to see the JSON-encoded received events in logcat.
- */
+ /** Use the debug mode to see the JSON-encoded received events in logcat. */
const val DEBUG_RECEIVED_EVENTS = false
const val INPUT_DEVICE_SOURCE_ALL = -1
@@ -101,14 +97,11 @@ class UinputRecordingIntegrationTests {
private lateinit var instrumentation: Instrumentation
private lateinit var parser: InputJsonParser
- @get:Rule
- val debugInputRule = DebugInputRule()
+ @get:Rule val debugInputRule = DebugInputRule()
- @get:Rule
- val testName = TestName()
+ @get:Rule val testName = TestName()
- @Parameterized.Parameter(0)
- lateinit var testData: TestData
+ @Parameterized.Parameter(0) lateinit var testData: TestData
@Before
fun setUp() {
@@ -120,43 +113,47 @@ class UinputRecordingIntegrationTests {
@Test
fun testEvemuRecording() {
VirtualDisplayActivityScenario.AutoClose<CaptureEventActivity>(
- testName,
- size = testData.displaySize
- ).use { scenario ->
- scenario.activity.window.decorView.requestUnbufferedDispatch(INPUT_DEVICE_SOURCE_ALL)
-
- EvemuDevice(
- instrumentation,
- testData.deviceSources,
- testData.vendorId,
- testData.productId,
- testData.uinputRecordingResource,
- scenario.virtualDisplay.display
- ).use { evemuDevice ->
-
- evemuDevice.injectEvents()
-
- if (DEBUG_RECEIVED_EVENTS) {
- printReceivedEventsToLogcat(scenario.activity)
- fail("Test cannot pass in debug mode!")
- }
-
- val verifier = EventVerifier(
- BatchedEventSplitter { scenario.activity.getInputEvent() }
+ testName,
+ size = testData.displaySize,
+ )
+ .use { scenario ->
+ scenario.activity.window.decorView.requestUnbufferedDispatch(
+ INPUT_DEVICE_SOURCE_ALL
)
- verifyEvents(verifier)
- scenario.activity.assertNoEvents()
+
+ EvemuDevice(
+ instrumentation,
+ testData.deviceSources,
+ testData.vendorId,
+ testData.productId,
+ testData.uinputRecordingResource,
+ scenario.virtualDisplay.display,
+ )
+ .use { evemuDevice ->
+ evemuDevice.injectEvents()
+
+ if (DEBUG_RECEIVED_EVENTS) {
+ printReceivedEventsToLogcat(scenario.activity)
+ fail("Test cannot pass in debug mode!")
+ }
+
+ val verifier =
+ EventVerifier(
+ BatchedEventSplitter { scenario.activity.getInputEvent() }
+ )
+ verifyEvents(verifier)
+ scenario.activity.assertNoEvents()
+ }
}
- }
}
private fun printReceivedEventsToLogcat(activity: CaptureEventActivity) {
val getNextEvent = BatchedEventSplitter { activity.getInputEvent() }
var receivedEvent: InputEvent? = getNextEvent()
while (receivedEvent != null) {
- Log.d(TAG,
- parser.encodeEvent(receivedEvent)?.toString()
- ?: "(Failed to encode received event)"
+ Log.d(
+ TAG,
+ parser.encodeEvent(receivedEvent)?.toString() ?: "(Failed to encode received event)",
)
receivedEvent = getNextEvent()
}
diff --git a/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt b/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt
index 1e44617af111..0366abed1d48 100644
--- a/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt
+++ b/tests/Input/src/com/android/test/input/UnresponsiveGestureMonitorActivity.kt
@@ -1,17 +1,15 @@
/**
* Copyright (c) 2020 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
*
- * 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.
+ * 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.
*/
// InputMonitor is deprecated, but we still need to test it.
diff --git a/tests/Input/src/com/android/test/input/ViewFrameInfoTest.kt b/tests/Input/src/com/android/test/input/ViewFrameInfoTest.kt
index 6ef1ecdae59b..8405a67332ef 100644
--- a/tests/Input/src/com/android/test/input/ViewFrameInfoTest.kt
+++ b/tests/Input/src/com/android/test/input/ViewFrameInfoTest.kt
@@ -28,6 +28,7 @@ class ViewFrameInfoTest {
companion object {
private const val TAG = "ViewFrameInfoTest"
}
+
private val mViewFrameInfo = ViewFrameInfo()
private var mTimeStarted: Long = 0
@@ -65,8 +66,8 @@ class ViewFrameInfoTest {
// The values inside FrameInfo should match those from ViewFrameInfo after we update them
mViewFrameInfo.populateFrameInfo(frameInfo)
assertThat(frameInfo.frameInfo[FrameInfo.INPUT_EVENT_ID]).isEqualTo(139)
- assertThat(frameInfo.frameInfo[FrameInfo.FLAGS]).isEqualTo(
- FrameInfo.FLAG_WINDOW_VISIBILITY_CHANGED)
+ assertThat(frameInfo.frameInfo[FrameInfo.FLAGS])
+ .isEqualTo(FrameInfo.FLAG_WINDOW_VISIBILITY_CHANGED)
assertThat(frameInfo.frameInfo[FrameInfo.DRAW_START]).isGreaterThan(mTimeStarted)
}
-} \ No newline at end of file
+}
diff --git a/tests/Tracing/src/com/android/internal/protolog/ProcessedPerfettoProtoLogImplTest.java b/tests/Tracing/src/com/android/internal/protolog/ProcessedPerfettoProtoLogImplTest.java
index ed256e72b415..34fef25b187c 100644
--- a/tests/Tracing/src/com/android/internal/protolog/ProcessedPerfettoProtoLogImplTest.java
+++ b/tests/Tracing/src/com/android/internal/protolog/ProcessedPerfettoProtoLogImplTest.java
@@ -552,7 +552,7 @@ public class ProcessedPerfettoProtoLogImplTest {
}
final ResultReader reader = new ResultReader(mWriter.write(), mTraceConfig);
- assertThrows(IllegalStateException.class, reader::readProtoLogTrace);
+ assertThrows(java.net.ConnectException.class, reader::readProtoLogTrace);
}
@Test