content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * Copyright (C) 2023 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.customization.picker.preview.ui.section import android.app.WallpaperManager import android.content.Context import android.graphics.Rect import android.view.TouchDelegate import android.view.View import android.view.View.OnAttachStateChangeListener import android.view.ViewStub import androidx.activity.ComponentActivity import androidx.constraintlayout.helper.widget.Carousel import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.Guideline import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.get import androidx.lifecycle.lifecycleScope import com.android.customization.model.themedicon.domain.interactor.ThemedIconInteractor import com.android.customization.picker.clock.ui.binder.ClockCarouselViewBinder import com.android.customization.picker.clock.ui.fragment.ClockSettingsFragment import com.android.customization.picker.clock.ui.view.ClockCarouselView import com.android.customization.picker.clock.ui.view.ClockViewFactory import com.android.customization.picker.clock.ui.viewmodel.ClockCarouselViewModel import com.android.customization.picker.color.domain.interactor.ColorPickerInteractor import com.android.wallpaper.R import com.android.wallpaper.model.CustomizationSectionController import com.android.wallpaper.model.CustomizationSectionController.CustomizationSectionNavigationController import com.android.wallpaper.model.WallpaperPreviewNavigator import com.android.wallpaper.module.CurrentWallpaperInfoFactory import com.android.wallpaper.module.CustomizationSections import com.android.wallpaper.picker.customization.data.repository.WallpaperColorsRepository import com.android.wallpaper.picker.customization.domain.interactor.WallpaperInteractor import com.android.wallpaper.picker.customization.ui.section.ScreenPreviewClickView import com.android.wallpaper.picker.customization.ui.section.ScreenPreviewSectionController import com.android.wallpaper.picker.customization.ui.section.ScreenPreviewView import com.android.wallpaper.picker.customization.ui.viewmodel.CustomizationPickerViewModel import com.android.wallpaper.util.DisplayUtils import kotlinx.coroutines.Job import kotlinx.coroutines.launch /** * A ThemePicker version of the [ScreenPreviewSectionController] that adjusts the preview for the * clock carousel, and also updates the preview on theme changes. */ class PreviewWithClockCarouselSectionController( activity: ComponentActivity, private val lifecycleOwner: LifecycleOwner, private val screen: CustomizationSections.Screen, wallpaperInfoFactory: CurrentWallpaperInfoFactory, wallpaperColorsRepository: WallpaperColorsRepository, displayUtils: DisplayUtils, clockCarouselViewModelFactory: ClockCarouselViewModel.Factory, private val clockViewFactory: ClockViewFactory, wallpaperPreviewNavigator: WallpaperPreviewNavigator, private val navigationController: CustomizationSectionNavigationController, wallpaperInteractor: WallpaperInteractor, themedIconInteractor: ThemedIconInteractor, colorPickerInteractor: ColorPickerInteractor, wallpaperManager: WallpaperManager, private val isTwoPaneAndSmallWidth: Boolean, customizationPickerViewModel: CustomizationPickerViewModel, ) : PreviewWithThemeSectionController( activity, lifecycleOwner, screen, wallpaperInfoFactory, wallpaperColorsRepository, displayUtils, wallpaperPreviewNavigator, wallpaperInteractor, themedIconInteractor, colorPickerInteractor, wallpaperManager, isTwoPaneAndSmallWidth, customizationPickerViewModel, ) { private val viewModel = ViewModelProvider( activity, clockCarouselViewModelFactory, ) .get() as ClockCarouselViewModel private var clockColorAndSizeButton: View? = null override val hideLockScreenClockPreview = true override fun createView( context: Context, params: CustomizationSectionController.ViewCreationParams, ): ScreenPreviewView { val view = super.createView(context, params) if (screen == CustomizationSections.Screen.LOCK_SCREEN) { val screenPreviewClickView: ScreenPreviewClickView = view.requireViewById(R.id.screen_preview_click_view) val clockColorAndSizeButtonStub: ViewStub = view.requireViewById(R.id.clock_color_and_size_button) clockColorAndSizeButtonStub.layoutResource = R.layout.clock_color_and_size_button clockColorAndSizeButton = clockColorAndSizeButtonStub.inflate() as View clockColorAndSizeButton?.setOnClickListener { navigationController.navigateTo(ClockSettingsFragment()) } // clockColorAndSizeButton's touch target has to be increased programmatically // rather than with padding because this button only appears in the lock screen tab. view.post { val rect = Rect() clockColorAndSizeButton?.getHitRect(rect) val padding = context .getResources() .getDimensionPixelSize(R.dimen.screen_preview_section_vertical_space) rect.top -= padding rect.bottom += padding val touchDelegate = TouchDelegate(rect, clockColorAndSizeButton) view.setTouchDelegate(touchDelegate) } val carouselViewStub: ViewStub = view.requireViewById(R.id.clock_carousel_view_stub) carouselViewStub.layoutResource = R.layout.clock_carousel_view val carouselView = carouselViewStub.inflate() as ClockCarouselView if (isTwoPaneAndSmallWidth) { val guidelineMargin = context.resources.getDimensionPixelSize( R.dimen.clock_carousel_guideline_margin_for_2_pane_small_width ) val guidelineStart = carouselView.requireViewById<Guideline>(R.id.guideline_start) var layoutParams = guidelineStart.layoutParams as ConstraintLayout.LayoutParams layoutParams.guideBegin = guidelineMargin guidelineStart.layoutParams = layoutParams val guidelineEnd = carouselView.requireViewById<Guideline>(R.id.guideline_end) layoutParams = guidelineEnd.layoutParams as ConstraintLayout.LayoutParams layoutParams.guideEnd = guidelineMargin guidelineEnd.layoutParams = layoutParams } /** * Only bind after [Carousel.onAttachedToWindow]. This is to avoid the race condition * that the flow emits before attached to window where [Carousel.mMotionLayout] is still * null. */ var onAttachStateChangeListener: OnAttachStateChangeListener? = null var bindJob: Job? = null onAttachStateChangeListener = object : OnAttachStateChangeListener { override fun onViewAttachedToWindow(view: View) { bindJob = lifecycleOwner.lifecycleScope.launch { ClockCarouselViewBinder.bind( context = context, carouselView = carouselView, screenPreviewClickView = screenPreviewClickView, viewModel = viewModel, clockViewFactory = clockViewFactory, lifecycleOwner = lifecycleOwner, isTwoPaneAndSmallWidth = isTwoPaneAndSmallWidth, ) if (onAttachStateChangeListener != null) { carouselView.carousel.removeOnAttachStateChangeListener( onAttachStateChangeListener, ) } } } override fun onViewDetachedFromWindow(view: View) { bindJob?.cancel() } } carouselView.carousel.addOnAttachStateChangeListener(onAttachStateChangeListener) } return view } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/preview/ui/section/PreviewWithClockCarouselSectionController.kt
963716771
/* * Copyright (C) 2023 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.customization.picker.preview.ui.section import android.app.Activity import android.app.WallpaperManager import android.content.Context import androidx.lifecycle.LifecycleOwner import com.android.customization.model.themedicon.domain.interactor.ThemedIconInteractor import com.android.customization.picker.color.domain.interactor.ColorPickerInteractor import com.android.customization.picker.preview.ui.viewmodel.PreviewWithThemeViewModel import com.android.wallpaper.R import com.android.wallpaper.model.WallpaperPreviewNavigator import com.android.wallpaper.module.CurrentWallpaperInfoFactory import com.android.wallpaper.module.CustomizationSections import com.android.wallpaper.picker.customization.data.repository.WallpaperColorsRepository import com.android.wallpaper.picker.customization.domain.interactor.WallpaperInteractor import com.android.wallpaper.picker.customization.ui.section.ScreenPreviewSectionController import com.android.wallpaper.picker.customization.ui.viewmodel.CustomizationPickerViewModel import com.android.wallpaper.picker.customization.ui.viewmodel.ScreenPreviewViewModel import com.android.wallpaper.util.DisplayUtils import com.android.wallpaper.util.PreviewUtils import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.suspendCancellableCoroutine /** * A ThemePicker version of the [ScreenPreviewSectionController] that binds the preview view with * the [PreviewWithThemeViewModel] to allow preview updates on theme changes. */ open class PreviewWithThemeSectionController( activity: Activity, lifecycleOwner: LifecycleOwner, private val screen: CustomizationSections.Screen, private val wallpaperInfoFactory: CurrentWallpaperInfoFactory, private val wallpaperColorsRepository: WallpaperColorsRepository, displayUtils: DisplayUtils, wallpaperPreviewNavigator: WallpaperPreviewNavigator, private val wallpaperInteractor: WallpaperInteractor, private val themedIconInteractor: ThemedIconInteractor, private val colorPickerInteractor: ColorPickerInteractor, wallpaperManager: WallpaperManager, isTwoPaneAndSmallWidth: Boolean, customizationPickerViewModel: CustomizationPickerViewModel, ) : ScreenPreviewSectionController( activity, lifecycleOwner, screen, wallpaperInfoFactory, wallpaperColorsRepository, displayUtils, wallpaperPreviewNavigator, wallpaperInteractor, wallpaperManager, isTwoPaneAndSmallWidth, customizationPickerViewModel, ) { @OptIn(ExperimentalCoroutinesApi::class) override fun createScreenPreviewViewModel(context: Context): ScreenPreviewViewModel { return PreviewWithThemeViewModel( previewUtils = if (isOnLockScreen) { PreviewUtils( context = context, authority = context.getString( R.string.lock_screen_preview_provider_authority, ), ) } else { PreviewUtils( context = context, authorityMetadataKey = context.getString( R.string.grid_control_metadata_name, ), ) }, wallpaperInfoProvider = { forceReload -> suspendCancellableCoroutine { continuation -> wallpaperInfoFactory.createCurrentWallpaperInfos( context, forceReload, ) { homeWallpaper, lockWallpaper, _ -> val wallpaper = if (isOnLockScreen) { lockWallpaper ?: homeWallpaper } else { homeWallpaper ?: lockWallpaper } loadInitialColors( context = context, screen = screen, ) continuation.resume(wallpaper, null) } } }, onWallpaperColorChanged = { colors -> if (isOnLockScreen) { wallpaperColorsRepository.setLockWallpaperColors(colors) } else { wallpaperColorsRepository.setHomeWallpaperColors(colors) } }, initialExtrasProvider = { getInitialExtras(isOnLockScreen) }, wallpaperInteractor = wallpaperInteractor, themedIconInteractor = themedIconInteractor, colorPickerInteractor = colorPickerInteractor, screen = screen, ) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/preview/ui/section/PreviewWithThemeSectionController.kt
2784357399
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.ui.viewmodel import com.android.wallpaper.picker.common.icon.ui.viewmodel.Icon import com.android.wallpaper.picker.common.text.ui.viewmodel.Text data class KeyguardQuickAffordanceSummaryViewModel( val description: Text, val icon1: Icon?, val icon2: Icon?, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/ui/viewmodel/KeyguardQuickAffordanceSummaryViewModel.kt
2694517030
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.ui.viewmodel import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable import android.os.Bundle import androidx.annotation.DrawableRes import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.android.customization.module.logging.ThemesUserEventLogger import com.android.customization.picker.quickaffordance.domain.interactor.KeyguardQuickAffordancePickerInteractor import com.android.systemui.shared.keyguard.shared.model.KeyguardQuickAffordanceSlots import com.android.systemui.shared.quickaffordance.shared.model.KeyguardPreviewConstants import com.android.wallpaper.R import com.android.wallpaper.module.CurrentWallpaperInfoFactory import com.android.wallpaper.module.CustomizationSections import com.android.wallpaper.picker.common.button.ui.viewmodel.ButtonStyle import com.android.wallpaper.picker.common.button.ui.viewmodel.ButtonViewModel import com.android.wallpaper.picker.common.dialog.ui.viewmodel.DialogViewModel import com.android.wallpaper.picker.common.icon.ui.viewmodel.Icon import com.android.wallpaper.picker.common.text.ui.viewmodel.Text import com.android.wallpaper.picker.customization.domain.interactor.WallpaperInteractor import com.android.wallpaper.picker.customization.ui.viewmodel.ScreenPreviewViewModel import com.android.wallpaper.picker.option.ui.viewmodel.OptionItemViewModel import com.android.wallpaper.util.PreviewUtils import kotlinx.coroutines.ExperimentalCoroutinesApi 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.combine import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.suspendCancellableCoroutine /** Models UI state for a lock screen quick affordance picker experience. */ @OptIn(ExperimentalCoroutinesApi::class) class KeyguardQuickAffordancePickerViewModel private constructor( context: Context, private val quickAffordanceInteractor: KeyguardQuickAffordancePickerInteractor, private val wallpaperInteractor: WallpaperInteractor, private val wallpaperInfoFactory: CurrentWallpaperInfoFactory, private val logger: ThemesUserEventLogger, ) : ViewModel() { @SuppressLint("StaticFieldLeak") private val applicationContext = context.applicationContext val preview = ScreenPreviewViewModel( previewUtils = PreviewUtils( context = applicationContext, authority = applicationContext.getString( R.string.lock_screen_preview_provider_authority, ), ), initialExtrasProvider = { Bundle().apply { putString( KeyguardPreviewConstants.KEY_INITIALLY_SELECTED_SLOT_ID, selectedSlotId.value, ) putBoolean( KeyguardPreviewConstants.KEY_HIGHLIGHT_QUICK_AFFORDANCES, true, ) } }, wallpaperInfoProvider = { forceReload -> suspendCancellableCoroutine { continuation -> wallpaperInfoFactory.createCurrentWallpaperInfos( context, forceReload, ) { homeWallpaper, lockWallpaper, _ -> continuation.resume(lockWallpaper ?: homeWallpaper, null) } } }, wallpaperInteractor = wallpaperInteractor, screen = CustomizationSections.Screen.LOCK_SCREEN, ) /** A locally-selected slot, if the user ever switched from the original one. */ private val _selectedSlotId = MutableStateFlow<String?>(null) /** The ID of the selected slot. */ val selectedSlotId: StateFlow<String> = combine( quickAffordanceInteractor.slots, _selectedSlotId, ) { slots, selectedSlotIdOrNull -> if (selectedSlotIdOrNull != null) { slots.first { slot -> slot.id == selectedSlotIdOrNull } } else { // If we haven't yet selected a new slot locally, default to the first slot. slots[0] } } .map { selectedSlot -> selectedSlot.id } .stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(), initialValue = "", ) /** View-models for each slot, keyed by slot ID. */ val slots: Flow<Map<String, KeyguardQuickAffordanceSlotViewModel>> = combine( quickAffordanceInteractor.slots, quickAffordanceInteractor.affordances, quickAffordanceInteractor.selections, selectedSlotId, ) { slots, affordances, selections, selectedSlotId -> slots.associate { slot -> val selectedAffordanceIds = selections .filter { selection -> selection.slotId == slot.id } .map { selection -> selection.affordanceId } .toSet() val selectedAffordances = affordances.filter { affordance -> selectedAffordanceIds.contains(affordance.id) } val isSelected = selectedSlotId == slot.id slot.id to KeyguardQuickAffordanceSlotViewModel( name = getSlotName(slot.id), isSelected = isSelected, selectedQuickAffordances = selectedAffordances.map { affordanceModel -> OptionItemViewModel<Icon>( key = MutableStateFlow("${slot.id}::${affordanceModel.id}") as StateFlow<String>, payload = Icon.Loaded( drawable = getAffordanceIcon(affordanceModel.iconResourceId), contentDescription = Text.Loaded(getSlotContentDescription(slot.id)), ), text = Text.Loaded(affordanceModel.name), isSelected = MutableStateFlow(true) as StateFlow<Boolean>, onClicked = flowOf(null), onLongClicked = null, isEnabled = true, ) }, maxSelectedQuickAffordances = slot.maxSelectedQuickAffordances, onClicked = if (isSelected) { null } else { { _selectedSlotId.tryEmit(slot.id) } }, ) } } /** * The set of IDs of the currently-selected affordances. These change with user selection of new * or different affordances in the currently-selected slot or when slot selection changes. */ private val selectedAffordanceIds: Flow<Set<String>> = combine( quickAffordanceInteractor.selections, selectedSlotId, ) { selections, selectedSlotId -> selections .filter { selection -> selection.slotId == selectedSlotId } .map { selection -> selection.affordanceId } .toSet() } .shareIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(), replay = 1, ) /** The list of all available quick affordances for the selected slot. */ val quickAffordances: Flow<List<OptionItemViewModel<Icon>>> = quickAffordanceInteractor.affordances.map { affordances -> val isNoneSelected = selectedAffordanceIds.map { it.isEmpty() }.stateIn(viewModelScope) listOf( none( slotId = selectedSlotId, isSelected = isNoneSelected, onSelected = combine( isNoneSelected, selectedSlotId, ) { isSelected, selectedSlotId -> if (!isSelected) { { viewModelScope.launch { quickAffordanceInteractor.unselectAllFromSlot( selectedSlotId ) logger.logShortcutApplied( shortcut = "none", shortcutSlotId = selectedSlotId, ) } } } else { null } } ) ) + affordances.map { affordance -> val affordanceIcon = getAffordanceIcon(affordance.iconResourceId) val isSelectedFlow: StateFlow<Boolean> = selectedAffordanceIds .map { it.contains(affordance.id) } .stateIn(viewModelScope) OptionItemViewModel<Icon>( key = selectedSlotId .map { slotId -> "$slotId::${affordance.id}" } .stateIn(viewModelScope), payload = Icon.Loaded(drawable = affordanceIcon, contentDescription = null), text = Text.Loaded(affordance.name), isSelected = isSelectedFlow, onClicked = if (affordance.isEnabled) { combine( isSelectedFlow, selectedSlotId, ) { isSelected, selectedSlotId -> if (!isSelected) { { viewModelScope.launch { quickAffordanceInteractor.select( slotId = selectedSlotId, affordanceId = affordance.id, ) logger.logShortcutApplied( shortcut = affordance.id, shortcutSlotId = selectedSlotId, ) } } } else { null } } } else { flowOf { showEnablementDialog( icon = affordanceIcon, name = affordance.name, explanation = affordance.enablementExplanation, actionText = affordance.enablementActionText, actionIntent = affordance.enablementActionIntent, ) } }, onLongClicked = if (affordance.configureIntent != null) { { requestActivityStart(affordance.configureIntent) } } else { null }, isEnabled = affordance.isEnabled, ) } } @SuppressLint("UseCompatLoadingForDrawables") val summary: Flow<KeyguardQuickAffordanceSummaryViewModel> = slots.map { slots -> val icon2 = (slots[KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END] ?.selectedQuickAffordances ?.firstOrNull()) ?.payload val icon1 = (slots[KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START] ?.selectedQuickAffordances ?.firstOrNull()) ?.payload KeyguardQuickAffordanceSummaryViewModel( description = toDescriptionText(context, slots), icon1 = icon1 ?: if (icon2 == null) { Icon.Resource( res = R.drawable.link_off, contentDescription = null, ) } else { null }, icon2 = icon2, ) } private val _dialog = MutableStateFlow<DialogViewModel?>(null) /** * The current dialog to show. If `null`, no dialog should be shown. * * When the dialog is dismissed, [onDialogDismissed] must be called. */ val dialog: Flow<DialogViewModel?> = _dialog.asStateFlow() private val _activityStartRequests = MutableStateFlow<Intent?>(null) /** * Requests to start an activity with the given [Intent]. * * Important: once the activity is started, the [Intent] should be consumed by calling * [onActivityStarted]. */ val activityStartRequests: StateFlow<Intent?> = _activityStartRequests.asStateFlow() /** Notifies that the dialog has been dismissed in the UI. */ fun onDialogDismissed() { _dialog.value = null } /** * Notifies that an activity request from [activityStartRequests] has been fulfilled (e.g. the * activity was started and the view-model can forget needing to start this activity). */ fun onActivityStarted() { _activityStartRequests.value = null } private fun requestActivityStart( intent: Intent, ) { _activityStartRequests.value = intent } private fun showEnablementDialog( icon: Drawable, name: String, explanation: String, actionText: String?, actionIntent: Intent?, ) { _dialog.value = DialogViewModel( icon = Icon.Loaded( drawable = icon, contentDescription = null, ), headline = Text.Resource(R.string.keyguard_affordance_enablement_dialog_headline), message = Text.Loaded(explanation), buttons = buildList { add( ButtonViewModel( text = Text.Resource( if (actionText != null) { // This is not the only button on the dialog. R.string.cancel } else { // This is the only button on the dialog. R.string .keyguard_affordance_enablement_dialog_dismiss_button } ), style = ButtonStyle.Secondary, ), ) if (actionText != null) { add( ButtonViewModel( text = Text.Loaded(actionText), style = ButtonStyle.Primary, onClicked = { actionIntent?.let { intent -> requestActivityStart(intent) } } ), ) } }, ) } /** Returns a view-model for the special "None" option. */ @SuppressLint("UseCompatLoadingForDrawables") private suspend fun none( slotId: StateFlow<String>, isSelected: StateFlow<Boolean>, onSelected: Flow<(() -> Unit)?>, ): OptionItemViewModel<Icon> { return OptionItemViewModel<Icon>( key = slotId.map { "$it::none" }.stateIn(viewModelScope), payload = Icon.Resource(res = R.drawable.link_off, contentDescription = null), text = Text.Resource(res = R.string.keyguard_affordance_none), isSelected = isSelected, onClicked = onSelected, onLongClicked = null, isEnabled = true, ) } private fun getSlotName(slotId: String): String { return applicationContext.getString( when (slotId) { KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START -> R.string.keyguard_slot_name_bottom_start KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END -> R.string.keyguard_slot_name_bottom_end else -> error("No name for slot with ID of \"$slotId\"!") } ) } private fun getSlotContentDescription(slotId: String): String { return applicationContext.getString( when (slotId) { KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START -> R.string.keyguard_slot_name_bottom_start KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END -> R.string.keyguard_slot_name_bottom_end else -> error("No accessibility label for slot with ID \"$slotId\"!") } ) } private suspend fun getAffordanceIcon(@DrawableRes iconResourceId: Int): Drawable { return quickAffordanceInteractor.getAffordanceIcon(iconResourceId) } private fun toDescriptionText( context: Context, slots: Map<String, KeyguardQuickAffordanceSlotViewModel>, ): Text { val bottomStartAffordanceName = slots[KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START] ?.selectedQuickAffordances ?.firstOrNull() ?.text val bottomEndAffordanceName = slots[KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END] ?.selectedQuickAffordances ?.firstOrNull() ?.text return when { bottomStartAffordanceName != null && bottomEndAffordanceName != null -> { Text.Loaded( context.getString( R.string.keyguard_quick_affordance_two_selected_template, bottomStartAffordanceName.asString(context), bottomEndAffordanceName.asString(context), ) ) } bottomStartAffordanceName != null -> bottomStartAffordanceName bottomEndAffordanceName != null -> bottomEndAffordanceName else -> Text.Resource(R.string.keyguard_quick_affordance_none_selected) } } class Factory( private val context: Context, private val quickAffordanceInteractor: KeyguardQuickAffordancePickerInteractor, private val wallpaperInteractor: WallpaperInteractor, private val wallpaperInfoFactory: CurrentWallpaperInfoFactory, private val logger: ThemesUserEventLogger, ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return KeyguardQuickAffordancePickerViewModel( context = context, quickAffordanceInteractor = quickAffordanceInteractor, wallpaperInteractor = wallpaperInteractor, wallpaperInfoFactory = wallpaperInfoFactory, logger = logger, ) as T } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/ui/viewmodel/KeyguardQuickAffordancePickerViewModel.kt
701510776
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.ui.viewmodel import com.android.wallpaper.picker.common.icon.ui.viewmodel.Icon import com.android.wallpaper.picker.option.ui.viewmodel.OptionItemViewModel /** Models UI state for a single lock screen quick affordance slot in a picker experience. */ data class KeyguardQuickAffordanceSlotViewModel( /** User-visible name for the slot. */ val name: String, /** Whether this is the currently-selected slot in the picker. */ val isSelected: Boolean, /** * The list of quick affordances selected for this slot. * * Useful for preview. */ val selectedQuickAffordances: List<OptionItemViewModel<Icon>>, /** * The maximum number of quick affordances that can be selected for this slot. * * Useful for picker and preview. */ val maxSelectedQuickAffordances: Int, /** Notifies that the slot has been clicked by the user. */ val onClicked: (() -> Unit)?, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/ui/viewmodel/KeyguardQuickAffordanceSlotViewModel.kt
4026809698
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.ui.section import android.content.Context import android.view.LayoutInflater import androidx.lifecycle.LifecycleOwner import com.android.customization.picker.quickaffordance.ui.binder.KeyguardQuickAffordanceSectionViewBinder import com.android.customization.picker.quickaffordance.ui.fragment.KeyguardQuickAffordancePickerFragment import com.android.customization.picker.quickaffordance.ui.view.KeyguardQuickAffordanceSectionView import com.android.customization.picker.quickaffordance.ui.viewmodel.KeyguardQuickAffordancePickerViewModel import com.android.wallpaper.R import com.android.wallpaper.config.BaseFlags import com.android.wallpaper.model.CustomizationSectionController import com.android.wallpaper.model.CustomizationSectionController.CustomizationSectionNavigationController as NavigationController class KeyguardQuickAffordanceSectionController( private val navigationController: NavigationController, private val viewModel: KeyguardQuickAffordancePickerViewModel, private val lifecycleOwner: LifecycleOwner, ) : CustomizationSectionController<KeyguardQuickAffordanceSectionView> { override fun isAvailable(context: Context): Boolean { return BaseFlags.get().isKeyguardQuickAffordanceEnabled(context) } override fun createView(context: Context): KeyguardQuickAffordanceSectionView { val view = LayoutInflater.from(context) .inflate( R.layout.keyguard_quick_affordance_section_view, null, ) as KeyguardQuickAffordanceSectionView KeyguardQuickAffordanceSectionViewBinder.bind( view = view, viewModel = viewModel, lifecycleOwner = lifecycleOwner, ) { navigationController.navigateTo(KeyguardQuickAffordancePickerFragment.newInstance()) } return view } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/ui/section/KeyguardQuickAffordanceSectionController.kt
309952807
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.ui.binder import android.app.Dialog import android.content.Context import android.view.View import android.view.ViewGroup import android.view.accessibility.AccessibilityEvent import android.widget.ImageView import androidx.core.view.AccessibilityDelegateCompat import androidx.core.view.ViewCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.customization.picker.common.ui.view.ItemSpacing import com.android.customization.picker.quickaffordance.ui.adapter.SlotTabAdapter import com.android.customization.picker.quickaffordance.ui.viewmodel.KeyguardQuickAffordancePickerViewModel import com.android.wallpaper.R import com.android.wallpaper.picker.common.dialog.ui.viewbinder.DialogViewBinder import com.android.wallpaper.picker.common.dialog.ui.viewmodel.DialogViewModel import com.android.wallpaper.picker.common.icon.ui.viewbinder.IconViewBinder import com.android.wallpaper.picker.common.icon.ui.viewmodel.Icon import com.android.wallpaper.picker.option.ui.adapter.OptionItemAdapter import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.collectIndexed import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch @OptIn(ExperimentalCoroutinesApi::class) object KeyguardQuickAffordancePickerBinder { /** Binds view with view-model for a lock screen quick affordance picker experience. */ @JvmStatic fun bind( view: View, viewModel: KeyguardQuickAffordancePickerViewModel, lifecycleOwner: LifecycleOwner, ) { val slotTabView: RecyclerView = view.requireViewById(R.id.slot_tabs) val affordancesView: RecyclerView = view.requireViewById(R.id.affordances) val slotTabAdapter = SlotTabAdapter() slotTabView.adapter = slotTabAdapter slotTabView.layoutManager = LinearLayoutManager(view.context, RecyclerView.HORIZONTAL, false) slotTabView.addItemDecoration(ItemSpacing(ItemSpacing.TAB_ITEM_SPACING_DP)) // Setting a custom accessibility delegate so that the default content descriptions // for items in a list aren't announced (for left & right shortcuts). We populate // the content description for these shortcuts later on with the right (expected) // values. val slotTabViewDelegate: AccessibilityDelegateCompat = object : AccessibilityDelegateCompat() { override fun onRequestSendAccessibilityEvent( host: ViewGroup, child: View, event: AccessibilityEvent ): Boolean { if (event.eventType != AccessibilityEvent.TYPE_VIEW_FOCUSED) { child.contentDescription = null } return super.onRequestSendAccessibilityEvent(host, child, event) } } ViewCompat.setAccessibilityDelegate(slotTabView, slotTabViewDelegate) val affordancesAdapter = OptionItemAdapter( layoutResourceId = R.layout.keyguard_quick_affordance, lifecycleOwner = lifecycleOwner, bindIcon = { foregroundView: View, gridIcon: Icon -> val imageView = foregroundView as? ImageView imageView?.let { IconViewBinder.bind(imageView, gridIcon) } } ) affordancesView.adapter = affordancesAdapter affordancesView.layoutManager = LinearLayoutManager(view.context, RecyclerView.HORIZONTAL, false) affordancesView.addItemDecoration(ItemSpacing(ItemSpacing.ITEM_SPACING_DP)) var dialog: Dialog? = null lifecycleOwner.lifecycleScope.launch { lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { launch { viewModel.slots .map { slotById -> slotById.values } .collect { slots -> slotTabAdapter.setItems(slots.toList()) } } launch { viewModel.quickAffordances.collect { affordances -> affordancesAdapter.setItems(affordances) } } launch { viewModel.quickAffordances .flatMapLatest { affordances -> combine(affordances.map { affordance -> affordance.isSelected }) { selectedFlags -> selectedFlags.indexOfFirst { it } } } .collectIndexed { index, selectedPosition -> // Scroll the view to show the first selected affordance. if (selectedPosition != -1) { // We use "post" because we need to give the adapter item a pass to // update the view. affordancesView.post { if (index == 0) { // don't animate on initial collection affordancesView.scrollToPosition(selectedPosition) } else { affordancesView.smoothScrollToPosition(selectedPosition) } } } } } launch { viewModel.dialog.distinctUntilChanged().collect { dialogRequest -> dialog?.dismiss() dialog = if (dialogRequest != null) { showDialog( context = view.context, request = dialogRequest, onDismissed = viewModel::onDialogDismissed ) } else { null } } } launch { viewModel.activityStartRequests.collect { intent -> if (intent != null) { view.context.startActivity(intent) viewModel.onActivityStarted() } } } } } } private fun showDialog( context: Context, request: DialogViewModel, onDismissed: () -> Unit, ): Dialog { return DialogViewBinder.show( context = context, viewModel = request, onDismissed = onDismissed, ) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/ui/binder/KeyguardQuickAffordancePickerBinder.kt
3441970210
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.ui.binder import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.core.view.isVisible import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import com.android.customization.picker.quickaffordance.ui.viewmodel.KeyguardQuickAffordancePickerViewModel import com.android.wallpaper.R import com.android.wallpaper.picker.common.icon.ui.viewbinder.IconViewBinder import com.android.wallpaper.picker.common.text.ui.viewbinder.TextViewBinder import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch object KeyguardQuickAffordanceSectionViewBinder { fun bind( view: View, viewModel: KeyguardQuickAffordancePickerViewModel, lifecycleOwner: LifecycleOwner, onClicked: () -> Unit, ) { view.setOnClickListener { onClicked() } val descriptionView: TextView = view.requireViewById(R.id.keyguard_quick_affordance_description) val icon1: ImageView = view.requireViewById(R.id.icon_1) val icon2: ImageView = view.requireViewById(R.id.icon_2) lifecycleOwner.lifecycleScope.launch { viewModel.summary .flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED) .collectLatest { summary -> TextViewBinder.bind( view = descriptionView, viewModel = summary.description, ) if (summary.icon1 != null) { IconViewBinder.bind( view = icon1, viewModel = summary.icon1, ) } icon1.isVisible = summary.icon1 != null if (summary.icon2 != null) { IconViewBinder.bind( view = icon2, viewModel = summary.icon2, ) } icon2.isVisible = summary.icon2 != null } } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/ui/binder/KeyguardQuickAffordanceSectionViewBinder.kt
3599132140
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.ui.binder import android.app.Activity import android.os.Bundle import androidx.cardview.widget.CardView import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.flowWithLifecycle import androidx.lifecycle.lifecycleScope import com.android.customization.picker.quickaffordance.ui.viewmodel.KeyguardQuickAffordancePickerViewModel import com.android.systemui.shared.quickaffordance.shared.model.KeyguardPreviewConstants import com.android.wallpaper.R import com.android.wallpaper.picker.customization.ui.binder.ScreenPreviewBinder import kotlinx.coroutines.launch object KeyguardQuickAffordancePreviewBinder { /** Binds view for the preview of the lock screen. */ @JvmStatic fun bind( activity: Activity, previewView: CardView, viewModel: KeyguardQuickAffordancePickerViewModel, lifecycleOwner: LifecycleOwner, offsetToStart: Boolean, ) { val binding = ScreenPreviewBinder.bind( activity = activity, previewView = previewView, viewModel = viewModel.preview, lifecycleOwner = lifecycleOwner, offsetToStart = offsetToStart, dimWallpaper = true, onWallpaperPreviewDirty = { activity.recreate() }, ) previewView.contentDescription = previewView.context.getString( R.string.lockscreen_wallpaper_preview_card_content_description ) lifecycleOwner.lifecycleScope.launch { viewModel.selectedSlotId .flowWithLifecycle(lifecycleOwner.lifecycle, Lifecycle.State.STARTED) .collect { slotId -> binding.sendMessage( KeyguardPreviewConstants.MESSAGE_ID_SLOT_SELECTED, Bundle().apply { putString(KeyguardPreviewConstants.KEY_SLOT_ID, slotId) }, ) } } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/ui/binder/KeyguardQuickAffordancePreviewBinder.kt
4035288317
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.android.customization.picker.quickaffordance.ui.viewmodel.KeyguardQuickAffordanceSlotViewModel import com.android.wallpaper.R /** Adapts between lock screen quick affordance slot items and views. */ class SlotTabAdapter : RecyclerView.Adapter<SlotTabAdapter.ViewHolder>() { private val items = mutableListOf<KeyguardQuickAffordanceSlotViewModel>() fun setItems(items: List<KeyguardQuickAffordanceSlotViewModel>) { this.items.clear() this.items.addAll(items) notifyDataSetChanged() } override fun getItemCount(): Int { return items.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( LayoutInflater.from(parent.context) .inflate( R.layout.picker_fragment_tab, parent, false, ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = items[position] holder.itemView.isSelected = item.isSelected holder.textView.text = item.name holder.itemView.setOnClickListener( if (item.onClicked != null) { View.OnClickListener { item.onClicked.invoke() } } else { null } ) val stateDescription = item.selectedQuickAffordances .find { it.isSelected.value } ?.text ?.asString(holder.itemView.context) holder.itemView.stateDescription = stateDescription ?: holder.itemView.resources.getString(R.string.keyguard_affordance_none) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val textView: TextView = itemView.requireViewById(R.id.text) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/ui/adapter/SlotTabAdapter.kt
148820147
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowInsets import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.get import androidx.transition.Transition import androidx.transition.doOnStart import com.android.customization.module.ThemePickerInjector import com.android.customization.picker.quickaffordance.ui.binder.KeyguardQuickAffordancePickerBinder import com.android.customization.picker.quickaffordance.ui.binder.KeyguardQuickAffordancePreviewBinder import com.android.customization.picker.quickaffordance.ui.viewmodel.KeyguardQuickAffordancePickerViewModel import com.android.wallpaper.R import com.android.wallpaper.module.InjectorProvider import com.android.wallpaper.picker.AppbarFragment class KeyguardQuickAffordancePickerFragment : AppbarFragment() { companion object { const val DESTINATION_ID = "quick_affordances" @JvmStatic fun newInstance(): KeyguardQuickAffordancePickerFragment { return KeyguardQuickAffordancePickerFragment() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view = inflater.inflate( R.layout.fragment_lock_screen_quick_affordances, container, false, ) setUpToolbar(view) // For nav bar edge-to-edge effect. view.setOnApplyWindowInsetsListener { v: View, windowInsets: WindowInsets -> v.setPadding( v.paddingLeft, v.paddingTop, v.paddingRight, windowInsets.systemWindowInsetBottom ) windowInsets } val injector = InjectorProvider.getInjector() as ThemePickerInjector val viewModel: KeyguardQuickAffordancePickerViewModel = ViewModelProvider( requireActivity(), injector.getKeyguardQuickAffordancePickerViewModelFactory(requireContext()), ) .get() KeyguardQuickAffordancePreviewBinder.bind( activity = requireActivity(), previewView = view.requireViewById(R.id.preview), viewModel = viewModel, lifecycleOwner = this, offsetToStart = requireActivity().let { injector.getDisplayUtils(it).isSingleDisplayOrUnfoldedHorizontalHinge(it) } ) KeyguardQuickAffordancePickerBinder.bind( view = view, viewModel = viewModel, lifecycleOwner = this, ) postponeEnterTransition() view.post { startPostponedEnterTransition() } (returnTransition as? Transition)?.doOnStart { // Hide preview during exit transition animation view?.findViewById<View>(R.id.preview)?.isVisible = false } return view } override fun getDefaultTitle(): CharSequence { return requireContext().getString(R.string.keyguard_quick_affordance_title) } override fun getToolbarColorId(): Int { return android.R.color.transparent } override fun getToolbarTextColor(): Int { return ContextCompat.getColor(requireContext(), R.color.system_on_surface) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/ui/fragment/KeyguardQuickAffordancePickerFragment.kt
3204005615
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.ui.view import android.content.Context import android.util.AttributeSet import com.android.wallpaper.picker.SectionView class KeyguardQuickAffordanceSectionView( context: Context?, attrs: AttributeSet?, ) : SectionView( context, attrs, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/ui/view/KeyguardQuickAffordanceSectionView.kt
2155018663
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.shared.model /** Models a lock screen quick affordance slot (or position) where affordances can be displayed. */ data class KeyguardQuickAffordancePickerSlotModel( val id: String, /** Maximum number of affordances allowed to be set on this slot. */ val maxSelectedQuickAffordances: Int, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/shared/model/KeyguardQuickAffordancePickerSlotModel.kt
6203060
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.shared.model import android.content.Intent import androidx.annotation.DrawableRes /** Models a quick affordance. */ data class KeyguardQuickAffordancePickerAffordanceModel( val id: String, val name: String, /** * The resource ID for a drawable of the icon. This is in the namespace of system UI so it * should be queries from that package. */ @DrawableRes val iconResourceId: Int, /** Whether this quick affordance is enabled. */ val isEnabled: Boolean, /** If not enabled, the user-visible message explaining why. */ val enablementExplanation: String, /** * If not enabled, an optional label for a button that takes the user to a destination where * they can re-enable it. */ val enablementActionText: String?, /** * If not enabled, an optional [Intent] for a button that takes the user to a destination where * they can re-enable it. */ val enablementActionIntent: Intent?, /** Optional [Intent] to use to start an activity to configure this affordance. */ val configureIntent: Intent?, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/shared/model/KeyguardQuickAffordancePickerAffordanceModel.kt
2806176261
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.shared.model /** Models a selection of an affordance on a slot. */ data class KeyguardQuickAffordancePickerSelectionModel( val slotId: String, val affordanceId: String, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/shared/model/KeyguardQuickAffordancePickerSelectionModel.kt
191039234
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.data.repository import com.android.customization.picker.quickaffordance.shared.model.KeyguardQuickAffordancePickerAffordanceModel as AffordanceModel import com.android.customization.picker.quickaffordance.shared.model.KeyguardQuickAffordancePickerSelectionModel as SelectionModel import com.android.customization.picker.quickaffordance.shared.model.KeyguardQuickAffordancePickerSlotModel as SlotModel import com.android.systemui.shared.customization.data.content.CustomizationProviderClient as Client import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.shareIn /** * Abstracts access to application state related to functionality for selecting, picking, or setting * lock screen quick affordances. */ class KeyguardQuickAffordancePickerRepository( private val client: Client, private val scope: CoroutineScope ) { /** List of slots available on the device. */ val slots: Flow<List<SlotModel>> = client.observeSlots().map { slots -> slots.map { slot -> slot.toModel() } } /** List of all available quick affordances. */ val affordances: Flow<List<AffordanceModel>> = client .observeAffordances() .map { affordances -> affordances.map { affordance -> affordance.toModel() } } .shareIn(scope, replay = 1, started = SharingStarted.Lazily) /** List of slot-affordance pairs, modeling what the user has currently chosen for each slot. */ val selections: Flow<List<SelectionModel>> = client .observeSelections() .map { selections -> selections.map { selection -> selection.toModel() } } .shareIn(scope, replay = 1, started = SharingStarted.Lazily) private fun Client.Slot.toModel(): SlotModel { return SlotModel( id = id, maxSelectedQuickAffordances = capacity, ) } private fun Client.Affordance.toModel(): AffordanceModel { return AffordanceModel( id = id, name = name, iconResourceId = iconResourceId, isEnabled = isEnabled, enablementExplanation = enablementExplanation ?: "", enablementActionText = enablementActionText, enablementActionIntent = enablementActionIntent, configureIntent = configureIntent, ) } private fun Client.Selection.toModel(): SelectionModel { return SelectionModel( slotId = slotId, affordanceId = affordanceId, ) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/data/repository/KeyguardQuickAffordancePickerRepository.kt
1445344589
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.domain.interactor import com.android.systemui.shared.customization.data.content.CustomizationProviderClient import com.android.wallpaper.picker.undo.domain.interactor.SnapshotRestorer import com.android.wallpaper.picker.undo.domain.interactor.SnapshotStore import com.android.wallpaper.picker.undo.shared.model.RestorableSnapshot /** Handles state restoration for the quick affordances system. */ class KeyguardQuickAffordanceSnapshotRestorer( private val interactor: KeyguardQuickAffordancePickerInteractor, private val client: CustomizationProviderClient, ) : SnapshotRestorer { private var snapshotStore: SnapshotStore = SnapshotStore.NOOP suspend fun storeSnapshot() { snapshotStore.store(snapshot()) } override suspend fun setUpSnapshotRestorer( store: SnapshotStore, ): RestorableSnapshot { snapshotStore = store return snapshot() } override suspend fun restoreToSnapshot(snapshot: RestorableSnapshot) { // reset all current selections interactor.unselectAll() val allSelections = checkNotNull(snapshot.args[KEY_SELECTIONS]) if (allSelections.isEmpty()) return val selections: List<Pair<String, String>> = allSelections.split(SELECTION_SEPARATOR).map { selection -> val (slotId, affordanceId) = selection.split(SLOT_AFFORDANCE_SEPARATOR) slotId to affordanceId } selections.forEach { (slotId, affordanceId) -> interactor.select( slotId, affordanceId, ) } } private suspend fun snapshot(): RestorableSnapshot { return RestorableSnapshot( mapOf( KEY_SELECTIONS to client.querySelections().joinToString(SELECTION_SEPARATOR) { selection -> "${selection.slotId}${SLOT_AFFORDANCE_SEPARATOR}${selection.affordanceId}" } ) ) } companion object { private const val KEY_SELECTIONS = "selections" private const val SLOT_AFFORDANCE_SEPARATOR = "->" private const val SELECTION_SEPARATOR = "|" } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/domain/interactor/KeyguardQuickAffordanceSnapshotRestorer.kt
1871027246
/* * Copyright (C) 2022 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.customization.picker.quickaffordance.domain.interactor import android.graphics.drawable.Drawable import androidx.annotation.DrawableRes import com.android.customization.picker.quickaffordance.data.repository.KeyguardQuickAffordancePickerRepository import com.android.customization.picker.quickaffordance.shared.model.KeyguardQuickAffordancePickerAffordanceModel as AffordanceModel import com.android.customization.picker.quickaffordance.shared.model.KeyguardQuickAffordancePickerSelectionModel as SelectionModel import com.android.customization.picker.quickaffordance.shared.model.KeyguardQuickAffordancePickerSlotModel as SlotModel import com.android.systemui.shared.customization.data.content.CustomizationProviderClient as Client import javax.inject.Provider import kotlinx.coroutines.flow.Flow /** * Single entry-point for all application state and business logic related to quick affordances on * the lock screen. */ class KeyguardQuickAffordancePickerInteractor( private val repository: KeyguardQuickAffordancePickerRepository, private val client: Client, private val snapshotRestorer: Provider<KeyguardQuickAffordanceSnapshotRestorer>, ) { /** List of slots available on the device. */ val slots: Flow<List<SlotModel>> = repository.slots /** List of all available quick affordances. */ val affordances: Flow<List<AffordanceModel>> = repository.affordances /** List of slot-affordance pairs, modeling what the user has currently chosen for each slot. */ val selections: Flow<List<SelectionModel>> = repository.selections /** * Selects an affordance with the given ID for a slot with the given ID. * * Note that the maximum affordance per slot is automatically managed. If trying to select an * affordance for a slot that's already full, the oldest affordance is removed to make room. * * Note that if an affordance with the given ID is already selected on the slot with the given * ID, that affordance is moved to the newest position on the slot. */ suspend fun select(slotId: String, affordanceId: String) { client.insertSelection( slotId = slotId, affordanceId = affordanceId, ) snapshotRestorer.get().storeSnapshot() } /** Unselects all affordances from the slot with the given ID. */ suspend fun unselectAllFromSlot(slotId: String) { client.deleteAllSelections( slotId = slotId, ) snapshotRestorer.get().storeSnapshot() } /** Unselects all affordances from all slots. */ suspend fun unselectAll() { client.querySlots().forEach { client.deleteAllSelections(it.id) } } /** Returns a [Drawable] for the given resource ID, from the system UI package. */ suspend fun getAffordanceIcon( @DrawableRes iconResourceId: Int, ): Drawable { return client.getAffordanceIcon(iconResourceId) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/quickaffordance/domain/interactor/KeyguardQuickAffordancePickerInteractor.kt
2855573494
/* * Copyright (C) 2023 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.customization.picker.notifications.ui.viewmodel import androidx.annotation.VisibleForTesting import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.android.customization.module.logging.ThemesUserEventLogger import com.android.customization.picker.notifications.domain.interactor.NotificationsInteractor import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch /** Models UI state for a section that lets the user control the notification settings. */ class NotificationSectionViewModel @VisibleForTesting constructor( private val interactor: NotificationsInteractor, private val logger: ThemesUserEventLogger, ) : ViewModel() { /** Whether the switch should be on. */ val isSwitchOn: Flow<Boolean> = interactor.settings.map { model -> model.isShowNotificationsOnLockScreenEnabled } /** Notifies that the section has been clicked. */ fun onClicked() { viewModelScope.launch { interactor.toggleShowNotificationsOnLockScreenEnabled() logger.logLockScreenNotificationApplied( interactor.getSettings().isShowNotificationsOnLockScreenEnabled ) } } class Factory( private val interactor: NotificationsInteractor, private val logger: ThemesUserEventLogger, ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return NotificationSectionViewModel( interactor = interactor, logger = logger, ) as T } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/notifications/ui/viewmodel/NotificationSectionViewModel.kt
2453591308
/* * Copyright (C) 2023 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.customization.picker.notifications.ui.section import android.annotation.SuppressLint import android.content.Context import android.view.LayoutInflater import androidx.lifecycle.LifecycleOwner import com.android.customization.picker.notifications.ui.binder.NotificationSectionBinder import com.android.customization.picker.notifications.ui.view.NotificationSectionView import com.android.customization.picker.notifications.ui.viewmodel.NotificationSectionViewModel import com.android.wallpaper.R import com.android.wallpaper.model.CustomizationSectionController /** Controls a section with UI that lets the user toggle notification settings. */ class NotificationSectionController( private val viewModel: NotificationSectionViewModel, private val lifecycleOwner: LifecycleOwner, ) : CustomizationSectionController<NotificationSectionView> { override fun isAvailable(context: Context): Boolean { return true } @SuppressLint("InflateParams") // We don't care that the parent is null. override fun createView(context: Context): NotificationSectionView { val view = LayoutInflater.from(context) .inflate( R.layout.notification_section, /* parent= */ null, ) as NotificationSectionView NotificationSectionBinder.bind( view = view, viewModel = viewModel, lifecycleOwner = lifecycleOwner, ) return view } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/notifications/ui/section/NotificationSectionController.kt
3151061753
/* * Copyright (C) 2023 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.customization.picker.notifications.ui.binder import android.annotation.SuppressLint import android.view.View import android.widget.Switch import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.android.customization.picker.notifications.ui.viewmodel.NotificationSectionViewModel import com.android.wallpaper.R import kotlinx.coroutines.launch /** * Binds between view and view-model for a section that lets the user control notification settings. */ object NotificationSectionBinder { @SuppressLint("UseSwitchCompatOrMaterialCode") // We're using Switch and that's okay for SysUI. fun bind( view: View, viewModel: NotificationSectionViewModel, lifecycleOwner: LifecycleOwner, ) { val switch: Switch = view.requireViewById(R.id.switcher) view.setOnClickListener { viewModel.onClicked() } lifecycleOwner.lifecycleScope.launch { lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { launch { viewModel.isSwitchOn.collect { switch.isChecked = it } } } } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/notifications/ui/binder/NotificationSectionBinder.kt
645751860
/* * Copyright (C) 2023 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.customization.picker.notifications.ui.view import android.content.Context import android.util.AttributeSet import com.android.wallpaper.picker.SectionView class NotificationSectionView( context: Context?, attrs: AttributeSet?, ) : SectionView( context, attrs, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/notifications/ui/view/NotificationSectionView.kt
1528498998
/* * Copyright (C) 2023 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.customization.picker.notifications.shared.model /** Models notification settings. */ data class NotificationSettingsModel( /** Whether notifications are shown on the lock screen. */ val isShowNotificationsOnLockScreenEnabled: Boolean = false, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/notifications/shared/model/NotificationSettingsModel.kt
310050740
/* * Copyright (C) 2023 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.customization.picker.notifications.data.repository import android.provider.Settings import com.android.customization.picker.notifications.shared.model.NotificationSettingsModel import com.android.wallpaper.settings.data.repository.SecureSettingsRepository import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.shareIn import kotlinx.coroutines.withContext /** Provides access to state related to notifications. */ class NotificationsRepository( scope: CoroutineScope, private val backgroundDispatcher: CoroutineDispatcher, private val secureSettingsRepository: SecureSettingsRepository, ) { /** The current state of the notification setting. */ val settings: SharedFlow<NotificationSettingsModel> = secureSettingsRepository .intSetting( name = Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, ) .map { lockScreenShowNotificationsInt -> NotificationSettingsModel( isShowNotificationsOnLockScreenEnabled = lockScreenShowNotificationsInt == 1, ) } .shareIn( scope = scope, started = SharingStarted.WhileSubscribed(), replay = 1, ) suspend fun getSettings(): NotificationSettingsModel { return withContext(backgroundDispatcher) { NotificationSettingsModel( isShowNotificationsOnLockScreenEnabled = secureSettingsRepository.get( name = Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, defaultValue = 0, ) == 1 ) } } suspend fun setSettings(model: NotificationSettingsModel) { withContext(backgroundDispatcher) { secureSettingsRepository.set( name = Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, value = if (model.isShowNotificationsOnLockScreenEnabled) 1 else 0, ) } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/notifications/data/repository/NotificationsRepository.kt
2765622138
/* * Copyright (C) 2023 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.customization.picker.notifications.domain.interactor import com.android.customization.picker.notifications.shared.model.NotificationSettingsModel import com.android.wallpaper.picker.undo.domain.interactor.SnapshotRestorer import com.android.wallpaper.picker.undo.domain.interactor.SnapshotStore import com.android.wallpaper.picker.undo.shared.model.RestorableSnapshot /** Handles state restoration for notification settings. */ class NotificationsSnapshotRestorer( private val interactor: NotificationsInteractor, ) : SnapshotRestorer { private var snapshotStore: SnapshotStore = SnapshotStore.NOOP fun storeSnapshot(model: NotificationSettingsModel) { snapshotStore.store(snapshot(model)) } override suspend fun setUpSnapshotRestorer( store: SnapshotStore, ): RestorableSnapshot { snapshotStore = store return snapshot(interactor.getSettings()) } override suspend fun restoreToSnapshot(snapshot: RestorableSnapshot) { val isShowNotificationsOnLockScreenEnabled = snapshot.args[KEY_IS_SHOW_NOTIFICATIONS_ON_LOCK_SCREEN_ENABLED]?.toBoolean() ?: false interactor.setSettings( NotificationSettingsModel( isShowNotificationsOnLockScreenEnabled = isShowNotificationsOnLockScreenEnabled, ) ) } private fun snapshot(model: NotificationSettingsModel): RestorableSnapshot { return RestorableSnapshot( mapOf( KEY_IS_SHOW_NOTIFICATIONS_ON_LOCK_SCREEN_ENABLED to model.isShowNotificationsOnLockScreenEnabled.toString(), ) ) } companion object { private const val KEY_IS_SHOW_NOTIFICATIONS_ON_LOCK_SCREEN_ENABLED = "is_show_notifications_on_lock_screen_enabled" } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/notifications/domain/interactor/NotificationsSnapshotRestorer.kt
1055610162
/* * Copyright (C) 2023 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.customization.picker.notifications.domain.interactor import com.android.customization.picker.notifications.data.repository.NotificationsRepository import com.android.customization.picker.notifications.shared.model.NotificationSettingsModel import javax.inject.Provider import kotlinx.coroutines.flow.Flow /** Encapsulates business logic for interacting with notifications. */ class NotificationsInteractor( private val repository: NotificationsRepository, private val snapshotRestorer: Provider<NotificationsSnapshotRestorer>, ) { /** The current state of the notification setting. */ val settings: Flow<NotificationSettingsModel> = repository.settings /** Toggles the setting to show or hide notifications on the lock screen. */ suspend fun toggleShowNotificationsOnLockScreenEnabled() { val currentModel = repository.getSettings() setSettings( currentModel.copy( isShowNotificationsOnLockScreenEnabled = !currentModel.isShowNotificationsOnLockScreenEnabled, ) ) } suspend fun setSettings(model: NotificationSettingsModel) { repository.setSettings(model) snapshotRestorer.get().storeSnapshot(model) } suspend fun getSettings(): NotificationSettingsModel { return repository.getSettings() } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/notifications/domain/interactor/NotificationsInteractor.kt
3811444100
/* * Copyright (C) 2023 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.customization.picker.clock.ui.viewmodel import android.content.Context import androidx.core.graphics.ColorUtils import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.android.customization.model.color.ColorOptionImpl import com.android.customization.module.logging.ThemesUserEventLogger import com.android.customization.module.logging.ThemesUserEventLogger.Companion.NULL_SEED_COLOR import com.android.customization.picker.clock.domain.interactor.ClockPickerInteractor import com.android.customization.picker.clock.shared.ClockSize import com.android.customization.picker.clock.shared.model.ClockMetadataModel import com.android.customization.picker.clock.shared.toClockSizeForLogging import com.android.customization.picker.color.domain.interactor.ColorPickerInteractor import com.android.customization.picker.color.shared.model.ColorOptionModel import com.android.customization.picker.color.shared.model.ColorType import com.android.customization.picker.color.ui.viewmodel.ColorOptionIconViewModel import com.android.wallpaper.R import com.android.wallpaper.picker.common.text.ui.viewmodel.Text import com.android.wallpaper.picker.option.ui.viewmodel.OptionItemViewModel import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay 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.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch /** View model for the clock settings screen. */ class ClockSettingsViewModel private constructor( context: Context, private val clockPickerInteractor: ClockPickerInteractor, private val colorPickerInteractor: ColorPickerInteractor, private val getIsReactiveToTone: (clockId: String?) -> Boolean, private val logger: ThemesUserEventLogger, ) : ViewModel() { enum class Tab { COLOR, SIZE, } private val colorMap = ClockColorViewModel.getPresetColorMap(context.resources) val selectedClockId: StateFlow<String?> = clockPickerInteractor.selectedClockId .distinctUntilChanged() .stateIn(viewModelScope, SharingStarted.Eagerly, null) private val selectedColorId: StateFlow<String?> = clockPickerInteractor.selectedColorId.stateIn(viewModelScope, SharingStarted.Eagerly, null) private val sliderColorToneProgress = MutableStateFlow(ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS) val isSliderEnabled: Flow<Boolean> = combine(selectedClockId, clockPickerInteractor.selectedColorId) { clockId, colorId -> if (colorId == null) { false } else { getIsReactiveToTone(clockId) } } .distinctUntilChanged() val sliderProgress: Flow<Int> = merge(clockPickerInteractor.colorToneProgress, sliderColorToneProgress) private val _seedColor: MutableStateFlow<Int?> = MutableStateFlow(null) val seedColor: Flow<Int?> = merge(clockPickerInteractor.seedColor, _seedColor) /** * The slider color tone updates are quick. Do not set color tone and the blended color to the * settings until [onSliderProgressStop] is called. Update to a locally cached temporary * [sliderColorToneProgress] and [_seedColor] instead. */ fun onSliderProgressChanged(progress: Int) { sliderColorToneProgress.value = progress val selectedColorId = selectedColorId.value ?: return val clockColorViewModel = colorMap[selectedColorId] ?: return _seedColor.value = blendColorWithTone( color = clockColorViewModel.color, colorTone = clockColorViewModel.getColorTone(progress), ) } suspend fun onSliderProgressStop(progress: Int) { val selectedColorId = selectedColorId.value ?: return val clockColorViewModel = colorMap[selectedColorId] ?: return val seedColor = blendColorWithTone( color = clockColorViewModel.color, colorTone = clockColorViewModel.getColorTone(progress), ) clockPickerInteractor.setClockColor( selectedColorId = selectedColorId, colorToneProgress = progress, seedColor = seedColor, ) logger.logClockColorApplied(seedColor) } @OptIn(ExperimentalCoroutinesApi::class) val colorOptions: Flow<List<OptionItemViewModel<ColorOptionIconViewModel>>> = colorPickerInteractor.colorOptions.map { colorOptions -> // Use mapLatest and delay(100) here to prevent too many selectedClockColor update // events from ClockRegistry upstream, caused by sliding the saturation level bar. delay(COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS) buildList { val defaultThemeColorOptionViewModel = (colorOptions[ColorType.WALLPAPER_COLOR]?.find { it.isSelected }) ?.toOptionItemViewModel(context) ?: (colorOptions[ColorType.PRESET_COLOR]?.find { it.isSelected }) ?.toOptionItemViewModel(context) if (defaultThemeColorOptionViewModel != null) { add(defaultThemeColorOptionViewModel) } colorMap.values.forEachIndexed { index, colorModel -> val isSelectedFlow = selectedColorId .map { colorMap.keys.indexOf(it) == index } .stateIn(viewModelScope) val colorToneProgress = ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS add( OptionItemViewModel<ColorOptionIconViewModel>( key = MutableStateFlow(colorModel.colorId) as StateFlow<String>, payload = ColorOptionIconViewModel( lightThemeColor0 = colorModel.color, lightThemeColor1 = colorModel.color, lightThemeColor2 = colorModel.color, lightThemeColor3 = colorModel.color, darkThemeColor0 = colorModel.color, darkThemeColor1 = colorModel.color, darkThemeColor2 = colorModel.color, darkThemeColor3 = colorModel.color, ), text = Text.Loaded( context.getString( R.string.content_description_color_option, index, ) ), isTextUserVisible = false, isSelected = isSelectedFlow, onClicked = isSelectedFlow.map { isSelected -> if (isSelected) { null } else { { viewModelScope.launch { val seedColor = blendColorWithTone( color = colorModel.color, colorTone = colorModel.getColorTone( colorToneProgress, ), ) clockPickerInteractor.setClockColor( selectedColorId = colorModel.colorId, colorToneProgress = colorToneProgress, seedColor = seedColor, ) logger.logClockColorApplied(seedColor) } } } }, ) ) } } } @OptIn(ExperimentalCoroutinesApi::class) val selectedColorOptionPosition: Flow<Int> = colorOptions.flatMapLatest { colorOptions -> combine(colorOptions.map { colorOption -> colorOption.isSelected }) { selectedFlags -> selectedFlags.indexOfFirst { it } } } private suspend fun ColorOptionModel.toOptionItemViewModel( context: Context ): OptionItemViewModel<ColorOptionIconViewModel> { val lightThemeColors = (colorOption as ColorOptionImpl) .previewInfo .resolveColors( /** darkTheme= */ false ) val darkThemeColors = colorOption.previewInfo.resolveColors( /** darkTheme= */ true ) val isSelectedFlow = selectedColorId.map { it == null }.stateIn(viewModelScope) return OptionItemViewModel<ColorOptionIconViewModel>( key = MutableStateFlow(key) as StateFlow<String>, payload = ColorOptionIconViewModel( lightThemeColor0 = lightThemeColors[0], lightThemeColor1 = lightThemeColors[1], lightThemeColor2 = lightThemeColors[2], lightThemeColor3 = lightThemeColors[3], darkThemeColor0 = darkThemeColors[0], darkThemeColor1 = darkThemeColors[1], darkThemeColor2 = darkThemeColors[2], darkThemeColor3 = darkThemeColors[3], ), text = Text.Loaded(context.getString(R.string.default_theme_title)), isTextUserVisible = true, isSelected = isSelectedFlow, onClicked = isSelectedFlow.map { isSelected -> if (isSelected) { null } else { { viewModelScope.launch { clockPickerInteractor.setClockColor( selectedColorId = null, colorToneProgress = ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS, seedColor = null, ) logger.logClockColorApplied(NULL_SEED_COLOR) } } } }, ) } val selectedClockSize: Flow<ClockSize> = clockPickerInteractor.selectedClockSize fun setClockSize(size: ClockSize) { viewModelScope.launch { clockPickerInteractor.setClockSize(size) logger.logClockSizeApplied(size.toClockSizeForLogging()) } } private val _selectedTabPosition = MutableStateFlow(Tab.COLOR) val selectedTab: StateFlow<Tab> = _selectedTabPosition.asStateFlow() val tabs: Flow<List<ClockSettingsTabViewModel>> = selectedTab.map { listOf( ClockSettingsTabViewModel( name = context.resources.getString(R.string.clock_color), isSelected = it == Tab.COLOR, onClicked = if (it == Tab.COLOR) { null } else { { _selectedTabPosition.tryEmit(Tab.COLOR) } } ), ClockSettingsTabViewModel( name = context.resources.getString(R.string.clock_size), isSelected = it == Tab.SIZE, onClicked = if (it == Tab.SIZE) { null } else { { _selectedTabPosition.tryEmit(Tab.SIZE) } } ), ) } companion object { private val helperColorLab: DoubleArray by lazy { DoubleArray(3) } fun blendColorWithTone(color: Int, colorTone: Double): Int { ColorUtils.colorToLAB(color, helperColorLab) return ColorUtils.LABToColor( colorTone, helperColorLab[1], helperColorLab[2], ) } const val COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS: Long = 100 } class Factory( private val context: Context, private val clockPickerInteractor: ClockPickerInteractor, private val colorPickerInteractor: ColorPickerInteractor, private val logger: ThemesUserEventLogger, private val getIsReactiveToTone: (clockId: String?) -> Boolean, ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return ClockSettingsViewModel( context = context, clockPickerInteractor = clockPickerInteractor, colorPickerInteractor = colorPickerInteractor, logger = logger, getIsReactiveToTone = getIsReactiveToTone, ) as T } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/viewmodel/ClockSettingsViewModel.kt
3087739743
/* * Copyright (C) 2023 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.customization.picker.clock.ui.viewmodel import android.content.res.Resources import android.graphics.Color import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.android.customization.module.logging.ThemesUserEventLogger import com.android.customization.picker.clock.domain.interactor.ClockPickerInteractor import com.android.customization.picker.clock.shared.ClockSize import com.android.customization.picker.clock.ui.view.ClockViewFactory import com.android.wallpaper.R import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch /** * Clock carousel view model that provides data for the carousel of clock previews. When there is * only one item, we should show a single clock preview instead of a carousel. */ class ClockCarouselViewModel( private val interactor: ClockPickerInteractor, private val backgroundDispatcher: CoroutineDispatcher, private val clockViewFactory: ClockViewFactory, private val resources: Resources, private val logger: ThemesUserEventLogger, ) : ViewModel() { @OptIn(ExperimentalCoroutinesApi::class) val allClocks: StateFlow<List<ClockCarouselItemViewModel>> = interactor.allClocks .mapLatest { allClocks -> // Delay to avoid the case that the full list of clocks is not initiated. delay(CLOCKS_EVENT_UPDATE_DELAY_MILLIS) allClocks.map { val contentDescription = resources.getString( R.string.select_clock_action_description, clockViewFactory.getController(it.clockId).config.description ) ClockCarouselItemViewModel(it.clockId, it.isSelected, contentDescription) } } .stateIn(viewModelScope, SharingStarted.Eagerly, emptyList()) val selectedClockSize: Flow<ClockSize> = interactor.selectedClockSize val seedColor: Flow<Int?> = interactor.seedColor fun getClockCardColorResId(isDarkThemeEnabled: Boolean): Flow<Int> { return interactor.seedColor.map { it.let { seedColor -> // if seedColor is null, default clock color is selected if (seedColor == null) { if (isDarkThemeEnabled) { // In dark mode, use darkest surface container color R.color.system_surface_container_high } else { // In light mode, use lightest surface container color R.color.system_surface_bright } } else { val luminance = Color.luminance(seedColor) if (isDarkThemeEnabled) { if (luminance <= CARD_COLOR_CHANGE_LUMINANCE_THRESHOLD_DARK_THEME) { R.color.system_surface_bright } else { R.color.system_surface_container_high } } else { if (luminance <= CARD_COLOR_CHANGE_LUMINANCE_THRESHOLD_LIGHT_THEME) { R.color.system_surface_bright } else { R.color.system_surface_container_highest } } } } } } @OptIn(ExperimentalCoroutinesApi::class) val selectedIndex: Flow<Int> = allClocks .flatMapLatest { allClockIds -> interactor.selectedClockId.map { selectedClockId -> val index = allClockIds.indexOfFirst { it.clockId == selectedClockId } /** Making sure there is no active [setSelectedClockJob] */ val isSetClockIdJobActive = setSelectedClockJob?.isActive == true if (index >= 0 && !isSetClockIdJobActive) { index } else { null } } } .mapNotNull { it } private var setSelectedClockJob: Job? = null fun setSelectedClock(clockId: String) { setSelectedClockJob?.cancel() setSelectedClockJob = viewModelScope.launch(backgroundDispatcher) { interactor.setSelectedClock(clockId) logger.logClockApplied(clockId) } } class Factory( private val interactor: ClockPickerInteractor, private val backgroundDispatcher: CoroutineDispatcher, private val clockViewFactory: ClockViewFactory, private val resources: Resources, private val logger: ThemesUserEventLogger, ) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return ClockCarouselViewModel( interactor = interactor, backgroundDispatcher = backgroundDispatcher, clockViewFactory = clockViewFactory, resources = resources, logger = logger, ) as T } } companion object { const val CLOCKS_EVENT_UPDATE_DELAY_MILLIS: Long = 100 const val CARD_COLOR_CHANGE_LUMINANCE_THRESHOLD_LIGHT_THEME: Float = 0.85f const val CARD_COLOR_CHANGE_LUMINANCE_THRESHOLD_DARK_THEME: Float = 0.03f } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/viewmodel/ClockCarouselViewModel.kt
4171229016
/* * Copyright (C) 2023 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.customization.picker.clock.ui.viewmodel /** View model for the tabs on the clock settings screen. */ class ClockSettingsTabViewModel( /** User-visible name for the tab. */ val name: String, /** Whether this is the currently-selected tab in the picker. */ val isSelected: Boolean, /** Notifies that the tab has been clicked by the user. */ val onClicked: (() -> Unit)?, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/viewmodel/ClockSettingsTabViewModel.kt
1796292642
/* * Copyright (C) 2023 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.customization.picker.clock.ui.viewmodel import android.annotation.ColorInt import android.content.res.Resources import android.graphics.Color import com.android.wallpaper.R /** The view model that defines custom clock colors. */ data class ClockColorViewModel( val colorId: String, val colorName: String?, @ColorInt val color: Int, private val colorToneMin: Double, private val colorToneMax: Double, ) { fun getColorTone(progress: Int): Double { return colorToneMin + (progress.toDouble() * (colorToneMax - colorToneMin)) / 100 } companion object { private const val DEFAULT_COLOR_TONE_MIN = 0 private const val DEFAULT_COLOR_TONE_MAX = 100 fun getPresetColorMap(resources: Resources): Map<String, ClockColorViewModel> { val ids = resources.getStringArray(R.array.clock_color_ids) val names = resources.obtainTypedArray(R.array.clock_color_names) val colors = resources.obtainTypedArray(R.array.clock_colors) val colorToneMinList = resources.obtainTypedArray(R.array.clock_color_tone_min) val colorToneMaxList = resources.obtainTypedArray(R.array.clock_color_tone_max) return buildList { ids.indices.forEach { index -> add( ClockColorViewModel( ids[index], names.getString(index), colors.getColor(index, Color.TRANSPARENT), colorToneMinList.getInt(index, DEFAULT_COLOR_TONE_MIN).toDouble(), colorToneMaxList.getInt(index, DEFAULT_COLOR_TONE_MAX).toDouble(), ) ) } } .associateBy { it.colorId } .also { names.recycle() colors.recycle() colorToneMinList.recycle() colorToneMaxList.recycle() } } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/viewmodel/ClockColorViewModel.kt
970371930
/* * Copyright (C) 2023 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.customization.picker.clock.ui.viewmodel class ClockCarouselItemViewModel( val clockId: String, val isSelected: Boolean, val contentDescription: String, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/viewmodel/ClockCarouselItemViewModel.kt
2634171472
/* * Copyright (C) 2023 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.customization.picker.clock.ui.binder import android.content.Context import android.content.res.Configuration import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.android.customization.picker.clock.ui.view.ClockCarouselView import com.android.customization.picker.clock.ui.view.ClockViewFactory import com.android.customization.picker.clock.ui.viewmodel.ClockCarouselViewModel import com.android.wallpaper.picker.customization.ui.section.ScreenPreviewClickView import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch object ClockCarouselViewBinder { @JvmStatic fun bind( context: Context, carouselView: ClockCarouselView, screenPreviewClickView: ScreenPreviewClickView, viewModel: ClockCarouselViewModel, clockViewFactory: ClockViewFactory, lifecycleOwner: LifecycleOwner, isTwoPaneAndSmallWidth: Boolean, ) { carouselView.setClockViewFactory(clockViewFactory) carouselView.isVisible = true clockViewFactory.updateRegionDarkness() val carouselAccessibilityDelegate = CarouselAccessibilityDelegate( context, scrollForwardCallback = { // Callback code for scrolling forward carouselView.transitionToNext() }, scrollBackwardCallback = { // Callback code for scrolling backward carouselView.transitionToPrevious() } ) lifecycleOwner.lifecycleScope.launch { lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { launch { combine(viewModel.selectedClockSize, viewModel.allClocks, ::Pair).collect { (size, allClocks) -> carouselView.setUpClockCarouselView( clockSize = size, clocks = allClocks, onClockSelected = { clock -> viewModel.setSelectedClock(clock.clockId) }, isTwoPaneAndSmallWidth = isTwoPaneAndSmallWidth, ) screenPreviewClickView.accessibilityDelegate = carouselAccessibilityDelegate screenPreviewClickView.setOnSideClickedListener { isStart -> if (isStart) carouselView.scrollToPrevious() else carouselView.scrollToNext() } } } launch { viewModel.allClocks.collect { it.forEach { clock -> clockViewFactory.updateTimeFormat(clock.clockId) } } } launch { viewModel.selectedIndex.collect { selectedIndex -> carouselAccessibilityDelegate.contentDescriptionOfSelectedClock = carouselView.getContentDescription(selectedIndex) carouselView.setSelectedClockIndex(selectedIndex) } } launch { viewModel.seedColor.collect { clockViewFactory.updateColorForAllClocks(it) } } launch { val night = (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES) viewModel.getClockCardColorResId(night).collect { carouselView.setCarouselCardColor(ContextCompat.getColor(context, it)) } } } } lifecycleOwner.lifecycle.addObserver( LifecycleEventObserver { source, event -> when (event) { Lifecycle.Event.ON_RESUME -> { clockViewFactory.registerTimeTicker(source) } Lifecycle.Event.ON_PAUSE -> { clockViewFactory.unregisterTimeTicker(source) } else -> {} } } ) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/binder/ClockCarouselViewBinder.kt
1008858625
/* * Copyright (C) 2023 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.customization.picker.clock.ui.binder import android.content.Context import android.content.res.Configuration import android.text.Spannable import android.text.SpannableString import android.text.style.TextAppearanceSpan import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.RadioButton import android.widget.RadioGroup import android.widget.RadioGroup.OnCheckedChangeListener import android.widget.SeekBar import androidx.core.view.doOnPreDraw import androidx.core.view.isInvisible import androidx.core.view.isVisible import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.customization.picker.clock.shared.ClockSize import com.android.customization.picker.clock.ui.adapter.ClockSettingsTabAdapter import com.android.customization.picker.clock.ui.view.ClockCarouselView import com.android.customization.picker.clock.ui.view.ClockHostView import com.android.customization.picker.clock.ui.view.ClockViewFactory import com.android.customization.picker.clock.ui.viewmodel.ClockSettingsViewModel import com.android.customization.picker.color.ui.binder.ColorOptionIconBinder import com.android.customization.picker.common.ui.view.ItemSpacing import com.android.wallpaper.R import com.android.wallpaper.picker.option.ui.binder.OptionItemBinder import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.launch /** Bind between the clock settings screen and its view model. */ object ClockSettingsBinder { private const val SLIDER_ENABLED_ALPHA = 1f private const val SLIDER_DISABLED_ALPHA = .3f private const val COLOR_PICKER_ITEM_PREFIX_ID = 1234 fun bind( view: View, viewModel: ClockSettingsViewModel, clockViewFactory: ClockViewFactory, lifecycleOwner: LifecycleOwner, ) { val clockHostView: ClockHostView = view.requireViewById(R.id.clock_host_view) val tabView: RecyclerView = view.requireViewById(R.id.tabs) val tabAdapter = ClockSettingsTabAdapter() tabView.adapter = tabAdapter tabView.layoutManager = LinearLayoutManager(view.context, RecyclerView.HORIZONTAL, false) tabView.addItemDecoration(ItemSpacing(ItemSpacing.TAB_ITEM_SPACING_DP)) val colorOptionContainerListView: LinearLayout = view.requireViewById(R.id.color_options) val slider: SeekBar = view.requireViewById(R.id.slider) slider.setOnSeekBarChangeListener( object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(p0: SeekBar?, progress: Int, fromUser: Boolean) { if (fromUser) { viewModel.onSliderProgressChanged(progress) } } override fun onStartTrackingTouch(seekBar: SeekBar?) = Unit override fun onStopTrackingTouch(seekBar: SeekBar?) { seekBar?.progress?.let { lifecycleOwner.lifecycleScope.launch { viewModel.onSliderProgressStop(it) } } } } ) val onCheckedChangeListener = OnCheckedChangeListener { _, id -> when (id) { R.id.radio_dynamic -> viewModel.setClockSize(ClockSize.DYNAMIC) R.id.radio_small -> viewModel.setClockSize(ClockSize.SMALL) } } val clockSizeRadioGroup = view.requireViewById<RadioGroup>(R.id.clock_size_radio_button_group) clockSizeRadioGroup.setOnCheckedChangeListener(onCheckedChangeListener) view.requireViewById<RadioButton>(R.id.radio_dynamic).text = getRadioText( view.context.applicationContext, view.resources.getString(R.string.clock_size_dynamic), view.resources.getString(R.string.clock_size_dynamic_description) ) view.requireViewById<RadioButton>(R.id.radio_small).text = getRadioText( view.context.applicationContext, view.resources.getString(R.string.clock_size_small), view.resources.getString(R.string.clock_size_small_description) ) val colorOptionContainer = view.requireViewById<View>(R.id.color_picker_container) lifecycleOwner.lifecycleScope.launch { lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { launch { viewModel.seedColor.collect { seedColor -> viewModel.selectedClockId.value?.let { selectedClockId -> clockViewFactory.updateColor(selectedClockId, seedColor) } } } launch { viewModel.tabs.collect { tabAdapter.setItems(it) } } launch { viewModel.selectedTab.collect { tab -> when (tab) { ClockSettingsViewModel.Tab.COLOR -> { colorOptionContainer.isVisible = true clockSizeRadioGroup.isInvisible = true } ClockSettingsViewModel.Tab.SIZE -> { colorOptionContainer.isInvisible = true clockSizeRadioGroup.isVisible = true } } } } launch { viewModel.colorOptions.collect { colorOptions -> colorOptionContainerListView.removeAllViews() colorOptions.forEachIndexed { index, colorOption -> colorOption.payload?.let { payload -> val item = LayoutInflater.from(view.context) .inflate( R.layout.clock_color_option, colorOptionContainerListView, false, ) as LinearLayout val darkMode = (view.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES) ColorOptionIconBinder.bind( item.requireViewById(R.id.foreground), payload, darkMode ) OptionItemBinder.bind( view = item, viewModel = colorOptions[index], lifecycleOwner = lifecycleOwner, foregroundTintSpec = null, ) val id = COLOR_PICKER_ITEM_PREFIX_ID + index item.id = id colorOptionContainerListView.addView(item) } } } } launch { viewModel.selectedColorOptionPosition.collect { selectedPosition -> if (selectedPosition != -1) { val colorOptionContainerListView: LinearLayout = view.requireViewById(R.id.color_options) val selectedView = colorOptionContainerListView.findViewById<View>( COLOR_PICKER_ITEM_PREFIX_ID + selectedPosition ) selectedView?.parent?.requestChildFocus(selectedView, selectedView) } } } launch { combine( viewModel.selectedClockId.mapNotNull { it }, viewModel.selectedClockSize, ::Pair, ) .collect { (clockId, size) -> clockHostView.removeAllViews() val clockView = when (size) { ClockSize.DYNAMIC -> clockViewFactory.getLargeView(clockId) ClockSize.SMALL -> clockViewFactory.getSmallView(clockId) } // The clock view might still be attached to an existing parent. Detach // before adding to another parent. (clockView.parent as? ViewGroup)?.removeView(clockView) clockHostView.addView(clockView) when (size) { ClockSize.DYNAMIC -> { // When clock size data flow emits clock size signal, we want // to update the view without triggering on checked change, // which is supposed to be triggered by user interaction only. clockSizeRadioGroup.setOnCheckedChangeListener(null) clockSizeRadioGroup.check(R.id.radio_dynamic) clockSizeRadioGroup.setOnCheckedChangeListener( onCheckedChangeListener ) clockHostView.doOnPreDraw { it.pivotX = it.width / 2F it.pivotY = it.height / 2F } } ClockSize.SMALL -> { // When clock size data flow emits clock size signal, we want // to update the view without triggering on checked change, // which is supposed to be triggered by user interaction only. clockSizeRadioGroup.setOnCheckedChangeListener(null) clockSizeRadioGroup.check(R.id.radio_small) clockSizeRadioGroup.setOnCheckedChangeListener( onCheckedChangeListener ) clockHostView.doOnPreDraw { it.pivotX = ClockCarouselView.getCenteredHostViewPivotX(it) it.pivotY = 0F } } } } } launch { viewModel.sliderProgress.collect { progress -> slider.setProgress(progress, true) } } launch { viewModel.isSliderEnabled.collect { isEnabled -> slider.isEnabled = isEnabled slider.alpha = if (isEnabled) SLIDER_ENABLED_ALPHA else SLIDER_DISABLED_ALPHA } } } } lifecycleOwner.lifecycle.addObserver( LifecycleEventObserver { source, event -> when (event) { Lifecycle.Event.ON_RESUME -> { clockViewFactory.registerTimeTicker(source) } Lifecycle.Event.ON_PAUSE -> { clockViewFactory.unregisterTimeTicker(source) } else -> {} } } ) } private fun getRadioText( context: Context, title: String, description: String ): SpannableString { val text = SpannableString(title + "\n" + description) text.setSpan( TextAppearanceSpan(context, R.style.SectionTitleTextStyle), 0, title.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) text.setSpan( TextAppearanceSpan(context, R.style.SectionSubtitleTextStyle), title.length + 1, title.length + 1 + description.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) return text } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/binder/ClockSettingsBinder.kt
2904000075
/* * Copyright (C) 2023 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.customization.picker.clock.ui.binder import android.content.Context import android.os.Bundle import android.view.View import android.view.accessibility.AccessibilityNodeInfo import com.android.wallpaper.R class CarouselAccessibilityDelegate( private val context: Context, private val scrollForwardCallback: () -> Unit, private val scrollBackwardCallback: () -> Unit ) : View.AccessibilityDelegate() { var contentDescriptionOfSelectedClock = "" private val ACTION_SCROLL_BACKWARD = R.id.action_scroll_backward private val ACTION_SCROLL_FORWARD = R.id.action_scroll_forward override fun onInitializeAccessibilityNodeInfo(host: View, info: AccessibilityNodeInfo) { super.onInitializeAccessibilityNodeInfo(host, info) info.isScrollable = true info.addAction( AccessibilityNodeInfo.AccessibilityAction( ACTION_SCROLL_FORWARD, context.getString(R.string.scroll_forward_and_select) ) ) info.addAction( AccessibilityNodeInfo.AccessibilityAction( ACTION_SCROLL_BACKWARD, context.getString(R.string.scroll_backward_and_select) ) ) info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_ACCESSIBILITY_FOCUS) // We need to specifically set the content description since for some reason the talkback // service does not go to children of the clock carousel in the view hierarchy info.contentDescription = contentDescriptionOfSelectedClock } override fun performAccessibilityAction(host: View, action: Int, args: Bundle?): Boolean { when (action) { ACTION_SCROLL_BACKWARD -> { scrollBackwardCallback.invoke() return true } ACTION_SCROLL_FORWARD -> { scrollForwardCallback.invoke() return true } } return super.performAccessibilityAction(host, action, args) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/binder/CarouselAccessibilityDelegate.kt
2793840054
/* * Copyright (C) 2023 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.customization.picker.clock.ui.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.android.customization.picker.clock.ui.viewmodel.ClockSettingsTabViewModel import com.android.wallpaper.R /** Adapter for the tab recycler view on the clock settings screen. */ class ClockSettingsTabAdapter : RecyclerView.Adapter<ClockSettingsTabAdapter.ViewHolder>() { private val items = mutableListOf<ClockSettingsTabViewModel>() fun setItems(items: List<ClockSettingsTabViewModel>) { this.items.clear() this.items.addAll(items) notifyDataSetChanged() } override fun getItemCount(): Int { return items.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( LayoutInflater.from(parent.context) .inflate( R.layout.picker_fragment_tab, parent, false, ) ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = items[position] holder.itemView.isSelected = item.isSelected holder.textView.text = item.name holder.itemView.setOnClickListener( if (item.onClicked != null) { View.OnClickListener { item.onClicked.invoke() } } else { null } ) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val textView: TextView = itemView.requireViewById(R.id.text) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/adapter/ClockSettingsTabAdapter.kt
525417301
/* * Copyright (C) 2023 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.customization.picker.clock.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.cardview.widget.CardView import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.get import androidx.transition.Transition import androidx.transition.doOnStart import com.android.customization.module.ThemePickerInjector import com.android.customization.picker.clock.ui.binder.ClockSettingsBinder import com.android.systemui.shared.clocks.shared.model.ClockPreviewConstants import com.android.wallpaper.R import com.android.wallpaper.module.CustomizationSections import com.android.wallpaper.module.InjectorProvider import com.android.wallpaper.picker.AppbarFragment import com.android.wallpaper.picker.customization.ui.binder.ScreenPreviewBinder import com.android.wallpaper.picker.customization.ui.viewmodel.ScreenPreviewViewModel import com.android.wallpaper.util.PreviewUtils import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.suspendCancellableCoroutine @OptIn(ExperimentalCoroutinesApi::class) class ClockSettingsFragment : AppbarFragment() { companion object { const val DESTINATION_ID = "clock_settings" @JvmStatic fun newInstance(): ClockSettingsFragment { return ClockSettingsFragment() } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view = inflater.inflate( R.layout.fragment_clock_settings, container, false, ) setUpToolbar(view) val context = requireContext() val activity = requireActivity() val injector = InjectorProvider.getInjector() as ThemePickerInjector val lockScreenView: CardView = view.requireViewById(R.id.lock_preview) val wallpaperColorsRepository = injector.getWallpaperColorsRepository() val displayUtils = injector.getDisplayUtils(context) ScreenPreviewBinder.bind( activity = activity, previewView = lockScreenView, viewModel = ScreenPreviewViewModel( previewUtils = PreviewUtils( context = context, authority = resources.getString( R.string.lock_screen_preview_provider_authority, ), ), wallpaperInfoProvider = { forceReload -> suspendCancellableCoroutine { continuation -> injector .getCurrentWallpaperInfoFactory(context) .createCurrentWallpaperInfos( context, forceReload, ) { homeWallpaper, lockWallpaper, _ -> continuation.resume( lockWallpaper ?: homeWallpaper, null, ) } } }, onWallpaperColorChanged = { colors -> wallpaperColorsRepository.setLockWallpaperColors(colors) }, initialExtrasProvider = { Bundle().apply { // Hide the clock from the system UI rendered preview so we can // place the carousel on top of it. putBoolean( ClockPreviewConstants.KEY_HIDE_CLOCK, true, ) } }, wallpaperInteractor = injector.getWallpaperInteractor(requireContext()), screen = CustomizationSections.Screen.LOCK_SCREEN, ), lifecycleOwner = this, offsetToStart = displayUtils.isSingleDisplayOrUnfoldedHorizontalHinge(activity), onWallpaperPreviewDirty = { activity.recreate() }, ) ClockSettingsBinder.bind( view, ViewModelProvider( this, injector.getClockSettingsViewModelFactory( context, injector.getWallpaperColorsRepository(), injector.getClockViewFactory(activity), ), ) .get(), injector.getClockViewFactory(activity), viewLifecycleOwner, ) (returnTransition as? Transition)?.doOnStart { lockScreenView.isVisible = false } return view } override fun getDefaultTitle(): CharSequence { return requireContext().getString(R.string.clock_color_and_size_title) } override fun getToolbarColorId(): Int { return android.R.color.transparent } override fun getToolbarTextColor(): Int { return ContextCompat.getColor(requireContext(), R.color.system_on_surface) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/fragment/ClockSettingsFragment.kt
1189733410
/* * Copyright (C) 2023 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.customization.picker.clock.ui.view import android.content.Context import android.content.res.ColorStateList import android.content.res.Resources import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.constraintlayout.helper.widget.Carousel import androidx.constraintlayout.motion.widget.MotionLayout import androidx.constraintlayout.widget.ConstraintSet import androidx.core.view.doOnPreDraw import androidx.core.view.get import androidx.core.view.isNotEmpty import com.android.customization.picker.clock.shared.ClockSize import com.android.customization.picker.clock.ui.viewmodel.ClockCarouselItemViewModel import com.android.systemui.plugins.clocks.ClockController import com.android.wallpaper.R import com.android.wallpaper.picker.FixedWidthDisplayRatioFrameLayout import java.lang.Float.max class ClockCarouselView( context: Context, attrs: AttributeSet, ) : FrameLayout( context, attrs, ) { val carousel: Carousel private val motionLayout: MotionLayout private lateinit var adapter: ClockCarouselAdapter private lateinit var clockViewFactory: ClockViewFactory private var toCenterClockController: ClockController? = null private var offCenterClockController: ClockController? = null private var toCenterClockScaleView: View? = null private var offCenterClockScaleView: View? = null private var toCenterClockHostView: ClockHostView? = null private var offCenterClockHostView: ClockHostView? = null private var toCenterCardView: View? = null private var offCenterCardView: View? = null init { val clockCarousel = LayoutInflater.from(context).inflate(R.layout.clock_carousel, this) carousel = clockCarousel.requireViewById(R.id.carousel) motionLayout = clockCarousel.requireViewById(R.id.motion_container) motionLayout.contentDescription = context.getString(R.string.custom_clocks_label) } /** * Make sure to set [clockViewFactory] before calling any functions from [ClockCarouselView]. */ fun setClockViewFactory(factory: ClockViewFactory) { clockViewFactory = factory } // This function is for the custom accessibility action to trigger a transition to the next // carousel item. If the current item is the last item in the carousel, the next item // will be the first item. fun transitionToNext() { if (carousel.count != 0) { val index = (carousel.currentIndex + 1) % carousel.count carousel.jumpToIndex(index) // Explicitly called this since using transitionToIndex(index) leads to // race-condition between announcement of content description of the correct clock-face // and the selection of clock face itself adapter.onNewItem(index) } } // This function is for the custom accessibility action to trigger a transition to // the previous carousel item. If the current item is the first item in the carousel, // the previous item will be the last item. fun transitionToPrevious() { if (carousel.count != 0) { val index = (carousel.currentIndex + carousel.count - 1) % carousel.count carousel.jumpToIndex(index) // Explicitly called this since using transitionToIndex(index) leads to // race-condition between announcement of content description of the correct clock-face // and the selection of clock face itself adapter.onNewItem(index) } } fun scrollToNext() { if ( carousel.count <= 1 || (!carousel.isInfinite && carousel.currentIndex == carousel.count - 1) ) { // No need to scroll if the count is equal or less than 1 return } if (motionLayout.currentState == R.id.start) { motionLayout.transitionToState(R.id.next, TRANSITION_DURATION) } } fun scrollToPrevious() { if (carousel.count <= 1 || (!carousel.isInfinite && carousel.currentIndex == 0)) { // No need to scroll if the count is equal or less than 1 return } if (motionLayout.currentState == R.id.start) { motionLayout.transitionToState(R.id.previous, TRANSITION_DURATION) } } fun getContentDescription(index: Int): String { return adapter.getContentDescription(index, resources) } fun setUpClockCarouselView( clockSize: ClockSize, clocks: List<ClockCarouselItemViewModel>, onClockSelected: (clock: ClockCarouselItemViewModel) -> Unit, isTwoPaneAndSmallWidth: Boolean, ) { if (isTwoPaneAndSmallWidth) { overrideScreenPreviewWidth() } adapter = ClockCarouselAdapter(clockSize, clocks, clockViewFactory, onClockSelected) carousel.isInfinite = clocks.size >= MIN_CLOCKS_TO_ENABLE_INFINITE_CAROUSEL carousel.setAdapter(adapter) val indexOfSelectedClock = clocks .indexOfFirst { it.isSelected } // If not found, default to the first clock as selected: .takeIf { it != -1 } ?: 0 carousel.jumpToIndex(indexOfSelectedClock) motionLayout.setTransitionListener( object : MotionLayout.TransitionListener { override fun onTransitionStarted( motionLayout: MotionLayout?, startId: Int, endId: Int ) { if (motionLayout == null) { return } when (clockSize) { ClockSize.DYNAMIC -> prepareDynamicClockView(motionLayout, endId) ClockSize.SMALL -> prepareSmallClockView(motionLayout, endId) } prepareCardView(motionLayout, endId) setCarouselItemAnimationState(true) } override fun onTransitionChange( motionLayout: MotionLayout?, startId: Int, endId: Int, progress: Float, ) { when (clockSize) { ClockSize.DYNAMIC -> onDynamicClockViewTransition(progress) ClockSize.SMALL -> onSmallClockViewTransition(progress) } onCardViewTransition(progress) } override fun onTransitionCompleted(motionLayout: MotionLayout?, currentId: Int) { setCarouselItemAnimationState(currentId == R.id.start) } private fun prepareDynamicClockView(motionLayout: MotionLayout, endId: Int) { val scalingDownClockId = adapter.clocks[carousel.currentIndex].clockId val scalingUpIdx = if (endId == R.id.next) (carousel.currentIndex + 1) % adapter.count() else (carousel.currentIndex - 1 + adapter.count()) % adapter.count() val scalingUpClockId = adapter.clocks[scalingUpIdx].clockId offCenterClockController = clockViewFactory.getController(scalingDownClockId) toCenterClockController = clockViewFactory.getController(scalingUpClockId) offCenterClockScaleView = motionLayout.findViewById(R.id.clock_scale_view_2) toCenterClockScaleView = motionLayout.findViewById( if (endId == R.id.next) R.id.clock_scale_view_3 else R.id.clock_scale_view_1 ) } private fun prepareSmallClockView(motionLayout: MotionLayout, endId: Int) { offCenterClockHostView = motionLayout.findViewById(R.id.clock_host_view_2) toCenterClockHostView = motionLayout.findViewById( if (endId == R.id.next) R.id.clock_host_view_3 else R.id.clock_host_view_1 ) } private fun prepareCardView(motionLayout: MotionLayout, endId: Int) { offCenterCardView = motionLayout.findViewById(R.id.item_card_2) toCenterCardView = motionLayout.findViewById( if (endId == R.id.next) R.id.item_card_3 else R.id.item_card_1 ) } private fun onCardViewTransition(progress: Float) { offCenterCardView?.alpha = getShowingAlpha(progress) toCenterCardView?.alpha = getHidingAlpha(progress) } private fun onDynamicClockViewTransition(progress: Float) { offCenterClockController ?.largeClock ?.animations ?.onPickerCarouselSwiping(1 - progress) toCenterClockController ?.largeClock ?.animations ?.onPickerCarouselSwiping(progress) val scalingDownScale = getScalingDownScale(progress) val scalingUpScale = getScalingUpScale(progress) offCenterClockScaleView?.scaleX = scalingDownScale offCenterClockScaleView?.scaleY = scalingDownScale toCenterClockScaleView?.scaleX = scalingUpScale toCenterClockScaleView?.scaleY = scalingUpScale } private fun onSmallClockViewTransition(progress: Float) { val offCenterClockHostView = offCenterClockHostView ?: return val toCenterClockHostView = toCenterClockHostView ?: return val offCenterClockFrame = if (offCenterClockHostView.isNotEmpty()) { offCenterClockHostView[0] } else { null } ?: return val toCenterClockFrame = if (toCenterClockHostView.isNotEmpty()) { toCenterClockHostView[0] } else { null } ?: return offCenterClockHostView.doOnPreDraw { it.pivotX = progress * it.width / 2 + (1 - progress) * getCenteredHostViewPivotX(it) it.pivotY = progress * it.height / 2 } toCenterClockHostView.doOnPreDraw { it.pivotX = (1 - progress) * it.width / 2 + progress * getCenteredHostViewPivotX(it) it.pivotY = (1 - progress) * it.height / 2 } offCenterClockFrame.translationX = getTranslationDistance( offCenterClockHostView.width, offCenterClockFrame.width, offCenterClockFrame.left, ) * progress offCenterClockFrame.translationY = getTranslationDistance( offCenterClockHostView.height, offCenterClockFrame.height, offCenterClockFrame.top, ) * progress toCenterClockFrame.translationX = getTranslationDistance( toCenterClockHostView.width, toCenterClockFrame.width, toCenterClockFrame.left, ) * (1 - progress) toCenterClockFrame.translationY = getTranslationDistance( toCenterClockHostView.height, toCenterClockFrame.height, toCenterClockFrame.top, ) * (1 - progress) } private fun setCarouselItemAnimationState(isStart: Boolean) { when (clockSize) { ClockSize.DYNAMIC -> onDynamicClockViewTransition(if (isStart) 0f else 1f) ClockSize.SMALL -> onSmallClockViewTransition(if (isStart) 0f else 1f) } onCardViewTransition(if (isStart) 0f else 1f) } override fun onTransitionTrigger( motionLayout: MotionLayout?, triggerId: Int, positive: Boolean, progress: Float ) {} } ) } fun setSelectedClockIndex( index: Int, ) { // 1. setUpClockCarouselView() can possibly not be called before setSelectedClockIndex(). // We need to check if index out of bound. // 2. jumpToIndex() to the same position can cause the views unnecessarily populate again. // We only call jumpToIndex when the index is different from the current carousel. if (index < carousel.count && index != carousel.currentIndex) { carousel.jumpToIndex(index) } } fun setCarouselCardColor(color: Int) { itemViewIds.forEach { id -> val cardViewId = getClockCardViewId(id) cardViewId?.let { val cardView = motionLayout.requireViewById<View>(it) cardView.backgroundTintList = ColorStateList.valueOf(color) } } } private fun overrideScreenPreviewWidth() { val overrideWidth = context.resources.getDimensionPixelSize( R.dimen.screen_preview_width_for_2_pane_small_width ) itemViewIds.forEach { id -> val itemView = motionLayout.requireViewById<FrameLayout>(id) val itemViewLp = itemView.layoutParams itemViewLp.width = overrideWidth itemView.layoutParams = itemViewLp getClockScaleViewId(id)?.let { val scaleView = motionLayout.requireViewById<FixedWidthDisplayRatioFrameLayout>(it) val scaleViewLp = scaleView.layoutParams scaleViewLp.width = overrideWidth scaleView.layoutParams = scaleViewLp } } val previousConstaintSet = motionLayout.getConstraintSet(R.id.previous) val startConstaintSet = motionLayout.getConstraintSet(R.id.start) val nextConstaintSet = motionLayout.getConstraintSet(R.id.next) val constaintSetList = listOf<ConstraintSet>(previousConstaintSet, startConstaintSet, nextConstaintSet) constaintSetList.forEach { constraintSet -> itemViewIds.forEach { id -> constraintSet.getConstraint(id)?.let { constraint -> val layout = constraint.layout if ( constraint.layout.mWidth == context.resources.getDimensionPixelSize(R.dimen.screen_preview_width) ) { layout.mWidth = overrideWidth } if ( constraint.layout.widthMax == context.resources.getDimensionPixelSize(R.dimen.screen_preview_width) ) { layout.widthMax = overrideWidth } } } } } private class ClockCarouselAdapter( val clockSize: ClockSize, val clocks: List<ClockCarouselItemViewModel>, private val clockViewFactory: ClockViewFactory, private val onClockSelected: (clock: ClockCarouselItemViewModel) -> Unit ) : Carousel.Adapter { fun getContentDescription(index: Int, resources: Resources): String { return clocks[index].contentDescription } override fun count(): Int { return clocks.size } override fun populate(view: View?, index: Int) { val viewRoot = view as? ViewGroup ?: return val cardView = getClockCardViewId(viewRoot.id)?.let { viewRoot.findViewById(it) as? View } ?: return val clockScaleView = getClockScaleViewId(viewRoot.id)?.let { viewRoot.findViewById(it) as? View } ?: return val clockHostView = getClockHostViewId(viewRoot.id)?.let { viewRoot.findViewById(it) as? ClockHostView } ?: return val clockId = clocks[index].clockId // Add the clock view to the cloc host view clockHostView.removeAllViews() val clockView = when (clockSize) { ClockSize.DYNAMIC -> clockViewFactory.getLargeView(clockId) ClockSize.SMALL -> clockViewFactory.getSmallView(clockId) } // The clock view might still be attached to an existing parent. Detach before adding to // another parent. (clockView.parent as? ViewGroup)?.removeView(clockView) clockHostView.addView(clockView) val isMiddleView = isMiddleView(viewRoot.id) // Accessibility viewRoot.contentDescription = getContentDescription(index, view.resources) viewRoot.isSelected = isMiddleView when (clockSize) { ClockSize.DYNAMIC -> initializeDynamicClockView( isMiddleView, clockScaleView, clockId, clockHostView, ) ClockSize.SMALL -> initializeSmallClockView( isMiddleView, clockHostView, clockView, ) } cardView.alpha = if (isMiddleView) 0f else 1f } private fun initializeDynamicClockView( isMiddleView: Boolean, clockScaleView: View, clockId: String, clockHostView: ClockHostView, ) { clockHostView.doOnPreDraw { it.pivotX = it.width / 2F it.pivotY = it.height / 2F } if (isMiddleView) { clockScaleView.scaleX = 1f clockScaleView.scaleY = 1f clockViewFactory .getController(clockId) .largeClock .animations .onPickerCarouselSwiping(1F) } else { clockScaleView.scaleX = CLOCK_CAROUSEL_VIEW_SCALE clockScaleView.scaleY = CLOCK_CAROUSEL_VIEW_SCALE clockViewFactory .getController(clockId) .largeClock .animations .onPickerCarouselSwiping(0F) } } private fun initializeSmallClockView( isMiddleView: Boolean, clockHostView: ClockHostView, clockView: View, ) { clockHostView.doOnPreDraw { if (isMiddleView) { it.pivotX = getCenteredHostViewPivotX(it) it.pivotY = 0F clockView.translationX = 0F clockView.translationY = 0F } else { it.pivotX = it.width / 2F it.pivotY = it.height / 2F clockView.translationX = getTranslationDistance( clockHostView.width, clockView.width, clockView.left, ) clockView.translationY = getTranslationDistance( clockHostView.height, clockView.height, clockView.top, ) } } } override fun onNewItem(index: Int) { onClockSelected.invoke(clocks[index]) } } companion object { // The carousel needs to have at least 5 different clock faces to be infinite const val MIN_CLOCKS_TO_ENABLE_INFINITE_CAROUSEL = 5 const val CLOCK_CAROUSEL_VIEW_SCALE = 0.5f const val TRANSITION_DURATION = 250 val itemViewIds = listOf( R.id.item_view_0, R.id.item_view_1, R.id.item_view_2, R.id.item_view_3, R.id.item_view_4 ) fun getScalingUpScale(progress: Float) = CLOCK_CAROUSEL_VIEW_SCALE + progress * (1f - CLOCK_CAROUSEL_VIEW_SCALE) fun getScalingDownScale(progress: Float) = 1f - progress * (1f - CLOCK_CAROUSEL_VIEW_SCALE) // This makes the card only starts to reveal in the last quarter of the trip so // the card won't overlap the preview. fun getShowingAlpha(progress: Float) = max(progress - 0.75f, 0f) * 4 // This makes the card starts to hide in the first quarter of the trip so the // card won't overlap the preview. fun getHidingAlpha(progress: Float) = max(1f - progress * 4, 0f) fun getClockHostViewId(rootViewId: Int): Int? { return when (rootViewId) { R.id.item_view_0 -> R.id.clock_host_view_0 R.id.item_view_1 -> R.id.clock_host_view_1 R.id.item_view_2 -> R.id.clock_host_view_2 R.id.item_view_3 -> R.id.clock_host_view_3 R.id.item_view_4 -> R.id.clock_host_view_4 else -> null } } fun getClockScaleViewId(rootViewId: Int): Int? { return when (rootViewId) { R.id.item_view_0 -> R.id.clock_scale_view_0 R.id.item_view_1 -> R.id.clock_scale_view_1 R.id.item_view_2 -> R.id.clock_scale_view_2 R.id.item_view_3 -> R.id.clock_scale_view_3 R.id.item_view_4 -> R.id.clock_scale_view_4 else -> null } } fun getClockCardViewId(rootViewId: Int): Int? { return when (rootViewId) { R.id.item_view_0 -> R.id.item_card_0 R.id.item_view_1 -> R.id.item_card_1 R.id.item_view_2 -> R.id.item_card_2 R.id.item_view_3 -> R.id.item_card_3 R.id.item_view_4 -> R.id.item_card_4 else -> null } } fun isMiddleView(rootViewId: Int): Boolean { return rootViewId == R.id.item_view_2 } fun getCenteredHostViewPivotX(hostView: View): Float { return if (hostView.isLayoutRtl) hostView.width.toFloat() else 0F } private fun getTranslationDistance( hostLength: Int, frameLength: Int, edgeDimen: Int, ): Float { return ((hostLength - frameLength) / 2 - edgeDimen).toFloat() } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/view/ClockCarouselView.kt
568861811
/* * Copyright (C) 2023 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.customization.picker.clock.ui.view import android.content.pm.ActivityInfo import android.content.res.Resources import android.graphics.Rect import android.graphics.drawable.Drawable import android.graphics.drawable.DrawableWrapper import android.graphics.drawable.InsetDrawable /** * [DrawableWrapper] to use in the progress of brightness slider. * * This drawable is used to change the bounds of the enclosed drawable depending on the level to * simulate a sliding progress, instead of using clipping or scaling. That way, the shape of the * edges is maintained. * * Meant to be used with a rounded ends background, it will also prevent deformation when the slider * is meant to be smaller than the rounded corner. The background should have rounded corners that * are half of the height. * * This class also assumes that a "thumb" icon exists within the end's edge of the progress * drawable, and the slider's width, when interacted on, if offset by half the size of the thumb * icon which puts the icon directly underneath the user's finger. */ class SaturationProgressDrawable @JvmOverloads constructor(drawable: Drawable? = null) : InsetDrawable(drawable, 0) { companion object { private const val MAX_LEVEL = 10000 } override fun onLayoutDirectionChanged(layoutDirection: Int): Boolean { onLevelChange(level) return super.onLayoutDirectionChanged(layoutDirection) } override fun onBoundsChange(bounds: Rect) { super.onBoundsChange(bounds) onLevelChange(level) } override fun onLevelChange(level: Int): Boolean { val drawableBounds = drawable?.bounds!! // The thumb offset shifts the sun icon directly under the user's thumb val thumbOffset = bounds.height() / 2 val width = bounds.width() * level / MAX_LEVEL + thumbOffset // On 0, the width is bounds.height (a circle), and on MAX_LEVEL, the width is bounds.width // TODO (b/268541542) Test if RTL devices also works for the slider drawable?.setBounds( bounds.left, drawableBounds.top, width.coerceAtMost(bounds.width()).coerceAtLeast(bounds.height()), drawableBounds.bottom ) return super.onLevelChange(level) } override fun getConstantState(): ConstantState { // This should not be null as it was created with a state in the constructor. return RoundedCornerState(super.getConstantState()!!) } override fun getChangingConfigurations(): Int { return super.getChangingConfigurations() or ActivityInfo.CONFIG_DENSITY } override fun canApplyTheme(): Boolean { return (drawable?.canApplyTheme() ?: false) || super.canApplyTheme() } private class RoundedCornerState(private val wrappedState: ConstantState) : ConstantState() { override fun newDrawable(): Drawable { return newDrawable(null, null) } override fun newDrawable(res: Resources?, theme: Resources.Theme?): Drawable { val wrapper = wrappedState.newDrawable(res, theme) as DrawableWrapper return SaturationProgressDrawable(wrapper.drawable) } override fun getChangingConfigurations(): Int { return wrappedState.changingConfigurations } override fun canApplyTheme(): Boolean { return true } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/view/SaturationProgressDrawable.kt
625231808
/* * Copyright (C) 2023 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.customization.picker.clock.ui.view import android.view.View import androidx.annotation.ColorInt import androidx.lifecycle.LifecycleOwner import com.android.systemui.plugins.clocks.ClockController interface ClockViewFactory { fun getController(clockId: String): ClockController /** * Reset the large view to its initial state when getting the view. This is because some view * configs, e.g. animation state, might change during the reuse of the clock view in the app. */ fun getLargeView(clockId: String): View /** * Reset the small view to its initial state when getting the view. This is because some view * configs, e.g. translation X, might change during the reuse of the clock view in the app. */ fun getSmallView(clockId: String): View fun updateColorForAllClocks(@ColorInt seedColor: Int?) fun updateColor(clockId: String, @ColorInt seedColor: Int?) fun updateRegionDarkness() fun updateTimeFormat(clockId: String) fun registerTimeTicker(owner: LifecycleOwner) fun onDestroy() fun unregisterTimeTicker(owner: LifecycleOwner) }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/view/ClockViewFactory.kt
3742099646
/* * Copyright (C) 2022 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.customization.picker.clock.ui.view import android.content.Context import android.util.AttributeSet import com.android.wallpaper.picker.SectionView /** The [SectionView] for app clock. */ class ClockSectionView(context: Context?, attrs: AttributeSet?) : SectionView(context, attrs)
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/view/ClockSectionView.kt
616575849
/* * Copyright (C) 2023 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.customization.picker.clock.ui.view import android.app.WallpaperColors import android.app.WallpaperManager import android.content.Context import android.content.res.Resources import android.graphics.Point import android.graphics.Rect import android.view.View import android.widget.FrameLayout import androidx.annotation.ColorInt import androidx.core.text.util.LocalePreferences import androidx.lifecycle.LifecycleOwner import com.android.systemui.plugins.clocks.ClockController import com.android.systemui.plugins.clocks.WeatherData import com.android.systemui.shared.clocks.ClockRegistry import com.android.wallpaper.R import com.android.wallpaper.util.TimeUtils.TimeTicker import java.util.concurrent.ConcurrentHashMap /** * Provide reusable clock view and related util functions. * * @property screenSize The Activity or Fragment's window size. */ class ClockViewFactoryImpl( private val appContext: Context, val screenSize: Point, private val wallpaperManager: WallpaperManager, private val registry: ClockRegistry, ) : ClockViewFactory { private val resources = appContext.resources private val timeTickListeners: ConcurrentHashMap<Int, TimeTicker> = ConcurrentHashMap() private val clockControllers: HashMap<String, ClockController> = HashMap() private val smallClockFrames: HashMap<String, FrameLayout> = HashMap() override fun getController(clockId: String): ClockController { return clockControllers[clockId] ?: initClockController(clockId).also { clockControllers[clockId] = it } } /** * Reset the large view to its initial state when getting the view. This is because some view * configs, e.g. animation state, might change during the reuse of the clock view in the app. */ override fun getLargeView(clockId: String): View { return getController(clockId).largeClock.let { it.animations.onPickerCarouselSwiping(1F) it.view } } /** * Reset the small view to its initial state when getting the view. This is because some view * configs, e.g. translation X, might change during the reuse of the clock view in the app. */ override fun getSmallView(clockId: String): View { val smallClockFrame = smallClockFrames[clockId] ?: createSmallClockFrame().also { it.addView(getController(clockId).smallClock.view) smallClockFrames[clockId] = it } smallClockFrame.translationX = 0F smallClockFrame.translationY = 0F return smallClockFrame } private fun createSmallClockFrame(): FrameLayout { val smallClockFrame = FrameLayout(appContext) val layoutParams = FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, resources.getDimensionPixelSize(R.dimen.small_clock_height) ) layoutParams.topMargin = getSmallClockTopMargin() layoutParams.marginStart = getSmallClockStartPadding() smallClockFrame.layoutParams = layoutParams smallClockFrame.clipChildren = false return smallClockFrame } private fun getSmallClockTopMargin() = getStatusBarHeight(appContext.resources) + appContext.resources.getDimensionPixelSize(R.dimen.small_clock_padding_top) private fun getSmallClockStartPadding() = appContext.resources.getDimensionPixelSize(R.dimen.clock_padding_start) override fun updateColorForAllClocks(@ColorInt seedColor: Int?) { clockControllers.values.forEach { it.events.onSeedColorChanged(seedColor = seedColor) } } override fun updateColor(clockId: String, @ColorInt seedColor: Int?) { clockControllers[clockId]?.events?.onSeedColorChanged(seedColor) } override fun updateRegionDarkness() { val isRegionDark = isLockscreenWallpaperDark() clockControllers.values.forEach { it.largeClock.events.onRegionDarknessChanged(isRegionDark) it.smallClock.events.onRegionDarknessChanged(isRegionDark) } } private fun isLockscreenWallpaperDark(): Boolean { val colors = wallpaperManager.getWallpaperColors(WallpaperManager.FLAG_LOCK) return (colors?.colorHints?.and(WallpaperColors.HINT_SUPPORTS_DARK_TEXT)) == 0 } override fun updateTimeFormat(clockId: String) { getController(clockId) .events .onTimeFormatChanged(android.text.format.DateFormat.is24HourFormat(appContext)) } override fun registerTimeTicker(owner: LifecycleOwner) { val hashCode = owner.hashCode() if (timeTickListeners.keys.contains(hashCode)) { return } timeTickListeners[hashCode] = TimeTicker.registerNewReceiver(appContext) { onTimeTick() } } override fun onDestroy() { timeTickListeners.forEach { (_, timeTicker) -> appContext.unregisterReceiver(timeTicker) } timeTickListeners.clear() clockControllers.clear() smallClockFrames.clear() } private fun onTimeTick() { clockControllers.values.forEach { it.largeClock.events.onTimeTick() it.smallClock.events.onTimeTick() } } override fun unregisterTimeTicker(owner: LifecycleOwner) { val hashCode = owner.hashCode() timeTickListeners[hashCode]?.let { appContext.unregisterReceiver(it) timeTickListeners.remove(hashCode) } } private fun initClockController(clockId: String): ClockController { val controller = registry.createExampleClock(clockId).also { it?.initialize(resources, 0f, 0f) } checkNotNull(controller) val isWallpaperDark = isLockscreenWallpaperDark() // Initialize large clock controller.largeClock.events.onRegionDarknessChanged(isWallpaperDark) controller.largeClock.events.onFontSettingChanged( resources.getDimensionPixelSize(R.dimen.large_clock_text_size).toFloat() ) controller.largeClock.events.onTargetRegionChanged(getLargeClockRegion()) // Initialize small clock controller.smallClock.events.onRegionDarknessChanged(isWallpaperDark) controller.smallClock.events.onFontSettingChanged( resources.getDimensionPixelSize(R.dimen.small_clock_text_size).toFloat() ) controller.smallClock.events.onTargetRegionChanged(getSmallClockRegion()) // Use placeholder for weather clock preview in picker. // Use locale default temp unit since assistant default is not available in this context. val useCelsius = LocalePreferences.getTemperatureUnit() == LocalePreferences.TemperatureUnit.CELSIUS controller.events.onWeatherDataChanged( WeatherData( description = DESCRIPTION_PLACEHODLER, state = WEATHERICON_PLACEHOLDER, temperature = if (useCelsius) TEMPERATURE_CELSIUS_PLACEHOLDER else TEMPERATURE_FAHRENHEIT_PLACEHOLDER, useCelsius = useCelsius, ) ) return controller } /** * Simulate the function of getLargeClockRegion in KeyguardClockSwitch so that we can get a * proper region corresponding to lock screen in picker and for onTargetRegionChanged to scale * and position the clock view */ private fun getLargeClockRegion(): Rect { val largeClockTopMargin = resources.getDimensionPixelSize(R.dimen.keyguard_large_clock_top_margin) val targetHeight = resources.getDimensionPixelSize(R.dimen.large_clock_text_size) * 2 val top = (screenSize.y / 2 - targetHeight / 2 + largeClockTopMargin / 2) return Rect(0, top, screenSize.x, (top + targetHeight)) } /** * Simulate the function of getSmallClockRegion in KeyguardClockSwitch so that we can get a * proper region corresponding to lock screen in picker and for onTargetRegionChanged to scale * and position the clock view */ private fun getSmallClockRegion(): Rect { val topMargin = getSmallClockTopMargin() val targetHeight = resources.getDimensionPixelSize(R.dimen.small_clock_height) return Rect(getSmallClockStartPadding(), topMargin, screenSize.x, topMargin + targetHeight) } companion object { const val DESCRIPTION_PLACEHODLER = "" const val TEMPERATURE_FAHRENHEIT_PLACEHOLDER = 58 const val TEMPERATURE_CELSIUS_PLACEHOLDER = 21 val WEATHERICON_PLACEHOLDER = WeatherData.WeatherStateIcon.MOSTLY_SUNNY const val USE_CELSIUS_PLACEHODLER = false private fun getStatusBarHeight(resource: Resources): Int { var result = 0 val resourceId: Int = resource.getIdentifier("status_bar_height", "dimen", "android") if (resourceId > 0) { result = resource.getDimensionPixelSize(resourceId) } return result } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/view/ClockViewFactoryImpl.kt
2983701961
package com.android.customization.picker.clock.ui.view import android.content.Context import android.util.AttributeSet import android.view.View import android.view.View.MeasureSpec.EXACTLY import android.widget.FrameLayout import com.android.wallpaper.util.ScreenSizeCalculator /** * The parent view for each clock view in picker carousel This view will give a container with the * same size of lockscreen to layout clock and scale down it to the size in picker carousel * according to ratio of preview to LS */ class ClockHostView( context: Context, attrs: AttributeSet?, ) : FrameLayout(context, attrs) { private var previewRatio: Float = 1F set(value) { if (field != value) { field = value scaleX = previewRatio scaleY = previewRatio invalidate() } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val screenSize = ScreenSizeCalculator.getInstance().getScreenSize(display) previewRatio = measuredWidth / screenSize.x.toFloat() } /** * In clock picker, we want to clock layout and render at lockscreen size and scale down so that * the preview in clock carousel will be the same as lockscreen */ override fun measureChildWithMargins( child: View?, parentWidthMeasureSpec: Int, widthUsed: Int, parentHeightMeasureSpec: Int, heightUsed: Int ) { val screenSize = ScreenSizeCalculator.getInstance().getScreenSize(display) super.measureChildWithMargins( child, MeasureSpec.makeMeasureSpec(screenSize.x, EXACTLY), widthUsed, MeasureSpec.makeMeasureSpec(screenSize.y, EXACTLY), heightUsed ) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/ui/view/ClockHostView.kt
3177050026
/* * Copyright (C) 2023 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.customization.picker.clock.shared import android.stats.style.StyleEnums import com.android.customization.module.logging.ThemesUserEventLogger enum class ClockSize { DYNAMIC, SMALL, } @ThemesUserEventLogger.ClockSize fun ClockSize.toClockSizeForLogging(): Int { return when (this) { ClockSize.DYNAMIC -> StyleEnums.CLOCK_SIZE_DYNAMIC ClockSize.SMALL -> StyleEnums.CLOCK_SIZE_SMALL } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/shared/ClockSize.kt
4253822811
/* * Copyright (C) 2023 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.customization.picker.clock.shared.model import androidx.annotation.ColorInt import androidx.annotation.IntRange import com.android.customization.picker.clock.shared.ClockSize /** Models application state for a clock option in a picker experience. */ data class ClockSnapshotModel( val clockId: String? = null, val clockSize: ClockSize? = null, val selectedColorId: String? = null, @IntRange(from = 0, to = 100) val colorToneProgress: Int? = null, @ColorInt val seedColor: Int? = null, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/shared/model/ClockSnapshotModel.kt
828742242
/* * Copyright (C) 2023 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.customization.picker.clock.shared.model import androidx.annotation.ColorInt import androidx.annotation.IntRange /** Model for clock metadata. */ data class ClockMetadataModel( val clockId: String, val isSelected: Boolean, val selectedColorId: String?, @IntRange(from = 0, to = 100) val colorToneProgress: Int, @ColorInt val seedColor: Int?, ) { companion object { const val DEFAULT_COLOR_TONE_PROGRESS = 75 } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/shared/model/ClockMetadataModel.kt
3352219657
/* * Copyright (C) 2023 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.customization.picker.clock.data.repository import android.provider.Settings import androidx.annotation.ColorInt import androidx.annotation.IntRange import com.android.customization.picker.clock.shared.ClockSize import com.android.customization.picker.clock.shared.model.ClockMetadataModel import com.android.systemui.plugins.clocks.ClockMetadata import com.android.systemui.shared.clocks.ClockRegistry import com.android.wallpaper.settings.data.repository.SecureSettingsRepository import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.shareIn import org.json.JSONObject /** Implementation of [ClockPickerRepository], using [ClockRegistry]. */ class ClockPickerRepositoryImpl( private val secureSettingsRepository: SecureSettingsRepository, private val registry: ClockRegistry, scope: CoroutineScope, mainDispatcher: CoroutineDispatcher, ) : ClockPickerRepository { @OptIn(ExperimentalCoroutinesApi::class) override val allClocks: Flow<List<ClockMetadataModel>> = callbackFlow { fun send() { val activeClockId = registry.activeClockId val allClocks = registry.getClocks().map { it.toModel(isSelected = it.clockId == activeClockId) } trySend(allClocks) } val listener = object : ClockRegistry.ClockChangeListener { override fun onAvailableClocksChanged() { send() } } registry.registerClockChangeListener(listener) send() awaitClose { registry.unregisterClockChangeListener(listener) } } .flowOn(mainDispatcher) .mapLatest { allClocks -> // Loading list of clock plugins can cause many consecutive calls of // onAvailableClocksChanged(). We only care about the final fully-initiated clock // list. Delay to avoid unnecessary too many emits. delay(100) allClocks } /** The currently-selected clock. This also emits the clock color information. */ override val selectedClock: Flow<ClockMetadataModel> = callbackFlow { fun send() { val activeClockId = registry.activeClockId val metadata = registry.settings?.metadata val model = registry .getClocks() .find { clockMetadata -> clockMetadata.clockId == activeClockId } ?.toModel( isSelected = true, selectedColorId = metadata?.getSelectedColorId(), colorTone = metadata?.getColorTone() ?: ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS, seedColor = registry.seedColor ) trySend(model) } val listener = object : ClockRegistry.ClockChangeListener { override fun onCurrentClockChanged() { send() } override fun onAvailableClocksChanged() { send() } } registry.registerClockChangeListener(listener) send() awaitClose { registry.unregisterClockChangeListener(listener) } } .flowOn(mainDispatcher) .mapNotNull { it } override suspend fun setSelectedClock(clockId: String) { registry.mutateSetting { oldSettings -> val newSettings = oldSettings.copy(clockId = clockId) newSettings.metadata = oldSettings.metadata newSettings } } override suspend fun setClockColor( selectedColorId: String?, @IntRange(from = 0, to = 100) colorToneProgress: Int, @ColorInt seedColor: Int?, ) { registry.mutateSetting { oldSettings -> val newSettings = oldSettings.copy(seedColor = seedColor) newSettings.metadata = oldSettings.metadata .put(KEY_METADATA_SELECTED_COLOR_ID, selectedColorId) .put(KEY_METADATA_COLOR_TONE_PROGRESS, colorToneProgress) newSettings } } override val selectedClockSize: SharedFlow<ClockSize> = secureSettingsRepository .intSetting( name = Settings.Secure.LOCKSCREEN_USE_DOUBLE_LINE_CLOCK, defaultValue = DEFAULT_CLOCK_SIZE, ) .map { setting -> setting == 1 } .map { isDynamic -> if (isDynamic) ClockSize.DYNAMIC else ClockSize.SMALL } .distinctUntilChanged() .shareIn( scope = scope, started = SharingStarted.Eagerly, replay = 1, ) override suspend fun setClockSize(size: ClockSize) { secureSettingsRepository.set( name = Settings.Secure.LOCKSCREEN_USE_DOUBLE_LINE_CLOCK, value = if (size == ClockSize.DYNAMIC) 1 else 0, ) } private fun JSONObject.getSelectedColorId(): String? { return if (this.isNull(KEY_METADATA_SELECTED_COLOR_ID)) { null } else { this.getString(KEY_METADATA_SELECTED_COLOR_ID) } } private fun JSONObject.getColorTone(): Int { return this.optInt( KEY_METADATA_COLOR_TONE_PROGRESS, ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS ) } /** By default, [ClockMetadataModel] has no color information unless specified. */ private fun ClockMetadata.toModel( isSelected: Boolean, selectedColorId: String? = null, @IntRange(from = 0, to = 100) colorTone: Int = 0, @ColorInt seedColor: Int? = null, ): ClockMetadataModel { return ClockMetadataModel( clockId = clockId, isSelected = isSelected, selectedColorId = selectedColorId, colorToneProgress = colorTone, seedColor = seedColor, ) } companion object { // The selected color in the color option list private const val KEY_METADATA_SELECTED_COLOR_ID = "metadataSelectedColorId" // The color tone to apply to the selected color private const val KEY_METADATA_COLOR_TONE_PROGRESS = "metadataColorToneProgress" // The default clock size is 1, which means dynamic private const val DEFAULT_CLOCK_SIZE = 1 } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/data/repository/ClockPickerRepositoryImpl.kt
2185807337
/* * Copyright (C) 2023 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.customization.picker.clock.data.repository import androidx.annotation.ColorInt import androidx.annotation.IntRange import com.android.customization.picker.clock.shared.ClockSize import com.android.customization.picker.clock.shared.model.ClockMetadataModel import kotlinx.coroutines.flow.Flow /** * Repository for accessing application clock settings, as well as selecting and configuring custom * clocks. */ interface ClockPickerRepository { val allClocks: Flow<List<ClockMetadataModel>> val selectedClock: Flow<ClockMetadataModel> val selectedClockSize: Flow<ClockSize> suspend fun setSelectedClock(clockId: String) /** * Set clock color to the settings. * * @param selectedColor selected color in the color option list. * @param colorToneProgress color tone from 0 to 100 to apply to the selected color * @param seedColor the actual clock color after blending the selected color and color tone */ suspend fun setClockColor( selectedColorId: String?, @IntRange(from = 0, to = 100) colorToneProgress: Int, @ColorInt seedColor: Int?, ) suspend fun setClockSize(size: ClockSize) }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/data/repository/ClockPickerRepository.kt
621058990
/* * Copyright (C) 2023 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.customization.picker.clock.data.repository import android.app.NotificationManager import android.content.ComponentName import android.content.Context import android.view.LayoutInflater import com.android.systemui.plugins.Plugin import com.android.systemui.plugins.PluginManager import com.android.systemui.shared.clocks.ClockRegistry import com.android.systemui.shared.clocks.DefaultClockProvider import com.android.systemui.shared.plugins.PluginActionManager import com.android.systemui.shared.plugins.PluginEnabler import com.android.systemui.shared.plugins.PluginInstance import com.android.systemui.shared.plugins.PluginManagerImpl import com.android.systemui.shared.plugins.PluginPrefs import com.android.systemui.shared.system.UncaughtExceptionPreHandlerManager_Factory import com.android.wallpaper.module.InjectorProvider import java.util.concurrent.Executors import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope /** * Provide the [ClockRegistry] singleton. Note that we need to make sure that the [PluginManager] * needs to be connected before [ClockRegistry] is ready to use. */ class ClockRegistryProvider( private val context: Context, private val coroutineScope: CoroutineScope, private val mainDispatcher: CoroutineDispatcher, private val backgroundDispatcher: CoroutineDispatcher, ) { private val clockRegistry: ClockRegistry by lazy { ClockRegistry( context, createPluginManager(context), coroutineScope, mainDispatcher, backgroundDispatcher, isEnabled = true, handleAllUsers = false, DefaultClockProvider(context, LayoutInflater.from(context), context.resources), keepAllLoaded = true, subTag = "Picker", isTransitClockEnabled = InjectorProvider.getInjector().getFlags().isTransitClockEnabled(context) ) } init { // Listeners in ClockRegistry get cleaned up when app ended clockRegistry.registerListeners() } fun get() = clockRegistry private fun createPluginManager(context: Context): PluginManager { val privilegedPlugins = listOf<String>() val isDebugDevice = true val instanceFactory = PluginInstance.Factory( this::class.java.classLoader, PluginInstance.InstanceFactory<Plugin>(), PluginInstance.VersionCheckerImpl(), privilegedPlugins, isDebugDevice, ) /* * let SystemUI handle plugin, in this class assume plugins are enabled */ val pluginEnabler = object : PluginEnabler { override fun setEnabled(component: ComponentName) = Unit override fun setDisabled( component: ComponentName, @PluginEnabler.DisableReason reason: Int ) = Unit override fun isEnabled(component: ComponentName): Boolean { return true } @PluginEnabler.DisableReason override fun getDisableReason(componentName: ComponentName): Int { return PluginEnabler.ENABLED } } val pluginActionManager = PluginActionManager.Factory( context, context.packageManager, context.mainExecutor, Executors.newSingleThreadExecutor(), context.getSystemService(NotificationManager::class.java), pluginEnabler, privilegedPlugins, instanceFactory, ) return PluginManagerImpl( context, pluginActionManager, isDebugDevice, UncaughtExceptionPreHandlerManager_Factory.create().get(), pluginEnabler, PluginPrefs(context), listOf(), ) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/data/repository/ClockRegistryProvider.kt
3987378594
/* * Copyright (C) 2023 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.customization.picker.clock.domain.interactor import androidx.annotation.ColorInt import androidx.annotation.IntRange import com.android.customization.picker.clock.data.repository.ClockPickerRepository import com.android.customization.picker.clock.shared.ClockSize import com.android.customization.picker.clock.shared.model.ClockMetadataModel import com.android.customization.picker.clock.shared.model.ClockSnapshotModel import javax.inject.Provider import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.map /** * Interactor for accessing application clock settings, as well as selecting and configuring custom * clocks. */ class ClockPickerInteractor( private val repository: ClockPickerRepository, private val snapshotRestorer: Provider<ClockPickerSnapshotRestorer>, ) { val allClocks: Flow<List<ClockMetadataModel>> = repository.allClocks val selectedClockId: Flow<String> = repository.selectedClock.map { clock -> clock.clockId }.distinctUntilChanged() val selectedColorId: Flow<String?> = repository.selectedClock.map { clock -> clock.selectedColorId }.distinctUntilChanged() val colorToneProgress: Flow<Int> = repository.selectedClock.map { clock -> clock.colorToneProgress } val seedColor: Flow<Int?> = repository.selectedClock.map { clock -> clock.seedColor } val selectedClockSize: Flow<ClockSize> = repository.selectedClockSize suspend fun setSelectedClock(clockId: String) { // Use the [clockId] to override saved clock id, since it might not be updated in time setClockOption(ClockSnapshotModel(clockId = clockId)) } suspend fun setClockColor( selectedColorId: String?, @IntRange(from = 0, to = 100) colorToneProgress: Int, @ColorInt seedColor: Int?, ) { // Use the color to override saved color, since it might not be updated in time setClockOption( ClockSnapshotModel( selectedColorId = selectedColorId, colorToneProgress = colorToneProgress, seedColor = seedColor, ) ) } suspend fun setClockSize(size: ClockSize) { // Use the [ClockSize] to override saved clock size, since it might not be updated in time setClockOption(ClockSnapshotModel(clockSize = size)) } suspend fun setClockOption(clockSnapshotModel: ClockSnapshotModel) { // [ClockCarouselViewModel] is monitoring the [ClockPickerInteractor.setSelectedClock] job, // so it needs to finish last. storeCurrentClockOption(clockSnapshotModel) clockSnapshotModel.clockSize?.let { repository.setClockSize(it) } clockSnapshotModel.colorToneProgress?.let { repository.setClockColor( selectedColorId = clockSnapshotModel.selectedColorId, colorToneProgress = clockSnapshotModel.colorToneProgress, seedColor = clockSnapshotModel.seedColor ) } clockSnapshotModel.clockId?.let { repository.setSelectedClock(it) } } /** * Gets the [ClockSnapshotModel] from the storage and override with [latestOption]. * * The storage might be in the middle of a write, and not reflecting the user's options, always * pass in a [ClockSnapshotModel] if we know it's the latest option from a user's point of view. * * [selectedColorId] and [seedColor] have null state collide with nullable type, but we know * they are presented whenever there's a [colorToneProgress]. */ suspend fun getCurrentClockToRestore(latestOption: ClockSnapshotModel? = null) = ClockSnapshotModel( clockId = latestOption?.clockId ?: selectedClockId.firstOrNull(), clockSize = latestOption?.clockSize ?: selectedClockSize.firstOrNull(), colorToneProgress = latestOption?.colorToneProgress ?: colorToneProgress.firstOrNull(), selectedColorId = latestOption?.colorToneProgress?.let { latestOption.selectedColorId } ?: selectedColorId.firstOrNull(), seedColor = latestOption?.colorToneProgress?.let { latestOption.seedColor } ?: seedColor.firstOrNull(), ) private suspend fun storeCurrentClockOption(clockSnapshotModel: ClockSnapshotModel) { val option = getCurrentClockToRestore(clockSnapshotModel) snapshotRestorer.get().storeSnapshot(option) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/domain/interactor/ClockPickerInteractor.kt
1304064541
/* * Copyright (C) 2023 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.customization.picker.clock.domain.interactor import android.text.TextUtils import android.util.Log import com.android.customization.picker.clock.shared.model.ClockSnapshotModel import com.android.wallpaper.picker.undo.domain.interactor.SnapshotRestorer import com.android.wallpaper.picker.undo.domain.interactor.SnapshotStore import com.android.wallpaper.picker.undo.shared.model.RestorableSnapshot /** Handles state restoration for clocks. */ class ClockPickerSnapshotRestorer(private val interactor: ClockPickerInteractor) : SnapshotRestorer { private var snapshotStore: SnapshotStore = SnapshotStore.NOOP private var originalOption: ClockSnapshotModel? = null override suspend fun setUpSnapshotRestorer( store: SnapshotStore, ): RestorableSnapshot { snapshotStore = store originalOption = interactor.getCurrentClockToRestore() return snapshot(originalOption) } override suspend fun restoreToSnapshot(snapshot: RestorableSnapshot) { originalOption?.let { optionToRestore -> if ( TextUtils.isEmpty(optionToRestore.clockId) || optionToRestore.clockId != snapshot.args[KEY_CLOCK_ID] || optionToRestore.clockSize?.toString() != snapshot.args[KEY_CLOCK_SIZE] || optionToRestore.colorToneProgress?.toString() != snapshot.args[KEY_COLOR_TONE_PROGRESS] || optionToRestore.seedColor?.toString() != snapshot.args[KEY_SEED_COLOR] || optionToRestore.selectedColorId != snapshot.args[KEY_COLOR_ID] ) { Log.wtf( TAG, """ Original clock option does not match snapshot option to restore to. The | current implementation doesn't support undo, only a reset back to the | original clock option.""" .trimMargin(), ) } interactor.setClockOption(optionToRestore) } } fun storeSnapshot(clockSnapshotModel: ClockSnapshotModel) { snapshotStore.store(snapshot(clockSnapshotModel)) } private fun snapshot(clockSnapshotModel: ClockSnapshotModel? = null): RestorableSnapshot { val options = if (clockSnapshotModel == null) emptyMap() else buildMap { clockSnapshotModel.clockId?.let { put(KEY_CLOCK_ID, it) } clockSnapshotModel.clockSize?.let { put(KEY_CLOCK_SIZE, it.toString()) } clockSnapshotModel.selectedColorId?.let { put(KEY_COLOR_ID, it) } clockSnapshotModel.colorToneProgress?.let { put(KEY_COLOR_TONE_PROGRESS, it.toString()) } clockSnapshotModel.seedColor?.let { put(KEY_SEED_COLOR, it.toString()) } } return RestorableSnapshot(options) } companion object { private const val TAG = "ClockPickerSnapshotRestorer" private const val KEY_CLOCK_ID = "clock_id" private const val KEY_CLOCK_SIZE = "clock_size" private const val KEY_COLOR_ID = "color_id" private const val KEY_COLOR_TONE_PROGRESS = "color_tone_progress" private const val KEY_SEED_COLOR = "seed_color" } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/clock/domain/interactor/ClockPickerSnapshotRestorer.kt
4237935560
/* * Copyright (C) 2023 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.customization.picker.grid.ui.viewmodel data class GridIconViewModel( val columns: Int, val rows: Int, val path: String, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/grid/ui/viewmodel/GridIconViewModel.kt
2711975924
/* * Copyright (C) 2023 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.customization.picker.grid.ui.viewmodel import android.annotation.SuppressLint import android.content.Context import android.content.res.Resources import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.android.customization.model.ResourceConstants import com.android.customization.picker.grid.domain.interactor.GridInteractor import com.android.customization.picker.grid.shared.model.GridOptionItemsModel import com.android.wallpaper.picker.common.text.ui.viewmodel.Text import com.android.wallpaper.picker.option.ui.viewmodel.OptionItemViewModel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch class GridScreenViewModel( context: Context, private val interactor: GridInteractor, ) : ViewModel() { @SuppressLint("StaticFieldLeak") // We're not leaking this context as it is the app context. private val applicationContext = context.applicationContext val optionItems: Flow<List<OptionItemViewModel<GridIconViewModel>>> = interactor.options.map { model -> toViewModel(model) } private fun toViewModel( model: GridOptionItemsModel, ): List<OptionItemViewModel<GridIconViewModel>> { val iconShapePath = applicationContext.resources.getString( Resources.getSystem() .getIdentifier( ResourceConstants.CONFIG_ICON_MASK, "string", ResourceConstants.ANDROID_PACKAGE, ) ) return when (model) { is GridOptionItemsModel.Loaded -> model.options.map { option -> val text = Text.Loaded(option.name) OptionItemViewModel<GridIconViewModel>( key = MutableStateFlow("${option.cols}x${option.rows}") as StateFlow<String>, payload = GridIconViewModel( columns = option.cols, rows = option.rows, path = iconShapePath, ), text = text, isSelected = option.isSelected, onClicked = option.isSelected.map { isSelected -> if (!isSelected) { { viewModelScope.launch { option.onSelected() } } } else { null } }, ) } is GridOptionItemsModel.Error -> emptyList() } } class Factory( context: Context, private val interactor: GridInteractor, ) : ViewModelProvider.Factory { private val applicationContext = context.applicationContext @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return GridScreenViewModel( context = applicationContext, interactor = interactor, ) as T } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/grid/ui/viewmodel/GridScreenViewModel.kt
454410313
package com.android.customization.picker.grid.ui.binder import android.widget.ImageView import com.android.customization.picker.grid.ui.viewmodel.GridIconViewModel import com.android.customization.widget.GridTileDrawable object GridIconViewBinder { fun bind(view: ImageView, viewModel: GridIconViewModel) { view.setImageDrawable( GridTileDrawable( viewModel.columns, viewModel.rows, viewModel.path, ) ) } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/grid/ui/binder/GridIconViewBinder.kt
3940637723
/* * Copyright (C) 2023 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.customization.picker.grid.ui.binder import android.view.View import android.widget.Button import android.widget.ImageView import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.customization.picker.common.ui.view.ItemSpacing import com.android.customization.picker.grid.ui.viewmodel.GridIconViewModel import com.android.customization.picker.grid.ui.viewmodel.GridScreenViewModel import com.android.wallpaper.R import com.android.wallpaper.picker.option.ui.adapter.OptionItemAdapter import com.android.wallpaper.picker.option.ui.binder.OptionItemBinder import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.launch object GridScreenBinder { fun bind( view: View, viewModel: GridScreenViewModel, lifecycleOwner: LifecycleOwner, backgroundDispatcher: CoroutineDispatcher, onOptionsChanged: () -> Unit, isGridApplyButtonEnabled: Boolean, onOptionApplied: () -> Unit, ) { val optionView: RecyclerView = view.requireViewById(R.id.options) optionView.layoutManager = LinearLayoutManager( view.context, RecyclerView.HORIZONTAL, /* reverseLayout= */ false, ) optionView.addItemDecoration(ItemSpacing(ItemSpacing.ITEM_SPACING_DP)) val adapter = OptionItemAdapter( layoutResourceId = R.layout.grid_option, lifecycleOwner = lifecycleOwner, backgroundDispatcher = backgroundDispatcher, foregroundTintSpec = OptionItemBinder.TintSpec( selectedColor = view.context.getColor(R.color.system_on_surface), unselectedColor = view.context.getColor(R.color.system_on_surface), ), bindIcon = { foregroundView: View, gridIcon: GridIconViewModel -> val imageView = foregroundView as? ImageView imageView?.let { GridIconViewBinder.bind(imageView, gridIcon) } } ) optionView.adapter = adapter if (isGridApplyButtonEnabled) { val applyButton: Button = view.requireViewById(R.id.apply_button) applyButton.visibility = View.VISIBLE view.requireViewById<View>(R.id.apply_button_note).visibility = View.VISIBLE applyButton.setOnClickListener { onOptionApplied() } } lifecycleOwner.lifecycleScope.launch { lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { launch { viewModel.optionItems.collect { options -> adapter.setItems(options) onOptionsChanged() } } } } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/grid/ui/binder/GridScreenBinder.kt
1883760056
/* * Copyright (C) 2023 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.customization.picker.grid.ui.fragment import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.Toast import androidx.core.content.ContextCompat import androidx.core.view.isVisible import androidx.lifecycle.ViewModelProvider import androidx.transition.Transition import androidx.transition.doOnStart import com.android.customization.model.CustomizationManager.Callback import com.android.customization.module.ThemePickerInjector import com.android.customization.picker.grid.domain.interactor.GridInteractor import com.android.customization.picker.grid.ui.binder.GridScreenBinder import com.android.customization.picker.grid.ui.viewmodel.GridScreenViewModel import com.android.wallpaper.R import com.android.wallpaper.config.BaseFlags import com.android.wallpaper.module.CurrentWallpaperInfoFactory import com.android.wallpaper.module.CustomizationSections import com.android.wallpaper.module.InjectorProvider import com.android.wallpaper.picker.AppbarFragment import com.android.wallpaper.picker.customization.domain.interactor.WallpaperInteractor import com.android.wallpaper.picker.customization.ui.binder.ScreenPreviewBinder import com.android.wallpaper.picker.customization.ui.viewmodel.ScreenPreviewViewModel import com.android.wallpaper.util.PreviewUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.suspendCancellableCoroutine private val TAG = GridFragment::class.java.simpleName @OptIn(ExperimentalCoroutinesApi::class) class GridFragment : AppbarFragment() { private lateinit var gridInteractor: GridInteractor override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view = inflater.inflate( R.layout.fragment_grid, container, false, ) setUpToolbar(view) val isGridApplyButtonEnabled = BaseFlags.get().isGridApplyButtonEnabled(requireContext()) val injector = InjectorProvider.getInjector() as ThemePickerInjector val wallpaperInfoFactory = injector.getCurrentWallpaperInfoFactory(requireContext()) var screenPreviewBinding = bindScreenPreview( view, wallpaperInfoFactory, injector.getWallpaperInteractor(requireContext()), injector.getGridInteractor(requireContext()) ) val viewModelFactory = injector.getGridScreenViewModelFactory(requireContext()) gridInteractor = injector.getGridInteractor(requireContext()) GridScreenBinder.bind( view = view, viewModel = ViewModelProvider( this, viewModelFactory, )[GridScreenViewModel::class.java], lifecycleOwner = this, backgroundDispatcher = Dispatchers.IO, onOptionsChanged = { screenPreviewBinding.destroy() screenPreviewBinding = bindScreenPreview( view, wallpaperInfoFactory, injector.getWallpaperInteractor(requireContext()), gridInteractor, ) if (isGridApplyButtonEnabled) { val applyButton: Button = view.requireViewById(R.id.apply_button) applyButton.isEnabled = !gridInteractor.isSelectedOptionApplied() } }, isGridApplyButtonEnabled = isGridApplyButtonEnabled, onOptionApplied = { gridInteractor.applySelectedOption( object : Callback { override fun onSuccess() { Toast.makeText( context, getString( R.string.toast_of_changing_grid, gridInteractor.getSelectOptionNonSuspend()?.title ), Toast.LENGTH_SHORT ) .show() val applyButton: Button = view.requireViewById(R.id.apply_button) applyButton.isEnabled = false } override fun onError(throwable: Throwable?) { val errorMsg = getString( R.string.toast_of_failure_to_change_grid, gridInteractor.getSelectOptionNonSuspend()?.title ) Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show() Log.e(TAG, errorMsg, throwable) } } ) } ) (returnTransition as? Transition)?.doOnStart { view.requireViewById<View>(R.id.preview).isVisible = false } return view } override fun getDefaultTitle(): CharSequence { return getString(R.string.grid_title) } override fun getToolbarColorId(): Int { return android.R.color.transparent } override fun getToolbarTextColor(): Int { return ContextCompat.getColor(requireContext(), R.color.system_on_surface) } private fun bindScreenPreview( view: View, wallpaperInfoFactory: CurrentWallpaperInfoFactory, wallpaperInteractor: WallpaperInteractor, gridInteractor: GridInteractor ): ScreenPreviewBinder.Binding { return ScreenPreviewBinder.bind( activity = requireActivity(), previewView = view.requireViewById(R.id.preview), viewModel = ScreenPreviewViewModel( previewUtils = PreviewUtils( context = requireContext(), authorityMetadataKey = requireContext() .getString( R.string.grid_control_metadata_name, ), ), initialExtrasProvider = { val bundle = Bundle() bundle.putString("name", gridInteractor.getSelectOptionNonSuspend()?.name) bundle }, wallpaperInfoProvider = { suspendCancellableCoroutine { continuation -> wallpaperInfoFactory.createCurrentWallpaperInfos( context, /* forceRefresh= */ true, ) { homeWallpaper, lockWallpaper, _ -> continuation.resume(homeWallpaper ?: lockWallpaper, null) } } }, wallpaperInteractor = wallpaperInteractor, screen = CustomizationSections.Screen.HOME_SCREEN, ), lifecycleOwner = viewLifecycleOwner, offsetToStart = false, onWallpaperPreviewDirty = { activity?.recreate() }, ) } override fun onBackPressed(): Boolean { if (BaseFlags.get().isGridApplyButtonEnabled(requireContext())) { gridInteractor.clearSelectedOption() } return super.onBackPressed() } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/grid/ui/fragment/GridFragment.kt
1353425576
/* * Copyright (C) 2023 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.customization.picker.grid.shared.model import kotlinx.coroutines.flow.StateFlow data class GridOptionItemModel( val name: String, val cols: Int, val rows: Int, val isSelected: StateFlow<Boolean>, val onSelected: suspend () -> Unit, )
android_packages_apps_ThemePicker/src/com/android/customization/picker/grid/shared/model/GridOptionItemModel.kt
1414407371
/* * Copyright (C) 2023 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.customization.picker.grid.shared.model sealed class GridOptionItemsModel { data class Loaded( val options: List<GridOptionItemModel>, ) : GridOptionItemsModel() data class Error( val throwable: Throwable?, ) : GridOptionItemsModel() }
android_packages_apps_ThemePicker/src/com/android/customization/picker/grid/shared/model/GridOptionItemsModel.kt
439093986
/* * Copyright (C) 2023 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.customization.picker.grid.data.repository import androidx.lifecycle.asFlow import com.android.customization.model.CustomizationManager import com.android.customization.model.CustomizationManager.Callback import com.android.customization.model.grid.GridOption import com.android.customization.model.grid.GridOptionsManager import com.android.customization.picker.grid.shared.model.GridOptionItemModel import com.android.customization.picker.grid.shared.model.GridOptionItemsModel import kotlin.coroutines.resume import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext interface GridRepository { suspend fun isAvailable(): Boolean fun getOptionChanges(): Flow<Unit> suspend fun getOptions(): GridOptionItemsModel fun getSelectedOption(): GridOption? fun applySelectedOption(callback: Callback) fun clearSelectedOption() fun isSelectedOptionApplied(): Boolean } class GridRepositoryImpl( private val applicationScope: CoroutineScope, private val manager: GridOptionsManager, private val backgroundDispatcher: CoroutineDispatcher, private val isGridApplyButtonEnabled: Boolean, ) : GridRepository { override suspend fun isAvailable(): Boolean { return withContext(backgroundDispatcher) { manager.isAvailable } } override fun getOptionChanges(): Flow<Unit> = manager.getOptionChangeObservable(/* handler= */ null).asFlow().map {} private val selectedOption = MutableStateFlow<GridOption?>(null) private var appliedOption: GridOption? = null override fun getSelectedOption() = selectedOption.value override suspend fun getOptions(): GridOptionItemsModel { return withContext(backgroundDispatcher) { suspendCancellableCoroutine { continuation -> manager.fetchOptions( object : CustomizationManager.OptionsFetchedListener<GridOption> { override fun onOptionsLoaded(options: MutableList<GridOption>?) { val optionsOrEmpty = options ?: emptyList() // After Apply Button is added, we will rely on onSelected() method // to update selectedOption. if (!isGridApplyButtonEnabled || selectedOption.value == null) { selectedOption.value = optionsOrEmpty.find { it.isActive(manager) } } if (isGridApplyButtonEnabled && appliedOption == null) { appliedOption = selectedOption.value } continuation.resume( GridOptionItemsModel.Loaded( optionsOrEmpty.map { option -> toModel(option) } ) ) } override fun onError(throwable: Throwable?) { continuation.resume( GridOptionItemsModel.Error( throwable ?: Exception("Failed to load grid options!") ), ) } }, /* reload= */ true, ) } } } private fun toModel(option: GridOption): GridOptionItemModel { return GridOptionItemModel( name = option.title, rows = option.rows, cols = option.cols, isSelected = selectedOption .map { it.key() } .map { selectedOptionKey -> option.key() == selectedOptionKey } .stateIn( scope = applicationScope, started = SharingStarted.Eagerly, initialValue = false, ), onSelected = { onSelected(option) }, ) } private suspend fun onSelected(option: GridOption) { withContext(backgroundDispatcher) { suspendCancellableCoroutine { continuation -> if (isGridApplyButtonEnabled) { selectedOption.value?.setIsCurrent(false) selectedOption.value = option selectedOption.value?.setIsCurrent(true) manager.preview(option) continuation.resume(true) } else { manager.apply( option, object : CustomizationManager.Callback { override fun onSuccess() { continuation.resume(true) } override fun onError(throwable: Throwable?) { continuation.resume(false) } }, ) } } } } override fun applySelectedOption(callback: Callback) { val option = getSelectedOption() manager.apply( option, if (isGridApplyButtonEnabled) { object : Callback { override fun onSuccess() { callback.onSuccess() appliedOption = option } override fun onError(throwable: Throwable?) { callback.onError(throwable) } } } else callback ) } override fun clearSelectedOption() { if (!isGridApplyButtonEnabled) { return } selectedOption.value?.setIsCurrent(false) selectedOption.value = null } override fun isSelectedOptionApplied() = selectedOption.value?.name == appliedOption?.name private fun GridOption?.key(): String? { return if (this != null) "${cols}x${rows}" else null } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/grid/data/repository/GridRepository.kt
2137849132
/* * Copyright (C) 2023 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.customization.picker.grid.domain.interactor import com.android.customization.model.CustomizationManager import com.android.customization.model.grid.GridOption import com.android.customization.picker.grid.data.repository.GridRepository import com.android.customization.picker.grid.shared.model.GridOptionItemModel import com.android.customization.picker.grid.shared.model.GridOptionItemsModel import javax.inject.Provider import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.shareIn class GridInteractor( private val applicationScope: CoroutineScope, private val repository: GridRepository, private val snapshotRestorer: Provider<GridSnapshotRestorer>, ) { val options: Flow<GridOptionItemsModel> = flow { emit(repository.isAvailable()) } .flatMapLatest { isAvailable -> if (isAvailable) { // this upstream flow tells us each time the options are changed. repository .getOptionChanges() // when we start, we pretend the options _just_ changed. This way, we load // something as soon as possible into the flow so it's ready by the time the // first observer starts to observe. .onStart { emit(Unit) } // each time the options changed, we load them. .map { reload() } // we place the loaded options in a SharedFlow so downstream observers all // share the same flow and don't trigger a new one each time they want to // start observing. .shareIn( scope = applicationScope, started = SharingStarted.WhileSubscribed(), replay = 1, ) } else { emptyFlow() } } suspend fun setSelectedOption(model: GridOptionItemModel) { model.onSelected.invoke() } suspend fun getSelectedOption(): GridOptionItemModel? { return (repository.getOptions() as? GridOptionItemsModel.Loaded)?.options?.firstOrNull { optionItem -> optionItem.isSelected.value } } fun getSelectOptionNonSuspend(): GridOption? = repository.getSelectedOption() fun clearSelectedOption() = repository.clearSelectedOption() fun isSelectedOptionApplied() = repository.isSelectedOptionApplied() fun applySelectedOption(callback: CustomizationManager.Callback) { repository.applySelectedOption(callback) } private suspend fun reload(): GridOptionItemsModel { val model = repository.getOptions() return if (model is GridOptionItemsModel.Loaded) { GridOptionItemsModel.Loaded( options = model.options.map { option -> GridOptionItemModel( name = option.name, cols = option.cols, rows = option.rows, isSelected = option.isSelected, onSelected = { option.onSelected() snapshotRestorer.get().store(option) }, ) } ) } else { model } } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/grid/domain/interactor/GridInteractor.kt
1572774866
/* * Copyright (C) 2023 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.customization.picker.grid.domain.interactor import android.util.Log import com.android.customization.picker.grid.shared.model.GridOptionItemModel import com.android.wallpaper.picker.undo.domain.interactor.SnapshotRestorer import com.android.wallpaper.picker.undo.domain.interactor.SnapshotStore import com.android.wallpaper.picker.undo.shared.model.RestorableSnapshot class GridSnapshotRestorer( private val interactor: GridInteractor, ) : SnapshotRestorer { private var store: SnapshotStore = SnapshotStore.NOOP private var originalOption: GridOptionItemModel? = null override suspend fun setUpSnapshotRestorer(store: SnapshotStore): RestorableSnapshot { this.store = store val option = interactor.getSelectedOption() originalOption = option return snapshot(option) } override suspend fun restoreToSnapshot(snapshot: RestorableSnapshot) { val optionNameFromSnapshot = snapshot.args[KEY_GRID_OPTION_NAME] originalOption?.let { optionToRestore -> if (optionToRestore.name != optionNameFromSnapshot) { Log.wtf( TAG, """Original snapshot name was ${optionToRestore.name} but we're being told to | restore to $optionNameFromSnapshot. The current implementation doesn't | support undo, only a reset back to the original grid option.""" .trimMargin(), ) } interactor.setSelectedOption(optionToRestore) } } fun store(option: GridOptionItemModel) { store.store(snapshot(option)) } private fun snapshot(option: GridOptionItemModel?): RestorableSnapshot { return RestorableSnapshot( args = buildMap { option?.name?.let { optionName -> put(KEY_GRID_OPTION_NAME, optionName) } } ) } companion object { private const val TAG = "GridSnapshotRestorer" private const val KEY_GRID_OPTION_NAME = "grid_option" } }
android_packages_apps_ThemePicker/src/com/android/customization/picker/grid/domain/interactor/GridSnapshotRestorer.kt
2071781337
/* * Copyright (C) 2019 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.customization.module import android.app.Activity import android.app.UiModeManager import android.app.WallpaperColors import android.app.WallpaperManager import android.content.Context import android.content.Intent import android.content.res.Resources import android.net.Uri import android.text.TextUtils import androidx.activity.ComponentActivity import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModelProvider import com.android.customization.model.color.ColorCustomizationManager import com.android.customization.model.color.ColorOptionsProvider.COLOR_SOURCE_PRESET import com.android.customization.model.color.ThemedWallpaperColorResources import com.android.customization.model.color.WallpaperColorResources import com.android.customization.model.grid.GridOptionsManager import com.android.customization.model.mode.DarkModeSnapshotRestorer import com.android.customization.model.theme.OverlayManagerCompat import com.android.customization.model.themedicon.ThemedIconSwitchProvider import com.android.customization.model.themedicon.data.repository.ThemeIconRepository import com.android.customization.model.themedicon.domain.interactor.ThemedIconInteractor import com.android.customization.model.themedicon.domain.interactor.ThemedIconSnapshotRestorer import com.android.customization.module.logging.ThemesUserEventLogger import com.android.customization.picker.clock.data.repository.ClockPickerRepositoryImpl import com.android.customization.picker.clock.data.repository.ClockRegistryProvider import com.android.customization.picker.clock.domain.interactor.ClockPickerInteractor import com.android.customization.picker.clock.domain.interactor.ClockPickerSnapshotRestorer import com.android.customization.picker.clock.ui.view.ClockViewFactory import com.android.customization.picker.clock.ui.view.ClockViewFactoryImpl import com.android.customization.picker.clock.ui.viewmodel.ClockCarouselViewModel import com.android.customization.picker.clock.ui.viewmodel.ClockSettingsViewModel import com.android.customization.picker.color.data.repository.ColorPickerRepositoryImpl import com.android.customization.picker.color.domain.interactor.ColorPickerInteractor import com.android.customization.picker.color.domain.interactor.ColorPickerSnapshotRestorer import com.android.customization.picker.color.ui.viewmodel.ColorPickerViewModel import com.android.customization.picker.grid.data.repository.GridRepositoryImpl import com.android.customization.picker.grid.domain.interactor.GridInteractor import com.android.customization.picker.grid.domain.interactor.GridSnapshotRestorer import com.android.customization.picker.grid.ui.viewmodel.GridScreenViewModel import com.android.customization.picker.notifications.data.repository.NotificationsRepository import com.android.customization.picker.notifications.domain.interactor.NotificationsInteractor import com.android.customization.picker.notifications.domain.interactor.NotificationsSnapshotRestorer import com.android.customization.picker.notifications.ui.viewmodel.NotificationSectionViewModel import com.android.customization.picker.quickaffordance.data.repository.KeyguardQuickAffordancePickerRepository import com.android.customization.picker.quickaffordance.domain.interactor.KeyguardQuickAffordancePickerInteractor import com.android.customization.picker.quickaffordance.domain.interactor.KeyguardQuickAffordanceSnapshotRestorer import com.android.customization.picker.quickaffordance.ui.viewmodel.KeyguardQuickAffordancePickerViewModel import com.android.systemui.shared.clocks.ClockRegistry import com.android.systemui.shared.customization.data.content.CustomizationProviderClient import com.android.systemui.shared.customization.data.content.CustomizationProviderClientImpl import com.android.wallpaper.config.BaseFlags import com.android.wallpaper.module.CustomizationSections import com.android.wallpaper.module.FragmentFactory import com.android.wallpaper.module.WallpaperPicker2Injector import com.android.wallpaper.picker.CustomizationPickerActivity import com.android.wallpaper.picker.customization.data.content.WallpaperClientImpl import com.android.wallpaper.picker.customization.data.repository.WallpaperColorsRepository import com.android.wallpaper.picker.customization.data.repository.WallpaperRepository import com.android.wallpaper.picker.customization.domain.interactor.WallpaperInteractor import com.android.wallpaper.picker.di.modules.BackgroundDispatcher import com.android.wallpaper.picker.di.modules.MainDispatcher import com.android.wallpaper.picker.undo.domain.interactor.SnapshotRestorer import com.android.wallpaper.util.ScreenSizeCalculator import javax.inject.Inject import javax.inject.Singleton import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope @Singleton open class ThemePickerInjector @Inject internal constructor( @MainDispatcher private val mainScope: CoroutineScope, @MainDispatcher private val mainDispatcher: CoroutineDispatcher, @BackgroundDispatcher private val bgDispatcher: CoroutineDispatcher, private val userEventLogger: ThemesUserEventLogger, ) : WallpaperPicker2Injector(mainScope, bgDispatcher, userEventLogger), CustomizationInjector { private var customizationSections: CustomizationSections? = null private var wallpaperInteractor: WallpaperInteractor? = null private var keyguardQuickAffordancePickerInteractor: KeyguardQuickAffordancePickerInteractor? = null private var keyguardQuickAffordancePickerViewModelFactory: KeyguardQuickAffordancePickerViewModel.Factory? = null private var customizationProviderClient: CustomizationProviderClient? = null private var fragmentFactory: FragmentFactory? = null private var keyguardQuickAffordanceSnapshotRestorer: KeyguardQuickAffordanceSnapshotRestorer? = null private var notificationsSnapshotRestorer: NotificationsSnapshotRestorer? = null private var clockPickerInteractor: ClockPickerInteractor? = null private var clockCarouselViewModelFactory: ClockCarouselViewModel.Factory? = null private var clockViewFactory: ClockViewFactory? = null private var clockPickerSnapshotRestorer: ClockPickerSnapshotRestorer? = null private var notificationsInteractor: NotificationsInteractor? = null private var notificationSectionViewModelFactory: NotificationSectionViewModel.Factory? = null private var colorPickerInteractor: ColorPickerInteractor? = null private var colorPickerViewModelFactory: ColorPickerViewModel.Factory? = null private var colorPickerSnapshotRestorer: ColorPickerSnapshotRestorer? = null private var colorCustomizationManager: ColorCustomizationManager? = null private var darkModeSnapshotRestorer: DarkModeSnapshotRestorer? = null private var themedIconSnapshotRestorer: ThemedIconSnapshotRestorer? = null private var themedIconInteractor: ThemedIconInteractor? = null private var clockSettingsViewModelFactory: ClockSettingsViewModel.Factory? = null private var gridInteractor: GridInteractor? = null private var gridSnapshotRestorer: GridSnapshotRestorer? = null private var gridScreenViewModelFactory: GridScreenViewModel.Factory? = null private var clockRegistryProvider: ClockRegistryProvider? = null override fun getCustomizationSections(activity: ComponentActivity): CustomizationSections { val appContext = activity.applicationContext val clockViewFactory = getClockViewFactory(activity) val resources = activity.resources return customizationSections ?: DefaultCustomizationSections( getColorPickerViewModelFactory( context = appContext, wallpaperColorsRepository = getWallpaperColorsRepository(), ), getKeyguardQuickAffordancePickerViewModelFactory(appContext), getNotificationSectionViewModelFactory(appContext), getFlags(), getClockCarouselViewModelFactory( interactor = getClockPickerInteractor(appContext), clockViewFactory = clockViewFactory, resources = resources, logger = userEventLogger, ), clockViewFactory, getThemedIconSnapshotRestorer(appContext), getThemedIconInteractor(), getColorPickerInteractor(appContext, getWallpaperColorsRepository()), getUserEventLogger(appContext), ) .also { customizationSections = it } } override fun getDeepLinkRedirectIntent(context: Context, uri: Uri): Intent { val intent = Intent() intent.setClass(context, CustomizationPickerActivity::class.java) intent.data = uri intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK return intent } override fun getDownloadableIntentAction(): String? { return null } @Synchronized override fun getUserEventLogger(context: Context): ThemesUserEventLogger { return userEventLogger } override fun getFragmentFactory(): FragmentFactory? { return fragmentFactory ?: ThemePickerFragmentFactory().also { fragmentFactory } } override fun getSnapshotRestorers( context: Context, ): Map<Int, SnapshotRestorer> { return super<WallpaperPicker2Injector>.getSnapshotRestorers(context).toMutableMap().apply { this[KEY_QUICK_AFFORDANCE_SNAPSHOT_RESTORER] = getKeyguardQuickAffordanceSnapshotRestorer(context) // TODO(b/285047815): Enable after adding wallpaper id for default static wallpaper if (getFlags().isWallpaperRestorerEnabled()) { this[KEY_WALLPAPER_SNAPSHOT_RESTORER] = getWallpaperSnapshotRestorer(context) } this[KEY_NOTIFICATIONS_SNAPSHOT_RESTORER] = getNotificationsSnapshotRestorer(context) this[KEY_DARK_MODE_SNAPSHOT_RESTORER] = getDarkModeSnapshotRestorer(context) this[KEY_THEMED_ICON_SNAPSHOT_RESTORER] = getThemedIconSnapshotRestorer(context) this[KEY_APP_GRID_SNAPSHOT_RESTORER] = getGridSnapshotRestorer(context) this[KEY_COLOR_PICKER_SNAPSHOT_RESTORER] = getColorPickerSnapshotRestorer(context, getWallpaperColorsRepository()) this[KEY_CLOCKS_SNAPSHOT_RESTORER] = getClockPickerSnapshotRestorer(context) } } override fun getCustomizationPreferences(context: Context): CustomizationPreferences { return getPreferences(context) as CustomizationPreferences } override fun getWallpaperInteractor(context: Context): WallpaperInteractor { if (getFlags().isMultiCropEnabled() && getFlags().isMultiCropPreviewUiEnabled()) { return injectedWallpaperInteractor } val appContext = context.applicationContext return wallpaperInteractor ?: WallpaperInteractor( repository = WallpaperRepository( scope = getApplicationCoroutineScope(), client = WallpaperClientImpl( context = appContext, wallpaperManager = WallpaperManager.getInstance(appContext), wallpaperPreferences = getPreferences(appContext) ), wallpaperPreferences = getPreferences(context = appContext), backgroundDispatcher = bgDispatcher, ), shouldHandleReload = { TextUtils.equals( getColorCustomizationManager(appContext).currentColorSource, COLOR_SOURCE_PRESET, ) } ) .also { wallpaperInteractor = it } } override fun getKeyguardQuickAffordancePickerInteractor( context: Context ): KeyguardQuickAffordancePickerInteractor { return keyguardQuickAffordancePickerInteractor ?: getKeyguardQuickAffordancePickerInteractorImpl(context).also { keyguardQuickAffordancePickerInteractor = it } } fun getKeyguardQuickAffordancePickerViewModelFactory( context: Context ): KeyguardQuickAffordancePickerViewModel.Factory { return keyguardQuickAffordancePickerViewModelFactory ?: KeyguardQuickAffordancePickerViewModel.Factory( context.applicationContext, getKeyguardQuickAffordancePickerInteractor(context), getWallpaperInteractor(context), getCurrentWallpaperInfoFactory(context), getUserEventLogger(context), ) .also { keyguardQuickAffordancePickerViewModelFactory = it } } private fun getKeyguardQuickAffordancePickerInteractorImpl( context: Context ): KeyguardQuickAffordancePickerInteractor { val client = getKeyguardQuickAffordancePickerProviderClient(context) val appContext = context.applicationContext return KeyguardQuickAffordancePickerInteractor( KeyguardQuickAffordancePickerRepository(client, getApplicationCoroutineScope()), client ) { getKeyguardQuickAffordanceSnapshotRestorer(appContext) } } private fun getKeyguardQuickAffordancePickerProviderClient( context: Context ): CustomizationProviderClient { return customizationProviderClient ?: CustomizationProviderClientImpl(context.applicationContext, bgDispatcher).also { customizationProviderClient = it } } private fun getKeyguardQuickAffordanceSnapshotRestorer( context: Context ): KeyguardQuickAffordanceSnapshotRestorer { return keyguardQuickAffordanceSnapshotRestorer ?: KeyguardQuickAffordanceSnapshotRestorer( getKeyguardQuickAffordancePickerInteractor(context), getKeyguardQuickAffordancePickerProviderClient(context) ) .also { keyguardQuickAffordanceSnapshotRestorer = it } } fun getNotificationSectionViewModelFactory( context: Context, ): NotificationSectionViewModel.Factory { return notificationSectionViewModelFactory ?: NotificationSectionViewModel.Factory( interactor = getNotificationsInteractor(context), logger = getUserEventLogger(context), ) .also { notificationSectionViewModelFactory = it } } private fun getNotificationsInteractor( context: Context, ): NotificationsInteractor { val appContext = context.applicationContext return notificationsInteractor ?: NotificationsInteractor( repository = NotificationsRepository( scope = getApplicationCoroutineScope(), backgroundDispatcher = bgDispatcher, secureSettingsRepository = getSecureSettingsRepository(context), ), snapshotRestorer = { getNotificationsSnapshotRestorer(appContext) }, ) .also { notificationsInteractor = it } } private fun getNotificationsSnapshotRestorer(context: Context): NotificationsSnapshotRestorer { return notificationsSnapshotRestorer ?: NotificationsSnapshotRestorer( interactor = getNotificationsInteractor( context = context, ), ) .also { notificationsSnapshotRestorer = it } } override fun getClockRegistry(context: Context): ClockRegistry { return (clockRegistryProvider ?: ClockRegistryProvider( context = context.applicationContext, coroutineScope = getApplicationCoroutineScope(), mainDispatcher = mainDispatcher, backgroundDispatcher = bgDispatcher, ) .also { clockRegistryProvider = it }) .get() } override fun getClockPickerInteractor( context: Context, ): ClockPickerInteractor { val appContext = context.applicationContext return clockPickerInteractor ?: ClockPickerInteractor( repository = ClockPickerRepositoryImpl( secureSettingsRepository = getSecureSettingsRepository(appContext), registry = getClockRegistry(appContext), scope = getApplicationCoroutineScope(), mainDispatcher = mainDispatcher, ), snapshotRestorer = { getClockPickerSnapshotRestorer(appContext) }, ) .also { clockPickerInteractor = it } } override fun getClockCarouselViewModelFactory( interactor: ClockPickerInteractor, clockViewFactory: ClockViewFactory, resources: Resources, logger: ThemesUserEventLogger, ): ClockCarouselViewModel.Factory { return clockCarouselViewModelFactory ?: ClockCarouselViewModel.Factory( interactor, bgDispatcher, clockViewFactory, resources, logger, ) .also { clockCarouselViewModelFactory = it } } override fun getClockViewFactory(activity: ComponentActivity): ClockViewFactory { return clockViewFactory ?: ClockViewFactoryImpl( activity.applicationContext, ScreenSizeCalculator.getInstance() .getScreenSize(activity.windowManager.defaultDisplay), WallpaperManager.getInstance(activity.applicationContext), getClockRegistry(activity.applicationContext), ) .also { clockViewFactory = it activity.lifecycle.addObserver( object : DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { super.onDestroy(owner) if ((owner as Activity).isChangingConfigurations()) return clockViewFactory?.onDestroy() } } ) } } private fun getClockPickerSnapshotRestorer( context: Context, ): ClockPickerSnapshotRestorer { return clockPickerSnapshotRestorer ?: ClockPickerSnapshotRestorer(getClockPickerInteractor(context)).also { clockPickerSnapshotRestorer = it } } override fun getWallpaperColorResources( wallpaperColors: WallpaperColors, context: Context ): WallpaperColorResources { return ThemedWallpaperColorResources(wallpaperColors, context) } override fun getColorPickerInteractor( context: Context, wallpaperColorsRepository: WallpaperColorsRepository, ): ColorPickerInteractor { val appContext = context.applicationContext return colorPickerInteractor ?: ColorPickerInteractor( repository = ColorPickerRepositoryImpl( wallpaperColorsRepository, getColorCustomizationManager(appContext) ), snapshotRestorer = { getColorPickerSnapshotRestorer(appContext, wallpaperColorsRepository) } ) .also { colorPickerInteractor = it } } override fun getColorPickerViewModelFactory( context: Context, wallpaperColorsRepository: WallpaperColorsRepository, ): ColorPickerViewModel.Factory { return colorPickerViewModelFactory ?: ColorPickerViewModel.Factory( context.applicationContext, getColorPickerInteractor(context, wallpaperColorsRepository), userEventLogger, ) .also { colorPickerViewModelFactory = it } } private fun getColorPickerSnapshotRestorer( context: Context, wallpaperColorsRepository: WallpaperColorsRepository, ): ColorPickerSnapshotRestorer { return colorPickerSnapshotRestorer ?: ColorPickerSnapshotRestorer( getColorPickerInteractor(context, wallpaperColorsRepository) ) .also { colorPickerSnapshotRestorer = it } } private fun getColorCustomizationManager(context: Context): ColorCustomizationManager { return colorCustomizationManager ?: ColorCustomizationManager.getInstance(context, OverlayManagerCompat(context)).also { colorCustomizationManager = it } } fun getDarkModeSnapshotRestorer( context: Context, ): DarkModeSnapshotRestorer { val appContext = context.applicationContext return darkModeSnapshotRestorer ?: DarkModeSnapshotRestorer( context = appContext, manager = appContext.getSystemService(Context.UI_MODE_SERVICE) as UiModeManager, backgroundDispatcher = bgDispatcher, ) .also { darkModeSnapshotRestorer = it } } protected fun getThemedIconSnapshotRestorer( context: Context, ): ThemedIconSnapshotRestorer { val optionProvider = ThemedIconSwitchProvider.getInstance(context) return themedIconSnapshotRestorer ?: ThemedIconSnapshotRestorer( isActivated = { optionProvider.isThemedIconEnabled }, setActivated = { isActivated -> optionProvider.isThemedIconEnabled = isActivated }, interactor = getThemedIconInteractor(), ) .also { themedIconSnapshotRestorer = it } } protected fun getThemedIconInteractor(): ThemedIconInteractor { return themedIconInteractor ?: ThemedIconInteractor( repository = ThemeIconRepository(), ) .also { themedIconInteractor = it } } override fun getClockSettingsViewModelFactory( context: Context, wallpaperColorsRepository: WallpaperColorsRepository, clockViewFactory: ClockViewFactory, ): ClockSettingsViewModel.Factory { return clockSettingsViewModelFactory ?: ClockSettingsViewModel.Factory( context.applicationContext, getClockPickerInteractor(context), getColorPickerInteractor( context, wallpaperColorsRepository, ), userEventLogger, ) { clockId -> clockId?.let { clockViewFactory.getController(clockId).config.isReactiveToTone } ?: false } .also { clockSettingsViewModelFactory = it } } fun getGridScreenViewModelFactory( context: Context, ): ViewModelProvider.Factory { return gridScreenViewModelFactory ?: GridScreenViewModel.Factory( context = context, interactor = getGridInteractor(context), ) .also { gridScreenViewModelFactory = it } } fun getGridInteractor(context: Context): GridInteractor { val appContext = context.applicationContext return gridInteractor ?: GridInteractor( applicationScope = getApplicationCoroutineScope(), repository = GridRepositoryImpl( applicationScope = getApplicationCoroutineScope(), manager = GridOptionsManager.getInstance(context), backgroundDispatcher = bgDispatcher, isGridApplyButtonEnabled = BaseFlags.get().isGridApplyButtonEnabled(appContext), ), snapshotRestorer = { getGridSnapshotRestorer(appContext) }, ) .also { gridInteractor = it } } private fun getGridSnapshotRestorer( context: Context, ): GridSnapshotRestorer { return gridSnapshotRestorer ?: GridSnapshotRestorer( interactor = getGridInteractor(context), ) .also { gridSnapshotRestorer = it } } override fun isCurrentSelectedColorPreset(context: Context): Boolean { val colorManager = ColorCustomizationManager.getInstance(context, OverlayManagerCompat(context)) return COLOR_SOURCE_PRESET == colorManager.currentColorSource } companion object { @JvmStatic private val KEY_QUICK_AFFORDANCE_SNAPSHOT_RESTORER = WallpaperPicker2Injector.MIN_SNAPSHOT_RESTORER_KEY @JvmStatic private val KEY_WALLPAPER_SNAPSHOT_RESTORER = KEY_QUICK_AFFORDANCE_SNAPSHOT_RESTORER + 1 @JvmStatic private val KEY_NOTIFICATIONS_SNAPSHOT_RESTORER = KEY_WALLPAPER_SNAPSHOT_RESTORER + 1 @JvmStatic private val KEY_DARK_MODE_SNAPSHOT_RESTORER = KEY_NOTIFICATIONS_SNAPSHOT_RESTORER + 1 @JvmStatic private val KEY_THEMED_ICON_SNAPSHOT_RESTORER = KEY_DARK_MODE_SNAPSHOT_RESTORER + 1 @JvmStatic private val KEY_APP_GRID_SNAPSHOT_RESTORER = KEY_THEMED_ICON_SNAPSHOT_RESTORER + 1 @JvmStatic private val KEY_COLOR_PICKER_SNAPSHOT_RESTORER = KEY_APP_GRID_SNAPSHOT_RESTORER + 1 @JvmStatic private val KEY_CLOCKS_SNAPSHOT_RESTORER = KEY_COLOR_PICKER_SNAPSHOT_RESTORER + 1 /** * When this injector is overridden, this is the minimal value that should be used by * restorers returns in [getSnapshotRestorers]. * * It should always be greater than the biggest restorer key. */ @JvmStatic protected val MIN_SNAPSHOT_RESTORER_KEY = KEY_CLOCKS_SNAPSHOT_RESTORER + 1 } }
android_packages_apps_ThemePicker/src/com/android/customization/module/ThemePickerInjector.kt
260449418
/* * Copyright (C) 2019 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.customization.module import android.content.Context import com.android.wallpaper.module.DefaultWallpaperPreferences open class DefaultCustomizationPreferences(context: Context) : DefaultWallpaperPreferences(context), CustomizationPreferences { override fun getSerializedCustomThemes(): String? { return sharedPrefs.getString(CustomizationPreferences.KEY_CUSTOM_THEME, null) } override fun storeCustomThemes(serializedCustomThemes: String) { sharedPrefs .edit() .putString(CustomizationPreferences.KEY_CUSTOM_THEME, serializedCustomThemes) .apply() } override fun getTabVisited(id: String): Boolean { return sharedPrefs.getBoolean(CustomizationPreferences.KEY_VISITED_PREFIX + id, false) } override fun setTabVisited(id: String) { sharedPrefs .edit() .putBoolean(CustomizationPreferences.KEY_VISITED_PREFIX + id, true) .apply() } override fun getThemedIconEnabled(): Boolean { return sharedPrefs.getBoolean(CustomizationPreferences.KEY_THEMED_ICON_ENABLED, false) } override fun setThemedIconEnabled(enabled: Boolean) { sharedPrefs .edit() .putBoolean(CustomizationPreferences.KEY_THEMED_ICON_ENABLED, enabled) .apply() } }
android_packages_apps_ThemePicker/src/com/android/customization/module/DefaultCustomizationPreferences.kt
2017284189
/* * Copyright (C) 2019 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.customization.module import android.content.Context import android.content.res.Resources import androidx.activity.ComponentActivity import com.android.customization.module.logging.ThemesUserEventLogger import com.android.customization.picker.clock.domain.interactor.ClockPickerInteractor import com.android.customization.picker.clock.ui.view.ClockViewFactory import com.android.customization.picker.clock.ui.viewmodel.ClockCarouselViewModel import com.android.customization.picker.clock.ui.viewmodel.ClockSettingsViewModel import com.android.customization.picker.color.domain.interactor.ColorPickerInteractor import com.android.customization.picker.color.ui.viewmodel.ColorPickerViewModel import com.android.customization.picker.quickaffordance.domain.interactor.KeyguardQuickAffordancePickerInteractor import com.android.systemui.shared.clocks.ClockRegistry import com.android.wallpaper.module.Injector import com.android.wallpaper.picker.customization.data.repository.WallpaperColorsRepository interface CustomizationInjector : Injector { fun getCustomizationPreferences(context: Context): CustomizationPreferences fun getKeyguardQuickAffordancePickerInteractor( context: Context, ): KeyguardQuickAffordancePickerInteractor fun getClockRegistry(context: Context): ClockRegistry? fun getClockPickerInteractor(context: Context): ClockPickerInteractor fun getColorPickerInteractor( context: Context, wallpaperColorsRepository: WallpaperColorsRepository, ): ColorPickerInteractor fun getColorPickerViewModelFactory( context: Context, wallpaperColorsRepository: WallpaperColorsRepository, ): ColorPickerViewModel.Factory fun getClockCarouselViewModelFactory( interactor: ClockPickerInteractor, clockViewFactory: ClockViewFactory, resources: Resources, logger: ThemesUserEventLogger, ): ClockCarouselViewModel.Factory fun getClockViewFactory(activity: ComponentActivity): ClockViewFactory fun getClockSettingsViewModelFactory( context: Context, wallpaperColorsRepository: WallpaperColorsRepository, clockViewFactory: ClockViewFactory, ): ClockSettingsViewModel.Factory }
android_packages_apps_ThemePicker/src/com/android/customization/module/CustomizationInjector.kt
2407419495
/* * Copyright (C) 2022 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.customization.module.logging import android.stats.style.StyleEnums.CLOCK_SIZE_UNSPECIFIED import android.stats.style.StyleEnums.COLOR_SOURCE_UNSPECIFIED import android.stats.style.StyleEnums.DATE_PREFERENCE_UNSPECIFIED import android.stats.style.StyleEnums.EFFECT_PREFERENCE_UNSPECIFIED import android.stats.style.StyleEnums.LAUNCHED_PREFERENCE_UNSPECIFIED import android.stats.style.StyleEnums.LOCATION_PREFERENCE_UNSPECIFIED import android.stats.style.StyleEnums.SET_WALLPAPER_ENTRY_POINT_UNSPECIFIED import android.stats.style.StyleEnums.WALLPAPER_DESTINATION_UNSPECIFIED import com.android.systemui.shared.system.SysUiStatsLog import com.android.systemui.shared.system.SysUiStatsLog.STYLE_UI_CHANGED import com.android.wallpaper.module.logging.UserEventLogger.SetWallpaperEntryPoint /** The builder for [SysUiStatsLog]. */ class SysUiStatsLogger(val action: Int) { private var colorPackageHash = 0 private var fontPackageHash = 0 private var shapePackageHash = 0 private var clockPackageHash = 0 private var launcherGrid = 0 private var wallpaperCategoryHash = 0 private var wallpaperIdHash = 0 private var colorPreference = 0 private var locationPreference = LOCATION_PREFERENCE_UNSPECIFIED private var datePreference = DATE_PREFERENCE_UNSPECIFIED private var launchedPreference = LAUNCHED_PREFERENCE_UNSPECIFIED private var effectPreference = EFFECT_PREFERENCE_UNSPECIFIED private var effectIdHash = 0 private var lockWallpaperCategoryHash = 0 private var lockWallpaperIdHash = 0 private var firstLaunchDateSinceSetup = 0 private var firstWallpaperApplyDateSinceSetup = 0 private var appLaunchCount = 0 private var colorVariant = 0 private var timeElapsedMillis = 0L private var effectResultCode = -1 private var appSessionId = 0 private var setWallpaperEntryPoint = SET_WALLPAPER_ENTRY_POINT_UNSPECIFIED private var wallpaperDestination = WALLPAPER_DESTINATION_UNSPECIFIED private var colorSource = COLOR_SOURCE_UNSPECIFIED private var seedColor = 0 private var clockSize = CLOCK_SIZE_UNSPECIFIED private var toggleOn = false private var shortcut = "" private var shortcutSlotId = "" fun setColorPackageHash(colorPackageHash: Int) = apply { this.colorPackageHash = colorPackageHash } fun setFontPackageHash(fontPackageHash: Int) = apply { this.fontPackageHash = fontPackageHash } fun setShapePackageHash(shapePackageHash: Int) = apply { this.shapePackageHash = shapePackageHash } fun setClockPackageHash(clockPackageHash: Int) = apply { this.clockPackageHash = clockPackageHash } fun setLauncherGrid(launcherGrid: Int) = apply { this.launcherGrid = launcherGrid } fun setWallpaperCategoryHash(wallpaperCategoryHash: Int) = apply { this.wallpaperCategoryHash = wallpaperCategoryHash } fun setWallpaperIdHash(wallpaperIdHash: Int) = apply { this.wallpaperIdHash = wallpaperIdHash } fun setColorPreference(colorPreference: Int) = apply { this.colorPreference = colorPreference } fun setLocationPreference(locationPreference: Int) = apply { this.locationPreference = locationPreference } fun setDatePreference(datePreference: Int) = apply { this.datePreference = datePreference } fun setLaunchedPreference(launchedPreference: Int) = apply { this.launchedPreference = launchedPreference } fun setEffectPreference(effectPreference: Int) = apply { this.effectPreference = effectPreference } fun setEffectIdHash(effectIdHash: Int) = apply { this.effectIdHash = effectIdHash } fun setLockWallpaperCategoryHash(lockWallpaperCategoryHash: Int) = apply { this.lockWallpaperCategoryHash = lockWallpaperCategoryHash } fun setLockWallpaperIdHash(lockWallpaperIdHash: Int) = apply { this.lockWallpaperIdHash = lockWallpaperIdHash } fun setFirstLaunchDateSinceSetup(firstLaunchDateSinceSetup: Int) = apply { this.firstLaunchDateSinceSetup = firstLaunchDateSinceSetup } fun setFirstWallpaperApplyDateSinceSetup(firstWallpaperApplyDateSinceSetup: Int) = apply { this.firstWallpaperApplyDateSinceSetup = firstWallpaperApplyDateSinceSetup } fun setAppLaunchCount(appLaunchCount: Int) = apply { this.appLaunchCount = appLaunchCount } fun setColorVariant(colorVariant: Int) = apply { this.colorVariant = colorVariant } fun setTimeElapsed(timeElapsedMillis: Long) = apply { this.timeElapsedMillis = timeElapsedMillis } fun setEffectResultCode(effectResultCode: Int) = apply { this.effectResultCode = effectResultCode } fun setAppSessionId(sessionId: Int) = apply { this.appSessionId = sessionId } fun setSetWallpaperEntryPoint(@SetWallpaperEntryPoint setWallpaperEntryPoint: Int) = apply { this.setWallpaperEntryPoint = setWallpaperEntryPoint } fun setWallpaperDestination(wallpaperDestination: Int) = apply { this.wallpaperDestination = wallpaperDestination } fun setColorSource(colorSource: Int) = apply { this.colorSource = colorSource } fun setSeedColor(seedColor: Int) = apply { this.seedColor = seedColor } fun setClockSize(clockSize: Int) = apply { this.clockSize = clockSize } fun setToggleOn(toggleOn: Boolean) = apply { this.toggleOn = toggleOn } fun setShortcut(shortcut: String) = apply { this.shortcut = shortcut } fun setShortcutSlotId(shortcutSlotId: String) = apply { this.shortcutSlotId = shortcutSlotId } fun log() { SysUiStatsLog.write( STYLE_UI_CHANGED, action, colorPackageHash, fontPackageHash, shapePackageHash, clockPackageHash, launcherGrid, wallpaperCategoryHash, wallpaperIdHash, colorPreference, locationPreference, datePreference, launchedPreference, effectPreference, effectIdHash, lockWallpaperCategoryHash, lockWallpaperIdHash, firstLaunchDateSinceSetup, firstWallpaperApplyDateSinceSetup, appLaunchCount, colorVariant, timeElapsedMillis, effectResultCode, appSessionId, setWallpaperEntryPoint, wallpaperDestination, colorSource, seedColor, clockSize, toggleOn, shortcut, shortcutSlotId, ) } }
android_packages_apps_ThemePicker/src/com/android/customization/module/logging/SysUiStatsLogger.kt
2359614458
/* * Copyright (C) 2019 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.customization.module.logging import android.stats.style.StyleEnums import androidx.annotation.IntDef import com.android.customization.model.grid.GridOption import com.android.wallpaper.module.logging.UserEventLogger /** Extension of [UserEventLogger] that adds ThemePicker specific events. */ interface ThemesUserEventLogger : UserEventLogger { fun logThemeColorApplied(@ColorSource source: Int, style: Int, seedColor: Int) fun logGridApplied(grid: GridOption) fun logClockApplied(clockId: String) fun logClockColorApplied(seedColor: Int) fun logClockSizeApplied(@ClockSize clockSize: Int) fun logThemedIconApplied(useThemeIcon: Boolean) fun logLockScreenNotificationApplied(showLockScreenNotifications: Boolean) fun logShortcutApplied(shortcut: String, shortcutSlotId: String) fun logDarkThemeApplied(useDarkTheme: Boolean) @IntDef( StyleEnums.COLOR_SOURCE_UNSPECIFIED, StyleEnums.COLOR_SOURCE_HOME_SCREEN_WALLPAPER, StyleEnums.COLOR_SOURCE_LOCK_SCREEN_WALLPAPER, StyleEnums.COLOR_SOURCE_PRESET_COLOR, ) @Retention(AnnotationRetention.SOURCE) annotation class ColorSource @IntDef( StyleEnums.CLOCK_SIZE_UNSPECIFIED, StyleEnums.CLOCK_SIZE_DYNAMIC, StyleEnums.CLOCK_SIZE_SMALL, ) @Retention(AnnotationRetention.SOURCE) annotation class ClockSize companion object { const val NULL_SEED_COLOR = 0 } }
android_packages_apps_ThemePicker/src/com/android/customization/module/logging/ThemesUserEventLogger.kt
9532176
/* * Copyright (C) 2019 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.customization.module.logging import android.app.WallpaperManager import android.content.Intent import android.stats.style.StyleEnums.APP_LAUNCHED import android.stats.style.StyleEnums.CLOCK_APPLIED import android.stats.style.StyleEnums.CLOCK_COLOR_APPLIED import android.stats.style.StyleEnums.CLOCK_SIZE_APPLIED import android.stats.style.StyleEnums.DARK_THEME_APPLIED import android.stats.style.StyleEnums.GRID_APPLIED import android.stats.style.StyleEnums.LAUNCHED_CROP_AND_SET_ACTION import android.stats.style.StyleEnums.LAUNCHED_DEEP_LINK import android.stats.style.StyleEnums.LAUNCHED_KEYGUARD import android.stats.style.StyleEnums.LAUNCHED_LAUNCHER import android.stats.style.StyleEnums.LAUNCHED_LAUNCH_ICON import android.stats.style.StyleEnums.LAUNCHED_PREFERENCE_UNSPECIFIED import android.stats.style.StyleEnums.LAUNCHED_SETTINGS import android.stats.style.StyleEnums.LAUNCHED_SETTINGS_SEARCH import android.stats.style.StyleEnums.LAUNCHED_SUW import android.stats.style.StyleEnums.LAUNCHED_TIPS import android.stats.style.StyleEnums.LOCK_SCREEN_NOTIFICATION_APPLIED import android.stats.style.StyleEnums.RESET_APPLIED import android.stats.style.StyleEnums.SHORTCUT_APPLIED import android.stats.style.StyleEnums.SNAPSHOT import android.stats.style.StyleEnums.THEMED_ICON_APPLIED import android.stats.style.StyleEnums.THEME_COLOR_APPLIED import android.stats.style.StyleEnums.WALLPAPER_APPLIED import android.stats.style.StyleEnums.WALLPAPER_DESTINATION_HOME_AND_LOCK_SCREEN import android.stats.style.StyleEnums.WALLPAPER_DESTINATION_HOME_SCREEN import android.stats.style.StyleEnums.WALLPAPER_DESTINATION_LOCK_SCREEN import android.stats.style.StyleEnums.WALLPAPER_EFFECT_APPLIED import android.stats.style.StyleEnums.WALLPAPER_EFFECT_FG_DOWNLOAD import android.stats.style.StyleEnums.WALLPAPER_EFFECT_PROBE import android.stats.style.StyleEnums.WALLPAPER_EXPLORE import android.text.TextUtils import com.android.customization.model.color.ColorCustomizationManager import com.android.customization.model.grid.GridOption import com.android.customization.module.logging.ThemesUserEventLogger.ClockSize import com.android.customization.module.logging.ThemesUserEventLogger.ColorSource import com.android.wallpaper.module.WallpaperPreferences import com.android.wallpaper.module.logging.UserEventLogger.EffectStatus import com.android.wallpaper.module.logging.UserEventLogger.SetWallpaperEntryPoint import com.android.wallpaper.module.logging.UserEventLogger.WallpaperDestination import com.android.wallpaper.util.ActivityUtils import com.android.wallpaper.util.LaunchSourceUtils import javax.inject.Inject import javax.inject.Singleton /** StatsLog-backed implementation of [ThemesUserEventLogger]. */ @Singleton class ThemesUserEventLoggerImpl @Inject constructor( private val preferences: WallpaperPreferences, private val colorManager: ColorCustomizationManager, private val appSessionId: AppSessionId, ) : ThemesUserEventLogger { override fun logSnapshot() { SysUiStatsLogger(SNAPSHOT) .setWallpaperCategoryHash(preferences.getHomeCategoryHash()) .setWallpaperIdHash(preferences.getHomeWallpaperIdHash()) .setLockWallpaperCategoryHash(preferences.getLockCategoryHash()) .setLockWallpaperIdHash(preferences.getLockWallpaperIdHash()) .setEffectIdHash(preferences.getHomeWallpaperEffectsIdHash()) .setColorSource(colorManager.currentColorSourceForLogging) .setColorVariant(colorManager.currentStyleForLogging) .setSeedColor(colorManager.currentSeedColorForLogging) .log() } override fun logAppLaunched(launchSource: Intent) { SysUiStatsLogger(APP_LAUNCHED) .setAppSessionId(appSessionId.createNewId().getId()) .setLaunchedPreference(launchSource.getAppLaunchSource()) .log() } override fun logWallpaperApplied( collectionId: String?, wallpaperId: String?, effects: String?, @SetWallpaperEntryPoint setWallpaperEntryPoint: Int, @WallpaperDestination destination: Int, ) { val categoryHash = getIdHashCode(collectionId) val wallpaperIdHash = getIdHashCode(wallpaperId) val isHomeWallpaperSet = destination == WALLPAPER_DESTINATION_HOME_SCREEN || destination == WALLPAPER_DESTINATION_HOME_AND_LOCK_SCREEN val isLockWallpaperSet = destination == WALLPAPER_DESTINATION_LOCK_SCREEN || destination == WALLPAPER_DESTINATION_HOME_AND_LOCK_SCREEN SysUiStatsLogger(WALLPAPER_APPLIED) .setAppSessionId(appSessionId.getId()) .setWallpaperCategoryHash(if (isHomeWallpaperSet) categoryHash else 0) .setWallpaperIdHash(if (isHomeWallpaperSet) wallpaperIdHash else 0) .setLockWallpaperCategoryHash(if (isLockWallpaperSet) categoryHash else 0) .setLockWallpaperIdHash(if (isLockWallpaperSet) wallpaperIdHash else 0) .setEffectIdHash(getIdHashCode(effects)) .setSetWallpaperEntryPoint(setWallpaperEntryPoint) .setWallpaperDestination(destination) .log() } override fun logEffectApply( effect: String, @EffectStatus status: Int, timeElapsedMillis: Long, resultCode: Int ) { SysUiStatsLogger(WALLPAPER_EFFECT_APPLIED) .setAppSessionId(appSessionId.getId()) .setEffectPreference(status) .setEffectIdHash(getIdHashCode(effect)) .setTimeElapsed(timeElapsedMillis) .setEffectResultCode(resultCode) .log() } override fun logEffectProbe(effect: String, @EffectStatus status: Int) { SysUiStatsLogger(WALLPAPER_EFFECT_PROBE) .setAppSessionId(appSessionId.getId()) .setEffectPreference(status) .setEffectIdHash(getIdHashCode(effect)) .log() } override fun logEffectForegroundDownload( effect: String, @EffectStatus status: Int, timeElapsedMillis: Long ) { SysUiStatsLogger(WALLPAPER_EFFECT_FG_DOWNLOAD) .setAppSessionId(appSessionId.getId()) .setEffectPreference(status) .setEffectIdHash(getIdHashCode(effect)) .setTimeElapsed(timeElapsedMillis) .log() } override fun logResetApplied() { SysUiStatsLogger(RESET_APPLIED).setAppSessionId(appSessionId.getId()).log() } override fun logWallpaperExploreButtonClicked() { SysUiStatsLogger(WALLPAPER_EXPLORE).setAppSessionId(appSessionId.getId()).log() } override fun logThemeColorApplied( @ColorSource source: Int, style: Int, seedColor: Int, ) { SysUiStatsLogger(THEME_COLOR_APPLIED) .setAppSessionId(appSessionId.getId()) .setColorSource(source) .setColorVariant(style) .setSeedColor(seedColor) .log() } override fun logGridApplied(grid: GridOption) { SysUiStatsLogger(GRID_APPLIED) .setAppSessionId(appSessionId.getId()) .setLauncherGrid(grid.getLauncherGridInt()) .log() } override fun logClockApplied(clockId: String) { SysUiStatsLogger(CLOCK_APPLIED) .setAppSessionId(appSessionId.getId()) .setClockPackageHash(getIdHashCode(clockId)) .log() } override fun logClockColorApplied(seedColor: Int) { SysUiStatsLogger(CLOCK_COLOR_APPLIED) .setAppSessionId(appSessionId.getId()) .setSeedColor(seedColor) .log() } override fun logClockSizeApplied(@ClockSize clockSize: Int) { SysUiStatsLogger(CLOCK_SIZE_APPLIED) .setAppSessionId(appSessionId.getId()) .setClockSize(clockSize) .log() } override fun logThemedIconApplied(useThemeIcon: Boolean) { SysUiStatsLogger(THEMED_ICON_APPLIED) .setAppSessionId(appSessionId.getId()) .setToggleOn(useThemeIcon) .log() } override fun logLockScreenNotificationApplied(showLockScreenNotifications: Boolean) { SysUiStatsLogger(LOCK_SCREEN_NOTIFICATION_APPLIED) .setAppSessionId(appSessionId.getId()) .setToggleOn(showLockScreenNotifications) .log() } override fun logShortcutApplied(shortcut: String, shortcutSlotId: String) { SysUiStatsLogger(SHORTCUT_APPLIED) .setAppSessionId(appSessionId.getId()) .setShortcut(shortcut) .setShortcutSlotId(shortcutSlotId) .log() } override fun logDarkThemeApplied(useDarkTheme: Boolean) { SysUiStatsLogger(DARK_THEME_APPLIED) .setAppSessionId(appSessionId.getId()) .setToggleOn(useDarkTheme) .log() } /** * The grid integer depends on the column and row numbers. For example: 4x5 is 405 13x37 is 1337 * The upper limit for the column / row count is 99. */ private fun GridOption.getLauncherGridInt(): Int { return cols * 100 + rows } private fun Intent.getAppLaunchSource(): Int { return if (hasExtra(LaunchSourceUtils.WALLPAPER_LAUNCH_SOURCE)) { when (getStringExtra(LaunchSourceUtils.WALLPAPER_LAUNCH_SOURCE)) { LaunchSourceUtils.LAUNCH_SOURCE_LAUNCHER -> LAUNCHED_LAUNCHER LaunchSourceUtils.LAUNCH_SOURCE_SETTINGS -> LAUNCHED_SETTINGS LaunchSourceUtils.LAUNCH_SOURCE_SUW -> LAUNCHED_SUW LaunchSourceUtils.LAUNCH_SOURCE_TIPS -> LAUNCHED_TIPS LaunchSourceUtils.LAUNCH_SOURCE_DEEP_LINK -> LAUNCHED_DEEP_LINK LaunchSourceUtils.LAUNCH_SOURCE_KEYGUARD -> LAUNCHED_KEYGUARD else -> LAUNCHED_PREFERENCE_UNSPECIFIED } } else if (ActivityUtils.isLaunchedFromSettingsSearch(this)) { LAUNCHED_SETTINGS_SEARCH } else if (action != null && action == WallpaperManager.ACTION_CROP_AND_SET_WALLPAPER) { LAUNCHED_CROP_AND_SET_ACTION } else if (categories != null && categories.contains(Intent.CATEGORY_LAUNCHER)) { LAUNCHED_LAUNCH_ICON } else { LAUNCHED_PREFERENCE_UNSPECIFIED } } /** If not set, the output hash is 0. */ private fun WallpaperPreferences.getHomeCategoryHash(): Int { return getIdHashCode(getHomeWallpaperCollectionId()) } /** If not set, the output hash is 0. */ private fun WallpaperPreferences.getHomeWallpaperIdHash(): Int { val remoteId = getHomeWallpaperRemoteId() val wallpaperId = if (!TextUtils.isEmpty(remoteId)) remoteId else getHomeWallpaperServiceName() return getIdHashCode(wallpaperId) } /** If not set, the output hash is 0. */ private fun WallpaperPreferences.getLockCategoryHash(): Int { return getIdHashCode(getLockWallpaperCollectionId()) } /** If not set, the output hash is 0. */ private fun WallpaperPreferences.getLockWallpaperIdHash(): Int { val remoteId = getLockWallpaperRemoteId() val wallpaperId = if (!TextUtils.isEmpty(remoteId)) remoteId else getLockWallpaperServiceName() return getIdHashCode(wallpaperId) } /** If not set, the output hash is 0. */ private fun WallpaperPreferences.getHomeWallpaperEffectsIdHash(): Int { return getIdHashCode(getHomeWallpaperEffects()) } private fun getIdHashCode(id: String?): Int { return id?.hashCode() ?: 0 } }
android_packages_apps_ThemePicker/src/com/android/customization/module/logging/ThemesUserEventLoggerImpl.kt
767611326
/* * Copyright (C) 2023 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.customization.module.logging import com.android.internal.logging.InstanceId import com.android.internal.logging.InstanceIdSequence import javax.inject.Inject import javax.inject.Singleton @Singleton class AppSessionId @Inject constructor() { private var sessionId: InstanceId = newInstanceId() fun createNewId(): AppSessionId { sessionId = newInstanceId() return this } fun getId(): Int { return sessionId.hashCode() } private fun newInstanceId(): InstanceId = InstanceIdSequence(INSTANCE_ID_MAX).newInstanceId() companion object { // At most 20 bits: ~1m possibilities, ~0.5% probability of collision in 100 values private const val INSTANCE_ID_MAX = 1 shl 20 } }
android_packages_apps_ThemePicker/src/com/android/customization/module/logging/AppSessionId.kt
2664575116
/* * Copyright (C) 2019 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.customization.module import com.android.wallpaper.module.WallpaperPreferences interface CustomizationPreferences : WallpaperPreferences { fun getSerializedCustomThemes(): String? fun storeCustomThemes(serializedCustomThemes: String) fun getTabVisited(id: String): Boolean fun setTabVisited(id: String) fun getThemedIconEnabled(): Boolean fun setThemedIconEnabled(enabled: Boolean) companion object { const val KEY_CUSTOM_THEME = "themepicker_custom_theme" const val KEY_VISITED_PREFIX = "themepicker_visited_" const val KEY_THEMED_ICON_ENABLED = "themepicker_themed_icon_enabled" } }
android_packages_apps_ThemePicker/src/com/android/customization/module/CustomizationPreferences.kt
4241967115
/* * Copyright (C) 2022 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.customization.module import androidx.fragment.app.Fragment import com.android.customization.picker.quickaffordance.ui.fragment.KeyguardQuickAffordancePickerFragment import com.android.wallpaper.module.FragmentFactory class ThemePickerFragmentFactory : FragmentFactory { override fun create(id: String): Fragment? { return when (id) { KeyguardQuickAffordancePickerFragment.DESTINATION_ID -> KeyguardQuickAffordancePickerFragment.newInstance() else -> null } } }
android_packages_apps_ThemePicker/src/com/android/customization/module/ThemePickerFragmentFactory.kt
2282331884
/* * Copyright (C) 2023 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.customization.model.mode import android.app.UiModeManager import android.content.Context import android.content.res.Configuration import androidx.annotation.VisibleForTesting import com.android.wallpaper.picker.undo.domain.interactor.SnapshotRestorer import com.android.wallpaper.picker.undo.domain.interactor.SnapshotStore import com.android.wallpaper.picker.undo.shared.model.RestorableSnapshot import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext class DarkModeSnapshotRestorer : SnapshotRestorer { private val backgroundDispatcher: CoroutineDispatcher private val isActive: () -> Boolean private val setActive: suspend (Boolean) -> Unit private var store: SnapshotStore = SnapshotStore.NOOP constructor( context: Context, manager: UiModeManager, backgroundDispatcher: CoroutineDispatcher, ) : this( backgroundDispatcher = backgroundDispatcher, isActive = { context.applicationContext.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_YES != 0 }, setActive = { isActive -> manager.setNightModeActivated(isActive) }, ) @VisibleForTesting constructor( backgroundDispatcher: CoroutineDispatcher, isActive: () -> Boolean, setActive: suspend (Boolean) -> Unit, ) { this.backgroundDispatcher = backgroundDispatcher this.isActive = isActive this.setActive = setActive } override suspend fun setUpSnapshotRestorer(store: SnapshotStore): RestorableSnapshot { this.store = store return snapshot( isActivated = isActive(), ) } override suspend fun restoreToSnapshot(snapshot: RestorableSnapshot) { val isActivated = snapshot.args[KEY]?.toBoolean() == true withContext(backgroundDispatcher) { setActive(isActivated) } } fun store( isActivated: Boolean, ) { store.store( snapshot( isActivated = isActivated, ), ) } private fun snapshot( isActivated: Boolean, ): RestorableSnapshot { return RestorableSnapshot( args = buildMap { put( KEY, isActivated.toString(), ) } ) } companion object { private const val KEY = "is_activated" } }
android_packages_apps_ThemePicker/src/com/android/customization/model/mode/DarkModeSnapshotRestorer.kt
1127227871
/* * Copyright (C) 2023 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.customization.model.color import android.R import android.app.WallpaperColors import android.content.Context import android.provider.Settings import android.util.Log import com.android.customization.model.ResourceConstants.OVERLAY_CATEGORY_THEME_STYLE import com.android.systemui.monet.ColorScheme import com.android.systemui.monet.Style import org.json.JSONException import org.json.JSONObject class ThemedWallpaperColorResources(wallpaperColors: WallpaperColors, context: Context) : WallpaperColorResources(wallpaperColors) { init { val wallpaperColorScheme = ColorScheme( wallpaperColors = wallpaperColors, darkTheme = false, style = fetchThemeStyleFromSetting(context) ) addOverlayColor(wallpaperColorScheme.neutral1, R.color.system_neutral1_10) addOverlayColor(wallpaperColorScheme.neutral2, R.color.system_neutral2_10) addOverlayColor(wallpaperColorScheme.accent1, R.color.system_accent1_10) addOverlayColor(wallpaperColorScheme.accent2, R.color.system_accent2_10) addOverlayColor(wallpaperColorScheme.accent3, R.color.system_accent3_10) } private fun fetchThemeStyleFromSetting(context: Context): Style { val overlayPackageJson = Settings.Secure.getString( context.contentResolver, Settings.Secure.THEME_CUSTOMIZATION_OVERLAY_PACKAGES, ) return if (!overlayPackageJson.isNullOrEmpty()) { try { val jsonObject = JSONObject(overlayPackageJson) Style.valueOf(jsonObject.getString(OVERLAY_CATEGORY_THEME_STYLE)) } catch (e: (JSONException)) { Log.i(TAG, "Failed to parse THEME_CUSTOMIZATION_OVERLAY_PACKAGES.", e) Style.TONAL_SPOT } catch (e: IllegalArgumentException) { Log.i(TAG, "Failed to parse THEME_CUSTOMIZATION_OVERLAY_PACKAGES.", e) Style.TONAL_SPOT } } else { Style.TONAL_SPOT } } companion object { private const val TAG = "ThemedWallpaperColorResources" } }
android_packages_apps_ThemePicker/src/com/android/customization/model/color/ThemedWallpaperColorResources.kt
2115955202
/* * Copyright (C) 2023 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.customization.model.color import android.content.Context import android.stats.style.StyleEnums import android.view.View import androidx.annotation.ColorInt import com.android.customization.model.color.ColorOptionsProvider.ColorSource import com.android.customization.picker.color.shared.model.ColorType import com.android.systemui.monet.Style import com.android.wallpaper.R /** * Represents a color option in the revamped UI, it can be used for both wallpaper and preset colors */ class ColorOptionImpl( title: String?, overlayPackages: Map<String, String?>, isDefault: Boolean, private val source: String?, style: Style, index: Int, private val previewInfo: PreviewInfo, val type: ColorType, ) : ColorOption(title, overlayPackages, isDefault, style, index) { class PreviewInfo( @ColorInt val lightColors: IntArray, @ColorInt val darkColors: IntArray, ) : ColorOption.PreviewInfo { @ColorInt fun resolveColors(darkTheme: Boolean): IntArray { return if (darkTheme) darkColors else lightColors } } override fun bindThumbnailTile(view: View?) { // Do nothing. This function will no longer be used in the Revamped UI } override fun getLayoutResId(): Int { return R.layout.color_option } override fun getPreviewInfo(): PreviewInfo { return previewInfo } override fun getContentDescription(context: Context): CharSequence? { return title } override fun getSource(): String? { return source } override fun getSourceForLogging(): Int { return when (getSource()) { ColorOptionsProvider.COLOR_SOURCE_PRESET -> StyleEnums.COLOR_SOURCE_PRESET_COLOR ColorOptionsProvider.COLOR_SOURCE_HOME -> StyleEnums.COLOR_SOURCE_HOME_SCREEN_WALLPAPER ColorOptionsProvider.COLOR_SOURCE_LOCK -> StyleEnums.COLOR_SOURCE_LOCK_SCREEN_WALLPAPER else -> StyleEnums.COLOR_SOURCE_UNSPECIFIED } } override fun getStyleForLogging(): Int = style.toString().hashCode() class Builder { var title: String? = null @ColorInt var lightColors: IntArray = intArrayOf() @ColorInt var darkColors: IntArray = intArrayOf() @ColorSource var source: String? = null var isDefault = false var style = Style.TONAL_SPOT var index = 0 var packages: MutableMap<String, String?> = HashMap() var type = ColorType.WALLPAPER_COLOR fun build(): ColorOptionImpl { return ColorOptionImpl( title, packages, isDefault, source, style, index, createPreviewInfo(), type ) } private fun createPreviewInfo(): PreviewInfo { return PreviewInfo(lightColors, darkColors) } fun addOverlayPackage(category: String?, packageName: String?): ColorOptionImpl.Builder { category?.let { packages[category] = packageName } return this } } }
android_packages_apps_ThemePicker/src/com/android/customization/model/color/ColorOptionImpl.kt
4221950642
/* * Copyright (C) 2022 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.customization.model.color import android.app.WallpaperColors import android.app.WallpaperManager import android.content.Context import android.content.res.ColorStateList import android.content.res.Resources import androidx.annotation.ColorInt import androidx.core.graphics.ColorUtils.setAlphaComponent import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import com.android.customization.model.CustomizationManager.OptionsFetchedListener import com.android.customization.model.ResourceConstants.COLOR_BUNDLES_ARRAY_NAME import com.android.customization.model.ResourceConstants.COLOR_BUNDLE_MAIN_COLOR_PREFIX import com.android.customization.model.ResourceConstants.COLOR_BUNDLE_NAME_PREFIX import com.android.customization.model.ResourceConstants.COLOR_BUNDLE_STYLE_PREFIX import com.android.customization.model.ResourceConstants.OVERLAY_CATEGORY_COLOR import com.android.customization.model.ResourceConstants.OVERLAY_CATEGORY_SYSTEM_PALETTE import com.android.customization.model.ResourcesApkProvider import com.android.customization.model.color.ColorOptionsProvider.COLOR_SOURCE_HOME import com.android.customization.model.color.ColorOptionsProvider.COLOR_SOURCE_LOCK import com.android.customization.model.color.ColorUtils.toColorString import com.android.customization.picker.color.shared.model.ColorType import com.android.systemui.monet.ColorScheme import com.android.systemui.monet.Style import com.android.wallpaper.R import com.android.wallpaper.module.InjectorProvider import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Default implementation of {@link ColorOptionsProvider} that reads preset colors from a stub APK. * TODO (b/311212666): Make [ColorProvider] and [ColorCustomizationManager] injectable */ class ColorProvider(private val context: Context, stubPackageName: String) : ResourcesApkProvider(context, stubPackageName), ColorOptionsProvider { companion object { const val themeStyleEnabled = true val styleSize = if (themeStyleEnabled) Style.values().size else 1 private const val TAG = "ColorProvider" private const val MAX_SEED_COLORS = 4 private const val MAX_PRESET_COLORS = 4 private const val ALPHA_MASK = 0xFF } private val monetEnabled = ColorUtils.isMonetEnabled(context) // TODO(b/202145216): Use style method to fetch the list of style. private var styleList = if (themeStyleEnabled) arrayOf(Style.TONAL_SPOT, Style.SPRITZ, Style.VIBRANT, Style.EXPRESSIVE) else arrayOf(Style.TONAL_SPOT) private var monochromeBundleName: String? = null private val scope = if (mContext is LifecycleOwner) { mContext.lifecycleScope } else { CoroutineScope(Dispatchers.Default + SupervisorJob()) } private var colorsAvailable = true private var colorBundles: List<ColorOption>? = null private var homeWallpaperColors: WallpaperColors? = null private var lockWallpaperColors: WallpaperColors? = null override fun isAvailable(): Boolean { return monetEnabled && super.isAvailable() && colorsAvailable } override fun fetch( callback: OptionsFetchedListener<ColorOption>?, reload: Boolean, homeWallpaperColors: WallpaperColors?, lockWallpaperColors: WallpaperColors?, ) { val wallpaperColorsChanged = this.homeWallpaperColors != homeWallpaperColors || this.lockWallpaperColors != lockWallpaperColors if (wallpaperColorsChanged) { this.homeWallpaperColors = homeWallpaperColors this.lockWallpaperColors = lockWallpaperColors } if (colorBundles == null || reload || wallpaperColorsChanged) { scope.launch { try { if (colorBundles == null || reload) { loadPreset() } if (wallpaperColorsChanged || reload) { loadSeedColors( homeWallpaperColors, lockWallpaperColors, ) } } catch (e: Throwable) { colorsAvailable = false callback?.onError(e) return@launch } callback?.onOptionsLoaded(colorBundles) } } else { callback?.onOptionsLoaded(colorBundles) } } private fun isLockScreenWallpaperLastApplied(): Boolean { // The WallpaperId increases every time a new wallpaper is set, so the larger wallpaper id // is the most recently set wallpaper val manager = WallpaperManager.getInstance(mContext) return manager.getWallpaperId(WallpaperManager.FLAG_LOCK) > manager.getWallpaperId(WallpaperManager.FLAG_SYSTEM) } private fun loadSeedColors( homeWallpaperColors: WallpaperColors?, lockWallpaperColors: WallpaperColors?, ) { if (homeWallpaperColors == null) return val bundles: MutableList<ColorOption> = ArrayList() val colorsPerSource = if (lockWallpaperColors == null) { MAX_SEED_COLORS } else { MAX_SEED_COLORS / 2 } if (lockWallpaperColors != null) { val shouldLockColorsGoFirst = isLockScreenWallpaperLastApplied() // First half of the colors buildColorSeeds( if (shouldLockColorsGoFirst) lockWallpaperColors else homeWallpaperColors, colorsPerSource, if (shouldLockColorsGoFirst) COLOR_SOURCE_LOCK else COLOR_SOURCE_HOME, true, bundles, ) // Second half of the colors buildColorSeeds( if (shouldLockColorsGoFirst) homeWallpaperColors else lockWallpaperColors, MAX_SEED_COLORS - bundles.size / styleSize, if (shouldLockColorsGoFirst) COLOR_SOURCE_HOME else COLOR_SOURCE_LOCK, false, bundles, ) } else { buildColorSeeds( homeWallpaperColors, colorsPerSource, COLOR_SOURCE_HOME, true, bundles, ) } // Insert monochrome in the second position if it is enabled and included in preset // colors if (InjectorProvider.getInjector().getFlags().isMonochromaticThemeEnabled(mContext)) { monochromeBundleName?.let { bundles.add(1, buildPreset(it, -1, Style.MONOCHROMATIC, ColorType.WALLPAPER_COLOR)) } } bundles.addAll( colorBundles?.filterNot { (it as ColorOptionImpl).type == ColorType.WALLPAPER_COLOR } ?: emptyList() ) colorBundles = bundles } private fun buildColorSeeds( wallpaperColors: WallpaperColors, maxColors: Int, source: String, containsDefault: Boolean, bundles: MutableList<ColorOption>, ) { val seedColors = ColorScheme.getSeedColors(wallpaperColors) val defaultSeed = seedColors.first() buildBundle(defaultSeed, 0, containsDefault, source, bundles) for ((i, colorInt) in seedColors.drop(1).take(maxColors - 1).withIndex()) { buildBundle(colorInt, i + 1, false, source, bundles) } } private fun buildBundle( colorInt: Int, i: Int, isDefault: Boolean, source: String, bundles: MutableList<ColorOption>, ) { // TODO(b/202145216): Measure time cost in the loop. for (style in styleList) { val lightColorScheme = ColorScheme(colorInt, /* darkTheme= */ false, style) val darkColorScheme = ColorScheme(colorInt, /* darkTheme= */ true, style) val builder = ColorOptionImpl.Builder() builder.lightColors = getLightColorPreview(lightColorScheme) builder.darkColors = getDarkColorPreview(darkColorScheme) builder.addOverlayPackage( OVERLAY_CATEGORY_SYSTEM_PALETTE, if (isDefault) "" else toColorString(colorInt) ) builder.title = when (style) { Style.TONAL_SPOT -> context.getString(R.string.content_description_dynamic_color_option) Style.SPRITZ -> context.getString(R.string.content_description_neutral_color_option) Style.VIBRANT -> context.getString(R.string.content_description_vibrant_color_option) Style.EXPRESSIVE -> context.getString(R.string.content_description_expressive_color_option) else -> context.getString(R.string.content_description_dynamic_color_option) } builder.source = source builder.style = style // Color option index value starts from 1. builder.index = i + 1 builder.isDefault = isDefault builder.type = ColorType.WALLPAPER_COLOR bundles.add(builder.build()) } } /** * Returns the light theme version of the Revamped UI preview of a ColorScheme based on this * order: top left, top right, bottom left, bottom right * * This color mapping corresponds to GM3 colors: Primary (light), Primary (light), Secondary * LStar 85, and Tertiary LStar 70 */ @ColorInt private fun getLightColorPreview(colorScheme: ColorScheme): IntArray { return intArrayOf( setAlphaComponent(colorScheme.accent1.s600, ALPHA_MASK), setAlphaComponent(colorScheme.accent1.s600, ALPHA_MASK), ColorStateList.valueOf(colorScheme.accent2.s500).withLStar(85f).colors[0], setAlphaComponent(colorScheme.accent3.s300, ALPHA_MASK), ) } /** * Returns the dark theme version of the Revamped UI preview of a ColorScheme based on this * order: top left, top right, bottom left, bottom right * * This color mapping corresponds to GM3 colors: Primary (dark), Primary (dark), Secondary LStar * 35, and Tertiary LStar 70 */ @ColorInt private fun getDarkColorPreview(colorScheme: ColorScheme): IntArray { return intArrayOf( setAlphaComponent(colorScheme.accent1.s200, ALPHA_MASK), setAlphaComponent(colorScheme.accent1.s200, ALPHA_MASK), ColorStateList.valueOf(colorScheme.accent2.s500).withLStar(35f).colors[0], setAlphaComponent(colorScheme.accent3.s300, ALPHA_MASK), ) } /** * Returns the light theme version of the Revamped UI preview of a ColorScheme based on this * order: top left, top right, bottom left, bottom right * * This color mapping corresponds to GM3 colors: Primary LStar 0, Primary LStar 0, Secondary * LStar 85, and Tertiary LStar 70 */ @ColorInt private fun getLightMonochromePreview(colorScheme: ColorScheme): IntArray { return intArrayOf( setAlphaComponent(colorScheme.accent1.s1000, ALPHA_MASK), setAlphaComponent(colorScheme.accent1.s1000, ALPHA_MASK), ColorStateList.valueOf(colorScheme.accent2.s500).withLStar(85f).colors[0], setAlphaComponent(colorScheme.accent3.s300, ALPHA_MASK), ) } /** * Returns the dark theme version of the Revamped UI preview of a ColorScheme based on this * order: top left, top right, bottom left, bottom right * * This color mapping corresponds to GM3 colors: Primary LStar 99, Primary LStar 99, Secondary * LStar 35, and Tertiary LStar 70 */ @ColorInt private fun getDarkMonochromePreview(colorScheme: ColorScheme): IntArray { return intArrayOf( setAlphaComponent(colorScheme.accent1.s10, ALPHA_MASK), setAlphaComponent(colorScheme.accent1.s10, ALPHA_MASK), ColorStateList.valueOf(colorScheme.accent2.s500).withLStar(35f).colors[0], setAlphaComponent(colorScheme.accent3.s300, ALPHA_MASK), ) } /** * Returns the Revamped UI preview of a preset ColorScheme based on this order: top left, top * right, bottom left, bottom right */ private fun getPresetColorPreview(colorScheme: ColorScheme, seed: Int): IntArray { val colors = when (colorScheme.style) { Style.FRUIT_SALAD -> intArrayOf(seed, colorScheme.accent1.s200) Style.TONAL_SPOT -> intArrayOf(colorScheme.accentColor, colorScheme.accentColor) Style.RAINBOW -> intArrayOf(colorScheme.accent1.s200, colorScheme.accent1.s200) else -> intArrayOf(colorScheme.accent1.s100, colorScheme.accent1.s100) } return intArrayOf( colors[0], colors[1], colors[0], colors[1], ) } private suspend fun loadPreset() = withContext(Dispatchers.IO) { val bundles: MutableList<ColorOption> = ArrayList() val bundleNames = if (isAvailable) getItemsFromStub(COLOR_BUNDLES_ARRAY_NAME) else emptyArray() // Color option index value starts from 1. var index = 1 val maxPresetColors = if (themeStyleEnabled) bundleNames.size else MAX_PRESET_COLORS // keep track of whether monochrome is included in preset colors to determine // inclusion in wallpaper colors var hasMonochrome = false for (bundleName in bundleNames.take(maxPresetColors)) { if (themeStyleEnabled) { val styleName = try { getItemStringFromStub(COLOR_BUNDLE_STYLE_PREFIX, bundleName) } catch (e: Resources.NotFoundException) { null } val style = try { if (styleName != null) Style.valueOf(styleName) else Style.TONAL_SPOT } catch (e: IllegalArgumentException) { Style.TONAL_SPOT } if (style == Style.MONOCHROMATIC) { if ( !InjectorProvider.getInjector() .getFlags() .isMonochromaticThemeEnabled(mContext) ) { continue } hasMonochrome = true monochromeBundleName = bundleName } bundles.add(buildPreset(bundleName, index, style)) } else { bundles.add(buildPreset(bundleName, index, null)) } index++ } if (!hasMonochrome) { monochromeBundleName = null } colorBundles = bundles } private fun buildPreset( bundleName: String, index: Int, style: Style? = null, type: ColorType = ColorType.PRESET_COLOR, ): ColorOptionImpl { val builder = ColorOptionImpl.Builder() builder.title = getItemStringFromStub(COLOR_BUNDLE_NAME_PREFIX, bundleName) builder.index = index builder.source = ColorOptionsProvider.COLOR_SOURCE_PRESET builder.type = type val colorFromStub = getItemColorFromStub(COLOR_BUNDLE_MAIN_COLOR_PREFIX, bundleName) var darkColorScheme = ColorScheme(colorFromStub, /* darkTheme= */ true) var lightColorScheme = ColorScheme(colorFromStub, /* darkTheme= */ false) val lightColor = lightColorScheme.accentColor val darkColor = darkColorScheme.accentColor var lightColors = intArrayOf(lightColor, lightColor, lightColor, lightColor) var darkColors = intArrayOf(darkColor, darkColor, darkColor, darkColor) builder.addOverlayPackage(OVERLAY_CATEGORY_COLOR, toColorString(colorFromStub)) builder.addOverlayPackage(OVERLAY_CATEGORY_SYSTEM_PALETTE, toColorString(colorFromStub)) if (style != null) { builder.style = style lightColorScheme = ColorScheme(colorFromStub, /* darkTheme= */ false, style) darkColorScheme = ColorScheme(colorFromStub, /* darkTheme= */ true, style) when (style) { Style.MONOCHROMATIC -> { darkColors = getDarkMonochromePreview(darkColorScheme) lightColors = getLightMonochromePreview(lightColorScheme) } else -> { darkColors = getPresetColorPreview(darkColorScheme, colorFromStub) lightColors = getPresetColorPreview(lightColorScheme, colorFromStub) } } } builder.lightColors = lightColors builder.darkColors = darkColors return builder.build() } }
android_packages_apps_ThemePicker/src/com/android/customization/model/color/ColorProvider.kt
477474605
/* * Copyright (C) 2023 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.customization.model.themedicon.data.repository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow class ThemeIconRepository { private val _isActivated = MutableStateFlow(false) val isActivated = _isActivated.asStateFlow() fun setActivated(isActivated: Boolean) { _isActivated.value = isActivated } }
android_packages_apps_ThemePicker/src/com/android/customization/model/themedicon/data/repository/ThemedIconRepository.kt
4244297466
/* * Copyright (C) 2023 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.customization.model.themedicon.domain.interactor import androidx.lifecycle.LiveData import androidx.lifecycle.asLiveData import com.android.customization.model.themedicon.data.repository.ThemeIconRepository class ThemedIconInteractor( private val repository: ThemeIconRepository, ) { val isActivated = repository.isActivated private var isActivatedAsLiveData: LiveData<Boolean>? = null fun isActivatedAsLiveData(): LiveData<Boolean> { return isActivatedAsLiveData ?: isActivated.asLiveData().also { isActivatedAsLiveData = it } } fun setActivated(isActivated: Boolean) { repository.setActivated(isActivated) } }
android_packages_apps_ThemePicker/src/com/android/customization/model/themedicon/domain/interactor/ThemedIconInteractor.kt
747032111
/* * Copyright (C) 2023 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.customization.model.themedicon.domain.interactor import com.android.wallpaper.picker.undo.domain.interactor.SnapshotRestorer import com.android.wallpaper.picker.undo.domain.interactor.SnapshotStore import com.android.wallpaper.picker.undo.shared.model.RestorableSnapshot class ThemedIconSnapshotRestorer( private val isActivated: () -> Boolean, private val setActivated: (isActivated: Boolean) -> Unit, private val interactor: ThemedIconInteractor, ) : SnapshotRestorer { private var store: SnapshotStore = SnapshotStore.NOOP override suspend fun setUpSnapshotRestorer(store: SnapshotStore): RestorableSnapshot { this.store = store return snapshot() } override suspend fun restoreToSnapshot(snapshot: RestorableSnapshot) { val isActivated = snapshot.args[KEY]?.toBoolean() == true setActivated(isActivated) interactor.setActivated(isActivated) } fun store( isActivated: Boolean, ) { store.store(snapshot(isActivated = isActivated)) } private fun snapshot( isActivated: Boolean? = null, ): RestorableSnapshot { return RestorableSnapshot( args = buildMap { put(KEY, (isActivated ?: isActivated()).toString()) } ) } companion object { private const val KEY = "is_activated" } }
android_packages_apps_ThemePicker/src/com/android/customization/model/themedicon/domain/interactor/ThemedIconSnapshotRestorer.kt
3018382376
package edu.quinnipiac.ser210.framelayoutexample import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("edu.quinnipiac.ser210.framelayoutexample", appContext.packageName) } }
headfirst-ch3-SamWoodburn25/FrameLayoutExample/app/src/androidTest/java/edu/quinnipiac/ser210/framelayoutexample/ExampleInstrumentedTest.kt
1445640673
package edu.quinnipiac.ser210.framelayoutexample import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
headfirst-ch3-SamWoodburn25/FrameLayoutExample/app/src/test/java/edu/quinnipiac/ser210/framelayoutexample/ExampleUnitTest.kt
3833591681
package edu.quinnipiac.ser210.framelayoutexample import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
headfirst-ch3-SamWoodburn25/FrameLayoutExample/app/src/main/java/edu/quinnipiac/ser210/framelayoutexample/MainActivity.kt
1935634175
package edu.quinnipiac.ser210.linearlayoutexample import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("edu.quinnipiac.ser210.linearlayoutexample", appContext.packageName) } }
headfirst-ch3-SamWoodburn25/LinearLayoutExample/app/src/androidTest/java/edu/quinnipiac/ser210/linearlayoutexample/ExampleInstrumentedTest.kt
1071570603
package edu.quinnipiac.ser210.linearlayoutexample import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
headfirst-ch3-SamWoodburn25/LinearLayoutExample/app/src/test/java/edu/quinnipiac/ser210/linearlayoutexample/ExampleUnitTest.kt
2241371765
package edu.quinnipiac.ser210.linearlayoutexample import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
headfirst-ch3-SamWoodburn25/LinearLayoutExample/app/src/main/java/edu/quinnipiac/ser210/linearlayoutexample/MainActivity.kt
4269395416
package edu.quinnipiac.ser210.scrollviewexample import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("edu.quinnipiac.ser210.scrollviewexample", appContext.packageName) } }
headfirst-ch3-SamWoodburn25/ScrollViewExample/app/src/androidTest/java/edu/quinnipiac/ser210/scrollviewexample/ExampleInstrumentedTest.kt
3038437903
package edu.quinnipiac.ser210.scrollviewexample import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
headfirst-ch3-SamWoodburn25/ScrollViewExample/app/src/test/java/edu/quinnipiac/ser210/scrollviewexample/ExampleUnitTest.kt
3845797568
package edu.quinnipiac.ser210.scrollviewexample import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
headfirst-ch3-SamWoodburn25/ScrollViewExample/app/src/main/java/edu/quinnipiac/ser210/scrollviewexample/MainActivity.kt
1076943991
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.ui import kweb.AttributeBuilder val attrs get() = AttributeBuilder() //val AttributeBuilder.uiBlurredBg: AttributeBuilder // get() { // classes("ui-blurred-bg") // return this // }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/ui/UiClasses.kt
3820684127
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.ui.component import dev.d1s.exkt.kweb.plugins.bootstrap.* import dev.d1s.salesanalyzer.data.renderWithCurrentSimulation import dev.d1s.salesanalyzer.entity.Simulation import dev.d1s.salesanalyzer.ui.attrs import kotlinx.serialization.json.JsonArray import kweb.* import kweb.components.Component import kweb.util.json import kotlin.math.roundToInt private const val CHART_CANVAS_ID = "simulation-chart" fun Component.simulationContent() { div(attrs.bsDFlex.bsW100.bsMt4) { renderWithCurrentSimulation { simulationResult -> simulationResult.onSuccess { simulation -> div(attrs.bsW100.bsDFlex.bsFlexColumn) { resultTable(simulation) resultChart(simulation) } } simulationResult.onFailure { noSimulationAlert(it.message ?: "Что-то пошло не так.") } } } } private fun Component.resultTable(simulation: Simulation) { fun Component.row(name: String, value: String) { tr { th().set("scope", "row").text(name) td().text(value) } } table(attrs.bsW100.bsTable.bsTableDark.bsTableStripedColumns) { tbody { row(name = "Наименование товара", value = simulation.product.name) row(name = "Количество реализаций", value = simulation.sales.size.toString()) row(name = "Итоговая прибыль", value = simulation.profit.toString()) row(name = "Валовая прибыль", value = simulation.totalProfit.toString()) row(name = "Коэффициент ROI", value = "${simulation.roi}%") row(name = "Итоговые издержки", value = simulation.totalExpense.toString()) row(name = "Остаток счета", value = simulation.balance.toString()) } } } private fun Component.resultChart(simulation: Simulation) { div(attrs.bsW100.bsH100.bsMt4) { element("canvas", attrs.id(CHART_CANVAS_ID)) } val data = simulation.sales.map { it.balance.roundToInt().json } browser.callJsFunction("renderSimulationChart({})", JsonArray(data)) } private fun Component.noSimulationAlert(message: String) { div(attrs.bsAlert.bsFs4) .set("role", "alert") .new { i(attrs.bi.biInfoCircle.bsMe2.bsTextDanger) span().text(message) } }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/ui/component/SimulationContentComponent.kt
3106383243
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.ui.component import dev.d1s.exkt.kweb.plugins.bootstrap.* import dev.d1s.salesanalyzer.data.SimulationRepository import dev.d1s.salesanalyzer.entity.Product import dev.d1s.salesanalyzer.entity.Simulation import dev.d1s.salesanalyzer.runner.SimulationRunner import dev.d1s.salesanalyzer.ui.attrs import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kweb.* import kweb.components.Component import org.lighthousegames.logging.logging private const val MODAL_ID = "simulation-form-modal" private const val FORM_TITLE = "Описание товара" private const val FORM_NAME_ID = "simulation-name-input" private const val FORM_NAME_LABEL = "Наименование" private const val FORM_COST_ID = "simulation-cost-input" private const val FORM_COST_LABEL = "Себестоимость" private const val FORM_SELL_ID = "simulation-sell-input" private const val FORM_SELL_LABEL = "Стоимость продажи" private const val FORM_COUNT_ID = "simulation-count-input" private const val FORM_COUNT_LABEL = "Кол-во штук в одной партии" private const val FORM_RETURN_RATIO_ID = "simulation-return-ratio-input" private const val FORM_RETURN_RATIO_VALUE_ID = "simulation-return-ration-input-value" private const val FORM_RETURN_RATIO_LABEL = "% возвратов" private const val FORM_EXPENSE_ID = "simulation-expense-input" private const val FORM_EXPENSE_LABEL = "Издержки" private const val START_BUTTON_TEXT = "Запустить симуляцию" private const val INCORRECT_DATA_MESSAGE = "Введены неверные данные." private val formHandlerScope = CoroutineScope(Dispatchers.IO) private val log = logging() fun Component.simulationModalForm() { div(attrs.bsModal.bsFade.id(MODAL_ID)) .set("tabindex", "-1") .new { div(attrs.bsModalDialog) { div(attrs.bsModalContent.bsBgDark) { div(attrs.bsModalHeader.bsBorderSuccess) { h1(attrs.bsModalTitle.bsFs5).text(FORM_TITLE) @Suppress("ReplaceGetOrSet") button(attrs.bsBtnClose.bsTextBgDanger) .set("type", "button") .set("data-bs-dismiss", "modal") } div(attrs.bsModalBody) { modalForm() } } } } } fun <E : Element> E.configureSimulationModalFormTrigger(): E { set("data-bs-toggle", "modal") set("data-bs-target", "#$MODAL_ID") return this } private fun Component.modalForm() { form().set("autocomplete", "off").new { textInput(FORM_NAME_ID, FORM_NAME_LABEL) textInput(FORM_COST_ID, FORM_COST_LABEL, type = InputType.number) textInput(FORM_SELL_ID, FORM_SELL_LABEL, type = InputType.number) textInput(FORM_COUNT_ID, FORM_COUNT_LABEL, type = InputType.number) rangeInput(FORM_RETURN_RATIO_ID, FORM_RETURN_RATIO_LABEL) textInput(FORM_EXPENSE_ID, FORM_EXPENSE_LABEL, type = InputType.number) button(attrs.bsBtn.bsBtnOutlineSuccess, type = ButtonType.submit) .set("data-bs-dismiss", "modal") .text(START_BUTTON_TEXT) .on(preventDefault = true).click { handleStart() } } } private fun Component.textInput(id: String, label: String, type: InputType = InputType.text) { div(attrs.bsMb3) { label(attrs.bsFormLabel).setFor(id).text(label) input(attrs.bsFormControl.bsBgDark.bsTextLight.id(id), type = type) } } private fun Component.rangeInput(id: String, label: String) { fun syncInputValue() { browser.callJsFunction( "document.getElementById('$FORM_RETURN_RATIO_VALUE_ID').innerText = (document.getElementById('$FORM_RETURN_RATIO_ID').value) + \"%\"" ) } div(attrs.bsMb3) { label(attrs.bsFormLabel).setFor(id).text(label) input(attrs.bsFormRange.id(id), type = InputType.range) .on.input { syncInputValue() } span(attrs.id(FORM_RETURN_RATIO_VALUE_ID)) } syncInputValue() } private fun Component.handleStart() { suspend fun localStorageValue(key: String): String = requireNotNull(browser.doc.localStorage.get(key)) formHandlerScope.launch { val rawName = localStorageValue(FORM_NAME_ID) val rawCost = localStorageValue(FORM_COST_ID) val rawSell = localStorageValue(FORM_SELL_ID) val rawCount = localStorageValue(FORM_COUNT_ID) val rawReturnRatio = localStorageValue(FORM_RETURN_RATIO_ID) val rawExpense = localStorageValue(FORM_EXPENSE_ID) val session = browser.sessionId val product = try { Product( name = rawName, cost = rawCost.toDouble(), sell = rawSell.toDouble(), count = rawCount.toInt(), returnRatio = rawReturnRatio.toInt() / 100.0, expense = rawExpense.toDouble() ) } catch (e: Exception) { log.e(e) { "Failure when parsing form" } val result = Result.failure<Simulation>(IllegalArgumentException(INCORRECT_DATA_MESSAGE)) SimulationRepository.saveBySession(session, result) return@launch } val validation = product.validate() validation.onSuccess { log.i { "New product: $product" } SimulationRunner.runSimulationAndSave(product, session) } validation.onFailure { val result = Result.failure<Simulation>(it) SimulationRepository.saveBySession(session, result) } } } private fun Product.validate() = runCatching { if (name.isBlank()) { error("Имя товара не может быть пустым.") } if (cost < 1) { error("Себестоимость не может быть меньше единицы.") } if (sell < cost) { error("Цена продажи не может быть меньше себестоимости.") } if (count < 1) { error("Кол-во не может быть меньше единицы.") } if (count > 1000) { error("Кол-во не может быть больше тысячи.") } if (returnRatio > 0.9) { error("Процент возвратов не должен превышать 90%.") } if (expense < 1) { error("Издержки не могут быть меньше единицы.") } }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/ui/component/SimulationModalFormComponent.kt
3107697763
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.ui.component import dev.d1s.exkt.kweb.plugins.bootstrap.* import dev.d1s.salesanalyzer.ui.attrs import kweb.a import kweb.components.Component import kweb.div import kweb.i private const val PROJECT_URL = "https://github.com/d1snin/sales-analyzer" private const val LINK_TEXT = "Код на GitHub" fun Component.footer() { div(attrs.bsW100.bsMt4.bsDFlex.bsJustifyContentCenter.bsTextSecondary) { i(attrs.bi.biGithub.bsTextSecondary.bsMe2) a(attrs.bsTextReset, href = PROJECT_URL).text(LINK_TEXT) } }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/ui/component/FooterComponent.kt
4228416314
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.ui.component import dev.d1s.exkt.kweb.plugins.bootstrap.* import dev.d1s.salesanalyzer.data.renderWithCurrentSimulation import dev.d1s.salesanalyzer.entity.Simulation import dev.d1s.salesanalyzer.runner.SimulationRunner import dev.d1s.salesanalyzer.ui.attrs import kweb.button import kweb.components.Component import kweb.div import kweb.h1 private const val HEADING = "Анализ продаж торговой точки" private const val NEW_SIMULATION_BUTTON_TEXT = "Новая симуляция" private const val REPEAT_BUTTON_TEXT = "Повторить симуляцию" fun Component.heading() { div(attrs.bsDFlex.bsFlexColumn) { h1(attrs.bsDisplay3.bsMb3).text(HEADING) buttons() } } private fun Component.buttons() { renderWithCurrentSimulation { simulation -> div(attrs.bsDFlex) { newSimulationButton() simulation.onSuccess { repeatButton(simulation = it) } } } } private fun Component.newSimulationButton() { button(attrs.bsBtn.bsBtnOutlineSuccess.bsMe3) .configureSimulationModalFormTrigger() .text(NEW_SIMULATION_BUTTON_TEXT) } private fun Component.repeatButton(simulation: Simulation) { button(attrs.bsBtn.bsBtnOutlineSecondary) .text(REPEAT_BUTTON_TEXT) .on.click { SimulationRunner.runSimulationAndSave(simulation.product, browser.sessionId) } }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/ui/component/HeadingComponent.kt
1612748073
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.ui.component import kweb.ElementCreator import kweb.html.Document import kweb.html.HeadElement import kweb.meta import kweb.title import kweb.viewport private const val TITLE = "Анализ продаж" private const val DESCRIPTION = "Анализ расходов и прибыли торговой точки." // https://colorpicker.me/#b3d4b5 private const val THEME_COLOR = "#b3d4b5" fun Document.createHead() { head { createCommonMeta() createTitleAndDescription() } } private fun ElementCreator<HeadElement>.createCommonMeta() { meta(charset = "utf-8") viewport() meta(name = "theme-color", content = THEME_COLOR) } private fun ElementCreator<HeadElement>.createTitleAndDescription() { title().text(TITLE) meta(name = "title", content = TITLE) meta(name = "description", content = DESCRIPTION) }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/ui/component/HeadComponent.kt
419876856
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.ui.component import dev.d1s.exkt.kweb.plugins.bootstrap.* import dev.d1s.salesanalyzer.ui.attrs import kweb.div import kweb.html.Document fun Document.createBody() { body { div(attrs.bsContainer.bsDFlex.bsFlexColumn.bsAlignItemsStart.bsPt5) { heading() simulationContent() footer() } simulationModalForm() } }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/ui/component/BodyComponent.kt
1522559554
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.configuration import dev.d1s.exkt.ktor.server.koin.configuration.ApplicationConfigurer import dev.d1s.exkt.kweb.plugins.bootstrap.bootstrapIconsPlugin import dev.d1s.exkt.kweb.plugins.bootstrap.bootstrapPlugin import dev.d1s.salesanalyzer.plugin.chartJsPlugin import dev.d1s.salesanalyzer.ui.component.createBody import dev.d1s.salesanalyzer.ui.component.createHead import io.ktor.server.application.* import io.ktor.server.config.* import io.ktor.server.plugins.compression.* import io.ktor.server.plugins.defaultheaders.* import io.ktor.server.websocket.* import kweb.Kweb import kweb.installKwebOnRemainingRoutes import kweb.plugins.css.CSSPlugin import kweb.plugins.javascript.JavascriptPlugin import org.koin.core.module.Module object Website : ApplicationConfigurer { override fun Application.configure(module: Module, config: ApplicationConfig) { install(DefaultHeaders) install(Compression) install(WebSockets) install(Kweb) { val cssPlugin = CSSPlugin("css", "main.css") val jsPlugin = JavascriptPlugin("js", setOf("form.js", "chart.js")) plugins = listOf(bootstrapPlugin, bootstrapIconsPlugin, chartJsPlugin, cssPlugin, jsPlugin) } installKwebOnRemainingRoutes { doc.apply { createHead() createBody() } } } }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/configuration/Website.kt
3393352036
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.configuration import dev.d1s.exkt.ktor.server.koin.configuration.ApplicationConfigurer import io.ktor.server.application.* import io.ktor.server.config.* import org.koin.core.module.Module object ApplicationConfigBean : ApplicationConfigurer { override fun Application.configure(module: Module, config: ApplicationConfig) { module.single { config } } }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/configuration/ApplicationConfigBean.kt
3711390418
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer import dev.d1s.exkt.ktor.server.koin.configuration.Configurers import dev.d1s.exkt.ktor.server.koin.configuration.ServerApplication import dev.d1s.exkt.ktor.server.koin.configuration.builtin.Connector import dev.d1s.exkt.ktor.server.koin.configuration.builtin.Di import dev.d1s.salesanalyzer.configuration.ApplicationConfigBean import dev.d1s.salesanalyzer.configuration.Website import io.ktor.server.engine.* import io.ktor.server.netty.* import org.koin.core.component.KoinComponent import org.lighthousegames.logging.logging class SalesAnalyzerApplication : ServerApplication(), KoinComponent { override val configurers: Configurers = listOf( Connector, ApplicationConfigBean, Website, Di ) private val logger = logging() override fun launch() { logger.i { "Starting website..." } val applicationEngineEnvironment = createApplicationEngineEnvironment() embeddedServer(Netty, applicationEngineEnvironment).start(wait = true) } }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/SalesAnalyzerApplication.kt
3598935284
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.entity data class Product( val name: String, val cost: Double, val sell: Double, val count: Int, val returnRatio: Double, val expense: Double )
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/entity/Product.kt
2110796977
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.entity import kweb.state.KVar typealias SimulationState = KVar<Result<Simulation>> typealias ProductSales = List<ProductSale> data class ProductSale( val success: Boolean, val balance: Double ) data class Simulation( val product: Product, val sales: ProductSales, val profit: Double, val totalProfit: Double, val roi: Int, val totalExpense: Double, val balance: Double )
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/entity/Simulation.kt
940431634
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.runner import dev.d1s.salesanalyzer.data.SimulationRepository import dev.d1s.salesanalyzer.entity.Product import dev.d1s.salesanalyzer.entity.ProductSale import dev.d1s.salesanalyzer.entity.ProductSales import dev.d1s.salesanalyzer.entity.Simulation import org.lighthousegames.logging.logging import kotlin.math.roundToInt import kotlin.random.Random object SimulationRunner { private val log = logging() fun runSimulationAndSave(product: Product, session: String) { val simulation = runSimulation(product) val result = Result.success(simulation) SimulationRepository.saveBySession(session, result) } fun runSimulation(product: Product): Simulation { log.i { "Running simulation on product: $product" } val sales = product.doSales() val profit = sales.calcProfit(product) val totalProfit = sales.calcTotalProfit(product) val totalExpense = sales.calcTotalExpense(product) val roi = calcRoi(profit, totalExpense) val balance = sales.last().balance val simulation = Simulation(product, sales, profit, totalProfit, roi, totalExpense, balance) log.i { "Ran simulation: $simulation" } return simulation } private fun Product.doSales(): ProductSales = buildList { var balance = -(expense * count) var totalSales = 0 var successfulSales = 0 var doSales = true while (doSales) { val success = Random.nextDouble() > returnRatio if (success) { balance += (sell - cost - expense) successfulSales++ } else { balance -= expense } val sale = ProductSale(success, balance) add(sale) totalSales++ if (successfulSales >= count) { doSales = false } } } private fun ProductSales.calcProfit(product: Product) = filter { it.success }.size * product.sell private fun ProductSales.calcTotalProfit(product: Product) = size * product.sell private fun calcRoi(profit: Double, totalExpense: Double) = (((profit - totalExpense) / totalExpense) * 100).roundToInt() private fun ProductSales.calcTotalExpense(product: Product) = size * product.expense }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/runner/SimulationRunner.kt
705406177
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer.plugin import kweb.plugins.KwebPlugin import org.jsoup.nodes.Document class ChartJsPlugin : KwebPlugin() { override fun decorate(doc: Document) { doc.head().appendElement("script") .attr("src", CHART_JS_URL) } private companion object { private const val CHART_JS_URL = "https://cdn.jsdelivr.net/npm/chart.js" } } val chartJsPlugin get() = ChartJsPlugin()
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/plugin/ChartJsPlugin.kt
594319486
/* * Copyright 2024 Mikhail Titov * * 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 dev.d1s.salesanalyzer fun main() { SalesAnalyzerApplication().launch() }
sales-analyzer/src/main/kotlin/dev/d1s/salesanalyzer/Main.kt
4190427062