content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package test.createx.heartrateapp.presentation.report
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import test.createx.heartrateapp.R
import test.createx.heartrateapp.presentation.common.EmptyDataScreen
import test.createx.heartrateapp.presentation.common.PeriodSelector
import test.createx.heartrateapp.presentation.report.components.ReportListItem
import test.createx.heartrateapp.ui.theme.BlackMain
import test.createx.heartrateapp.ui.theme.GreyBg
import test.createx.heartrateapp.ui.theme.RedAction
import java.time.format.DateTimeFormatter
@Composable
fun ReportScreen(
navController: NavController, viewModel: ReportViewModel
) {
val periods = stringArrayResource(id = R.array.periods_array)
LaunchedEffect(viewModel.isLoading.value) {
if (!viewModel.isLoading.value) {
viewModel.setPeriodsList(periods.asList())
}
}
val selectedPeriod = viewModel.selectedPeriod
Column(
modifier = Modifier
.fillMaxSize()
.background(GreyBg)
) {
if (viewModel.isLoading.value) {
Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(
modifier = Modifier
.align(Alignment.Center)
.size(24.dp),
color = RedAction
)
}
} else {
if (viewModel.heartRatesDailyList.isEmpty()) {
Box(modifier = Modifier.fillMaxSize()) {
EmptyDataScreen(
imageRes = R.drawable.report_img2,
titleRes = R.string.empty_reports_title,
navController = navController
)
}
} else {
Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
PeriodSelector(
periods = viewModel.periods,
selectedPeriod = selectedPeriod.value,
onPeriodChange = { period ->
if (period == periods[0] && viewModel.heartRatesWeeklyList.isEmpty()) {
/* No actions needed */
} else {
viewModel.togglePeriod(period)
}
},
)
Column {
viewModel.heartRatesDailyList.forEach { dailyRecords ->
Spacer(modifier = Modifier.height(20.dp))
Text(
modifier = Modifier
.padding(horizontal = 16.dp),
text = dailyRecords.dateTime.format(DateTimeFormatter.ofPattern("MMMM d, y")),
style = MaterialTheme.typography.displaySmall,
color = BlackMain
)
Column {
dailyRecords.heartRateList.forEach { heartRate ->
Column(
modifier = Modifier
.padding(horizontal = 16.dp)
) {
Spacer(modifier = Modifier.height(16.dp))
ReportListItem(heartRate = heartRate)
}
}
}
}
}
Spacer(modifier = Modifier.height(24.dp))
}
}
}
}
}
| HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/report/ReportScreen.kt | 2970416090 |
package test.createx.heartrateapp.presentation.report
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import test.createx.heartrateapp.data.database.entity.HeartRate
import test.createx.heartrateapp.data.database.entity.User
import test.createx.heartrateapp.data.database.repository.HeartRateRepositoryImpl
import test.createx.heartrateapp.data.database.repository.UserRepositoryImpl
import java.time.DayOfWeek
import java.time.OffsetDateTime
import java.time.temporal.TemporalAdjusters
import javax.inject.Inject
@HiltViewModel
class ReportViewModel @Inject constructor(
private val heartRateRepository: HeartRateRepositoryImpl,
userRepository: UserRepositoryImpl
) : ViewModel() {
private val usersFlow: Flow<List<User>> = userRepository.getAllUsersStream()
private val userId = mutableIntStateOf(1)
private var _heartRatesDailyList = mutableStateListOf<DailyRecords>()
val heartRatesDailyList: SnapshotStateList<DailyRecords> = _heartRatesDailyList
val periods = mutableListOf<String>()
private val _selectedPeriod = mutableStateOf("")
val selectedPeriod: State<String> = _selectedPeriod
private val _heartRatesWeeklyList = mutableStateListOf<HeartRate>()
val heartRatesWeeklyList : SnapshotStateList<HeartRate> = _heartRatesWeeklyList
private var heartRatesMonthlyList = mutableStateListOf<HeartRate>()
private val _isLoading = mutableStateOf(true)
val isLoading: State<Boolean> = _isLoading
init {
viewModelScope.launch {
usersFlow.collect { res ->
if (res.isNotEmpty()) {
userId.intValue = res[0].id
}
}
}
setWeekHeartRatesList()
setMonthHeartRatesList()
}
fun setPeriodsList(periods: List<String>){
this.periods.clear()
this.periods.addAll(periods)
if (_heartRatesWeeklyList.isEmpty()) {
togglePeriod(periods[1])
} else {
togglePeriod(periods[0])
}
}
private fun setDailyRecordsList(list: List<HeartRate>) {
val groupedItems = list.groupBy { it.dateTime.dayOfMonth }
val dataList = mutableListOf<DailyRecords>()
for (group in groupedItems) {
dataList.add(
DailyRecords(
dateTime = group.value[0].dateTime,
heartRateList = group.value
)
)
}
_heartRatesDailyList.clear()
_heartRatesDailyList.addAll(dataList)
}
fun togglePeriod(period: String) {
if (_selectedPeriod.value != period) {
_selectedPeriod.value = period
changeListItems()
}
}
private fun changeListItems() {
if (_selectedPeriod.value == periods[0]) {
setDailyRecordsList(heartRatesWeeklyList)
} else {
setDailyRecordsList(heartRatesMonthlyList)
}
}
private fun setWeekHeartRatesList() {
val now = OffsetDateTime.now()
val firstDayOfWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
val startDateOfTheWeek = firstDayOfWeek.withHour(0).withMinute(0).withSecond(0).withNano(0)
viewModelScope.launch {
heartRateRepository.getAllPeriodHeartRatesStream(userId.intValue, startDateOfTheWeek)
.collect { res ->
_heartRatesWeeklyList.addAll(res)
_isLoading.value = false
}
}
}
private fun setMonthHeartRatesList() {
val now = OffsetDateTime.now()
val firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth())
val startDateOfTheMonth =
firstDayOfMonth.withHour(0).withMinute(0).withSecond(0).withNano(0)
viewModelScope.launch {
heartRateRepository.getAllPeriodHeartRatesStream(userId.intValue, startDateOfTheMonth)
.collect { res ->
heartRatesMonthlyList.addAll(res)
}
}
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/report/ReportViewModel.kt | 3053807551 |
package test.createx.heartrateapp.presentation.report.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import co.yml.charts.common.extensions.isNotNull
import test.createx.heartrateapp.R
import test.createx.heartrateapp.data.database.entity.HeartRate
import test.createx.heartrateapp.presentation.heart_rate_measurement.UserState
import test.createx.heartrateapp.presentation.heart_rate_report.HeartRateStatus
import test.createx.heartrateapp.ui.theme.BlackMain
import test.createx.heartrateapp.ui.theme.GreyBg
import test.createx.heartrateapp.ui.theme.GreySubText
import test.createx.heartrateapp.ui.theme.HeartRateAppTheme
import test.createx.heartrateapp.ui.theme.White
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
@Composable
fun ReportListItem(heartRate: HeartRate) {
var iconStateRes by remember {
mutableIntStateOf(0)
}
for (userState in UserState.get()) {
if (stringResource(id = userState.title) == heartRate.userState) {
iconStateRes = userState.image
}
}
var heartRateStatusInstance by remember {
mutableStateOf(HeartRateStatus.get()[0])
}
for (heartRateStatus in HeartRateStatus.get()) {
if (stringResource(id = heartRateStatus.title).substringBefore(' ') == heartRate.heartRateStatus) {
heartRateStatusInstance = heartRateStatus
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.background(color = White, shape = RoundedCornerShape(18.dp))
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Row(
modifier = Modifier
.weight(1f)
.wrapContentWidth(Alignment.Start),
horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterHorizontally),
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.heart_icon),
contentDescription = stringResource(id = R.string.heart_icon_description),
modifier = Modifier.width(28.dp),
contentScale = ContentScale.FillWidth
)
Column(
modifier = Modifier.width(IntrinsicSize.Min),
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.Bottom),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = heartRate.heartRateValue.toString(),
color = BlackMain,
style = MaterialTheme.typography.displaySmall.copy(fontWeight = FontWeight.Bold)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = stringResource(id = R.string.bpm_title),
color = GreySubText,
style = MaterialTheme.typography.bodyMedium
)
}
if (heartRate.userState.isNotNull()) {
Box(
modifier = Modifier
.background(
color = GreyBg,
shape = RoundedCornerShape(50.dp)
)
.padding(vertical = 4.dp)
.width(56.dp),
contentAlignment = Alignment.Center
) {
Image(
painter = painterResource(id = iconStateRes),
contentDescription = stringResource(id = R.string.user_state_icon_description),
modifier = Modifier.size(24.dp),
contentScale = ContentScale.Fit
)
}
}
}
}
Column(
modifier = Modifier
.weight(1f)
.wrapContentWidth(Alignment.End)
.height(64.dp),
verticalArrangement = Arrangement.SpaceBetween,
horizontalAlignment = Alignment.End
)
{
Text(
text = heartRate.dateTime.format(DateTimeFormatter.ofPattern("MMM d , HH:mm")),
color = GreySubText,
style = MaterialTheme.typography.bodyMedium
)
Box(
modifier = Modifier.background(
heartRateStatusInstance.colorBg,
RoundedCornerShape(10.dp)
),
contentAlignment = Alignment.Center
) {
Text(
text = heartRate.heartRateStatus,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 7.dp),
style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold),
color = heartRateStatusInstance.colorText,
textAlign = TextAlign.Center
)
}
}
}
}
@Preview
@Composable
fun ItemPrev() {
HeartRateAppTheme {
ReportListItem(
heartRate = HeartRate(
1,
1,
80,
"Exercise",
"Normal",
OffsetDateTime.now()
)
)
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/report/components/ReportListItem.kt | 635838781 |
package test.createx.heartrateapp.presentation.report
import test.createx.heartrateapp.data.database.entity.HeartRate
import java.time.OffsetDateTime
data class DailyRecords(val dateTime: OffsetDateTime, val heartRateList: List<HeartRate>) | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/report/DailyRecords.kt | 192649944 |
package test.createx.heartrateapp.presentation.heart_rate_measurement
import android.view.SurfaceView
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import net.kibotu.heartrateometer.HeartRateOmeter
import test.createx.heartrateapp.presentation.heart_rate.Hint
import javax.inject.Inject
import kotlin.math.round
@HiltViewModel
class HeartRateMeasurementViewModel @Inject constructor() : ViewModel() {
private val _subscription: MutableState<CompositeDisposable?> = mutableStateOf(null)
private val _bpmUpdates: MutableState<Disposable?> = mutableStateOf(null)
private val _isPaused = mutableStateOf(true)
var isPaused: State<Boolean> = _isPaused
private val _rate = mutableStateOf("--")
val rate: State<String> = _rate
private val _hints = Hint.get()
private val _hint = mutableStateOf(_hints[0])
val hint: State<Hint> = _hint
val fullCycle = 30f
private val _timeLeft = mutableFloatStateOf(fullCycle)
val timeLeft: State<Float> = _timeLeft
fun startMeasurement() {
viewModelScope.launch {
while (!_isPaused.value) {
delay(100)
getHintsOnTime()
_timeLeft.floatValue -= 0.1f
if (_timeLeft.floatValue <= 0) {
disposeSubscription()
_isPaused.value=true
return@launch
}
}
if (_isPaused.value) {
setHintOnPause()
}
}
}
private fun getHintsOnTime() {
if (_hint.value==_hints[3]){
_hint.value = _hints[1]
return
}
val roundedTimeLeft = round(_timeLeft.floatValue * 10 / 10f)
if (roundedTimeLeft % 10 == 0f) {
_hint.value = _hints[1]
} else if (roundedTimeLeft % 5 == 0f) {
_hint.value = _hints[2]
}
}
fun disposeSubscription() {
if (_subscription.value?.isDisposed == false) {
_subscription.value?.clear()
_subscription.value?.dispose()
}
}
fun initBpmUpdates(surfaceView: SurfaceView) {
_subscription.value = CompositeDisposable()
_bpmUpdates.value = HeartRateOmeter()
.withAverageAfterSeconds(3)
.setFingerDetectionListener { isFingerDetected ->
_isPaused.value = !isFingerDetected
}.bpmUpdates(surfaceView = surfaceView)
.subscribe(
{ bpm: HeartRateOmeter.Bpm? -> _rate.value = bpm?.value.toString() },
{ println("${it.message}") }
)
_subscription.value?.add(_bpmUpdates.value!!)
}
fun areBpmUpdatesInitialized(): Boolean {
return if (_subscription.value != null) {
_subscription.value!!.size() > 0
} else {
false
}
}
private fun setHintOnPause() {
_hint.value = _hints[3]
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/heart_rate_measurement/HeartRateMeasurementViewModel.kt | 2740235208 |
package test.createx.heartrateapp.presentation.heart_rate_measurement
import android.view.SurfaceView
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.navigation.NavController
import co.yml.charts.common.extensions.isNotNull
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import test.createx.heartrateapp.R
import test.createx.heartrateapp.presentation.common.AlertDialog
import test.createx.heartrateapp.presentation.common.AnimationLottie
import test.createx.heartrateapp.presentation.common.CircularProgressIndicator
import test.createx.heartrateapp.presentation.heart_rate_measurement.components.StateBottomSheetDialog
import test.createx.heartrateapp.presentation.navigation.Route
import test.createx.heartrateapp.presentation.topAppBar.TopAppBarNavigationState
import test.createx.heartrateapp.ui.theme.BlackMain
import test.createx.heartrateapp.ui.theme.GreenRateText
import test.createx.heartrateapp.ui.theme.GreyBg
import test.createx.heartrateapp.ui.theme.GreyProgressbar
import test.createx.heartrateapp.ui.theme.GreySubText
import test.createx.heartrateapp.ui.theme.RedBg
import test.createx.heartrateapp.ui.theme.RedMain
import test.createx.heartrateapp.ui.theme.RedProgressbar
import test.createx.heartrateapp.ui.theme.White
import kotlin.math.ceil
@Composable
fun HeartRateMeasurementScreen(
viewModel: HeartRateMeasurementViewModel, onComposing: (TopAppBarNavigationState) -> Unit,
navController: NavController
) {
val rate = viewModel.rate
val hint = viewModel.hint
var showSheet by remember { mutableStateOf(false) }
val timeLeft = viewModel.timeLeft
val isPaused = viewModel.isPaused
var previewView: SurfaceView? by remember {
mutableStateOf(null)
}
var userState: String? by remember { mutableStateOf("") }
val openAlertDialog = remember { mutableStateOf(false) }
val coroutineScope = rememberCoroutineScope()
LaunchedEffect(Unit) {
onComposing(
TopAppBarNavigationState(
action = {
openAlertDialog.value = true
},
iconRes = R.drawable.close_icon
)
)
}
LaunchedEffect(previewView) {
if (previewView.isNotNull() && !viewModel.areBpmUpdatesInitialized()) {
delay(800)
viewModel.initBpmUpdates(previewView!!)
}
}
LaunchedEffect(timeLeft.value) {
if (timeLeft.value <= 0) {
showSheet = true
}
}
LaunchedEffect(isPaused.value) {
viewModel.startMeasurement()
}
LaunchedEffect(userState) {
if (userState != "") {
showSheet=false
delay(300)
navController.popBackStack()
navController.navigate("${Route.HeartRateReportScreen.route}?userState=${userState}&heartRate=${rate.value}")
}
}
DisposableEffect(Unit) {
onDispose {
viewModel.disposeSubscription()
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(White)
) {
Box(modifier = Modifier.size(1.dp)) {
AndroidView(
factory = { context ->
SurfaceView(context).apply {
this.clipToOutline = true
previewView = this
}
},
modifier = Modifier.matchParentSize(),
update = { previewView = it }
)
}
if (openAlertDialog.value) {
AlertDialog(
onDismissRequest = { openAlertDialog.value = false },
onConfirmation = {
viewModel.disposeSubscription()
openAlertDialog.value = false
showSheet = false
coroutineScope.launch { delay(300) }
navController.popBackStack()
},
dialogTitle = stringResource(R.string.measurements_alert_dialog_title),
dialogText = stringResource(R.string.measurements_alert_dialog_description),
confirmButtonText = stringResource(id = R.string.close_icon_description)
)
}
AnimatedContent(targetState = hint.value, transitionSpec = {
fadeIn(
animationSpec = tween(900),
) togetherWith fadeOut(
animationSpec = tween(900)
)
}, label = stringResource(R.string.hint_content_animation_label)) { targetState ->
Row(
modifier = Modifier
.padding(top = 10.dp, start = 16.dp, end = 16.dp)
.fillMaxWidth()
.wrapContentHeight()
.animateContentSize(animationSpec = tween(500))
.background(color = RedBg, shape = RoundedCornerShape(10.dp)),
) {
Text(
modifier = Modifier.weight(1f)
.padding(16.dp),
text = stringResource(id = targetState.hint),
style = MaterialTheme.typography.bodyMedium,
color = RedMain,
textAlign = TextAlign.Start
)
if (targetState.image != null) {
Image(
painter = painterResource(id = targetState.image),
contentDescription = stringResource(R.string.hint_image_description),
modifier = Modifier.padding(0.dp).height(84.dp),
contentScale = ContentScale.FillHeight
)
}
}
}
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.8f)
.padding(horizontal = 16.dp)
.align(Alignment.BottomCenter),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier
.padding(horizontal = 42.dp)
.fillMaxHeight(0.45f)
.aspectRatio(1f),
contentAlignment = Alignment.TopCenter
) {
CircularProgressIndicator(
modifier = Modifier
.fillMaxSize(),
positionValue = 100f - (timeLeft.value * 100 / viewModel.fullCycle),
primaryColor = RedProgressbar,
secondaryColor = GreyProgressbar,
)
Column(
modifier = Modifier
.fillMaxSize()
.padding(vertical = 15.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.SpaceEvenly
) {
Image(
painter = painterResource(id = R.drawable.heart_rate),
contentDescription = stringResource(id = R.string.heart_icon_description),
modifier = Modifier
.fillMaxSize(0.34f)
)
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = rate.value,
style = MaterialTheme.typography.titleLarge,
color = BlackMain,
textAlign = TextAlign.Center
)
Text(
text = stringResource(id = R.string.bpm_title),
style = MaterialTheme.typography.bodyMedium,
color = GreySubText,
textAlign = TextAlign.Center
)
}
}
}
Spacer(modifier = Modifier.fillMaxHeight(0.06f))
Box(
modifier = Modifier
.clip(RoundedCornerShape(50.dp))
.background(
color = GreyBg,
)
.border(
width = 2.dp,
color = if (timeLeft.value == viewModel.fullCycle) Color.Transparent else if (isPaused.value) RedMain else GreenRateText,
shape = RoundedCornerShape(50.dp)
)
) {
Column(
modifier = Modifier.padding(vertical = 16.dp, horizontal = 32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(2.dp, Alignment.CenterVertically)
) {
Text(
text = stringResource(id = R.string.measurement_time_text),
style = MaterialTheme.typography.bodySmall,
color = BlackMain,
textAlign = TextAlign.Center
)
Text(
text = if (ceil(timeLeft.value) == viewModel.fullCycle) stringResource(
R.string.measurement_time_init_text,
ceil(timeLeft.value).toInt()
) else stringResource(
R.string.measurement_time_left_text, ceil(
timeLeft.value
).toInt()
),
style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.SemiBold),
color = RedMain,
textAlign = TextAlign.Center
)
}
}
Spacer(modifier = Modifier.fillMaxHeight(0.1f))
Box(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 30.dp)
) {
AnimationLottie(
animationId = R.raw.pulse_indicator,
contentScale = ContentScale.FillWidth,
isPlaying = !isPaused.value
)
}
}
if (showSheet) {
StateBottomSheetDialog(
onShowDialogChange = { showDialog ->
openAlertDialog.value = showDialog
}, onCreateReport = { state ->
userState = state
showSheet = false
})
}
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/heart_rate_measurement/HeartRateMeasurementScreen.kt | 3474855872 |
package test.createx.heartrateapp.presentation.heart_rate_measurement.components
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.BottomSheetDefaults
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedCard
import androidx.compose.material3.SheetValue
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import test.createx.heartrateapp.R
import test.createx.heartrateapp.presentation.heart_rate_measurement.UserState
import test.createx.heartrateapp.ui.theme.BlackMain
import test.createx.heartrateapp.ui.theme.GreySubText
import test.createx.heartrateapp.ui.theme.RedAction
import test.createx.heartrateapp.ui.theme.RedBg
import test.createx.heartrateapp.ui.theme.RedMain
import test.createx.heartrateapp.ui.theme.White
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StateBottomSheetDialog(
onShowDialogChange: (Boolean) -> Unit,
onCreateReport: (String?) -> Unit
) {
val modalBottomSheetState =
rememberModalBottomSheetState(skipPartiallyExpanded = true, confirmValueChange = {
if (it == SheetValue.Hidden) {
onShowDialogChange(true)
false
} else {
true
}
})
val userStateList = UserState.get()
var selectedState: String? by remember {
mutableStateOf(null)
}
ModalBottomSheet(
onDismissRequest = {
onShowDialogChange(true)
},
sheetState = modalBottomSheetState,
dragHandle = { BottomSheetDefaults.DragHandle() },
containerColor = White
) {
Column(
modifier = Modifier.padding(horizontal = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top
) {
Image(
painter = painterResource(id = R.drawable.complete_icon),
contentDescription = "",
modifier = Modifier.size(77.dp)
)
Spacer(modifier = Modifier.height(3.dp))
Text(
text = stringResource(R.string.state_sheet_dialog_title),
style = MaterialTheme.typography.titleSmall,
color = BlackMain,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(R.string.state_sheet_dialog_description),
style = MaterialTheme.typography.bodyMedium,
color = GreySubText,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(24.dp))
LazyVerticalGrid(
columns = GridCells.Fixed(2),
verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically),
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally)
) {
items(items = userStateList) { item ->
val title = stringResource(id = item.title)
OutlinedCard(
onClick = { selectedState = title },
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.outlinedCardColors(
containerColor = if (selectedState == title) RedBg else White,
),
border = BorderStroke(
width = 2.dp,
color = if (selectedState == title) RedAction else RedMain.copy(
alpha = 0.2f
)
)
) {
Column(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(vertical = 16.dp),
verticalArrangement = Arrangement.spacedBy(
8.dp,
Alignment.CenterVertically
),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Image(
painter = painterResource(id = item.image),
contentDescription = stringResource(id = R.string.user_state_icon_description),
modifier = Modifier.size(50.dp),
alignment = Alignment.Center
)
Text(
text = title,
style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold),
color = if (selectedState == title) RedAction else BlackMain,
textAlign = TextAlign.Center
)
}
}
}
}
Spacer(modifier = Modifier.height(24.dp))
ElevatedButton(
onClick = {
onCreateReport(selectedState)
},
modifier = Modifier
.padding(bottom = 50.dp)
.size(width = 328.dp, height = 48.dp)
.shadow(
elevation = 10.dp,
shape = RoundedCornerShape(50.dp),
clip = true,
ambientColor = Color(0xFFCC0909),
spotColor = Color(0xFFCC0909),
),
colors = ButtonDefaults.elevatedButtonColors(
containerColor = RedMain,
disabledContainerColor = RedMain.copy(alpha = 0.5f),
disabledContentColor = RedMain.copy(alpha = 0.5f),
)
) {
Text(
text = stringResource(R.string.create_report_button_text),
style = MaterialTheme.typography.titleSmall,
color = Color.White
)
}
}
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/heart_rate_measurement/components/StateBottomSheetDialog.kt | 1489049952 |
package test.createx.heartrateapp.presentation.heart_rate_measurement
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import test.createx.heartrateapp.R
data class UserState(
@StringRes val title: Int,
@DrawableRes val image: Int,
) {
companion object {
fun get() = listOf(
UserState(
R.string.normal_state_title,
R.drawable.normal_emoji
), UserState(
R.string.resting_state_title,
R.drawable.resting_emoji
), UserState(
R.string.walking_state_title,
R.drawable.walking_emoji
), UserState(
R.string.exercise_state_title,
R.drawable.exercise_emoji
)
)
}
}
| HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/heart_rate_measurement/UserState.kt | 1013067221 |
package test.createx.heartrateapp.presentation.workout_exercises
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import test.createx.heartrateapp.R
import test.createx.heartrateapp.presentation.common.AlertDialog
import test.createx.heartrateapp.presentation.common.LinearProgressIndicator
import test.createx.heartrateapp.presentation.common.PageIndicator
import test.createx.heartrateapp.presentation.navigation.Route
import test.createx.heartrateapp.presentation.workout_exercises.components.WorkoutExercisePage
import test.createx.heartrateapp.ui.theme.BlackMain
import test.createx.heartrateapp.ui.theme.GreyProgressbar
import test.createx.heartrateapp.ui.theme.GreySubText
import test.createx.heartrateapp.ui.theme.RedMain
import test.createx.heartrateapp.ui.theme.RedProgressbar
import test.createx.heartrateapp.ui.theme.White
import kotlin.math.ceil
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun WorkoutExerciseScreen(navController: NavController, viewModel: WorkoutExerciseViewModel) {
val pages = Workout.get()
val pagerState = rememberPagerState(
initialPage = 0, initialPageOffsetFraction = 0f
) {
pages.size
}
val timeLeft = viewModel.timeLeft
val isPaused = viewModel.isPaused
val openAlertStopDialog = remember { mutableStateOf(false) }
val openAlertBackDialog = remember { mutableStateOf(false) }
val coroutineScope = rememberCoroutineScope()
val backButtonAlpha: State<Float> =
animateFloatAsState(
targetValue = if (pagerState.currentPage > 0) 1f else 0f,
animationSpec = tween(1000),
label = stringResource(R.string.back_button_animation_label)
)
Box(
modifier = Modifier
.fillMaxSize()
.background(White)
) {
if (openAlertBackDialog.value) {
AlertDialog(
onDismissRequest = {
if (viewModel.timeLeft.value != viewModel.fullCycle) {
viewModel.startExercise()
viewModel.startMeasurement()
}
openAlertBackDialog.value = false
},
onConfirmation = {
viewModel.restartTimer()
openAlertBackDialog.value = false
coroutineScope.launch {
pagerState.animateScrollToPage(
page = pagerState.currentPage - 1,
animationSpec = tween(1800)
)
}
},
dialogTitle = stringResource(R.string.return_alert_dialog_title),
confirmButtonText = stringResource(R.string.return_alert_dialog_button_text)
)
}
if (openAlertStopDialog.value) {
AlertDialog(
onDismissRequest = {
if (viewModel.timeLeft.value != viewModel.fullCycle) {
viewModel.startExercise()
viewModel.startMeasurement()
}
openAlertStopDialog.value = false
},
onConfirmation = {
openAlertStopDialog.value = false
coroutineScope.launch {
delay(200)
navController.popBackStack()
navController.navigate(Route.WorkoutScreen.route)
}
},
dialogTitle = stringResource(R.string.stop_alert_dialog_title),
dialogText = stringResource(R.string.stop_alert_dialog_text),
confirmButtonText = stringResource(R.string.stop_alert_dialog_button_text)
)
}
Column {
Row(
modifier = Modifier
.fillMaxWidth()
.height(56.dp)
.background(color = White),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
) {
IconButton(
onClick = {
openAlertBackDialog.value = true
viewModel.pauseMeasurement()
},
modifier = Modifier.alpha(backButtonAlpha.value),
enabled = pagerState.currentPage > 0,
) {
Icon(
painter = painterResource(id = R.drawable.return_icon),
contentDescription = stringResource(R.string.go_back_icon_description),
tint = BlackMain
)
}
PageIndicator(pageSize = pages.size, selectedPage = pagerState.currentPage)
TextButton(onClick = {
openAlertStopDialog.value = true
viewModel.pauseMeasurement()
}, content = {
Text(
text = stringResource(R.string.stop_alert_dialog_button_text),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
color = GreySubText
)
})
}
HorizontalPager(state = pagerState, userScrollEnabled = false) { index ->
WorkoutExercisePage(workout = pages[index])
}
}
Column(
modifier = Modifier
.width(328.dp)
.align(Alignment.BottomCenter)
.padding(bottom = 120.dp),
verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
horizontalArrangement = Arrangement.spacedBy(
4.dp,
Alignment.CenterHorizontally
),
verticalAlignment = Alignment.Bottom
) {
Text(
text = "${
ceil(
timeLeft.value
).toInt()
}",
style = MaterialTheme.typography.labelLarge.copy(fontWeight = FontWeight.Bold),
color = BlackMain
)
Text(
text = stringResource(R.string.workout_timer_text),
modifier = Modifier.padding(bottom = 4.dp),
style = MaterialTheme.typography.bodyMedium,
color = GreySubText
)
}
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.height(16.dp),
progress = 1 - timeLeft.value / viewModel.fullCycle,
progressColor = RedProgressbar,
lineColor = GreyProgressbar,
clipShape = RoundedCornerShape(9.dp)
)
}
val scope = rememberCoroutineScope()
ElevatedButton(
onClick = {
if (isPaused.value) {
viewModel.startExercise()
viewModel.startMeasurement()
} else if (timeLeft.value <= 0) {
viewModel.restartTimer()
scope.launch {
if (pagerState.currentPage == 4) {
navController.popBackStack()
navController.navigate(Route.WorkoutScreen.route)
} else {
pagerState.animateScrollToPage(
page = pagerState.currentPage + 1,
animationSpec = tween(1800)
)
}
}
}
},
modifier = Modifier
.padding(bottom = 35.dp)
.size(width = 328.dp, height = 48.dp)
.shadow(
elevation = 18.dp,
shape = RoundedCornerShape(50.dp),
clip = true,
ambientColor = Color(0xFFCC0909),
spotColor = Color(0xFFCC0909),
)
.align(Alignment.BottomCenter),
enabled = (isPaused.value && timeLeft.value == viewModel.fullCycle) || timeLeft.value <= 0,
colors = ButtonDefaults.elevatedButtonColors(
containerColor = RedMain,
disabledContainerColor = RedMain.copy(alpha = 0.5f),
disabledContentColor = RedMain.copy(alpha = 0.5f),
)
) {
Text(
text = if (isPaused.value && timeLeft.value == viewModel.fullCycle)
stringResource(R.string.start_exercise_text)
else
stringResource(R.string.next_exercise_text),
style = MaterialTheme.typography.titleSmall,
color = Color.White
)
}
}
}
| HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/workout_exercises/WorkoutExercisesScreen.kt | 3505099767 |
package test.createx.heartrateapp.presentation.workout_exercises
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class WorkoutExerciseViewModel @Inject constructor() : ViewModel() {
val fullCycle = 10f
private val _timeLeft = mutableFloatStateOf(fullCycle)
val timeLeft: State<Float> = _timeLeft
private val _isPaused = mutableStateOf(true)
var isPaused: State<Boolean> = _isPaused
fun startMeasurement() {
viewModelScope.launch {
while (!_isPaused.value) {
delay(100)
_timeLeft.floatValue -= 0.1f
if (_timeLeft.floatValue <= 0) {
return@launch
}
}
}
}
fun pauseMeasurement(){
_isPaused.value=true
}
fun startExercise(){
_isPaused.value=false
}
fun restartTimer(){
_isPaused.value=true
_timeLeft.floatValue=fullCycle
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/workout_exercises/WorkoutExerciseViewModel.kt | 845607207 |
package test.createx.heartrateapp.presentation.workout_exercises.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import test.createx.heartrateapp.R
import test.createx.heartrateapp.presentation.workout_exercises.Workout
import test.createx.heartrateapp.ui.theme.GreySubText
import test.createx.heartrateapp.ui.theme.HeartRateAppTheme
import test.createx.heartrateapp.ui.theme.RedBg
@Composable
fun WorkoutExercisePage(
workout: Workout,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.72f)
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Box(
modifier = Modifier.weight(1f),
// .fillMaxWidth()
// .fillMaxHeight(),
contentAlignment = Alignment.TopCenter
) {
Text(
textAlign = TextAlign.Center,
text = stringResource(id = workout.title),
style = MaterialTheme.typography.titleMedium
)
Image(
painter = painterResource(id = workout.imageRes),
contentDescription = stringResource(R.string.workout_image_description),
modifier = Modifier.fillMaxHeight(),
contentScale = ContentScale.FillHeight
)
}
Column(
modifier = Modifier
.offset(y = (-15).dp)
.background(color = RedBg, shape = RoundedCornerShape(10.dp))
.padding(vertical = 12.dp, horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically)
) {
stringResource(id = workout.descriptionRes).split('\n').forEach { descriptionItem ->
Text(
textAlign = TextAlign.Start,
text = descriptionItem,
style = MaterialTheme.typography.bodyMedium,
color = GreySubText
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun ExercisePrev() {
HeartRateAppTheme {
WorkoutExercisePage(workout = Workout.get()[0])
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/workout_exercises/components/WorkoutExercisePage.kt | 2667968656 |
package test.createx.heartrateapp.presentation.workout_exercises
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import test.createx.heartrateapp.R
data class Workout(
@StringRes val title: Int,
@DrawableRes val imageRes: Int,
@StringRes val descriptionRes: Int
) {
companion object {
fun get() = listOf(
Workout(
R.string.squats_workout_title,
R.drawable.squat_img,
R.string.squats_workout_description
),
Workout(
R.string.plank_workout_title,
R.drawable.plank_img,
R.string.plank_workout_description
),
Workout(
R.string.rope_workout_title,
R.drawable.rope_img,
R.string.rope_workout_description
),
Workout(
R.string.step_workout_title,
R.drawable.step_img,
R.string.step_workout_description
),
Workout(
R.string.biceps_workout_title,
R.drawable.biceps_img,
R.string.biceps_workout_description
),
)
}
}
| HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/workout_exercises/Workout.kt | 3536124577 |
package test.createx.heartrateapp.presentation.workout
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import test.createx.heartrateapp.R
import test.createx.heartrateapp.presentation.navigation.Graph
import test.createx.heartrateapp.ui.theme.BlackMain
import test.createx.heartrateapp.ui.theme.GreyBg
import test.createx.heartrateapp.ui.theme.GreySubText
import test.createx.heartrateapp.ui.theme.RedMain
import test.createx.heartrateapp.ui.theme.White
@Composable
fun WorkoutScreen(navController:NavController) {
Box(
modifier = Modifier
.fillMaxSize()
.background(GreyBg)
) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 24.dp)
.clip(RoundedCornerShape(18.dp))
.background(color = White)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.Top),
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
modifier = Modifier.fillMaxHeight(0.26f),
painter = painterResource(id = R.drawable.workout_img),
contentDescription = stringResource(R.string.workout_intro_image_description),
contentScale = ContentScale.FillHeight
)
Column(
verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.Top),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = stringResource(R.string.workout_intro_title),
style = MaterialTheme.typography.titleMedium,
color = BlackMain,
textAlign = TextAlign.Center
)
Text(
text = stringResource(R.string.workout_intro_description),
style = MaterialTheme.typography.bodyMedium,
color = GreySubText,
textAlign = TextAlign.Center
)
}
HorizontalDivider(
modifier = Modifier.width(159.dp),
thickness = 1.dp,
color = RedMain.copy(alpha = 0.25f)
)
Text(
text = stringResource(R.string.workout_intro_subscription_details_text),
style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold),
color = RedMain,
textAlign = TextAlign.Center
)
}
}
Column(modifier = Modifier
.align(Alignment.BottomCenter)) {
ElevatedButton(
onClick = {
navController.popBackStack()
navController.navigate(Graph.WorkoutGraph.route)
},
modifier = Modifier
.height(48.dp)
.shadow(
elevation = 10.dp,
shape = RoundedCornerShape(50.dp),
clip = true,
ambientColor = Color(0xFFCC0909),
spotColor = Color(0xFFCC0909),
),
colors = ButtonDefaults.elevatedButtonColors(
containerColor = RedMain,
disabledContainerColor = RedMain.copy(alpha = 0.5f),
disabledContentColor = RedMain.copy(alpha = 0.5f),
)
) {
Text(
text = stringResource(R.string.workout_intro_button_text),
style = MaterialTheme.typography.titleSmall,
color = Color.White
)
}
Spacer(
modifier = Modifier
.fillMaxHeight(0.065f)
)
}
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/workout/WorkoutScreen.kt | 2552631992 |
package test.createx.heartrateapp.presentation.paywall.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import test.createx.heartrateapp.R
import test.createx.heartrateapp.presentation.paywall.SubscriptionBenefitItem
import test.createx.heartrateapp.ui.theme.BlackMain
import test.createx.heartrateapp.ui.theme.GreySubText
import test.createx.heartrateapp.ui.theme.RedMain
@Composable
fun SubscriptionBenefitComponent(benefitItem: SubscriptionBenefitItem) {
Row(
horizontalArrangement = Arrangement.spacedBy(
16.dp, Alignment.CenterHorizontally
),
verticalAlignment = Alignment.Top,
) {
Icon(
painter = painterResource(id = benefitItem.icon),
contentDescription = stringResource(R.string.benefit_icon_description),
tint = RedMain
)
Column(
verticalArrangement = Arrangement.spacedBy(
2.dp, Alignment.CenterVertically
),
) {
Text(
text = stringResource(benefitItem.title),
style = MaterialTheme.typography.titleSmall,
color = BlackMain,
textAlign = TextAlign.Start
)
Text(
text = stringResource(benefitItem.description),
style = MaterialTheme.typography.bodyMedium,
color = GreySubText
)
}
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/paywall/components/SubscriptionBenefitComponent.kt | 1681292886 |
package test.createx.heartrateapp.presentation.paywall
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import test.createx.heartrateapp.R
data class SubscriptionBenefitItem(
@StringRes val title: Int,
@StringRes val description: Int,
@DrawableRes val icon: Int,
) {
companion object {
fun get() = listOf(
SubscriptionBenefitItem(
R.string.heart_statistics_title,
R.string.heart_statistics_description,
R.drawable.chart_icon,
),
SubscriptionBenefitItem(
R.string.health_suggestions_title,
R.string.health_suggestions_description,
R.drawable.idea_icon,
),
SubscriptionBenefitItem(
R.string.heart_rate_history_title,
R.string.heart_rate_history_description,
R.drawable.report_icon,
),
)
}
}
| HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/paywall/SubscriptionBenefitItem.kt | 337535288 |
package test.createx.heartrateapp.presentation.paywall
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import test.createx.heartrateapp.R
import test.createx.heartrateapp.presentation.common.AnimationLottie
import test.createx.heartrateapp.presentation.navigation.Route
import test.createx.heartrateapp.presentation.paywall.components.SubscriptionBenefitComponent
import test.createx.heartrateapp.ui.theme.BlackMain
import test.createx.heartrateapp.ui.theme.GreySubText
import test.createx.heartrateapp.ui.theme.HeartRateAppTheme
import test.createx.heartrateapp.ui.theme.RedMain
@Composable
fun PaywallScreen(navController: NavController) {
val subscriptionBenefitItems = SubscriptionBenefitItem.get()
Box(modifier = Modifier.fillMaxSize()) {
val bottomFade =
Brush.verticalGradient(0f to Color.White, 0.95f to Color.White, 1f to Color.Transparent)
AnimationLottie(
animationId = R.raw.subscription,
modifier = Modifier
.align(Alignment.TopCenter)
.fillMaxWidth()
.fadingEdge(bottomFade),
contentScale = ContentScale.FillWidth
)
Box(
modifier = Modifier.fillMaxSize()
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.Top,
) {
IconButton(onClick = { navController.navigate(Route.OnboardingDataScreen.route) }) {
Icon(
painter = painterResource(id = R.drawable.close_icon),
contentDescription = stringResource(R.string.close_icon_description),
tint = GreySubText
)
}
TextButton(
onClick = { /* TODO Add in-app billing restore */ },
content = {
Text(
text = stringResource(R.string.billing_restore_button_text),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold,
color = GreySubText
)
}
)
}
val topFade = Brush.verticalGradient(0f to Color.Transparent, 0.03f to Color.White)
Box(
modifier = Modifier
.background(brush = topFade, alpha = 0.85f)
.align(Alignment.BottomCenter)
) {
Image(
modifier = Modifier
.fillMaxWidth()
.height(156.dp)
.align(Alignment.BottomCenter),
painter = painterResource(id = R.drawable.paywall_bg),
contentDescription = stringResource(R.string.background_wave_image_description),
contentScale = ContentScale.FillBounds,
)
Column(
modifier = Modifier
.align(Alignment.BottomCenter),
verticalArrangement = Arrangement.Bottom,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
modifier = Modifier.padding(horizontal = 16.dp),
text = stringResource(R.string.billing_title),
style = MaterialTheme.typography.displayMedium,
color = BlackMain,
textAlign = TextAlign.Center
)
Column(
modifier = Modifier.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.Top),
horizontalAlignment = Alignment.Start,
) {
subscriptionBenefitItems.forEach { item ->
SubscriptionBenefitComponent(benefitItem = item)
}
}
Spacer(modifier = Modifier.fillMaxHeight(0.025f))
Column(
modifier = Modifier.padding(horizontal = 16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp, Alignment.Top),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = buildAnnotatedString {
withStyle(
style = SpanStyle(
color = RedMain,
)
) {
append(
stringResource(R.string.billing_trial_info_text).substringBefore(
','
)
)
}
withStyle(style = SpanStyle(color = GreySubText)) {
append(
stringResource(R.string.billing_trial_info_text).substringAfter(
','
)
)
}
}, style = MaterialTheme.typography.bodyMedium
)
ElevatedButton(
onClick = {
/* TODO Add in-app billing (subscription) */
navController.navigate(Route.OnboardingDataScreen.route)
},
modifier = Modifier
.size(width = 328.dp, height = 48.dp)
.shadow(
elevation = 18.dp,
shape = RoundedCornerShape(50.dp),
clip = true,
ambientColor = Color(0xFFCC0909),
spotColor = Color(0xFFCC0909),
),
colors = ButtonDefaults.elevatedButtonColors(
containerColor = RedMain,
disabledContainerColor = RedMain.copy(alpha = 0.5f),
disabledContentColor = RedMain.copy(alpha = 0.5f),
)
) {
Text(
text = stringResource(R.string.get_started_button_text),
style = MaterialTheme.typography.titleSmall,
color = Color.White
)
}
Row(
modifier = Modifier
.padding(bottom = 7.dp)
.height(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp, Alignment.Start),
verticalAlignment = Alignment.CenterVertically,
) {
TextButton(
onClick = { /* TODO Handle button click event */ },
content = {
Text(
text = stringResource(id = R.string.terms_of_use_title),
style = MaterialTheme.typography.labelSmall,
color = GreySubText
)
},
contentPadding = PaddingValues(0.dp)
)
HorizontalDivider(
modifier = Modifier
.height(16.dp)
.width(1.dp),
color = RedMain.copy(alpha = 0.2f)
)
TextButton(
onClick = { /* TODO Handle button click event */ },
content = {
Text(
text = stringResource(id = R.string.privacy_policy_title),
style = MaterialTheme.typography.labelSmall,
color = GreySubText
)
},
contentPadding = PaddingValues(0.dp)
)
}
}
}
}
}
}
}
fun Modifier.fadingEdge(brush: Brush) = this
.graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen)
.drawWithContent {
drawContent()
drawRect(brush = brush, blendMode = BlendMode.DstIn)
}
@Preview(showBackground = true)
@Composable
fun PaywallPrev() {
HeartRateAppTheme {
PaywallScreen(navController = rememberNavController())
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/paywall/PaywallScreen.kt | 2405588686 |
package test.createx.heartrateapp.presentation.onboarding.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import test.createx.heartrateapp.presentation.common.AnimationLottie
import test.createx.heartrateapp.presentation.onboarding.Page
import test.createx.heartrateapp.ui.theme.BlackMain
import test.createx.heartrateapp.ui.theme.GreySubText
import test.createx.heartrateapp.ui.theme.HeartRateAppTheme
import test.createx.heartrateapp.ui.theme.RedMain
@Composable
fun OnboardingPage(
page: Page,
) {
Column(
modifier = Modifier
.fillMaxSize(),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
textAlign = TextAlign.Center,
text = buildAnnotatedString {
withStyle(
style = SpanStyle(
color = BlackMain,
)
)
{
append(stringResource(id = page.title).substringBeforeLast(' '))
}
withStyle(style = SpanStyle(color = RedMain, fontWeight = FontWeight.Bold)) {
append(" ${stringResource(id = page.title).substringAfterLast(' ')}")
}
},
style = MaterialTheme.typography.displayMedium
)
Spacer(modifier = Modifier.height(16.dp))
Text(
textAlign = TextAlign.Center,
text = stringResource(id = page.description),
style = MaterialTheme.typography.bodyLarge,
color = GreySubText
)
}
Spacer(modifier = Modifier.fillMaxHeight(0.05f))
Box(
modifier = Modifier
.fillMaxWidth()
.height(370.dp)
) {
AnimationLottie(
animationId = page.image,
modifier = Modifier.fillMaxWidth(),
contentScale = ContentScale.FillWidth
)
}
}
}
@Preview(showBackground = true)
@Composable
fun OnboardingPagePreview() {
HeartRateAppTheme {
OnboardingPage(page = Page.get()[0])
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/onboarding/components/OnboardingPage.kt | 1288673085 |
package test.createx.heartrateapp.presentation.onboarding.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import kotlinx.coroutines.launch
import test.createx.heartrateapp.R
import test.createx.heartrateapp.presentation.common.PageIndicator
import test.createx.heartrateapp.presentation.navigation.Route
import test.createx.heartrateapp.presentation.onboarding.Page
import test.createx.heartrateapp.ui.theme.RedBg
import test.createx.heartrateapp.ui.theme.RedMain
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun OnboardingScreenContent(
pagerState: PagerState,
pages: List<Page>,
navController: NavController,
isContentVisible: Boolean
) {
AnimatedVisibility(
visible = isContentVisible,
enter = fadeIn(animationSpec = tween(2200)),
exit = fadeOut(animationSpec = tween(2200))
) {
Column(
modifier = Modifier
.fillMaxSize()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(
top = 25.dp
),
horizontalArrangement = Arrangement.Center
) {
PageIndicator(pageSize = pages.size, selectedPage = pagerState.currentPage)
}
Spacer(modifier = Modifier.fillMaxHeight(0.05f))
Box(
modifier = Modifier.fillMaxSize()
) {
HorizontalPager(state = pagerState, userScrollEnabled = false) { index ->
OnboardingPage(page = pages[index])
}
Box(
modifier = Modifier
.fillMaxWidth()
.height(170.dp)
.align(Alignment.BottomCenter)
.background(
brush = Brush.verticalGradient(
colors = listOf(Color.Transparent, RedBg),
)
)
)
val scope = rememberCoroutineScope()
ElevatedButton(
onClick = {
scope.launch {
if (pagerState.currentPage == 1) {
navController.navigate(Route.PaywallScreen.route)
} else {
pagerState.animateScrollToPage(
page = pagerState.currentPage + 1,
animationSpec = tween(1800)
)
}
}
},
modifier = Modifier
.padding(bottom = 35.dp)
.size(width = 328.dp, height = 48.dp)
.shadow(
elevation = 18.dp,
shape = RoundedCornerShape(50.dp),
clip = true,
ambientColor = Color(0xFFCC0909),
spotColor = Color(0xFFCC0909),
)
.align(Alignment.BottomCenter),
colors = ButtonDefaults.elevatedButtonColors(
containerColor = RedMain,
disabledContainerColor = RedMain.copy(alpha = 0.5f),
disabledContentColor = RedMain.copy(alpha = 0.5f),
)
) {
Text(
text = if (pagerState.currentPage == 0)
stringResource(id = R.string.continue_button_text)
else
stringResource(id = R.string.get_started_button_text),
style = MaterialTheme.typography.titleSmall,
color = Color.White
)
}
}
}
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/onboarding/components/OnboardingScreenContent.kt | 114467065 |
package test.createx.heartrateapp.presentation.onboarding
import androidx.annotation.RawRes
import androidx.annotation.StringRes
import test.createx.heartrateapp.R
data class Page(
@StringRes val title: Int,
@StringRes val description: Int,
@RawRes val image: Int,
@RawRes val bg: Int
){
companion object {
fun get() = listOf(
Page(
R.string.heart_rate_measurement_title,
R.string.heart_rate_measurement_description,
R.raw.image1,
R.raw.onboarding1
),
Page(
R.string.measurements_and_mood_statistics_title,
R.string.measurements_and_mood_statistics_description,
R.raw.image2,
R.raw.onboarding2
)
)
}
}
| HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/onboarding/Page.kt | 4270488902 |
package test.createx.heartrateapp.presentation.onboarding
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import kotlinx.coroutines.delay
import test.createx.heartrateapp.R
import test.createx.heartrateapp.presentation.onboarding.components.OnboardingScreenContent
import test.createx.heartrateapp.ui.theme.HeartRateAppTheme
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun OnboardingScreen(navController: NavController) {
val pages = Page.get()
val pagerState = rememberPagerState(
initialPage = 0, initialPageOffsetFraction = 0f
) {
pages.size
}
val compositionBg by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.onboarding1))
val bgAnimationState = animateLottieCompositionAsState(composition = compositionBg)
var isPlaying by remember { mutableStateOf(false) }
val compositionBg2 by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.onboarding2))
val bg2AnimationState =
animateLottieCompositionAsState(composition = compositionBg2, isPlaying = isPlaying)
var isContentVisible by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
delay(3000)
isContentVisible = true
}
LaunchedEffect(pagerState) {
snapshotFlow { pagerState.targetPage }.collect { page ->
if (page == 1) {
isPlaying = true
}
}
}
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
if (!isPlaying) {
LottieAnimation(
composition = compositionBg,
progress = { bgAnimationState.progress },
modifier = Modifier.fillMaxSize(),
alignment = Alignment.Center,
contentScale = ContentScale.Crop
)
} else {
LottieAnimation(
composition = compositionBg2,
progress = { bg2AnimationState.progress },
modifier = Modifier.fillMaxSize(),
alignment = Alignment.Center,
contentScale = ContentScale.Crop
)
}
OnboardingScreenContent(
pagerState = pagerState,
pages = pages,
navController = navController,
isContentVisible = isContentVisible
)
}
}
@Preview(showBackground = true)
@Composable
fun OnboardingPrev() {
HeartRateAppTheme {
OnboardingScreen(navController = rememberNavController())
}
} | HeartRateApp/app/src/main/java/test/createx/heartrateapp/presentation/onboarding/OnboardingScreen.kt | 2571698052 |
package com.example.barvolume
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("com.example.barvolume", appContext.packageName)
}
} | Dicod-test/app/src/androidTest/java/com/example/barvolume/ExampleInstrumentedTest.kt | 1953992475 |
package com.example.barvolume
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)
}
} | Dicod-test/app/src/test/java/com/example/barvolume/ExampleUnitTest.kt | 292265496 |
package com.example.barvolume
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.PersistableBundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var edtWidth: EditText
private lateinit var edtHeight: EditText
private lateinit var edtLength: EditText
private lateinit var btnCalculate: Button
private lateinit var tvResult: TextView
companion object{
private const val STATE_RESULT = "state_result"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
edtWidth = findViewById(R.id.edt_width)
edtHeight = findViewById(R.id.edt_height)
edtLength = findViewById(R.id.edt_length)
btnCalculate = findViewById(R.id.btn_calculate)
tvResult = findViewById(R.id.tv_result)
btnCalculate.setOnClickListener(this)
if (savedInstanceState != null){
val result =savedInstanceState.getString(STATE_RESULT)
tvResult.text = result
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(STATE_RESULT, tvResult.text.toString())
}
override fun onClick(view: View?) {
if (view?.id == R.id.btn_calculate) {
val inputLength = edtLength.text.toString().trim()
val inputWidth = edtWidth.text.toString().trim()
val inputHeight = edtHeight.text.toString().trim()
var isEmptyFields = false
/*
* validasi apakah inputan masih ada yang kosonng
* */
if (inputLength.isEmpty()){
isEmptyFields = true
edtLength.error = "Field ini tidak boleh kosong"
}
if (inputWidth.isEmpty()){
isEmptyFields = true
edtWidth.error = "Field ini tidak boleh kosong"
}
if (inputHeight.isEmpty()){
isEmptyFields = true
edtHeight.error = "Field ini tidak boleh kosong"
}
/*
* jika semua inputan valid maka tampilanka hasilnya
* */
if (!isEmptyFields){
val volume = inputLength.toDouble() * inputWidth.toDouble() * inputHeight.toDouble()
tvResult.text = volume.toString()
}
}
}
} | Dicod-test/app/src/main/java/com/example/barvolume/MainActivity.kt | 2276775840 |
package com.example.androidcomposecanvas
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("com.example.androidcomposecanvas", appContext.packageName)
}
} | AndroidComposeCanvas/app/src/androidTest/java/com/example/androidcomposecanvas/ExampleInstrumentedTest.kt | 502679630 |
package com.example.androidcomposecanvas
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)
}
} | AndroidComposeCanvas/app/src/test/java/com/example/androidcomposecanvas/ExampleUnitTest.kt | 1542233193 |
package com.example.androidcomposecanvas.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | AndroidComposeCanvas/app/src/main/java/com/example/androidcomposecanvas/ui/theme/Color.kt | 420864210 |
package com.example.androidcomposecanvas.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun AndroidComposeCanvasTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | AndroidComposeCanvas/app/src/main/java/com/example/androidcomposecanvas/ui/theme/Theme.kt | 3699351568 |
package com.example.androidcomposecanvas.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | AndroidComposeCanvas/app/src/main/java/com/example/androidcomposecanvas/ui/theme/Type.kt | 3791227473 |
package com.example.androidcomposecanvas
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.inset
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.drawscope.scale
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androidcomposecanvas.ui.theme.AndroidComposeCanvasTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AndroidComposeCanvasTheme {
//Simple rectangle
Canvas(modifier = Modifier.fillMaxSize()) {
val rectSize = size / 2f
inset(horizontal = 50f, vertical = 100f) {
drawRect(
color = Color.Magenta,
size = rectSize
)
}
//Drawing a line
val canvasWidth = size.width
val canvasHeight = size.height
drawLine(
start = Offset(x = canvasWidth, y = 0f),
end = Offset(x = 0f, y = canvasHeight),
color = Color.Blue
)
//Scaling the drawing content
translate(left = 100f, top = 300f) {
scale(scaleX = 1f, scaleY = 1f){
drawCircle(color = Color.Blue, radius = 120.dp.toPx())
}
}
rotate(degrees = 34F) {
drawRect(
color = Color.Gray,
topLeft = Offset(x = size.width / 3F, y = size.height / 3F),
size = size / 3F
)
}
}
Spacer(
modifier = Modifier
.drawWithCache {
val path = Path()
path.moveTo(0f, 0f)
path.lineTo(x = size.width/2f,y=size.height)
path.lineTo(size.width, 0f)
path.close()
onDrawBehind {
drawPath(path, Color.Magenta, style = Stroke(width = 10f))
}
}
.fillMaxSize()
)
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
AndroidComposeCanvasTheme {
Greeting("Android")
}
} | AndroidComposeCanvas/app/src/main/java/com/example/androidcomposecanvas/MainActivity.kt | 2997716308 |
package mbk.io.sabrina_hm4_5m
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("mbk.io.sabrina_hm4_5m", appContext.packageName)
}
} | hw5-6_5mon/app/src/androidTest/java/mbk/io/sabrina_hm4_5m/ExampleInstrumentedTest.kt | 2786007732 |
package mbk.io.sabrina_hm4_5m
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)
}
} | hw5-6_5mon/app/src/test/java/mbk/io/sabrina_hm4_5m/ExampleUnitTest.kt | 2684883312 |
package mbk.io.sabrina_hm4_5m
data class OnBoardingModel(
val image: Int? = null,
val title: String? = null,
val description: String? = null
) | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/OnBoardingModel.kt | 3659719328 |
package mbk.io.sabrina_hm4_5m
import android.app.Application
import androidx.room.Room
import dagger.hilt.android.HiltAndroidApp
import mbk.io.sabrina_hm4_5m.room.AppDatabase
@HiltAndroidApp
class App : Application() {
companion object {
lateinit var appDatabase: AppDatabase
}
override fun onCreate() {
super.onCreate()
appDatabase = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "love-file")
.allowMainThreadQueries().build()
}
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/App.kt | 1578933267 |
package mbk.io.sabrina_hm4_5m
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.findNavController
import dagger.hilt.android.AndroidEntryPoint
import mbk.io.sabrina_hm4_5m.databinding.ActivityMainBinding
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
@Inject
lateinit var pref: Pref
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navController = findNavController(R.id.nav_host_fragment_activity_main)
if (!pref.onShowed()) {
navController.navigate(R.id.onBoardingFragment)
}
}
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/MainActivity.kt | 1782122559 |
package mbk.io.sabrina_hm4_5m.di
import android.content.Context
import android.content.SharedPreferences
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import mbk.io.sabrina_hm4_5m.Hero
import mbk.io.sabrina_hm4_5m.model.LoveApi
import mbk.io.sabrina_hm4_5m.Pref
import mbk.io.sabrina_hm4_5m.Utils
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
@Module
@InstallIn(SingletonComponent::class)
class AppModule {
@Provides
fun provideApi(): LoveApi {
return Retrofit.Builder().baseUrl("https://love-calculator.p.rapidapi.com/")
.addConverterFactory(GsonConverterFactory.create()).build().create(LoveApi::class.java)
}
@Provides
fun provideUtils() = Utils()
@Provides
fun provideHero(): Hero {
return Hero()
}
@Provides
fun providePreferences(@ApplicationContext context: Context): SharedPreferences {
return context.getSharedPreferences("fileName", Context.MODE_PRIVATE)
}
@Provides
fun providePref(sharedPreferences: SharedPreferences): Pref {
return Pref(sharedPreferences)
}
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/di/AppModule.kt | 308045859 |
package mbk.io.sabrina_hm4_5m.room
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import mbk.io.sabrina_hm4_5m.model.LoveModel
@Dao
interface LoveDao {
@Query( "SELECT * FROM `love-table` ORDER by firstName ASC")
fun getAll(): List<LoveModel>
@Insert
fun insert(vararg model: LoveModel)
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/room/LoveDao.kt | 532610393 |
package mbk.io.sabrina_hm4_5m.room
import androidx.room.Database
import androidx.room.RoomDatabase
import mbk.io.sabrina_hm4_5m.model.LoveModel
@Database(entities = [LoveModel::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun getDao(): LoveDao
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/room/AppDatabase.kt | 3893300069 |
package mbk.io.sabrina_hm4_5m
import android.content.Context
import android.widget.Toast
class Utils {
fun showToast(context: Context, msg: String){
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
}
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/Utils.kt | 3308786063 |
package mbk.io.sabrina_hm4_5m
class Hero {
val name = "petya"
val damage = 12
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/Hero.kt | 2209379135 |
package mbk.io.sabrina_hm4_5m
import android.content.SharedPreferences
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
class Pref @Inject constructor (private val pref: SharedPreferences) {
fun onShowed():Boolean{
return pref.getBoolean(SHOWED_KEY, false)
}
fun onBoardingShow() {
pref.edit().putBoolean(SHOWED_KEY, true).apply()
}
companion object{
const val SHOWED_KEY = "showed.key"
}
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/Pref.kt | 3621615742 |
package mbk.io.sabrina_hm4_5m
import android.util.Log
import androidx.lifecycle.MutableLiveData
import mbk.io.sabrina_hm4_5m.model.LoveApi
import mbk.io.sabrina_hm4_5m.model.LoveModel
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import javax.inject.Inject
class Repository @Inject constructor(private val api: LoveApi){
fun getData(firstName: String, secondName: String): MutableLiveData<LoveModel> {
val mutableLiveData = MutableLiveData<LoveModel>()
api.getLovePerc(firstName, secondName).enqueue(object : Callback<LoveModel> {
override fun onResponse(call: Call<LoveModel>, response: Response<LoveModel>) {
if (response.isSuccessful) {
response.body()?.let { loveModel ->
mutableLiveData.postValue(loveModel)
}
}
}
override fun onFailure(call: Call<LoveModel>, t: Throwable) {
Log.e("ololo", "onFailure: ${t.message}")
}
})
return mutableLiveData
}
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/Repository.kt | 1094577857 |
package mbk.io.sabrina_hm4_5m
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import mbk.io.sabrina_hm4_5m.model.LoveModel
import javax.inject.Inject
@HiltViewModel
class LoveViewModel @Inject constructor(private val repository: Repository) : ViewModel() {
fun getLoveLiveData(firstName: String, secondName: String): LiveData<LoveModel> {
return repository.getData(firstName, secondName)
}
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/LoveViewModel.kt | 3585252599 |
package mbk.io.sabrina_hm4_5m
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import dagger.hilt.android.AndroidEntryPoint
import mbk.io.sabrina_hm4_5m.databinding.FragmentMainBinding
import mbk.io.sabrina_hm4_5m.databinding.FragmentSecondBinding
class SecondFragment : Fragment() {
private lateinit var binding: FragmentSecondBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentSecondBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val list = App.appDatabase.getDao().getAll()
list.forEach {
binding.tvHistory.append("$it")
}
}
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/SecondFragment.kt | 1203677266 |
package mbk.io.sabrina_hm4_5m.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
import java.io.Serializable
@Entity(tableName = "love-table")
data class LoveModel(
@SerializedName("fname")
val firstName: String,
@SerializedName("sname")
val secondName: String,
val percentage: String,
val result: String,
@PrimaryKey(autoGenerate = true)
var id: Int = 0
) {
override fun toString(): String {
return "$firstName\n$secondName\n$percentage%\n$result\n\n"
}
}
| hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/model/LoveModel.kt | 1270231263 |
package mbk.io.sabrina_hm4_5m.model
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Query
interface LoveApi {
@GET("getPercentage")
fun getLovePerc(
@Query("fname") firstName: String,
@Query("sname") secondName: String,
@Header("X-RapidAPI-Key") key: String = "7b0f97fcb6mshdc7acfc7bb09cbap141aa6jsn5ab895d1d335",
@Header("X-RapidAPI-Host") host: String = "love-calculator.p.rapidapi.com"
): Call<LoveModel>
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/model/LoveApi.kt | 2015496561 |
package mbk.io.sabrina_hm4_5m
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import dagger.hilt.android.AndroidEntryPoint
import mbk.io.sabrina_hm4_5m.databinding.FragmentMainBinding
import mbk.io.sabrina_hm4_5m.databinding.FragmentOnBoardingBinding
import javax.inject.Inject
@AndroidEntryPoint
class MainFragment : Fragment() {
private lateinit var binding: FragmentMainBinding
private val viewModel: LoveViewModel by viewModels()
@Inject
lateinit var pref: Pref
@Inject
lateinit var utils: Utils
@Inject
lateinit var hero: Hero
@Inject
lateinit var sharedPreferences: SharedPreferences
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentMainBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initClickers()
}
private fun initClickers() {
with(binding) {
btnHistory.setOnClickListener{
//startActivity(Intent(this@MainFragment, SecondFragment::class.java))
findNavController().navigate(R.id.secondFragment)
}
btnGet.setOnClickListener {
/*utils.showToast(this@MainActivity, hero.name + "${hero.damage}")
sharedPreferences.edit().putBoolean("as", true).apply()*/
viewModel.getLoveLiveData(etFname.text.toString(), etSname.text.toString())
.observe(viewLifecycleOwner, Observer {
App.appDatabase.getDao().insert(it)
tvResult.text = it.toString()
})
}
}
}
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/MainFragment.kt | 45847286 |
package mbk.io.sabrina_hm4_5m.onboarding.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import androidx.recyclerview.widget.RecyclerView.Adapter
import mbk.io.sabrina_hm4_5m.OnBoardingModel
import mbk.io.sabrina_hm4_5m.R
import mbk.io.sabrina_hm4_5m.databinding.ItemOnboardingBinding
class OnBoardingAdapter(private val onClick:()-> Unit): Adapter<OnBoardingAdapter.OnBoardingViewHolder>() {
private val list = arrayListOf<OnBoardingModel>(
OnBoardingModel(R.raw.anim_cat,"Have a good time","You should take the time to help those who need you"),
OnBoardingModel(R.raw.anim_heart,"Cherishing love","It is now no longer possible for you to cherish love"),
OnBoardingModel(R.raw.anim_sad,"Have a breakup?","We have made the correction for you don't worry"),
OnBoardingModel(R.raw.anim_cloud,"It's Funs","and many more"),
)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OnBoardingViewHolder {
return OnBoardingViewHolder(ItemOnboardingBinding.inflate(LayoutInflater.from(parent.context),parent, false))
}
override fun getItemCount(): Int = list.size
override fun onBindViewHolder(holder: OnBoardingViewHolder, position: Int) {
holder.bind(list[position])
}
inner class OnBoardingViewHolder(private val binding: ItemOnboardingBinding): ViewHolder(binding.root){
fun bind(boarding: OnBoardingModel){
binding.apply {
boarding.apply {
tvTitle.text = title
tvDescription.text = description
boarding.image?.let {
animationView.setAnimation(boarding.image)
animationView.playAnimation()
}
}
btnStart.isVisible = adapterPosition == list.lastIndex
btnStart.setOnClickListener{onClick()}
}
}
}
} | hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/onboarding/adapter/OnBoardingAdapter.kt | 2690731757 |
package mbk.io.sabrina_hm4_5m.onboarding
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import dagger.hilt.android.AndroidEntryPoint
import mbk.io.sabrina_hm4_5m.Pref
import mbk.io.sabrina_hm4_5m.R
import mbk.io.sabrina_hm4_5m.databinding.FragmentOnBoardingBinding
import mbk.io.sabrina_hm4_5m.onboarding.adapter.OnBoardingAdapter
import javax.inject.Inject
@AndroidEntryPoint
class OnBoardingFragment : Fragment() {
private val adapter = OnBoardingAdapter(this::onClick)
private lateinit var binding: FragmentOnBoardingBinding
@Inject
lateinit var pref: Pref
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentOnBoardingBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.viewPager.adapter = adapter
binding.circleIndicator.setViewPager(binding.viewPager)
}
private fun onClick() {
pref.onBoardingShow()
findNavController().navigate(R.id.mainFragment)
}
}
| hw5-6_5mon/app/src/main/java/mbk/io/sabrina_hm4_5m/onboarding/OnBoardingFragment.kt | 1257851635 |
/*
* 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.test.filters.SmallTest
import com.android.customization.module.logging.TestThemesUserEventLogger
import com.android.customization.module.logging.ThemesUserEventLogger
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.wallpaper.testing.FakeSecureSettingsRepository
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(RobolectricTestRunner::class)
class NotificationSectionViewModelTest {
private val logger: ThemesUserEventLogger = TestThemesUserEventLogger()
private lateinit var underTest: NotificationSectionViewModel
private lateinit var testScope: TestScope
private lateinit var interactor: NotificationsInteractor
@Before
fun setUp() {
val testDispatcher = UnconfinedTestDispatcher()
Dispatchers.setMain(testDispatcher)
testScope = TestScope(testDispatcher)
interactor =
NotificationsInteractor(
repository =
NotificationsRepository(
scope = testScope.backgroundScope,
backgroundDispatcher = testDispatcher,
secureSettingsRepository = FakeSecureSettingsRepository(),
),
snapshotRestorer = {
NotificationsSnapshotRestorer(
interactor = interactor,
)
.apply { runBlocking { setUpSnapshotRestorer(FakeSnapshotStore()) } }
},
)
underTest =
NotificationSectionViewModel(
interactor = interactor,
logger = logger,
)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `toggles back and forth`() =
testScope.runTest {
val isSwitchOn = collectLastValue(underTest.isSwitchOn)
val initialIsSwitchOn = isSwitchOn()
underTest.onClicked()
assertThat(isSwitchOn()).isNotEqualTo(initialIsSwitchOn)
underTest.onClicked()
assertThat(isSwitchOn()).isEqualTo(initialIsSwitchOn)
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/picker/notifications/ui/viewmodel/NotificationSectionViewModelTest.kt | 162634365 |
/*
* 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 androidx.test.filters.SmallTest
import com.android.customization.picker.notifications.shared.model.NotificationSettingsModel
import com.android.wallpaper.testing.FakeSecureSettingsRepository
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(JUnit4::class)
class NotificationsRepositoryTest {
private lateinit var underTest: NotificationsRepository
private lateinit var testScope: TestScope
private lateinit var secureSettingsRepository: FakeSecureSettingsRepository
@Before
fun setUp() {
val testDispatcher = StandardTestDispatcher()
testScope = TestScope(testDispatcher)
secureSettingsRepository = FakeSecureSettingsRepository()
underTest =
NotificationsRepository(
scope = testScope.backgroundScope,
backgroundDispatcher = testDispatcher,
secureSettingsRepository = secureSettingsRepository,
)
}
@Test
fun settings() =
testScope.runTest {
val settings = collectLastValue(underTest.settings)
secureSettingsRepository.set(
name = Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
value = 1,
)
assertThat(settings())
.isEqualTo(NotificationSettingsModel(isShowNotificationsOnLockScreenEnabled = true))
secureSettingsRepository.set(
name = Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS,
value = 0,
)
assertThat(settings())
.isEqualTo(
NotificationSettingsModel(isShowNotificationsOnLockScreenEnabled = false)
)
}
@Test
fun setSettings() =
testScope.runTest {
val settings = collectLastValue(underTest.settings)
val model1 = NotificationSettingsModel(isShowNotificationsOnLockScreenEnabled = true)
underTest.setSettings(model1)
assertThat(settings()).isEqualTo(model1)
val model2 = NotificationSettingsModel(isShowNotificationsOnLockScreenEnabled = false)
underTest.setSettings(model2)
assertThat(settings()).isEqualTo(model2)
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/picker/notifications/data/repository/NotificationsRepositoryTest.kt | 1306805547 |
/*
* 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 androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.android.customization.module.logging.TestThemesUserEventLogger
import com.android.customization.picker.clock.data.repository.ClockPickerRepository
import com.android.customization.picker.clock.data.repository.FakeClockPickerRepository
import com.android.customization.picker.clock.domain.interactor.ClockPickerInteractor
import com.android.customization.picker.clock.domain.interactor.ClockPickerSnapshotRestorer
import com.android.customization.picker.clock.shared.model.ClockMetadataModel
import com.android.customization.picker.clock.ui.FakeClockViewFactory
import com.android.customization.picker.clock.ui.view.ClockViewFactory
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(RobolectricTestRunner::class)
class ClockCarouselViewModelTest {
private val repositoryWithMultipleClocks by lazy { FakeClockPickerRepository() }
private val repositoryWithSingleClock by lazy {
FakeClockPickerRepository(
listOf(
ClockMetadataModel(
clockId = FakeClockPickerRepository.CLOCK_ID_0,
isSelected = true,
selectedColorId = null,
colorToneProgress = ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS,
seedColor = null,
),
)
)
}
private lateinit var testDispatcher: CoroutineDispatcher
private lateinit var underTest: ClockCarouselViewModel
private lateinit var interactor: ClockPickerInteractor
private lateinit var clockViewFactory: ClockViewFactory
@Before
fun setUp() {
testDispatcher = StandardTestDispatcher()
clockViewFactory = FakeClockViewFactory()
Dispatchers.setMain(testDispatcher)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun setSelectedClock() = runTest {
underTest =
ClockCarouselViewModel(
getClockPickerInteractor(repositoryWithMultipleClocks),
backgroundDispatcher = testDispatcher,
clockViewFactory = clockViewFactory,
resources = InstrumentationRegistry.getInstrumentation().targetContext.resources,
logger = TestThemesUserEventLogger(),
)
val observedSelectedIndex = collectLastValue(underTest.selectedIndex)
advanceTimeBy(ClockCarouselViewModel.CLOCKS_EVENT_UPDATE_DELAY_MILLIS)
underTest.setSelectedClock(FakeClockPickerRepository.fakeClocks[2].clockId)
assertThat(observedSelectedIndex()).isEqualTo(2)
}
private fun getClockPickerInteractor(repository: ClockPickerRepository): ClockPickerInteractor {
return ClockPickerInteractor(
repository = repository,
snapshotRestorer = {
ClockPickerSnapshotRestorer(interactor = interactor).apply {
runBlocking { setUpSnapshotRestorer(store = FakeSnapshotStore()) }
}
}
)
.also { interactor = it }
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/picker/clock/ui/viewmodel/ClockCarouselViewModelTest.kt | 1334425797 |
package com.android.customization.picker.clock.ui.viewmodel
import android.content.Context
import android.stats.style.StyleEnums
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.android.customization.module.logging.TestThemesUserEventLogger
import com.android.customization.picker.clock.data.repository.FakeClockPickerRepository
import com.android.customization.picker.clock.domain.interactor.ClockPickerInteractor
import com.android.customization.picker.clock.domain.interactor.ClockPickerSnapshotRestorer
import com.android.customization.picker.clock.shared.ClockSize
import com.android.customization.picker.clock.shared.model.ClockMetadataModel
import com.android.customization.picker.color.data.repository.FakeColorPickerRepository
import com.android.customization.picker.color.domain.interactor.ColorPickerInteractor
import com.android.customization.picker.color.domain.interactor.ColorPickerSnapshotRestorer
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(RobolectricTestRunner::class)
class ClockSettingsViewModelTest {
private val logger = TestThemesUserEventLogger()
private lateinit var context: Context
private lateinit var testScope: TestScope
private lateinit var colorPickerInteractor: ColorPickerInteractor
private lateinit var clockPickerInteractor: ClockPickerInteractor
private lateinit var underTest: ClockSettingsViewModel
private lateinit var colorMap: Map<String, ClockColorViewModel>
// We make the condition that CLOCK_ID_3 is not reactive to tone
private val getIsReactiveToTone: (clockId: String?) -> Boolean = { clockId ->
when (clockId) {
FakeClockPickerRepository.CLOCK_ID_0 -> true
FakeClockPickerRepository.CLOCK_ID_1 -> true
FakeClockPickerRepository.CLOCK_ID_2 -> true
FakeClockPickerRepository.CLOCK_ID_3 -> false
else -> false
}
}
@Before
fun setUp() {
val testDispatcher = StandardTestDispatcher()
Dispatchers.setMain(testDispatcher)
context = InstrumentationRegistry.getInstrumentation().targetContext
testScope = TestScope(testDispatcher)
clockPickerInteractor =
ClockPickerInteractor(
repository = FakeClockPickerRepository(),
snapshotRestorer = {
ClockPickerSnapshotRestorer(interactor = clockPickerInteractor).apply {
runBlocking { setUpSnapshotRestorer(store = FakeSnapshotStore()) }
}
},
)
colorPickerInteractor =
ColorPickerInteractor(
repository = FakeColorPickerRepository(context = context),
snapshotRestorer = {
ColorPickerSnapshotRestorer(interactor = colorPickerInteractor).apply {
runBlocking { setUpSnapshotRestorer(store = FakeSnapshotStore()) }
}
},
)
underTest =
ClockSettingsViewModel.Factory(
context = context,
clockPickerInteractor = clockPickerInteractor,
colorPickerInteractor = colorPickerInteractor,
logger = logger,
getIsReactiveToTone = getIsReactiveToTone,
)
.create(ClockSettingsViewModel::class.java)
colorMap = ClockColorViewModel.getPresetColorMap(context.resources)
testScope.launch {
clockPickerInteractor.setSelectedClock(FakeClockPickerRepository.CLOCK_ID_0)
}
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun clickOnColorSettingsTab() = runTest {
val tabs = collectLastValue(underTest.tabs)
assertThat(tabs()?.get(0)?.name).isEqualTo("Color")
assertThat(tabs()?.get(0)?.isSelected).isTrue()
assertThat(tabs()?.get(1)?.name).isEqualTo("Size")
assertThat(tabs()?.get(1)?.isSelected).isFalse()
tabs()?.get(1)?.onClicked?.invoke()
assertThat(tabs()?.get(0)?.isSelected).isFalse()
assertThat(tabs()?.get(1)?.isSelected).isTrue()
}
@Test
fun setSelectedColor() = runTest {
val observedClockColorOptions = collectLastValue(underTest.colorOptions)
val observedSelectedColorOptionPosition =
collectLastValue(underTest.selectedColorOptionPosition)
val observedSliderProgress = collectLastValue(underTest.sliderProgress)
val observedSeedColor = collectLastValue(underTest.seedColor)
// Advance COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS since there is a delay from colorOptions
advanceTimeBy(ClockSettingsViewModel.COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS)
val option0IsSelected = collectLastValue(observedClockColorOptions()!![0].isSelected)
val option0OnClicked = collectLastValue(observedClockColorOptions()!![0].onClicked)
assertThat(option0IsSelected()).isTrue()
assertThat(option0OnClicked()).isNull()
assertThat(observedSelectedColorOptionPosition()).isEqualTo(0)
val option1OnClickedBefore = collectLastValue(observedClockColorOptions()!![1].onClicked)
option1OnClickedBefore()?.invoke()
// Advance COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS since there is a delay from colorOptions
advanceTimeBy(ClockSettingsViewModel.COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS)
val option1IsSelected = collectLastValue(observedClockColorOptions()!![1].isSelected)
val option1OnClickedAfter = collectLastValue(observedClockColorOptions()!![1].onClicked)
assertThat(option1IsSelected()).isTrue()
assertThat(option1OnClickedAfter()).isNull()
assertThat(observedSelectedColorOptionPosition()).isEqualTo(1)
assertThat(observedSliderProgress())
.isEqualTo(ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS)
val expectedSelectedColorModel = colorMap.values.first() // RED
assertThat(observedSeedColor())
.isEqualTo(
ClockSettingsViewModel.blendColorWithTone(
expectedSelectedColorModel.color,
expectedSelectedColorModel.getColorTone(
ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS
),
)
)
}
@Test
fun setColorTone() = runTest {
val observedClockColorOptions = collectLastValue(underTest.colorOptions)
val observedIsSliderEnabled = collectLastValue(underTest.isSliderEnabled)
val observedSliderProgress = collectLastValue(underTest.sliderProgress)
val observedSeedColor = collectLastValue(underTest.seedColor)
// Advance COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS since there is a delay from colorOptions
advanceTimeBy(ClockSettingsViewModel.COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS)
val option0IsSelected = collectLastValue(observedClockColorOptions()!![0].isSelected)
assertThat(option0IsSelected()).isTrue()
assertThat(observedIsSliderEnabled()).isFalse()
val option1OnClicked = collectLastValue(observedClockColorOptions()!![1].onClicked)
option1OnClicked()?.invoke()
// Advance COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS since there is a delay from colorOptions
advanceTimeBy(ClockSettingsViewModel.COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS)
assertThat(observedIsSliderEnabled()).isTrue()
val targetProgress1 = 99
underTest.onSliderProgressChanged(targetProgress1)
assertThat(observedSliderProgress()).isEqualTo(targetProgress1)
val targetProgress2 = 55
testScope.launch { underTest.onSliderProgressStop(targetProgress2) }
assertThat(observedSliderProgress()).isEqualTo(targetProgress2)
val expectedSelectedColorModel = colorMap.values.first() // RED
assertThat(observedSeedColor())
.isEqualTo(
ClockSettingsViewModel.blendColorWithTone(
expectedSelectedColorModel.color,
expectedSelectedColorModel.getColorTone(targetProgress2),
)
)
}
@Test
fun setClockSize() = runTest {
val observedClockSize = collectLastValue(underTest.selectedClockSize)
underTest.setClockSize(ClockSize.DYNAMIC)
assertThat(observedClockSize()).isEqualTo(ClockSize.DYNAMIC)
assertThat(logger.getLoggedClockSize()).isEqualTo(StyleEnums.CLOCK_SIZE_DYNAMIC)
underTest.setClockSize(ClockSize.SMALL)
assertThat(observedClockSize()).isEqualTo(ClockSize.SMALL)
assertThat(logger.getLoggedClockSize()).isEqualTo(StyleEnums.CLOCK_SIZE_SMALL)
}
@Test
fun getIsReactiveToTone() = runTest {
val observedClockColorOptions = collectLastValue(underTest.colorOptions)
val isSliderEnabled = collectLastValue(underTest.isSliderEnabled)
// Advance COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS since there is a delay from colorOptions
advanceTimeBy(ClockSettingsViewModel.COLOR_OPTIONS_EVENT_UPDATE_DELAY_MILLIS)
val option1OnClicked = collectLastValue(observedClockColorOptions()!![1].onClicked)
option1OnClicked()?.invoke()
clockPickerInteractor.setSelectedClock(FakeClockPickerRepository.CLOCK_ID_0)
assertThat(isSliderEnabled()).isTrue()
// We make the condition that CLOCK_ID_0 is not reactive to tone
clockPickerInteractor.setSelectedClock(FakeClockPickerRepository.CLOCK_ID_3)
assertThat(isSliderEnabled()).isFalse()
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/picker/clock/ui/viewmodel/ClockSettingsViewModelTest.kt | 3505260511 |
package com.android.customization.picker.clock.ui
import android.content.res.Resources
import android.view.View
import androidx.lifecycle.LifecycleOwner
import com.android.customization.picker.clock.data.repository.FakeClockPickerRepository
import com.android.customization.picker.clock.ui.FakeClockViewFactory.Companion.fakeClocks
import com.android.customization.picker.clock.ui.view.ClockViewFactory
import com.android.systemui.plugins.clocks.ClockConfig
import com.android.systemui.plugins.clocks.ClockController
import com.android.systemui.plugins.clocks.ClockEvents
import com.android.systemui.plugins.clocks.ClockFaceController
import java.io.PrintWriter
/**
* This is a fake [ClockViewFactory]. Only implement the function if it's actually called in a test.
*/
class FakeClockViewFactory(
val clockControllers: MutableMap<String, ClockController> = fakeClocks.toMutableMap(),
) : ClockViewFactory {
class FakeClockController(
override var config: ClockConfig,
) : ClockController {
override val smallClock: ClockFaceController
get() = TODO("Not yet implemented")
override val largeClock: ClockFaceController
get() = TODO("Not yet implemented")
override val events: ClockEvents
get() = TODO("Not yet implemented")
override fun initialize(resources: Resources, dozeFraction: Float, foldFraction: Float) =
TODO("Not yet implemented")
override fun dump(pw: PrintWriter) = TODO("Not yet implemented")
}
override fun getController(clockId: String): ClockController = clockControllers.get(clockId)!!
override fun getLargeView(clockId: String): View {
TODO("Not yet implemented")
}
override fun getSmallView(clockId: String): View {
TODO("Not yet implemented")
}
override fun updateColorForAllClocks(seedColor: Int?) {
TODO("Not yet implemented")
}
override fun updateColor(clockId: String, seedColor: Int?) {
TODO("Not yet implemented")
}
override fun updateRegionDarkness() {
TODO("Not yet implemented")
}
override fun updateTimeFormat(clockId: String) {
TODO("Not yet implemented")
}
override fun registerTimeTicker(owner: LifecycleOwner) {
TODO("Not yet implemented")
}
override fun onDestroy() {
TODO("Not yet implemented")
}
override fun unregisterTimeTicker(owner: LifecycleOwner) {
TODO("Not yet implemented")
}
companion object {
val fakeClocks =
FakeClockPickerRepository.fakeClocks
.map { clock ->
clock.clockId to
FakeClockController(
ClockConfig(
id = clock.clockId,
name = "Name: ${clock.clockId}",
description = "Desc: ${clock.clockId}"
)
)
}
.toMap()
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/picker/clock/ui/FakeClockViewFactory.kt | 4030783238 |
/*
* 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.graphics.Color
import androidx.annotation.ColorInt
import androidx.annotation.IntRange
import com.android.customization.picker.clock.data.repository.FakeClockPickerRepository.Companion.fakeClocks
import com.android.customization.picker.clock.shared.ClockSize
import com.android.customization.picker.clock.shared.model.ClockMetadataModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
/** By default [FakeClockPickerRepository] uses [fakeClocks]. */
open class FakeClockPickerRepository(clocks: List<ClockMetadataModel> = fakeClocks) :
ClockPickerRepository {
override val allClocks: Flow<List<ClockMetadataModel>> = MutableStateFlow(clocks).asStateFlow()
private val selectedClockId = MutableStateFlow(fakeClocks[0].clockId)
@ColorInt private val selectedColorId = MutableStateFlow<String?>(null)
private val colorTone = MutableStateFlow(ClockMetadataModel.DEFAULT_COLOR_TONE_PROGRESS)
@ColorInt private val seedColor = MutableStateFlow<Int?>(null)
override val selectedClock: Flow<ClockMetadataModel> =
combine(
selectedClockId,
selectedColorId,
colorTone,
seedColor,
) { selectedClockId, selectedColor, colorTone, seedColor ->
val selectedClock = fakeClocks.find { clock -> clock.clockId == selectedClockId }
checkNotNull(selectedClock)
ClockMetadataModel(
clockId = selectedClock.clockId,
isSelected = true,
selectedColorId = selectedColor,
colorToneProgress = colorTone,
seedColor = seedColor,
)
}
private val _selectedClockSize = MutableStateFlow(ClockSize.SMALL)
override val selectedClockSize: Flow<ClockSize> = _selectedClockSize.asStateFlow()
override suspend fun setSelectedClock(clockId: String) {
selectedClockId.value = clockId
}
override suspend fun setClockColor(
selectedColorId: String?,
@IntRange(from = 0, to = 100) colorToneProgress: Int,
@ColorInt seedColor: Int?,
) {
this.selectedColorId.value = selectedColorId
this.colorTone.value = colorToneProgress
this.seedColor.value = seedColor
}
override suspend fun setClockSize(size: ClockSize) {
_selectedClockSize.value = size
}
companion object {
const val CLOCK_ID_0 = "clock0"
const val CLOCK_ID_1 = "clock1"
const val CLOCK_ID_2 = "clock2"
const val CLOCK_ID_3 = "clock3"
val fakeClocks =
listOf(
ClockMetadataModel(CLOCK_ID_0, true, null, 50, null),
ClockMetadataModel(CLOCK_ID_1, false, null, 50, null),
ClockMetadataModel(CLOCK_ID_2, false, null, 50, null),
ClockMetadataModel(CLOCK_ID_3, false, null, 50, null),
)
const val CLOCK_COLOR_ID = "RED"
const val CLOCK_COLOR_TONE_PROGRESS = 87
const val SEED_COLOR = Color.RED
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/picker/clock/data/repository/FakeClockPickerRepository.kt | 549616994 |
package com.android.customization.picker.clock.domain.interactor
import androidx.test.filters.SmallTest
import com.android.customization.picker.clock.data.repository.FakeClockPickerRepository
import com.android.customization.picker.clock.shared.ClockSize
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(RobolectricTestRunner::class)
class ClockPickerInteractorTest {
private lateinit var underTest: ClockPickerInteractor
@Before
fun setUp() {
val testDispatcher = StandardTestDispatcher()
Dispatchers.setMain(testDispatcher)
underTest =
ClockPickerInteractor(
repository = FakeClockPickerRepository(),
snapshotRestorer = {
ClockPickerSnapshotRestorer(interactor = underTest).apply {
runBlocking { setUpSnapshotRestorer(store = FakeSnapshotStore()) }
}
},
)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun setSelectedClock() = runTest {
val observedSelectedClockId = collectLastValue(underTest.selectedClockId)
underTest.setSelectedClock(FakeClockPickerRepository.fakeClocks[1].clockId)
Truth.assertThat(observedSelectedClockId())
.isEqualTo(FakeClockPickerRepository.fakeClocks[1].clockId)
}
@Test
fun setClockSize() = runTest {
val observedClockSize = collectLastValue(underTest.selectedClockSize)
underTest.setClockSize(ClockSize.DYNAMIC)
Truth.assertThat(observedClockSize()).isEqualTo(ClockSize.DYNAMIC)
underTest.setClockSize(ClockSize.SMALL)
Truth.assertThat(observedClockSize()).isEqualTo(ClockSize.SMALL)
}
@Test
fun setColor() = runTest {
val observedSelectedColor = collectLastValue(underTest.selectedColorId)
val observedColorToneProgress = collectLastValue(underTest.colorToneProgress)
val observedSeedColor = collectLastValue(underTest.seedColor)
underTest.setClockColor(
FakeClockPickerRepository.CLOCK_COLOR_ID,
FakeClockPickerRepository.CLOCK_COLOR_TONE_PROGRESS,
FakeClockPickerRepository.SEED_COLOR,
)
Truth.assertThat(observedSelectedColor())
.isEqualTo(FakeClockPickerRepository.CLOCK_COLOR_ID)
Truth.assertThat(observedColorToneProgress())
.isEqualTo(FakeClockPickerRepository.CLOCK_COLOR_TONE_PROGRESS)
Truth.assertThat(observedSeedColor()).isEqualTo(FakeClockPickerRepository.SEED_COLOR)
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/picker/clock/domain/interactor/ClockPickerInteractorTest.kt | 1844645242 |
/*
* 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 androidx.test.filters.SmallTest
import com.android.wallpaper.testing.FakeSnapshotStore
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(JUnit4::class)
class DarkModeSnapshotRestorerTest {
private lateinit var underTest: DarkModeSnapshotRestorer
private lateinit var testScope: TestScope
private var isActive = false
@Before
fun setUp() {
val testDispatcher = StandardTestDispatcher()
testScope = TestScope(testDispatcher)
underTest =
DarkModeSnapshotRestorer(
backgroundDispatcher = testDispatcher,
isActive = { isActive },
setActive = { isActive = it },
)
}
@Test
fun `set up and restore - active`() =
testScope.runTest {
isActive = true
val store = FakeSnapshotStore()
store.store(underTest.setUpSnapshotRestorer(store = store))
val storedSnapshot = store.retrieve()
underTest.restoreToSnapshot(snapshot = storedSnapshot)
assertThat(isActive).isTrue()
}
@Test
fun `set up and restore - inactive`() =
testScope.runTest {
isActive = false
val store = FakeSnapshotStore()
store.store(underTest.setUpSnapshotRestorer(store = store))
val storedSnapshot = store.retrieve()
underTest.restoreToSnapshot(snapshot = storedSnapshot)
assertThat(isActive).isFalse()
}
@Test
fun `set up - deactivate - restore to active`() =
testScope.runTest {
isActive = true
val store = FakeSnapshotStore()
store.store(underTest.setUpSnapshotRestorer(store = store))
val initialSnapshot = store.retrieve()
underTest.store(isActivated = false)
underTest.restoreToSnapshot(snapshot = initialSnapshot)
assertThat(isActive).isTrue()
}
@Test
fun `set up - activate - restore to inactive`() =
testScope.runTest {
isActive = false
val store = FakeSnapshotStore()
store.store(underTest.setUpSnapshotRestorer(store = store))
val initialSnapshot = store.retrieve()
underTest.store(isActivated = true)
underTest.restoreToSnapshot(snapshot = initialSnapshot)
assertThat(isActive).isFalse()
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/mode/DarkModeSnapshotRestorerTest.kt | 1037367997 |
/*
* 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.picker.color.ui.viewmodel
import android.content.Context
import android.graphics.Color
import android.stats.style.StyleEnums
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.android.customization.model.color.ColorOptionsProvider
import com.android.customization.module.logging.TestThemesUserEventLogger
import com.android.customization.picker.color.data.repository.FakeColorPickerRepository
import com.android.customization.picker.color.domain.interactor.ColorPickerInteractor
import com.android.customization.picker.color.domain.interactor.ColorPickerSnapshotRestorer
import com.android.customization.picker.color.shared.model.ColorType
import com.android.customization.picker.color.ui.viewmodel.ColorOptionIconViewModel
import com.android.customization.picker.color.ui.viewmodel.ColorPickerViewModel
import com.android.customization.picker.color.ui.viewmodel.ColorTypeTabViewModel
import com.android.systemui.monet.Style
import com.android.wallpaper.picker.option.ui.viewmodel.OptionItemViewModel
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(RobolectricTestRunner::class)
class ColorPickerViewModelTest {
private val logger = TestThemesUserEventLogger()
private lateinit var underTest: ColorPickerViewModel
private lateinit var repository: FakeColorPickerRepository
private lateinit var interactor: ColorPickerInteractor
private lateinit var store: FakeSnapshotStore
private lateinit var context: Context
private lateinit var testScope: TestScope
@Before
fun setUp() {
context = InstrumentationRegistry.getInstrumentation().targetContext
val testDispatcher = StandardTestDispatcher()
Dispatchers.setMain(testDispatcher)
testScope = TestScope(testDispatcher)
repository = FakeColorPickerRepository(context = context)
store = FakeSnapshotStore()
interactor =
ColorPickerInteractor(
repository = repository,
snapshotRestorer = {
ColorPickerSnapshotRestorer(interactor = interactor).apply {
runBlocking { setUpSnapshotRestorer(store = store) }
}
},
)
underTest =
ColorPickerViewModel.Factory(
context = context,
interactor = interactor,
logger = logger
)
.create(ColorPickerViewModel::class.java)
repository.setOptions(4, 4, ColorType.WALLPAPER_COLOR, 0)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `Select a color section color`() =
testScope.runTest {
val colorSectionOptions = collectLastValue(underTest.colorSectionOptions)
assertColorOptionUiState(
colorOptions = colorSectionOptions(),
selectedColorOptionIndex = 0
)
selectColorOption(colorSectionOptions, 2)
assertColorOptionUiState(
colorOptions = colorSectionOptions(),
selectedColorOptionIndex = 2
)
selectColorOption(colorSectionOptions, 4)
assertColorOptionUiState(
colorOptions = colorSectionOptions(),
selectedColorOptionIndex = 4
)
}
@Test
fun `Log selected wallpaper color`() =
testScope.runTest {
repository.setOptions(
listOf(
repository.buildWallpaperOption(
ColorOptionsProvider.COLOR_SOURCE_LOCK,
Style.EXPRESSIVE,
"121212"
)
),
listOf(repository.buildPresetOption(Style.FRUIT_SALAD, "#ABCDEF")),
ColorType.PRESET_COLOR,
0
)
val colorTypes = collectLastValue(underTest.colorTypeTabs)
val colorOptions = collectLastValue(underTest.colorOptions)
// Select "Wallpaper colors" tab
colorTypes()?.get(ColorType.WALLPAPER_COLOR)?.onClick?.invoke()
// Select a color option
selectColorOption(colorOptions, 0)
advanceUntilIdle()
assertThat(logger.themeColorSource)
.isEqualTo(StyleEnums.COLOR_SOURCE_LOCK_SCREEN_WALLPAPER)
assertThat(logger.themeColorStyle).isEqualTo(Style.EXPRESSIVE.toString().hashCode())
assertThat(logger.themeSeedColor).isEqualTo(Color.parseColor("#121212"))
}
@Test
fun `Log selected preset color`() =
testScope.runTest {
repository.setOptions(
listOf(
repository.buildWallpaperOption(
ColorOptionsProvider.COLOR_SOURCE_LOCK,
Style.EXPRESSIVE,
"121212"
)
),
listOf(repository.buildPresetOption(Style.FRUIT_SALAD, "#ABCDEF")),
ColorType.WALLPAPER_COLOR,
0
)
val colorTypes = collectLastValue(underTest.colorTypeTabs)
val colorOptions = collectLastValue(underTest.colorOptions)
// Select "Wallpaper colors" tab
colorTypes()?.get(ColorType.PRESET_COLOR)?.onClick?.invoke()
// Select a color option
selectColorOption(colorOptions, 0)
advanceUntilIdle()
assertThat(logger.themeColorSource).isEqualTo(StyleEnums.COLOR_SOURCE_PRESET_COLOR)
assertThat(logger.themeColorStyle).isEqualTo(Style.FRUIT_SALAD.toString().hashCode())
assertThat(logger.themeSeedColor).isEqualTo(Color.parseColor("#ABCDEF"))
}
@Test
fun `Select a preset color`() =
testScope.runTest {
val colorTypes = collectLastValue(underTest.colorTypeTabs)
val colorOptions = collectLastValue(underTest.colorOptions)
// Initially, the wallpaper color tab should be selected
assertPickerUiState(
colorTypes = colorTypes(),
colorOptions = colorOptions(),
selectedColorTypeText = "Wallpaper colors",
selectedColorOptionIndex = 0
)
// Select "Basic colors" tab
colorTypes()?.get(ColorType.PRESET_COLOR)?.onClick?.invoke()
assertPickerUiState(
colorTypes = colorTypes(),
colorOptions = colorOptions(),
selectedColorTypeText = "Basic colors",
selectedColorOptionIndex = -1
)
// Select a color option
selectColorOption(colorOptions, 2)
// Check original option is no longer selected
colorTypes()?.get(ColorType.WALLPAPER_COLOR)?.onClick?.invoke()
assertPickerUiState(
colorTypes = colorTypes(),
colorOptions = colorOptions(),
selectedColorTypeText = "Wallpaper colors",
selectedColorOptionIndex = -1
)
// Check new option is selected
colorTypes()?.get(ColorType.PRESET_COLOR)?.onClick?.invoke()
assertPickerUiState(
colorTypes = colorTypes(),
colorOptions = colorOptions(),
selectedColorTypeText = "Basic colors",
selectedColorOptionIndex = 2
)
}
/** Simulates a user selecting the affordance at the given index, if that is clickable. */
private fun TestScope.selectColorOption(
colorOptions: () -> List<OptionItemViewModel<ColorOptionIconViewModel>>?,
index: Int,
) {
val onClickedFlow = colorOptions()?.get(index)?.onClicked
val onClickedLastValueOrNull: (() -> (() -> Unit)?)? =
onClickedFlow?.let { collectLastValue(it) }
onClickedLastValueOrNull?.let { onClickedLastValue ->
val onClickedOrNull: (() -> Unit)? = onClickedLastValue()
onClickedOrNull?.let { onClicked -> onClicked() }
}
}
/**
* Asserts the entire picker UI state is what is expected. This includes the color type tabs and
* the color options list.
*
* @param colorTypes The observed color type view-models, keyed by ColorType
* @param colorOptions The observed color options
* @param selectedColorTypeText The text of the color type that's expected to be selected
* @param selectedColorOptionIndex The index of the color option that's expected to be selected,
* -1 stands for no color option should be selected
*/
private fun TestScope.assertPickerUiState(
colorTypes: Map<ColorType, ColorTypeTabViewModel>?,
colorOptions: List<OptionItemViewModel<ColorOptionIconViewModel>>?,
selectedColorTypeText: String,
selectedColorOptionIndex: Int,
) {
assertColorTypeTabUiState(
colorTypes = colorTypes,
colorTypeId = ColorType.WALLPAPER_COLOR,
isSelected = "Wallpaper colors" == selectedColorTypeText,
)
assertColorTypeTabUiState(
colorTypes = colorTypes,
colorTypeId = ColorType.PRESET_COLOR,
isSelected = "Basic colors" == selectedColorTypeText,
)
assertColorOptionUiState(colorOptions, selectedColorOptionIndex)
}
/**
* Asserts the picker section UI state is what is expected.
*
* @param colorOptions The observed color options
* @param selectedColorOptionIndex The index of the color option that's expected to be selected,
* -1 stands for no color option should be selected
*/
private fun TestScope.assertColorOptionUiState(
colorOptions: List<OptionItemViewModel<ColorOptionIconViewModel>>?,
selectedColorOptionIndex: Int,
) {
var foundSelectedColorOption = false
assertThat(colorOptions).isNotNull()
if (colorOptions != null) {
for (i in colorOptions.indices) {
val colorOptionHasSelectedIndex = i == selectedColorOptionIndex
val isSelected: Boolean? = collectLastValue(colorOptions[i].isSelected).invoke()
assertWithMessage(
"Expected color option with index \"${i}\" to have" +
" isSelected=$colorOptionHasSelectedIndex but it was" +
" ${isSelected}, num options: ${colorOptions.size}"
)
.that(isSelected)
.isEqualTo(colorOptionHasSelectedIndex)
foundSelectedColorOption = foundSelectedColorOption || colorOptionHasSelectedIndex
}
if (selectedColorOptionIndex == -1) {
assertWithMessage(
"Expected no color options to be selected, but a color option is" +
" selected"
)
.that(foundSelectedColorOption)
.isFalse()
} else {
assertWithMessage(
"Expected a color option to be selected, but no color option is" +
" selected"
)
.that(foundSelectedColorOption)
.isTrue()
}
}
}
/**
* Asserts that a color type tab has the correct UI state.
*
* @param colorTypes The observed color type view-models, keyed by ColorType enum
* @param colorTypeId the ID of the color type to assert
* @param isSelected Whether that color type should be selected
*/
private fun assertColorTypeTabUiState(
colorTypes: Map<ColorType, ColorTypeTabViewModel>?,
colorTypeId: ColorType,
isSelected: Boolean,
) {
val viewModel =
colorTypes?.get(colorTypeId) ?: error("No color type with ID \"$colorTypeId\"!")
assertThat(viewModel.isSelected).isEqualTo(isSelected)
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/picker/color/ui/viewmodel/ColorPickerViewModelTest.kt | 14852083 |
/*
* 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.picker.color.domain.interactor
import android.content.Context
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.android.customization.picker.color.data.repository.FakeColorPickerRepository
import com.android.customization.picker.color.domain.interactor.ColorPickerInteractor
import com.android.customization.picker.color.domain.interactor.ColorPickerSnapshotRestorer
import com.android.customization.picker.color.shared.model.ColorOptionModel
import com.android.customization.picker.color.shared.model.ColorType
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(RobolectricTestRunner::class)
class ColorPickerSnapshotRestorerTest {
private lateinit var underTest: ColorPickerSnapshotRestorer
private lateinit var repository: FakeColorPickerRepository
private lateinit var store: FakeSnapshotStore
private lateinit var context: Context
@Before
fun setUp() {
context = InstrumentationRegistry.getInstrumentation().targetContext
repository = FakeColorPickerRepository(context = context)
underTest =
ColorPickerSnapshotRestorer(
interactor =
ColorPickerInteractor(
repository = repository,
snapshotRestorer = { underTest },
)
)
store = FakeSnapshotStore()
}
@Test
fun restoreToSnapshot_noCallsToStore_restoresToInitialSnapshot() = runTest {
val colorOptions = collectLastValue(repository.colorOptions)
repository.setOptions(4, 4, ColorType.WALLPAPER_COLOR, 2)
val initialSnapshot = underTest.setUpSnapshotRestorer(store = store)
assertThat(initialSnapshot.args).isNotEmpty()
val colorOptionToSelect = colorOptions()?.get(ColorType.PRESET_COLOR)?.get(3)
colorOptionToSelect?.let { repository.select(it) }
assertState(colorOptions(), ColorType.PRESET_COLOR, 3)
underTest.restoreToSnapshot(initialSnapshot)
assertState(colorOptions(), ColorType.WALLPAPER_COLOR, 2)
}
@Test
fun restoreToSnapshot_withCallToStore_restoresToInitialSnapshot() = runTest {
val colorOptions = collectLastValue(repository.colorOptions)
repository.setOptions(4, 4, ColorType.WALLPAPER_COLOR, 2)
val initialSnapshot = underTest.setUpSnapshotRestorer(store = store)
assertThat(initialSnapshot.args).isNotEmpty()
val colorOptionToSelect = colorOptions()?.get(ColorType.PRESET_COLOR)?.get(3)
colorOptionToSelect?.let { repository.select(it) }
assertState(colorOptions(), ColorType.PRESET_COLOR, 3)
val colorOptionToStore = colorOptions()?.get(ColorType.PRESET_COLOR)?.get(1)
colorOptionToStore?.let { underTest.storeSnapshot(colorOptionToStore) }
underTest.restoreToSnapshot(initialSnapshot)
assertState(colorOptions(), ColorType.WALLPAPER_COLOR, 2)
}
private fun assertState(
colorOptions: Map<ColorType, List<ColorOptionModel>>?,
selectedColorType: ColorType,
selectedColorIndex: Int
) {
var foundSelectedColorOption = false
assertThat(colorOptions).isNotNull()
val optionsOfSelectedColorType = colorOptions?.get(selectedColorType)
assertThat(optionsOfSelectedColorType).isNotNull()
if (optionsOfSelectedColorType != null) {
for (i in optionsOfSelectedColorType.indices) {
val colorOptionHasSelectedIndex = i == selectedColorIndex
Truth.assertWithMessage(
"Expected color option with index \"${i}\" to have" +
" isSelected=$colorOptionHasSelectedIndex but it was" +
" ${optionsOfSelectedColorType[i].isSelected}, num options: ${colorOptions.size}"
)
.that(optionsOfSelectedColorType[i].isSelected)
.isEqualTo(colorOptionHasSelectedIndex)
foundSelectedColorOption = foundSelectedColorOption || colorOptionHasSelectedIndex
}
if (selectedColorIndex == -1) {
Truth.assertWithMessage(
"Expected no color options to be selected, but a color option is" +
" selected"
)
.that(foundSelectedColorOption)
.isFalse()
} else {
Truth.assertWithMessage(
"Expected a color option to be selected, but no color option is" +
" selected"
)
.that(foundSelectedColorOption)
.isTrue()
}
}
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/picker/color/domain/interactor/ColorPickerSnapshotRestorerTest.kt | 2678154697 |
/*
* 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.picker.color.domain.interactor
import android.content.Context
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.android.customization.picker.color.data.repository.FakeColorPickerRepository
import com.android.customization.picker.color.domain.interactor.ColorPickerInteractor
import com.android.customization.picker.color.domain.interactor.ColorPickerSnapshotRestorer
import com.android.customization.picker.color.shared.model.ColorType
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(RobolectricTestRunner::class)
class ColorPickerInteractorTest {
private lateinit var underTest: ColorPickerInteractor
private lateinit var repository: FakeColorPickerRepository
private lateinit var store: FakeSnapshotStore
private lateinit var context: Context
@Before
fun setUp() {
context = InstrumentationRegistry.getInstrumentation().targetContext
repository = FakeColorPickerRepository(context = context)
store = FakeSnapshotStore()
underTest =
ColorPickerInteractor(
repository = repository,
snapshotRestorer = {
ColorPickerSnapshotRestorer(interactor = underTest).apply {
runBlocking { setUpSnapshotRestorer(store = store) }
}
},
)
repository.setOptions(4, 4, ColorType.WALLPAPER_COLOR, 0)
}
@Test
fun select() = runTest {
val colorOptions = collectLastValue(underTest.colorOptions)
val wallpaperColorOptionModelBefore = colorOptions()?.get(ColorType.WALLPAPER_COLOR)?.get(2)
assertThat(wallpaperColorOptionModelBefore?.isSelected).isFalse()
wallpaperColorOptionModelBefore?.let { underTest.select(colorOptionModel = it) }
val wallpaperColorOptionModelAfter = colorOptions()?.get(ColorType.WALLPAPER_COLOR)?.get(2)
assertThat(wallpaperColorOptionModelAfter?.isSelected).isTrue()
val presetColorOptionModelBefore = colorOptions()?.get(ColorType.PRESET_COLOR)?.get(1)
assertThat(presetColorOptionModelBefore?.isSelected).isFalse()
presetColorOptionModelBefore?.let { underTest.select(colorOptionModel = it) }
val presetColorOptionModelAfter = colorOptions()?.get(ColorType.PRESET_COLOR)?.get(1)
assertThat(presetColorOptionModelAfter?.isSelected).isTrue()
}
@Test
fun snapshotRestorer_updatesSnapshot() = runTest {
val colorOptions = collectLastValue(underTest.colorOptions)
val wallpaperColorOptionModel0 = colorOptions()?.get(ColorType.WALLPAPER_COLOR)?.get(0)
val wallpaperColorOptionModel1 = colorOptions()?.get(ColorType.WALLPAPER_COLOR)?.get(1)
assertThat(wallpaperColorOptionModel0?.isSelected).isTrue()
assertThat(wallpaperColorOptionModel1?.isSelected).isFalse()
val storedSnapshot = store.retrieve()
wallpaperColorOptionModel1?.let { underTest.select(it) }
val wallpaperColorOptionModel0After = colorOptions()?.get(ColorType.WALLPAPER_COLOR)?.get(0)
val wallpaperColorOptionModel1After = colorOptions()?.get(ColorType.WALLPAPER_COLOR)?.get(1)
assertThat(wallpaperColorOptionModel0After?.isSelected).isFalse()
assertThat(wallpaperColorOptionModel1After?.isSelected).isTrue()
assertThat(store.retrieve()).isNotEqualTo(storedSnapshot)
}
@Test
fun snapshotRestorer_doesNotUpdateSnapshotOnExternalUpdates() = runTest {
val colorOptions = collectLastValue(underTest.colorOptions)
val wallpaperColorOptionModel0 = colorOptions()?.get(ColorType.WALLPAPER_COLOR)?.get(0)
val wallpaperColorOptionModel1 = colorOptions()?.get(ColorType.WALLPAPER_COLOR)?.get(1)
assertThat(wallpaperColorOptionModel0?.isSelected).isTrue()
assertThat(wallpaperColorOptionModel1?.isSelected).isFalse()
val storedSnapshot = store.retrieve()
repository.setOptions(4, 4, ColorType.WALLPAPER_COLOR, 1)
val wallpaperColorOptionModel0After = colorOptions()?.get(ColorType.WALLPAPER_COLOR)?.get(0)
val wallpaperColorOptionModel1After = colorOptions()?.get(ColorType.WALLPAPER_COLOR)?.get(1)
assertThat(wallpaperColorOptionModel0After?.isSelected).isFalse()
assertThat(wallpaperColorOptionModel1After?.isSelected).isTrue()
assertThat(store.retrieve()).isEqualTo(storedSnapshot)
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/picker/color/domain/interactor/ColorPickerInteractorTest.kt | 2205470958 |
/*
* 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.picker.quickaffordance.ui.viewmodel
import android.content.Context
import android.content.Intent
import androidx.test.core.app.ApplicationProvider
import androidx.test.filters.SmallTest
import com.android.customization.module.logging.TestThemesUserEventLogger
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.customization.picker.quickaffordance.ui.viewmodel.KeyguardQuickAffordanceSlotViewModel
import com.android.customization.picker.quickaffordance.ui.viewmodel.KeyguardQuickAffordanceSummaryViewModel
import com.android.systemui.shared.customization.data.content.CustomizationProviderClient
import com.android.systemui.shared.customization.data.content.FakeCustomizationProviderClient
import com.android.systemui.shared.keyguard.shared.model.KeyguardQuickAffordanceSlots
import com.android.wallpaper.R
import com.android.wallpaper.module.InjectorProvider
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.data.repository.WallpaperRepository
import com.android.wallpaper.picker.customization.domain.interactor.WallpaperInteractor
import com.android.wallpaper.picker.option.ui.viewmodel.OptionItemViewModel
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.FakeWallpaperClient
import com.android.wallpaper.testing.TestCurrentWallpaperInfoFactory
import com.android.wallpaper.testing.TestInjector
import com.android.wallpaper.testing.TestWallpaperPreferences
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(RobolectricTestRunner::class)
class KeyguardQuickAffordancePickerViewModelTest {
private val logger = TestThemesUserEventLogger()
private lateinit var underTest: KeyguardQuickAffordancePickerViewModel
private lateinit var context: Context
private lateinit var testScope: TestScope
private lateinit var client: FakeCustomizationProviderClient
private lateinit var quickAffordanceInteractor: KeyguardQuickAffordancePickerInteractor
private lateinit var wallpaperInteractor: WallpaperInteractor
@Before
fun setUp() {
InjectorProvider.setInjector(TestInjector(logger))
context = ApplicationProvider.getApplicationContext()
val testDispatcher = StandardTestDispatcher()
testScope = TestScope(testDispatcher)
Dispatchers.setMain(testDispatcher)
client = FakeCustomizationProviderClient()
quickAffordanceInteractor =
KeyguardQuickAffordancePickerInteractor(
repository =
KeyguardQuickAffordancePickerRepository(
client = client,
scope = testScope.backgroundScope,
),
client = client,
snapshotRestorer = {
KeyguardQuickAffordanceSnapshotRestorer(
interactor = quickAffordanceInteractor,
client = client,
)
.apply { runBlocking { setUpSnapshotRestorer(FakeSnapshotStore()) } }
},
)
wallpaperInteractor =
WallpaperInteractor(
repository =
WallpaperRepository(
scope = testScope.backgroundScope,
client = FakeWallpaperClient(),
wallpaperPreferences = TestWallpaperPreferences(),
backgroundDispatcher = testDispatcher,
),
)
underTest =
KeyguardQuickAffordancePickerViewModel.Factory(
context = context,
quickAffordanceInteractor = quickAffordanceInteractor,
wallpaperInteractor = wallpaperInteractor,
wallpaperInfoFactory = TestCurrentWallpaperInfoFactory(context),
logger = logger,
)
.create(KeyguardQuickAffordancePickerViewModel::class.java)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `Select an affordance for each side`() =
testScope.runTest {
val slots = collectLastValue(underTest.slots)
val quickAffordances = collectLastValue(underTest.quickAffordances)
// Initially, the first slot is selected with the "none" affordance selected.
assertPickerUiState(
slots = slots(),
affordances = quickAffordances(),
selectedSlotText = "Left button",
selectedAffordanceText = "None",
)
assertPreviewUiState(
slots = slots(),
expectedAffordanceNameBySlotId =
mapOf(
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START to null,
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END to null,
),
)
// Select "affordance 1" for the first slot.
selectAffordance(quickAffordances, 1)
assertPickerUiState(
slots = slots(),
affordances = quickAffordances(),
selectedSlotText = "Left button",
selectedAffordanceText = FakeCustomizationProviderClient.AFFORDANCE_1,
)
assertPreviewUiState(
slots = slots(),
expectedAffordanceNameBySlotId =
mapOf(
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START to
FakeCustomizationProviderClient.AFFORDANCE_1,
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END to null,
),
)
// Select an affordance for the second slot.
// First, switch to the second slot:
slots()?.get(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END)?.onClicked?.invoke()
// Second, select the "affordance 3" affordance:
selectAffordance(quickAffordances, 3)
assertPickerUiState(
slots = slots(),
affordances = quickAffordances(),
selectedSlotText = "Right button",
selectedAffordanceText = FakeCustomizationProviderClient.AFFORDANCE_3,
)
assertPreviewUiState(
slots = slots(),
expectedAffordanceNameBySlotId =
mapOf(
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START to
FakeCustomizationProviderClient.AFFORDANCE_1,
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END to
FakeCustomizationProviderClient.AFFORDANCE_3,
),
)
// Select a different affordance for the second slot.
selectAffordance(quickAffordances, 2)
assertPickerUiState(
slots = slots(),
affordances = quickAffordances(),
selectedSlotText = "Right button",
selectedAffordanceText = FakeCustomizationProviderClient.AFFORDANCE_2,
)
assertPreviewUiState(
slots = slots(),
expectedAffordanceNameBySlotId =
mapOf(
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START to
FakeCustomizationProviderClient.AFFORDANCE_1,
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END to
FakeCustomizationProviderClient.AFFORDANCE_2,
),
)
}
@Test
fun `Unselect - AKA selecting the none affordance - on one side`() =
testScope.runTest {
val slots = collectLastValue(underTest.slots)
val quickAffordances = collectLastValue(underTest.quickAffordances)
// Select "affordance 1" for the first slot.
selectAffordance(quickAffordances, 1)
// Select an affordance for the second slot.
// First, switch to the second slot:
slots()?.get(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END)?.onClicked?.invoke()
// Second, select the "affordance 3" affordance:
selectAffordance(quickAffordances, 3)
// Switch back to the first slot:
slots()?.get(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START)?.onClicked?.invoke()
// Select the "none" affordance, which is always in position 0:
selectAffordance(quickAffordances, 0)
assertPickerUiState(
slots = slots(),
affordances = quickAffordances(),
selectedSlotText = "Left button",
selectedAffordanceText = "None",
)
assertPreviewUiState(
slots = slots(),
expectedAffordanceNameBySlotId =
mapOf(
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START to null,
KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END to
FakeCustomizationProviderClient.AFFORDANCE_3,
),
)
}
@Test
fun `Show enablement dialog when selecting a disabled affordance`() =
testScope.runTest {
val slots = collectLastValue(underTest.slots)
val quickAffordances = collectLastValue(underTest.quickAffordances)
val dialog = collectLastValue(underTest.dialog)
val activityStartRequest = collectLastValue(underTest.activityStartRequests)
val enablementExplanation = "enablementExplanation"
val enablementActionText = "enablementActionText"
val packageName = "packageName"
val action = "action"
val enablementActionIntent = Intent(action).apply { `package` = packageName }
// Lets add a disabled affordance to the picker:
val affordanceIndex =
client.addAffordance(
CustomizationProviderClient.Affordance(
id = "disabled",
name = "disabled",
iconResourceId = 1,
isEnabled = false,
enablementExplanation = enablementExplanation,
enablementActionText = enablementActionText,
enablementActionIntent = enablementActionIntent,
)
)
// Lets try to select that disabled affordance:
selectAffordance(quickAffordances, affordanceIndex + 1)
// We expect there to be a dialog that should be shown:
assertThat(dialog()?.icon)
.isEqualTo(Icon.Loaded(FakeCustomizationProviderClient.ICON_1, null))
assertThat(dialog()?.headline)
.isEqualTo(Text.Resource(R.string.keyguard_affordance_enablement_dialog_headline))
assertThat(dialog()?.message).isEqualTo(Text.Loaded(enablementExplanation))
assertThat(dialog()?.buttons?.size).isEqualTo(2)
assertThat(dialog()?.buttons?.first()?.text).isEqualTo(Text.Resource(R.string.cancel))
assertThat(dialog()?.buttons?.get(1)?.text).isEqualTo(Text.Loaded(enablementActionText))
// When the button is clicked, we expect an intent of the given enablement action
// component name to be emitted.
dialog()?.buttons?.get(1)?.onClicked?.invoke()
assertThat(activityStartRequest()?.`package`).isEqualTo(packageName)
assertThat(activityStartRequest()?.action).isEqualTo(action)
// Once we report that the activity was started, the activity start request should be
// nullified.
underTest.onActivityStarted()
assertThat(activityStartRequest()).isNull()
// Once we report that the dialog has been dismissed by the user, we expect there to be
// no dialog to be shown:
underTest.onDialogDismissed()
assertThat(dialog()).isNull()
}
@Test
fun `Start settings activity when long-pressing an affordance`() =
testScope.runTest {
val quickAffordances = collectLastValue(underTest.quickAffordances)
val activityStartRequest = collectLastValue(underTest.activityStartRequests)
// Lets add a configurable affordance to the picker:
val configureIntent = Intent("some.action")
val affordanceIndex =
client.addAffordance(
CustomizationProviderClient.Affordance(
id = "affordance",
name = "affordance",
iconResourceId = 1,
isEnabled = true,
configureIntent = configureIntent,
)
)
// Lets try to long-click the affordance:
quickAffordances()?.get(affordanceIndex + 1)?.onLongClicked?.invoke()
assertThat(activityStartRequest()).isEqualTo(configureIntent)
// Once we report that the activity was started, the activity start request should be
// nullified.
underTest.onActivityStarted()
assertThat(activityStartRequest()).isNull()
}
@Test
fun `summary - affordance selected in both bottom-start and bottom-end`() =
testScope.runTest {
val slots = collectLastValue(underTest.slots)
val quickAffordances = collectLastValue(underTest.quickAffordances)
val summary = collectLastValue(underTest.summary)
// Select "affordance 1" for the first slot.
selectAffordance(quickAffordances, 1)
// Select an affordance for the second slot.
// First, switch to the second slot:
slots()?.get(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END)?.onClicked?.invoke()
// Second, select the "affordance 3" affordance:
selectAffordance(quickAffordances, 3)
assertThat(summary())
.isEqualTo(
KeyguardQuickAffordanceSummaryViewModel(
description =
Text.Loaded(
"${FakeCustomizationProviderClient.AFFORDANCE_1}," +
" ${FakeCustomizationProviderClient.AFFORDANCE_3}"
),
icon1 =
Icon.Loaded(
FakeCustomizationProviderClient.ICON_1,
Text.Loaded("Left shortcut")
),
icon2 =
Icon.Loaded(
FakeCustomizationProviderClient.ICON_3,
Text.Loaded("Right shortcut")
),
)
)
}
@Test
fun `summary - affordance selected only on bottom-start`() =
testScope.runTest {
val slots = collectLastValue(underTest.slots)
val quickAffordances = collectLastValue(underTest.quickAffordances)
val summary = collectLastValue(underTest.summary)
// Select "affordance 1" for the first slot.
selectAffordance(quickAffordances, 1)
assertThat(summary())
.isEqualTo(
KeyguardQuickAffordanceSummaryViewModel(
description = Text.Loaded(FakeCustomizationProviderClient.AFFORDANCE_1),
icon1 =
Icon.Loaded(
FakeCustomizationProviderClient.ICON_1,
Text.Loaded("Left shortcut")
),
icon2 = null,
)
)
}
@Test
fun `summary - affordance selected only on bottom-end`() =
testScope.runTest {
val slots = collectLastValue(underTest.slots)
val quickAffordances = collectLastValue(underTest.quickAffordances)
val summary = collectLastValue(underTest.summary)
// Select an affordance for the second slot.
// First, switch to the second slot:
slots()?.get(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END)?.onClicked?.invoke()
// Second, select the "affordance 3" affordance:
selectAffordance(quickAffordances, 3)
assertThat(summary())
.isEqualTo(
KeyguardQuickAffordanceSummaryViewModel(
description = Text.Loaded(FakeCustomizationProviderClient.AFFORDANCE_3),
icon1 = null,
icon2 =
Icon.Loaded(
FakeCustomizationProviderClient.ICON_3,
Text.Loaded("Right shortcut")
),
)
)
}
@Test
fun `summary - no affordances selected`() =
testScope.runTest {
val summary = collectLastValue(underTest.summary)
assertThat(summary()?.description)
.isEqualTo(Text.Resource(R.string.keyguard_quick_affordance_none_selected))
assertThat(summary()?.icon1).isNotNull()
assertThat(summary()?.icon2).isNull()
}
/** Simulates a user selecting the affordance at the given index, if that is clickable. */
private fun TestScope.selectAffordance(
affordances: () -> List<OptionItemViewModel<Icon>>?,
index: Int,
) {
val onClickedFlow = affordances()?.get(index)?.onClicked
val onClickedLastValueOrNull: (() -> (() -> Unit)?)? =
onClickedFlow?.let { collectLastValue(it) }
onClickedLastValueOrNull?.let { onClickedLastValue ->
val onClickedOrNull: (() -> Unit)? = onClickedLastValue()
onClickedOrNull?.let { onClicked -> onClicked() }
}
}
/**
* Asserts the entire picker UI state is what is expected. This includes the slot tabs and the
* affordance list.
*
* @param slots The observed slot view-models, keyed by slot ID
* @param affordances The observed affordances
* @param selectedSlotText The text of the slot that's expected to be selected
* @param selectedAffordanceText The text of the affordance that's expected to be selected
*/
private fun TestScope.assertPickerUiState(
slots: Map<String, KeyguardQuickAffordanceSlotViewModel>?,
affordances: List<OptionItemViewModel<Icon>>?,
selectedSlotText: String,
selectedAffordanceText: String,
) {
assertSlotTabUiState(
slots = slots,
slotId = KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START,
isSelected = "Left button" == selectedSlotText,
)
assertSlotTabUiState(
slots = slots,
slotId = KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END,
isSelected = "Right button" == selectedSlotText,
)
var foundSelectedAffordance = false
assertThat(affordances).isNotNull()
affordances?.forEach { affordance ->
val nameMatchesSelectedName =
Text.evaluationEquals(
context,
affordance.text,
Text.Loaded(selectedAffordanceText),
)
val isSelected: Boolean? = collectLastValue(affordance.isSelected).invoke()
assertWithMessage(
"Expected affordance with name \"${affordance.text}\" to have" +
" isSelected=$nameMatchesSelectedName but it was $isSelected"
)
.that(isSelected)
.isEqualTo(nameMatchesSelectedName)
foundSelectedAffordance = foundSelectedAffordance || nameMatchesSelectedName
}
assertWithMessage("No affordance is selected!").that(foundSelectedAffordance).isTrue()
}
/**
* Asserts that a slot tab has the correct UI state.
*
* @param slots The observed slot view-models, keyed by slot ID
* @param slotId the ID of the slot to assert
* @param isSelected Whether that slot should be selected
*/
private fun assertSlotTabUiState(
slots: Map<String, KeyguardQuickAffordanceSlotViewModel>?,
slotId: String,
isSelected: Boolean,
) {
val viewModel = slots?.get(slotId) ?: error("No slot with ID \"$slotId\"!")
assertThat(viewModel.isSelected).isEqualTo(isSelected)
}
/**
* Asserts the UI state of the preview.
*
* @param slots The observed slot view-models, keyed by slot ID
* @param expectedAffordanceNameBySlotId The expected name of the selected affordance for each
* slot ID or `null` if it's expected for there to be no affordance for that slot in the
* preview
*/
private fun assertPreviewUiState(
slots: Map<String, KeyguardQuickAffordanceSlotViewModel>?,
expectedAffordanceNameBySlotId: Map<String, String?>,
) {
assertThat(slots).isNotNull()
slots?.forEach { (slotId, slotViewModel) ->
val expectedAffordanceName = expectedAffordanceNameBySlotId[slotId]
val actualAffordanceName = slotViewModel.selectedQuickAffordances.firstOrNull()?.text
assertWithMessage(
"At slotId=\"$slotId\", expected affordance=\"$expectedAffordanceName\" but" +
" was \"${actualAffordanceName?.asString(context)}\"!"
)
.that(actualAffordanceName?.asString(context))
.isEqualTo(expectedAffordanceName)
}
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/picker/quickaffordance/ui/viewmodel/KeyguardQuickAffordancePickerViewModelTest.kt | 4030284225 |
/*
* 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.picker.quickaffordance.data.repository
import androidx.test.filters.SmallTest
import com.android.customization.picker.quickaffordance.data.repository.KeyguardQuickAffordancePickerRepository
import com.android.systemui.shared.customization.data.content.FakeCustomizationProviderClient
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(RobolectricTestRunner::class)
class KeyguardQuickAffordancePickerRepositoryTest {
private lateinit var underTest: KeyguardQuickAffordancePickerRepository
private lateinit var testScope: TestScope
private lateinit var client: FakeCustomizationProviderClient
@Before
fun setUp() {
client = FakeCustomizationProviderClient()
val coroutineDispatcher = UnconfinedTestDispatcher()
testScope = TestScope(coroutineDispatcher)
Dispatchers.setMain(coroutineDispatcher)
underTest =
KeyguardQuickAffordancePickerRepository(
client = client,
scope = testScope.backgroundScope,
)
}
// We need at least one test to prevent Studio errors
@Test
fun creationSucceeds() {
assertThat(underTest).isNotNull()
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/picker/quickaffordance/data/repository/KeyguardQuickAffordancePickerRepositoryTest.kt | 4040912293 |
/*
* 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.picker.quickaffordance.domain.interactor
import androidx.test.filters.SmallTest
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.shared.model.KeyguardQuickAffordancePickerSelectionModel
import com.android.systemui.shared.customization.data.content.FakeCustomizationProviderClient
import com.android.systemui.shared.keyguard.shared.model.KeyguardQuickAffordanceSlots
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(RobolectricTestRunner::class)
class KeyguardQuickAffordancePickerInteractorTest {
private lateinit var underTest: KeyguardQuickAffordancePickerInteractor
private lateinit var testScope: TestScope
private lateinit var client: FakeCustomizationProviderClient
@Before
fun setUp() {
val testDispatcher = StandardTestDispatcher()
testScope = TestScope(testDispatcher)
Dispatchers.setMain(testDispatcher)
client = FakeCustomizationProviderClient()
underTest =
KeyguardQuickAffordancePickerInteractor(
repository =
KeyguardQuickAffordancePickerRepository(
client = client,
scope = testScope.backgroundScope,
),
client = client,
snapshotRestorer = {
KeyguardQuickAffordanceSnapshotRestorer(
interactor = underTest,
client = client,
)
.apply { runBlocking { setUpSnapshotRestorer(FakeSnapshotStore()) } }
},
)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun select() =
testScope.runTest {
val selections = collectLastValue(underTest.selections)
underTest.select(
slotId = KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START,
affordanceId = FakeCustomizationProviderClient.AFFORDANCE_1,
)
assertThat(selections())
.isEqualTo(
listOf(
KeyguardQuickAffordancePickerSelectionModel(
slotId = KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START,
affordanceId = FakeCustomizationProviderClient.AFFORDANCE_1,
),
)
)
underTest.select(
slotId = KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START,
affordanceId = FakeCustomizationProviderClient.AFFORDANCE_2,
)
assertThat(selections())
.isEqualTo(
listOf(
KeyguardQuickAffordancePickerSelectionModel(
slotId = KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_START,
affordanceId = FakeCustomizationProviderClient.AFFORDANCE_2,
),
)
)
}
@Test
fun unselectAll() =
testScope.runTest {
client.setSlotCapacity(KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END, 3)
val selections = collectLastValue(underTest.selections)
underTest.select(
slotId = KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END,
affordanceId = FakeCustomizationProviderClient.AFFORDANCE_1,
)
underTest.select(
slotId = KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END,
affordanceId = FakeCustomizationProviderClient.AFFORDANCE_2,
)
underTest.select(
slotId = KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END,
affordanceId = FakeCustomizationProviderClient.AFFORDANCE_3,
)
underTest.unselectAllFromSlot(
slotId = KeyguardQuickAffordanceSlots.SLOT_ID_BOTTOM_END,
)
assertThat(selections()).isEmpty()
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/picker/quickaffordance/domain/interactor/KeyguardQuickAffordancePickerInteractorTest.kt | 2000022800 |
/*
* 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.content.Context
import android.graphics.Color
import androidx.test.core.app.ApplicationProvider
import com.android.customization.model.CustomizationManager
import com.android.customization.model.ResourceConstants.OVERLAY_CATEGORY_COLOR
import com.android.customization.model.ResourceConstants.OVERLAY_CATEGORY_SYSTEM_PALETTE
import com.android.customization.model.color.ColorOptionsProvider.COLOR_SOURCE_HOME
import com.android.customization.model.color.ColorOptionsProvider.COLOR_SOURCE_PRESET
import com.android.customization.model.color.ColorOptionsProvider.OVERLAY_COLOR_BOTH
import com.android.customization.model.color.ColorOptionsProvider.OVERLAY_COLOR_INDEX
import com.android.customization.model.color.ColorOptionsProvider.OVERLAY_COLOR_SOURCE
import com.android.customization.model.color.ColorOptionsProvider.OVERLAY_THEME_STYLE
import com.android.customization.model.theme.OverlayManagerCompat
import com.android.customization.picker.color.shared.model.ColorType
import com.android.systemui.monet.Style
import com.google.common.truth.Truth.assertThat
import org.json.JSONObject
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import org.robolectric.RobolectricTestRunner
/** Tests of {@link ColorCustomizationManager}. */
@RunWith(RobolectricTestRunner::class)
class ColorCustomizationManagerTest {
@get:Rule val rule: MockitoRule = MockitoJUnit.rule()
@Mock private lateinit var provider: ColorOptionsProvider
@Mock private lateinit var mockOM: OverlayManagerCompat
private lateinit var manager: ColorCustomizationManager
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
val application = ApplicationProvider.getApplicationContext<Context>()
manager = ColorCustomizationManager(provider, application.contentResolver, mockOM)
}
@Test
fun testParseSettings() {
val source = COLOR_SOURCE_HOME
val style = Style.SPRITZ
val someColor = "aabbcc"
val someOtherColor = "bbccdd"
val settings =
mapOf(
OVERLAY_CATEGORY_SYSTEM_PALETTE to someColor,
OVERLAY_CATEGORY_COLOR to someOtherColor,
OVERLAY_COLOR_SOURCE to source,
OVERLAY_THEME_STYLE to style.toString(),
ColorOption.TIMESTAMP_FIELD to "12345"
)
val json = JSONObject(settings).toString()
manager.parseSettings(json)
assertThat(manager.currentColorSource).isEqualTo(source)
assertThat(manager.currentStyle).isEqualTo(style.toString())
assertThat(manager.currentOverlays.size).isEqualTo(2)
assertThat(manager.currentOverlays[OVERLAY_CATEGORY_COLOR]).isEqualTo(someOtherColor)
assertThat(manager.currentOverlays[OVERLAY_CATEGORY_SYSTEM_PALETTE]).isEqualTo(someColor)
}
@Test
fun apply_PresetColorOption_index() {
testApplyPresetColorOption(1, "1")
testApplyPresetColorOption(2, "2")
testApplyPresetColorOption(3, "3")
testApplyPresetColorOption(4, "4")
}
private fun testApplyPresetColorOption(index: Int, value: String) {
manager.apply(
getPresetColorOption(index),
object : CustomizationManager.Callback {
override fun onSuccess() {}
override fun onError(throwable: Throwable?) {}
}
)
Thread.sleep(100)
val overlaysJson = JSONObject(manager.storedOverlays)
assertThat(overlaysJson.getString(OVERLAY_COLOR_INDEX)).isEqualTo(value)
}
@Test
fun apply_WallpaperColorOption_index() {
testApplyWallpaperColorOption(1, "1")
testApplyWallpaperColorOption(2, "2")
testApplyWallpaperColorOption(3, "3")
testApplyWallpaperColorOption(4, "4")
}
private fun testApplyWallpaperColorOption(index: Int, value: String) {
manager.apply(
getWallpaperColorOption(index),
object : CustomizationManager.Callback {
override fun onSuccess() {}
override fun onError(throwable: Throwable?) {}
}
)
Thread.sleep(100)
val overlaysJson = JSONObject(manager.storedOverlays)
assertThat(overlaysJson.getString(OVERLAY_COLOR_INDEX)).isEqualTo(value)
}
private fun getPresetColorOption(index: Int): ColorOptionImpl {
return ColorOptionImpl(
"fake color",
mapOf("fake_package" to "fake_color"),
/* isDefault= */ false,
COLOR_SOURCE_PRESET,
Style.TONAL_SPOT,
index,
ColorOptionImpl.PreviewInfo(intArrayOf(0), intArrayOf(0)),
ColorType.PRESET_COLOR
)
}
private fun getWallpaperColorOption(index: Int): ColorOptionImpl {
return ColorOptionImpl(
"fake color",
mapOf("fake_package" to "fake_color"),
/* isDefault= */ false,
COLOR_SOURCE_HOME,
Style.TONAL_SPOT,
index,
ColorOptionImpl.PreviewInfo(intArrayOf(0), intArrayOf(0)),
ColorType.WALLPAPER_COLOR
)
}
@Test
fun testApply_colorSeedFromWallpaperBoth_shouldReturnBothValue() {
val wallpaperColor = WallpaperColors(Color.valueOf(Color.RED), null, null)
manager.setWallpaperColors(wallpaperColor, wallpaperColor)
manager.apply(
getWallpaperColorOption(0),
object : CustomizationManager.Callback {
override fun onSuccess() {}
override fun onError(throwable: Throwable?) {}
}
)
Thread.sleep(100)
val overlaysJson = JSONObject(manager.storedOverlays)
assertThat(overlaysJson.getString(OVERLAY_COLOR_BOTH)).isEqualTo("1")
}
@Test
fun testApply_colorSeedFromWallpaperDifferent_shouldReturnNonBothValue() {
val wallpaperColor1 = WallpaperColors(Color.valueOf(Color.RED), null, null)
val wallpaperColor2 = WallpaperColors(Color.valueOf(Color.BLUE), null, null)
manager.setWallpaperColors(wallpaperColor1, wallpaperColor2)
manager.apply(
getWallpaperColorOption(0),
object : CustomizationManager.Callback {
override fun onSuccess() {}
override fun onError(throwable: Throwable?) {}
}
)
Thread.sleep(100)
val overlaysJson = JSONObject(manager.storedOverlays)
assertThat(overlaysJson.getString(OVERLAY_COLOR_BOTH)).isEqualTo("0")
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/color/ColorCustomizationManagerTest.kt | 3061684406 |
/*
* 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 com.android.customization.model.ResourceConstants.OVERLAY_CATEGORY_SYSTEM_PALETTE
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.ColorOptionsProvider.COLOR_SOURCE_PRESET
import com.android.customization.picker.color.shared.model.ColorType
import com.android.systemui.monet.Style
import com.google.common.truth.Truth.assertThat
import org.json.JSONObject
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import org.robolectric.RobolectricTestRunner
/** Tests of {@link ColorOption}. */
@RunWith(RobolectricTestRunner::class)
class ColorOptionTest {
@get:Rule val rule: MockitoRule = MockitoJUnit.rule()
@Mock private lateinit var manager: ColorCustomizationManager
@Test
fun colorOption_Source() {
testColorOptionSource(COLOR_SOURCE_HOME)
testColorOptionSource(COLOR_SOURCE_LOCK)
testColorOptionSource(COLOR_SOURCE_PRESET)
}
private fun testColorOptionSource(source: String) {
val colorOption: ColorOption =
ColorOptionImpl(
"fake color",
mapOf("fake_package" to "fake_color"),
false,
source,
Style.TONAL_SPOT,
/* index= */ 0,
ColorOptionImpl.PreviewInfo(intArrayOf(0), intArrayOf(0)),
ColorType.WALLPAPER_COLOR
)
assertThat(colorOption.source).isEqualTo(source)
}
@Test
fun colorOption_style() {
testColorOptionStyle(Style.TONAL_SPOT)
testColorOptionStyle(Style.SPRITZ)
testColorOptionStyle(Style.VIBRANT)
testColorOptionStyle(Style.EXPRESSIVE)
}
private fun testColorOptionStyle(style: Style) {
val colorOption: ColorOption =
ColorOptionImpl(
"fake color",
mapOf("fake_package" to "fake_color"),
/* isDefault= */ false,
"fake_source",
style,
0,
ColorOptionImpl.PreviewInfo(intArrayOf(0), intArrayOf(0)),
ColorType.WALLPAPER_COLOR
)
assertThat(colorOption.style).isEqualTo(style)
}
@Test
fun colorOption_index() {
testColorOptionIndex(1)
testColorOptionIndex(2)
testColorOptionIndex(3)
testColorOptionIndex(4)
}
private fun testColorOptionIndex(index: Int) {
val colorOption: ColorOption =
ColorOptionImpl(
"fake color",
mapOf("fake_package" to "fake_color"),
/* isDefault= */ false,
"fake_source",
Style.TONAL_SPOT,
index,
ColorOptionImpl.PreviewInfo(intArrayOf(0), intArrayOf(0)),
ColorType.WALLPAPER_COLOR
)
assertThat(colorOption.index).isEqualTo(index)
}
private fun setUpWallpaperColorOption(
isDefault: Boolean,
source: String = "some_source"
): ColorOptionImpl {
val overlays =
if (isDefault) {
HashMap()
} else {
mapOf("package" to "value", "otherPackage" to "otherValue")
}
`when`(manager.currentOverlays).thenReturn(overlays)
return ColorOptionImpl(
"seed",
overlays,
isDefault,
source,
Style.TONAL_SPOT,
/* index= */ 0,
ColorOptionImpl.PreviewInfo(intArrayOf(0), intArrayOf(0)),
ColorType.WALLPAPER_COLOR
)
}
@Test
fun wallpaperColorOption_isActive_notDefault_SourceSet() {
val source = "some_source"
val colorOption = setUpWallpaperColorOption(false, source)
`when`(manager.currentColorSource).thenReturn(source)
assertThat(colorOption.isActive(manager)).isTrue()
}
@Test
fun wallpaperColorOption_isActive_notDefault_NoSource() {
val colorOption = setUpWallpaperColorOption(false)
`when`(manager.currentColorSource).thenReturn(null)
assertThat(colorOption.isActive(manager)).isTrue()
}
@Test
fun wallpaperColorOption_isActive_notDefault_differentSource() {
val colorOption = setUpWallpaperColorOption(false)
`when`(manager.currentColorSource).thenReturn("some_other_source")
assertThat(colorOption.isActive(manager)).isFalse()
}
@Test
fun wallpaperColorOption_isActive_default_emptyJson() {
val colorOption = setUpWallpaperColorOption(true)
`when`(manager.storedOverlays).thenReturn("")
assertThat(colorOption.isActive(manager)).isTrue()
}
@Test
fun wallpaperColorOption_isActive_default_nonEmptyJson() {
val colorOption = setUpWallpaperColorOption(true)
`when`(manager.storedOverlays).thenReturn("{non-empty-json}")
// Should still be Active because overlays is empty
assertThat(colorOption.isActive(manager)).isTrue()
}
@Test
fun wallpaperColorOption_isActive_default_nonEmptyOverlays() {
val colorOption = setUpWallpaperColorOption(true)
val settings = mapOf(OVERLAY_CATEGORY_SYSTEM_PALETTE to "fake_color")
val json = JSONObject(settings).toString()
`when`(manager.storedOverlays).thenReturn(json)
`when`(manager.currentOverlays).thenReturn(settings)
assertThat(colorOption.isActive(manager)).isFalse()
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/color/ColorOptionTest.kt | 448402845 |
/*
* 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.test.filters.SmallTest
import com.android.customization.model.themedicon.data.repository.ThemeIconRepository
import com.android.wallpaper.testing.FakeSnapshotStore
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(JUnit4::class)
class ThemedIconSnapshotRestorerTest {
private lateinit var underTest: ThemedIconSnapshotRestorer
private var isActivated = false
@Before
fun setUp() {
isActivated = false
underTest =
ThemedIconSnapshotRestorer(
isActivated = { isActivated },
setActivated = { isActivated = it },
interactor =
ThemedIconInteractor(
repository = ThemeIconRepository(),
)
)
}
@Test
fun `set up and restore - active`() = runTest {
isActivated = true
val store = FakeSnapshotStore()
store.store(underTest.setUpSnapshotRestorer(store = store))
val storedSnapshot = store.retrieve()
underTest.restoreToSnapshot(snapshot = storedSnapshot)
assertThat(isActivated).isTrue()
}
@Test
fun `set up and restore - inactive`() = runTest {
isActivated = false
val store = FakeSnapshotStore()
store.store(underTest.setUpSnapshotRestorer(store = store))
val storedSnapshot = store.retrieve()
underTest.restoreToSnapshot(snapshot = storedSnapshot)
assertThat(isActivated).isFalse()
}
@Test
fun `set up - deactivate - restore to active`() = runTest {
isActivated = true
val store = FakeSnapshotStore()
store.store(underTest.setUpSnapshotRestorer(store = store))
val initialSnapshot = store.retrieve()
underTest.store(isActivated = false)
underTest.restoreToSnapshot(snapshot = initialSnapshot)
assertThat(isActivated).isTrue()
}
@Test
fun `set up - activate - restore to inactive`() = runTest {
isActivated = false
val store = FakeSnapshotStore()
store.store(underTest.setUpSnapshotRestorer(store = store))
val initialSnapshot = store.retrieve()
underTest.store(isActivated = true)
underTest.restoreToSnapshot(snapshot = initialSnapshot)
assertThat(isActivated).isFalse()
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/themedicon/domain/interactor/ThemedIconSnapshotRestorerTest.kt | 3892011398 |
/*
* 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.test.filters.SmallTest
import com.android.customization.model.themedicon.data.repository.ThemeIconRepository
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(JUnit4::class)
class ThemedIconInteractorTest {
private lateinit var underTest: ThemedIconInteractor
@Before
fun setUp() {
underTest =
ThemedIconInteractor(
repository = ThemeIconRepository(),
)
}
@Test
fun `end-to-end`() = runTest {
val isActivated = collectLastValue(underTest.isActivated)
underTest.setActivated(isActivated = true)
assertThat(isActivated()).isTrue()
underTest.setActivated(isActivated = false)
assertThat(isActivated()).isFalse()
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/themedicon/domain/interactor/ThemedIconInteractorTest.kt | 2508629114 |
/*
* 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.grid.ui.viewmodel
import androidx.test.filters.SmallTest
import androidx.test.platform.app.InstrumentationRegistry
import com.android.customization.model.grid.data.repository.FakeGridRepository
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.GridIconViewModel
import com.android.customization.picker.grid.ui.viewmodel.GridScreenViewModel
import com.android.wallpaper.picker.option.ui.viewmodel.OptionItemViewModel
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(JUnit4::class)
class GridScreenViewModelTest {
private lateinit var underTest: GridScreenViewModel
private lateinit var testScope: TestScope
private lateinit var interactor: GridInteractor
private lateinit var store: FakeSnapshotStore
@Before
fun setUp() {
testScope = TestScope()
store = FakeSnapshotStore()
interactor =
GridInteractor(
applicationScope = testScope.backgroundScope,
repository =
FakeGridRepository(
scope = testScope.backgroundScope,
initialOptionCount = 4,
),
snapshotRestorer = {
GridSnapshotRestorer(
interactor = interactor,
)
.apply { runBlocking { setUpSnapshotRestorer(store) } }
}
)
underTest =
GridScreenViewModel(
context = InstrumentationRegistry.getInstrumentation().targetContext,
interactor = interactor,
)
}
@Test
@Ignore("b/270371382")
fun clickOnItem_itGetsSelected() =
testScope.runTest {
val optionItemsValueProvider = collectLastValue(underTest.optionItems)
var optionItemsValue = checkNotNull(optionItemsValueProvider.invoke())
assertThat(optionItemsValue).hasSize(4)
assertThat(getSelectedIndex(optionItemsValue)).isEqualTo(0)
assertThat(getOnClick(optionItemsValue[0])).isNull()
val item1OnClickedValue = getOnClick(optionItemsValue[1])
assertThat(item1OnClickedValue).isNotNull()
item1OnClickedValue?.invoke()
optionItemsValue = checkNotNull(optionItemsValueProvider.invoke())
assertThat(optionItemsValue).hasSize(4)
assertThat(getSelectedIndex(optionItemsValue)).isEqualTo(1)
assertThat(getOnClick(optionItemsValue[0])).isNotNull()
assertThat(getOnClick(optionItemsValue[1])).isNull()
}
private fun TestScope.getSelectedIndex(
optionItems: List<OptionItemViewModel<GridIconViewModel>>
): Int {
return optionItems.indexOfFirst { optionItem ->
collectLastValue(optionItem.isSelected).invoke() == true
}
}
private fun TestScope.getOnClick(
optionItem: OptionItemViewModel<GridIconViewModel>
): (() -> Unit)? {
return collectLastValue(optionItem.onClicked).invoke()
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/grid/ui/viewmodel/GridScreenViewModelTest.kt | 2932314410 |
/*
* 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.grid.data.repository
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 kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
class FakeGridRepository(
private val scope: CoroutineScope,
initialOptionCount: Int,
var available: Boolean = true
) : GridRepository {
private val _optionChanges =
MutableSharedFlow<Unit>(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
override suspend fun isAvailable(): Boolean = available
override fun getOptionChanges(): Flow<Unit> = _optionChanges.asSharedFlow()
private val selectedOptionIndex = MutableStateFlow(0)
private var options: GridOptionItemsModel = createOptions(count = initialOptionCount)
override suspend fun getOptions(): GridOptionItemsModel {
return options
}
override fun getSelectedOption(): GridOption? = null
override fun applySelectedOption(callback: CustomizationManager.Callback) {}
override fun clearSelectedOption() {}
override fun isSelectedOptionApplied() = false
fun setOptions(
count: Int,
selectedIndex: Int = 0,
) {
options = createOptions(count, selectedIndex)
_optionChanges.tryEmit(Unit)
}
private fun createOptions(
count: Int,
selectedIndex: Int = 0,
): GridOptionItemsModel {
selectedOptionIndex.value = selectedIndex
return GridOptionItemsModel.Loaded(
options =
buildList {
repeat(times = count) { index ->
add(
GridOptionItemModel(
name = "option_$index",
cols = 4,
rows = index * 2,
isSelected =
selectedOptionIndex
.map { it == index }
.stateIn(
scope = scope,
started = SharingStarted.Eagerly,
initialValue = false,
),
onSelected = { selectedOptionIndex.value = index },
)
)
}
}
)
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/grid/data/repository/FakeGridRepository.kt | 621122179 |
/*
* 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.grid.domain.interactor
import androidx.test.filters.SmallTest
import com.android.customization.model.grid.data.repository.FakeGridRepository
import com.android.customization.picker.grid.domain.interactor.GridInteractor
import com.android.customization.picker.grid.domain.interactor.GridSnapshotRestorer
import com.android.customization.picker.grid.shared.model.GridOptionItemsModel
import com.android.wallpaper.testing.FakeSnapshotStore
import com.android.wallpaper.testing.collectLastValue
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(JUnit4::class)
class GridInteractorTest {
private lateinit var underTest: GridInteractor
private lateinit var testScope: TestScope
private lateinit var repository: FakeGridRepository
private lateinit var store: FakeSnapshotStore
@Before
fun setUp() {
testScope = TestScope()
repository =
FakeGridRepository(
scope = testScope.backgroundScope,
initialOptionCount = 3,
)
store = FakeSnapshotStore()
underTest =
GridInteractor(
applicationScope = testScope.backgroundScope,
repository = repository,
snapshotRestorer = {
GridSnapshotRestorer(
interactor = underTest,
)
.apply {
runBlocking {
setUpSnapshotRestorer(
store = store,
)
}
}
},
)
}
@Test
fun selectingOptionThroughModel_updatesOptions() =
testScope.runTest {
val options = collectLastValue(underTest.options)
assertThat(options()).isInstanceOf(GridOptionItemsModel.Loaded::class.java)
(options() as? GridOptionItemsModel.Loaded)?.let { loaded ->
assertThat(loaded.options).hasSize(3)
assertThat(loaded.options[0].isSelected.value).isTrue()
assertThat(loaded.options[1].isSelected.value).isFalse()
assertThat(loaded.options[2].isSelected.value).isFalse()
}
val storedSnapshot = store.retrieve()
(options() as? GridOptionItemsModel.Loaded)?.let { loaded ->
loaded.options[1].onSelected()
}
assertThat(options()).isInstanceOf(GridOptionItemsModel.Loaded::class.java)
(options() as? GridOptionItemsModel.Loaded)?.let { loaded ->
assertThat(loaded.options).hasSize(3)
assertThat(loaded.options[0].isSelected.value).isFalse()
assertThat(loaded.options[1].isSelected.value).isTrue()
assertThat(loaded.options[2].isSelected.value).isFalse()
}
assertThat(store.retrieve()).isNotEqualTo(storedSnapshot)
}
@Test
fun selectingOptionThroughSetter_returnsSelectedOptionFromGetter() =
testScope.runTest {
val options = collectLastValue(underTest.options)
assertThat(options()).isInstanceOf(GridOptionItemsModel.Loaded::class.java)
(options() as? GridOptionItemsModel.Loaded)?.let { loaded ->
assertThat(loaded.options).hasSize(3)
}
val storedSnapshot = store.retrieve()
(options() as? GridOptionItemsModel.Loaded)?.let { loaded ->
underTest.setSelectedOption(loaded.options[1])
runCurrent()
assertThat(underTest.getSelectedOption()?.name).isEqualTo(loaded.options[1].name)
assertThat(store.retrieve()).isNotEqualTo(storedSnapshot)
}
}
@Test
fun externalUpdates_reloadInvoked() =
testScope.runTest {
val options = collectLastValue(underTest.options)
assertThat(options()).isInstanceOf(GridOptionItemsModel.Loaded::class.java)
(options() as? GridOptionItemsModel.Loaded)?.let { loaded ->
assertThat(loaded.options).hasSize(3)
}
val storedSnapshot = store.retrieve()
repository.setOptions(4)
assertThat(options()).isInstanceOf(GridOptionItemsModel.Loaded::class.java)
(options() as? GridOptionItemsModel.Loaded)?.let { loaded ->
assertThat(loaded.options).hasSize(4)
}
// External updates do not record a new snapshot with the undo system.
assertThat(store.retrieve()).isEqualTo(storedSnapshot)
}
@Test
fun unavailableRepository_emptyOptions() =
testScope.runTest {
repository.available = false
val options = collectLastValue(underTest.options)
assertThat(options()).isNull()
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/grid/domain/interactor/GridInteractorTest.kt | 3878018150 |
/*
* 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.grid.domain.interactor
import androidx.test.filters.SmallTest
import com.android.customization.model.grid.data.repository.FakeGridRepository
import com.android.customization.picker.grid.domain.interactor.GridInteractor
import com.android.customization.picker.grid.domain.interactor.GridSnapshotRestorer
import com.android.customization.picker.grid.shared.model.GridOptionItemsModel
import com.android.wallpaper.testing.FakeSnapshotStore
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalCoroutinesApi::class)
@SmallTest
@RunWith(JUnit4::class)
class GridSnapshotRestorerTest {
private lateinit var underTest: GridSnapshotRestorer
private lateinit var testScope: TestScope
private lateinit var repository: FakeGridRepository
private lateinit var store: FakeSnapshotStore
@Before
fun setUp() {
testScope = TestScope()
repository =
FakeGridRepository(
scope = testScope.backgroundScope,
initialOptionCount = 4,
)
underTest =
GridSnapshotRestorer(
interactor =
GridInteractor(
applicationScope = testScope.backgroundScope,
repository = repository,
snapshotRestorer = { underTest },
)
)
store = FakeSnapshotStore()
}
@Test
fun restoreToSnapshot_noCallsToStore_restoresToInitialSnapshot() =
testScope.runTest {
runCurrent()
val initialSnapshot = underTest.setUpSnapshotRestorer(store = store)
assertThat(initialSnapshot.args).isNotEmpty()
repository.setOptions(
count = 4,
selectedIndex = 2,
)
runCurrent()
assertThat(getSelectedIndex()).isEqualTo(2)
underTest.restoreToSnapshot(initialSnapshot)
runCurrent()
assertThat(getSelectedIndex()).isEqualTo(0)
}
@Test
fun restoreToSnapshot_withCallToStore_restoresToInitialSnapshot() =
testScope.runTest {
runCurrent()
val initialSnapshot = underTest.setUpSnapshotRestorer(store = store)
assertThat(initialSnapshot.args).isNotEmpty()
repository.setOptions(
count = 4,
selectedIndex = 2,
)
runCurrent()
assertThat(getSelectedIndex()).isEqualTo(2)
underTest.store((repository.getOptions() as GridOptionItemsModel.Loaded).options[1])
runCurrent()
underTest.restoreToSnapshot(initialSnapshot)
runCurrent()
assertThat(getSelectedIndex()).isEqualTo(0)
}
private suspend fun getSelectedIndex(): Int {
return (repository.getOptions() as? GridOptionItemsModel.Loaded)?.options?.indexOfFirst {
optionItem ->
optionItem.isSelected.value
}
?: -1
}
}
| android_packages_apps_ThemePicker/tests/robotests/src/com/android/customization/model/grid/domain/interactor/GridSnapshotRestorerTest.kt | 4258353511 |
package com.android.customization
import androidx.test.core.app.ApplicationProvider
import com.android.customization.model.color.ColorCustomizationManager
import com.android.customization.model.theme.OverlayManagerCompat
import com.android.customization.module.CustomizationInjector
import com.android.customization.module.CustomizationPreferences
import com.android.customization.module.logging.TestThemesUserEventLogger
import com.android.customization.module.logging.ThemesUserEventLogger
import com.android.customization.testing.TestCustomizationInjector
import com.android.customization.testing.TestDefaultCustomizationPreferences
import com.android.wallpaper.module.AppModule
import com.android.wallpaper.module.Injector
import com.android.wallpaper.module.WallpaperPreferences
import com.android.wallpaper.module.logging.TestUserEventLogger
import com.android.wallpaper.module.logging.UserEventLogger
import com.android.wallpaper.testing.TestInjector
import com.android.wallpaper.testing.TestWallpaperPreferences
import com.android.wallpaper.util.converter.DefaultWallpaperModelFactory
import com.android.wallpaper.util.converter.WallpaperModelFactory
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.components.SingletonComponent
import dagger.hilt.testing.TestInstallIn
import javax.inject.Singleton
@Module
@TestInstallIn(components = [SingletonComponent::class], replaces = [AppModule::class])
abstract class TestModule {
//// WallpaperPicker2 prod
@Binds @Singleton abstract fun bindInjector(impl: TestCustomizationInjector): Injector
@Binds @Singleton abstract fun bindUserEventLogger(impl: TestUserEventLogger): UserEventLogger
@Binds
@Singleton
abstract fun bindThemesUserEventLogger(impl: TestThemesUserEventLogger): ThemesUserEventLogger
@Binds
@Singleton
abstract fun bindWallpaperPrefs(impl: TestDefaultCustomizationPreferences): WallpaperPreferences
//// WallpaperPicker2 test
@Binds @Singleton abstract fun bindTestInjector(impl: TestCustomizationInjector): TestInjector
@Binds
@Singleton
abstract fun bindTestWallpaperPrefs(
impl: TestDefaultCustomizationPreferences
): TestWallpaperPreferences
//// ThemePicker prod
@Binds
@Singleton
abstract fun bindCustomizationInjector(impl: TestCustomizationInjector): CustomizationInjector
@Binds
@Singleton
abstract fun bindCustomizationPrefs(
impl: TestDefaultCustomizationPreferences
): CustomizationPreferences
@Binds
@Singleton
abstract fun bindWallpaperModelFactory(
impl: DefaultWallpaperModelFactory
): WallpaperModelFactory
companion object {
@Provides
@Singleton
fun provideColorCustomizationManager(): ColorCustomizationManager {
return ColorCustomizationManager.getInstance(
ApplicationProvider.getApplicationContext(),
OverlayManagerCompat(ApplicationProvider.getApplicationContext())
)
}
}
}
| android_packages_apps_ThemePicker/tests/module/src/com/android/customization/TestModule.kt | 3214025424 |
/*
* 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 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.logging.TestUserEventLogger
import javax.inject.Inject
import javax.inject.Singleton
/** Test implementation of [ThemesUserEventLogger]. */
@Singleton
class TestThemesUserEventLogger @Inject constructor() :
TestUserEventLogger(), ThemesUserEventLogger {
@ClockSize private var clockSize: Int = StyleEnums.CLOCK_SIZE_UNSPECIFIED
@ColorSource
var themeColorSource: Int = StyleEnums.COLOR_SOURCE_UNSPECIFIED
private set
var themeColorStyle: Int = -1
private set
var themeSeedColor: Int = -1
private set
override fun logThemeColorApplied(@ColorSource source: Int, style: Int, seedColor: Int) {
this.themeColorSource = source
this.themeColorStyle = style
this.themeSeedColor = seedColor
}
override fun logGridApplied(grid: GridOption) {}
override fun logClockApplied(clockId: String) {}
override fun logClockColorApplied(seedColor: Int) {}
override fun logClockSizeApplied(@ClockSize clockSize: Int) {
this.clockSize = clockSize
}
override fun logThemedIconApplied(useThemeIcon: Boolean) {}
override fun logLockScreenNotificationApplied(showLockScreenNotifications: Boolean) {}
override fun logShortcutApplied(shortcut: String, shortcutSlotId: String) {}
override fun logDarkThemeApplied(useDarkTheme: Boolean) {}
@ClockSize
fun getLoggedClockSize(): Int {
return clockSize
}
}
| android_packages_apps_ThemePicker/tests/common/src/com/android/customization/module/logging/TestThemesUserEventLogger.kt | 2178693033 |
package com.android.customization.testing
import android.app.WallpaperColors
import android.content.Context
import android.content.res.Resources
import androidx.activity.ComponentActivity
import com.android.customization.model.color.ThemedWallpaperColorResources
import com.android.customization.model.color.WallpaperColorResources
import com.android.customization.module.CustomizationInjector
import com.android.customization.module.CustomizationPreferences
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.logging.UserEventLogger
import com.android.wallpaper.picker.customization.data.repository.WallpaperColorsRepository
import com.android.wallpaper.testing.TestInjector
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
open class TestCustomizationInjector
@Inject
constructor(
private val customPrefs: TestDefaultCustomizationPreferences,
private val themesUserEventLogger: ThemesUserEventLogger
) : TestInjector(themesUserEventLogger), CustomizationInjector {
/////////////////
// CustomizationInjector implementations
/////////////////
override fun getCustomizationPreferences(context: Context): CustomizationPreferences {
return customPrefs
}
override fun getKeyguardQuickAffordancePickerInteractor(
context: Context
): KeyguardQuickAffordancePickerInteractor {
throw UnsupportedOperationException("not implemented")
}
override fun getClockRegistry(context: Context): ClockRegistry? {
throw UnsupportedOperationException("not implemented")
}
override fun getClockPickerInteractor(context: Context): ClockPickerInteractor {
throw UnsupportedOperationException("not implemented")
}
override fun getWallpaperColorResources(
wallpaperColors: WallpaperColors,
context: Context
): WallpaperColorResources {
return ThemedWallpaperColorResources(wallpaperColors, context)
}
override fun getColorPickerInteractor(
context: Context,
wallpaperColorsRepository: WallpaperColorsRepository,
): ColorPickerInteractor {
throw UnsupportedOperationException("not implemented")
}
override fun getColorPickerViewModelFactory(
context: Context,
wallpaperColorsRepository: WallpaperColorsRepository,
): ColorPickerViewModel.Factory {
throw UnsupportedOperationException("not implemented")
}
override fun getClockCarouselViewModelFactory(
interactor: ClockPickerInteractor,
clockViewFactory: ClockViewFactory,
resources: Resources,
logger: ThemesUserEventLogger,
): ClockCarouselViewModel.Factory {
throw UnsupportedOperationException("not implemented")
}
override fun getClockViewFactory(activity: ComponentActivity): ClockViewFactory {
throw UnsupportedOperationException("not implemented")
}
override fun getClockSettingsViewModelFactory(
context: Context,
wallpaperColorsRepository: WallpaperColorsRepository,
clockViewFactory: ClockViewFactory,
): ClockSettingsViewModel.Factory {
throw UnsupportedOperationException("not implemented")
}
/////////////////
// TestInjector overrides
/////////////////
override fun getUserEventLogger(context: Context): UserEventLogger {
return themesUserEventLogger
}
}
| android_packages_apps_ThemePicker/tests/common/src/com/android/customization/testing/TestCustomizationInjector.kt | 2065684367 |
package com.android.customization.testing
import com.android.systemui.plugins.Plugin
import com.android.systemui.plugins.PluginListener
import com.android.systemui.plugins.PluginManager
class TestPluginManager : PluginManager {
override fun getPrivilegedPlugins(): Array<String> {
return emptyArray()
}
override fun <T : Plugin?> addPluginListener(listener: PluginListener<T>, cls: Class<T>) {}
override fun <T : Plugin?> addPluginListener(
listener: PluginListener<T>,
cls: Class<T>,
allowMultiple: Boolean
) {}
override fun <T : Plugin?> addPluginListener(
action: String,
listener: PluginListener<T>,
cls: Class<T>
) {}
override fun <T : Plugin?> addPluginListener(
action: String,
listener: PluginListener<T>,
cls: Class<T>,
allowMultiple: Boolean
) {}
override fun removePluginListener(listener: PluginListener<*>?) {}
override fun <T> dependsOn(p: Plugin, cls: Class<T>): Boolean {
return false
}
}
| android_packages_apps_ThemePicker/tests/common/src/com/android/customization/testing/TestPluginManager.kt | 1853191358 |
/*
* 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.testing
import com.android.customization.module.CustomizationPreferences
import com.android.wallpaper.testing.TestWallpaperPreferences
import javax.inject.Inject
import javax.inject.Singleton
/** Test implementation of [CustomizationPreferences]. */
@Singleton
open class TestDefaultCustomizationPreferences @Inject constructor() :
TestWallpaperPreferences(), CustomizationPreferences {
private var customThemes: String? = null
private val tabVisited: MutableSet<String> = HashSet()
private var themedIconEnabled = false
override fun getSerializedCustomThemes(): String? {
return customThemes
}
override fun storeCustomThemes(serializedCustomThemes: String) {
customThemes = serializedCustomThemes
}
override fun getTabVisited(id: String): Boolean {
return tabVisited.contains(id)
}
override fun setTabVisited(id: String) {
tabVisited.add(id)
}
override fun getThemedIconEnabled(): Boolean {
return themedIconEnabled
}
override fun setThemedIconEnabled(enabled: Boolean) {
themedIconEnabled = enabled
}
}
| android_packages_apps_ThemePicker/tests/common/src/com/android/customization/testing/TestDefaultCustomizationPreferences.kt | 131662100 |
/*
* 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.wallpaper.picker.di.modules
import android.text.TextUtils
import com.android.customization.model.color.ColorCustomizationManager
import com.android.customization.model.color.ColorOptionsProvider.COLOR_SOURCE_PRESET
import com.android.wallpaper.picker.customization.data.repository.WallpaperRepository
import com.android.wallpaper.picker.customization.domain.interactor.WallpaperInteractor
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
/** This class provides the singleton scoped interactors for theme picker. */
@InstallIn(SingletonComponent::class)
@Module
internal object InteractorModule {
@Provides
@Singleton
fun provideWallpaperInteractor(
wallpaperRepository: WallpaperRepository,
colorCustomizationManager: ColorCustomizationManager,
): WallpaperInteractor {
return WallpaperInteractor(wallpaperRepository) {
TextUtils.equals(colorCustomizationManager.currentColorSource, COLOR_SOURCE_PRESET)
}
}
}
| android_packages_apps_ThemePicker/src_override/com/android/wallpaper/picker/di/modules/InteractorModule.kt | 1025633815 |
/*
* 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.wallpaper.module
import android.content.Context
import com.android.customization.model.color.ColorCustomizationManager
import com.android.customization.model.theme.OverlayManagerCompat
import com.android.customization.module.CustomizationInjector
import com.android.customization.module.DefaultCustomizationPreferences
import com.android.customization.module.ThemePickerInjector
import com.android.customization.module.logging.ThemesUserEventLogger
import com.android.customization.module.logging.ThemesUserEventLoggerImpl
import com.android.wallpaper.module.logging.UserEventLogger
import com.android.wallpaper.util.converter.DefaultWallpaperModelFactory
import com.android.wallpaper.util.converter.WallpaperModelFactory
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class AppModule {
@Binds @Singleton abstract fun bindInjector(impl: ThemePickerInjector): CustomizationInjector
@Binds
@Singleton
abstract fun bindUserEventLogger(impl: ThemesUserEventLoggerImpl): UserEventLogger
@Binds
@Singleton
abstract fun bindThemesUserEventLogger(impl: ThemesUserEventLoggerImpl): ThemesUserEventLogger
@Binds
@Singleton
abstract fun bindWallpaperModelFactory(
impl: DefaultWallpaperModelFactory
): WallpaperModelFactory
companion object {
@Provides
@Singleton
fun provideWallpaperPreferences(
@ApplicationContext context: Context
): WallpaperPreferences {
return DefaultCustomizationPreferences(context)
}
@Provides
@Singleton
fun provideColorCustomizationManager(
@ApplicationContext context: Context
): ColorCustomizationManager {
return ColorCustomizationManager.getInstance(context, OverlayManagerCompat(context))
}
}
}
| android_packages_apps_ThemePicker/src_override/com/android/wallpaper/module/AppModule.kt | 4214963592 |
/*
* 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.settings.ui.section
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.provider.Settings
import android.view.LayoutInflater
import com.android.customization.picker.settings.ui.view.MoreSettingsSectionView
import com.android.wallpaper.R
import com.android.wallpaper.model.CustomizationSectionController
class MoreSettingsSectionController : CustomizationSectionController<MoreSettingsSectionView> {
override fun isAvailable(context: Context): Boolean {
return true
}
@SuppressLint("InflateParams") // We're okay not providing a parent view.
override fun createView(context: Context): MoreSettingsSectionView {
return LayoutInflater.from(context)
.inflate(R.layout.more_settings_section_view, null)
.apply {
setOnClickListener {
context.startActivity(Intent(Settings.ACTION_LOCKSCREEN_SETTINGS))
}
} as MoreSettingsSectionView
}
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/settings/ui/section/MoreSettingsSectionController.kt | 3759438912 |
/*
* 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.settings.ui.view
import android.content.Context
import android.util.AttributeSet
import com.android.wallpaper.picker.SectionView
class MoreSettingsSectionView(
context: Context,
attrs: AttributeSet?,
) :
SectionView(
context,
attrs,
)
| android_packages_apps_ThemePicker/src/com/android/customization/picker/settings/ui/view/MoreSettingsSectionView.kt | 3252370936 |
/*
* 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.color.ui.viewmodel
import android.annotation.ColorInt
/**
* Models UI state for a color options in a picker experience.
*
* TODO (b/272109171): Remove after clock settings is refactored to use OptionItemAdapter
*/
data class ColorOptionViewModel(
/** Colors for the color option. */
@ColorInt val color0: Int,
@ColorInt val color1: Int,
@ColorInt val color2: Int,
@ColorInt val color3: Int,
/** A content description for the color. */
val contentDescription: String,
/** Nullable option title. Null by default. */
val title: String? = null,
/** Whether this color is selected. */
val isSelected: Boolean,
/** Notifies that the color has been clicked by the user. */
val onClick: (() -> Unit)?,
)
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/ui/viewmodel/ColorOptionViewModel.kt | 3677929881 |
/*
* 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.color.ui.viewmodel
import android.annotation.ColorInt
data class ColorOptionIconViewModel(
@ColorInt val lightThemeColor0: Int,
@ColorInt val lightThemeColor1: Int,
@ColorInt val lightThemeColor2: Int,
@ColorInt val lightThemeColor3: Int,
@ColorInt val darkThemeColor0: Int,
@ColorInt val darkThemeColor1: Int,
@ColorInt val darkThemeColor2: Int,
@ColorInt val darkThemeColor3: Int,
)
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/ui/viewmodel/ColorOptionIconViewModel.kt | 3888712141 |
/*
* 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.color.ui.viewmodel
import android.content.Context
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.picker.color.domain.interactor.ColorPickerInteractor
import com.android.customization.picker.color.shared.model.ColorType
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 kotlin.math.max
import kotlin.math.min
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
/** Models UI state for a color picker experience. */
class ColorPickerViewModel
private constructor(
context: Context,
private val interactor: ColorPickerInteractor,
private val logger: ThemesUserEventLogger,
) : ViewModel() {
private val selectedColorTypeTabId = MutableStateFlow<ColorType?>(null)
/** View-models for each color tab. */
val colorTypeTabs: Flow<Map<ColorType, ColorTypeTabViewModel>> =
combine(
interactor.colorOptions,
selectedColorTypeTabId,
) { colorOptions, selectedColorTypeIdOrNull ->
colorOptions.keys
.mapIndexed { index, colorType ->
val isSelected =
(selectedColorTypeIdOrNull == null && index == 0) ||
selectedColorTypeIdOrNull == colorType
colorType to
ColorTypeTabViewModel(
name =
when (colorType) {
ColorType.WALLPAPER_COLOR ->
context.resources.getString(R.string.wallpaper_color_tab)
ColorType.PRESET_COLOR ->
context.resources.getString(R.string.preset_color_tab_2)
},
isSelected = isSelected,
onClick =
if (isSelected) {
null
} else {
{ this.selectedColorTypeTabId.value = colorType }
},
)
}
.toMap()
}
/** View-models for each color tab subheader */
val colorTypeTabSubheader: Flow<String> =
selectedColorTypeTabId.map { selectedColorTypeIdOrNull ->
when (selectedColorTypeIdOrNull ?: ColorType.WALLPAPER_COLOR) {
ColorType.WALLPAPER_COLOR ->
context.resources.getString(R.string.wallpaper_color_subheader)
ColorType.PRESET_COLOR ->
context.resources.getString(R.string.preset_color_subheader)
}
}
/** The list of all color options mapped by their color type */
private val allColorOptions:
Flow<Map<ColorType, List<OptionItemViewModel<ColorOptionIconViewModel>>>> =
interactor.colorOptions
.map { colorOptions ->
colorOptions
.map { colorOptionEntry ->
colorOptionEntry.key to
colorOptionEntry.value.map { colorOptionModel ->
val colorOption: ColorOptionImpl =
colorOptionModel.colorOption as ColorOptionImpl
val lightThemeColors =
colorOption.previewInfo.resolveColors(/* darkTheme= */ false)
val darkThemeColors =
colorOption.previewInfo.resolveColors(/* darkTheme= */ true)
val isSelectedFlow: StateFlow<Boolean> =
interactor.activeColorOption
.map {
it?.colorOption?.isEquivalent(
colorOptionModel.colorOption
)
?: colorOptionModel.isSelected
}
.stateIn(viewModelScope)
OptionItemViewModel<ColorOptionIconViewModel>(
key =
MutableStateFlow(colorOptionModel.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(
colorOption.getContentDescription(context).toString()
),
isTextUserVisible = false,
isSelected = isSelectedFlow,
onClicked =
isSelectedFlow.map { isSelected ->
if (isSelected) {
null
} else {
{
viewModelScope.launch {
interactor.select(colorOptionModel)
logger.logThemeColorApplied(
colorOptionModel.colorOption
.sourceForLogging,
colorOptionModel.colorOption
.styleForLogging,
colorOptionModel.colorOption
.seedColorForLogging,
)
}
}
}
},
)
}
}
.toMap()
}
.shareIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
replay = 1,
)
/** The list of all available color options for the selected Color Type. */
val colorOptions: Flow<List<OptionItemViewModel<ColorOptionIconViewModel>>> =
combine(allColorOptions, selectedColorTypeTabId) {
allColorOptions:
Map<ColorType, List<OptionItemViewModel<ColorOptionIconViewModel>>>,
selectedColorTypeIdOrNull ->
val selectedColorTypeId = selectedColorTypeIdOrNull ?: ColorType.WALLPAPER_COLOR
allColorOptions[selectedColorTypeId]!!
}
.shareIn(
scope = viewModelScope,
started = SharingStarted.Eagerly,
replay = 1,
)
/** The list of color options for the color section */
val colorSectionOptions: Flow<List<OptionItemViewModel<ColorOptionIconViewModel>>> =
allColorOptions
.map { allColorOptions ->
val wallpaperOptions = allColorOptions[ColorType.WALLPAPER_COLOR]
val presetOptions = allColorOptions[ColorType.PRESET_COLOR]
val subOptions =
wallpaperOptions!!.subList(
0,
min(COLOR_SECTION_OPTION_SIZE, wallpaperOptions.size)
)
// Add additional options based on preset colors if size of wallpaper color options
// is
// less than COLOR_SECTION_OPTION_SIZE
val additionalSubOptions =
presetOptions!!.subList(
0,
min(
max(0, COLOR_SECTION_OPTION_SIZE - wallpaperOptions.size),
presetOptions.size,
)
)
subOptions + additionalSubOptions
}
.shareIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(),
replay = 1,
)
class Factory(
private val context: Context,
private val interactor: ColorPickerInteractor,
private val logger: ThemesUserEventLogger,
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return ColorPickerViewModel(
context = context,
interactor = interactor,
logger = logger,
)
as T
}
}
companion object {
private const val COLOR_SECTION_OPTION_SIZE = 5
}
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/ui/viewmodel/ColorPickerViewModel.kt | 3570117434 |
/*
* 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.color.ui.viewmodel
/** Models UI state for a single color type in a picker experience. */
data class ColorTypeTabViewModel(
/** User-visible name for the color type. */
val name: String,
/** Whether this is the currently-selected color type in the picker. */
val isSelected: Boolean,
/** Notifies that the color type has been clicked by the user. */
val onClick: (() -> Unit)?,
)
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/ui/viewmodel/ColorTypeTabViewModel.kt | 3696328598 |
/*
* 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.color.ui.section
import android.content.Context
import android.view.LayoutInflater
import androidx.lifecycle.LifecycleOwner
import com.android.customization.picker.color.ui.binder.ColorSectionViewBinder
import com.android.customization.picker.color.ui.fragment.ColorPickerFragment
import com.android.customization.picker.color.ui.view.ColorSectionView
import com.android.customization.picker.color.ui.viewmodel.ColorPickerViewModel
import com.android.wallpaper.R
import com.android.wallpaper.model.CustomizationSectionController
import com.android.wallpaper.model.CustomizationSectionController.CustomizationSectionNavigationController as NavigationController
class ColorSectionController(
private val navigationController: NavigationController,
private val viewModel: ColorPickerViewModel,
private val lifecycleOwner: LifecycleOwner
) : CustomizationSectionController<ColorSectionView> {
override fun isAvailable(context: Context): Boolean {
return true
}
override fun createView(context: Context): ColorSectionView {
return createView(context, CustomizationSectionController.ViewCreationParams())
}
override fun createView(
context: Context,
params: CustomizationSectionController.ViewCreationParams
): ColorSectionView {
@SuppressWarnings("It is fine to inflate with null parent for our need.")
val view =
LayoutInflater.from(context)
.inflate(
R.layout.color_section_view,
null,
) as ColorSectionView
ColorSectionViewBinder.bind(
view = view,
viewModel = viewModel,
lifecycleOwner = lifecycleOwner,
navigationOnClick = {
navigationController.navigateTo(ColorPickerFragment.newInstance())
},
isConnectedHorizontallyToOtherSections = params.isConnectedHorizontallyToOtherSections,
)
return view
}
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/ui/section/ColorSectionController.kt | 623269939 |
/*
* 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.color.ui.binder
import android.content.res.Configuration
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import android.widget.TextView
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.color.ui.adapter.ColorTypeTabAdapter
import com.android.customization.picker.color.ui.view.ColorOptionIconView
import com.android.customization.picker.color.ui.viewmodel.ColorOptionIconViewModel
import com.android.customization.picker.color.ui.viewmodel.ColorPickerViewModel
import com.android.customization.picker.common.ui.view.ItemSpacing
import com.android.wallpaper.R
import com.android.wallpaper.picker.option.ui.adapter.OptionItemAdapter
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
object ColorPickerBinder {
/**
* Binds view with view-model for a color picker experience. The view should include a Recycler
* View for color type tabs with id [R.id.color_type_tabs] and a Recycler View for color options
* with id [R.id.color_options]
*/
@JvmStatic
fun bind(
view: View,
viewModel: ColorPickerViewModel,
lifecycleOwner: LifecycleOwner,
): Binding {
val colorTypeTabView: RecyclerView = view.requireViewById(R.id.color_type_tabs)
val colorTypeTabSubheaderView: TextView = view.requireViewById(R.id.color_type_tab_subhead)
val colorOptionContainerView: RecyclerView = view.requireViewById(R.id.color_options)
val colorTypeTabAdapter = ColorTypeTabAdapter()
colorTypeTabView.adapter = colorTypeTabAdapter
colorTypeTabView.layoutManager =
LinearLayoutManager(view.context, RecyclerView.HORIZONTAL, false)
colorTypeTabView.addItemDecoration(ItemSpacing(ItemSpacing.TAB_ITEM_SPACING_DP))
val colorOptionAdapter =
OptionItemAdapter(
layoutResourceId = R.layout.color_option,
lifecycleOwner = lifecycleOwner,
bindIcon = { foregroundView: View, colorIcon: ColorOptionIconViewModel ->
val colorOptionIconView = foregroundView as? ColorOptionIconView
val night =
(view.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK ==
Configuration.UI_MODE_NIGHT_YES)
colorOptionIconView?.let { ColorOptionIconBinder.bind(it, colorIcon, night) }
}
)
colorOptionContainerView.adapter = colorOptionAdapter
colorOptionContainerView.layoutManager =
LinearLayoutManager(view.context, RecyclerView.HORIZONTAL, false)
colorOptionContainerView.addItemDecoration(ItemSpacing(ItemSpacing.ITEM_SPACING_DP))
lifecycleOwner.lifecycleScope.launch {
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
launch {
viewModel.colorTypeTabs
.map { colorTypeById -> colorTypeById.values }
.collect { colorTypes -> colorTypeTabAdapter.setItems(colorTypes.toList()) }
}
launch {
viewModel.colorTypeTabSubheader.collect { subhead ->
colorTypeTabSubheaderView.text = subhead
}
}
launch {
viewModel.colorOptions.collect { colorOptions ->
// only set or restore instance state on a recycler view once data binding
// is complete to ensure scroll position is reflected correctly
colorOptionAdapter.setItems(colorOptions) {
// the same recycler view is used for different color types tabs
// the scroll state of each tab should be independent of others
if (layoutManagerSavedState != null) {
(colorOptionContainerView.layoutManager as LinearLayoutManager)
.onRestoreInstanceState(layoutManagerSavedState)
layoutManagerSavedState = null
} else {
var indexToFocus = colorOptions.indexOfFirst { it.isSelected.value }
indexToFocus = if (indexToFocus < 0) 0 else indexToFocus
(colorOptionContainerView.layoutManager as LinearLayoutManager)
.scrollToPositionWithOffset(indexToFocus, 0)
}
}
}
}
}
}
return object : Binding {
override fun saveInstanceState(savedState: Bundle) {
// as a workaround for the picker restarting twice after a config change, if the
// picker restarts before the saved state was applied and set to null,
// re-use the same saved state
savedState.putParcelable(
LAYOUT_MANAGER_SAVED_STATE,
layoutManagerSavedState
?: colorOptionContainerView.layoutManager?.onSaveInstanceState()
)
}
override fun restoreInstanceState(savedState: Bundle) {
layoutManagerSavedState = savedState.getParcelable(LAYOUT_MANAGER_SAVED_STATE)
}
}
}
interface Binding {
fun saveInstanceState(savedState: Bundle)
fun restoreInstanceState(savedState: Bundle)
}
private val LAYOUT_MANAGER_SAVED_STATE: String = "layout_manager_state"
private var layoutManagerSavedState: Parcelable? = null
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/ui/binder/ColorPickerBinder.kt | 1012208793 |
/*
* 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.color.ui.binder
import com.android.customization.picker.color.ui.view.ColorOptionIconView
import com.android.customization.picker.color.ui.viewmodel.ColorOptionIconViewModel
object ColorOptionIconBinder {
fun bind(
view: ColorOptionIconView,
viewModel: ColorOptionIconViewModel,
darkTheme: Boolean,
) {
if (darkTheme) {
view.bindColor(
viewModel.darkThemeColor0,
viewModel.darkThemeColor1,
viewModel.darkThemeColor2,
viewModel.darkThemeColor3,
)
} else {
view.bindColor(
viewModel.lightThemeColor0,
viewModel.lightThemeColor1,
viewModel.lightThemeColor2,
viewModel.lightThemeColor3,
)
}
}
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/ui/binder/ColorOptionIconBinder.kt | 3546611512 |
/*
* 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.color.ui.binder
import android.content.res.Configuration
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.android.customization.picker.color.ui.viewmodel.ColorOptionIconViewModel
import com.android.customization.picker.color.ui.viewmodel.ColorPickerViewModel
import com.android.wallpaper.R
import com.android.wallpaper.picker.common.icon.ui.viewbinder.ContentDescriptionViewBinder
import com.android.wallpaper.picker.option.ui.viewmodel.OptionItemViewModel
import kotlinx.coroutines.launch
object ColorSectionViewBinder {
/**
* Binds view with view-model for color picker section. The view should include a linear layout
* with id [R.id.color_section_option_container]
*/
@JvmStatic
fun bind(
view: View,
viewModel: ColorPickerViewModel,
lifecycleOwner: LifecycleOwner,
navigationOnClick: (View) -> Unit,
isConnectedHorizontallyToOtherSections: Boolean = false,
) {
val optionContainer: LinearLayout =
view.requireViewById(R.id.color_section_option_container)
val moreColorsButton: View = view.requireViewById(R.id.more_colors)
if (isConnectedHorizontallyToOtherSections) {
moreColorsButton.isVisible = true
moreColorsButton.setOnClickListener(navigationOnClick)
} else {
moreColorsButton.isVisible = false
}
lifecycleOwner.lifecycleScope.launch {
lifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
launch {
viewModel.colorSectionOptions.collect { colorOptions ->
setOptions(
options = colorOptions,
view = optionContainer,
lifecycleOwner = lifecycleOwner,
addOverflowOption = !isConnectedHorizontallyToOtherSections,
overflowOnClick = navigationOnClick,
)
}
}
}
}
}
fun setOptions(
options: List<OptionItemViewModel<ColorOptionIconViewModel>>,
view: LinearLayout,
lifecycleOwner: LifecycleOwner,
addOverflowOption: Boolean = false,
overflowOnClick: (View) -> Unit = {},
) {
view.removeAllViews()
// Color option slot size is the minimum between the color option size and the view column
// count. When having an overflow option, a slot is reserved for the overflow option.
val colorOptionSlotSize =
(if (addOverflowOption) {
minOf(view.weightSum.toInt() - 1, options.size)
} else {
minOf(view.weightSum.toInt(), options.size)
})
.let { if (it < 0) 0 else it }
options.subList(0, colorOptionSlotSize).forEach { item ->
val night =
(view.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK ==
Configuration.UI_MODE_NIGHT_YES)
val itemView =
LayoutInflater.from(view.context)
.inflate(R.layout.color_option_no_background, view, false)
item.payload?.let {
ColorOptionIconBinder.bind(
itemView.requireViewById(R.id.option_tile),
item.payload,
night
)
ContentDescriptionViewBinder.bind(
view = itemView.requireViewById(R.id.option_tile),
viewModel = item.text,
)
}
val optionSelectedView = itemView.requireViewById<ImageView>(R.id.option_selected)
lifecycleOwner.lifecycleScope.launch {
launch {
item.isSelected.collect { isSelected ->
optionSelectedView.isVisible = isSelected
}
}
launch {
item.onClicked.collect { onClicked ->
itemView.setOnClickListener(
if (onClicked != null) {
View.OnClickListener { onClicked.invoke() }
} else {
null
}
)
}
}
}
view.addView(itemView)
}
// add overflow option
if (addOverflowOption) {
val itemView =
LayoutInflater.from(view.context)
.inflate(R.layout.color_option_overflow_no_background, view, false)
itemView.setOnClickListener(overflowOnClick)
view.addView(itemView)
}
}
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/ui/binder/ColorSectionViewBinder.kt | 95914408 |
/*
* 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.color.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.color.ui.viewmodel.ColorTypeTabViewModel
import com.android.wallpaper.R
/** Adapts between color type items and views. */
class ColorTypeTabAdapter : RecyclerView.Adapter<ColorTypeTabAdapter.ViewHolder>() {
private val items = mutableListOf<ColorTypeTabViewModel>()
fun setItems(items: List<ColorTypeTabViewModel>) {
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.onClick != null) {
View.OnClickListener { item.onClick.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/color/ui/adapter/ColorTypeTabAdapter.kt | 1841707442 |
/*
* 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.color.ui.fragment
import android.app.WallpaperManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
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.lifecycle.lifecycleScope
import androidx.transition.Transition
import androidx.transition.doOnStart
import com.android.customization.model.mode.DarkModeSectionController
import com.android.customization.module.ThemePickerInjector
import com.android.customization.picker.color.ui.binder.ColorPickerBinder
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.data.repository.WallpaperColorsRepository
import com.android.wallpaper.picker.customization.shared.model.WallpaperColorsModel
import com.android.wallpaper.picker.customization.ui.binder.ScreenPreviewBinder
import com.android.wallpaper.picker.customization.ui.viewmodel.ScreenPreviewViewModel
import com.android.wallpaper.util.DisplayUtils
import com.android.wallpaper.util.PreviewUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
@OptIn(ExperimentalCoroutinesApi::class)
class ColorPickerFragment : AppbarFragment() {
private var binding: ColorPickerBinder.Binding? = null
companion object {
@JvmStatic
fun newInstance(): ColorPickerFragment {
return ColorPickerFragment()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view =
inflater.inflate(
R.layout.fragment_color_picker,
container,
false,
)
setUpToolbar(view)
val injector = InjectorProvider.getInjector() as ThemePickerInjector
val lockScreenView: CardView = view.requireViewById(R.id.lock_preview)
val homeScreenView: CardView = view.requireViewById(R.id.home_preview)
val wallpaperInfoFactory = injector.getCurrentWallpaperInfoFactory(requireContext())
val displayUtils: DisplayUtils = injector.getDisplayUtils(requireContext())
val wallpaperColorsRepository = injector.getWallpaperColorsRepository()
val wallpaperManager = WallpaperManager.getInstance(requireContext())
binding =
ColorPickerBinder.bind(
view = view,
viewModel =
ViewModelProvider(
requireActivity(),
injector.getColorPickerViewModelFactory(
context = requireContext(),
wallpaperColorsRepository = wallpaperColorsRepository,
),
)
.get(),
lifecycleOwner = this,
)
savedInstanceState?.let { binding?.restoreInstanceState(it) }
val lockScreenPreviewBinder =
ScreenPreviewBinder.bind(
activity = requireActivity(),
previewView = lockScreenView,
viewModel =
ScreenPreviewViewModel(
previewUtils =
PreviewUtils(
context = requireContext(),
authority =
requireContext()
.getString(
R.string.lock_screen_preview_provider_authority,
),
),
wallpaperInfoProvider = { forceReload ->
suspendCancellableCoroutine { continuation ->
wallpaperInfoFactory.createCurrentWallpaperInfos(
context,
forceReload,
) { homeWallpaper, lockWallpaper, _ ->
lifecycleScope.launch {
if (
wallpaperColorsRepository.lockWallpaperColors.value
is WallpaperColorsModel.Loading
) {
loadInitialColors(
wallpaperManager,
wallpaperColorsRepository,
CustomizationSections.Screen.LOCK_SCREEN
)
}
}
continuation.resume(lockWallpaper ?: homeWallpaper, null)
}
}
},
onWallpaperColorChanged = { colors ->
wallpaperColorsRepository.setLockWallpaperColors(colors)
},
wallpaperInteractor = injector.getWallpaperInteractor(requireContext()),
screen = CustomizationSections.Screen.LOCK_SCREEN,
),
lifecycleOwner = this,
offsetToStart =
displayUtils.isSingleDisplayOrUnfoldedHorizontalHinge(requireActivity()),
onWallpaperPreviewDirty = { activity?.recreate() },
)
val shouldMirrorHomePreview =
wallpaperManager.getWallpaperInfo(WallpaperManager.FLAG_SYSTEM) != null &&
wallpaperManager.getWallpaperId(WallpaperManager.FLAG_LOCK) < 0
val mirrorSurface = if (shouldMirrorHomePreview) lockScreenPreviewBinder.surface() else null
ScreenPreviewBinder.bind(
activity = requireActivity(),
previewView = homeScreenView,
viewModel =
ScreenPreviewViewModel(
previewUtils =
PreviewUtils(
context = requireContext(),
authorityMetadataKey =
requireContext()
.getString(
R.string.grid_control_metadata_name,
),
),
wallpaperInfoProvider = { forceReload ->
suspendCancellableCoroutine { continuation ->
wallpaperInfoFactory.createCurrentWallpaperInfos(
context,
forceReload,
) { homeWallpaper, lockWallpaper, _ ->
lifecycleScope.launch {
if (
wallpaperColorsRepository.homeWallpaperColors.value
is WallpaperColorsModel.Loading
) {
loadInitialColors(
wallpaperManager,
wallpaperColorsRepository,
CustomizationSections.Screen.HOME_SCREEN
)
}
}
continuation.resume(homeWallpaper ?: lockWallpaper, null)
}
}
},
onWallpaperColorChanged = { colors ->
wallpaperColorsRepository.setHomeWallpaperColors(colors)
},
wallpaperInteractor = injector.getWallpaperInteractor(requireContext()),
screen = CustomizationSections.Screen.HOME_SCREEN,
),
lifecycleOwner = this,
offsetToStart =
displayUtils.isSingleDisplayOrUnfoldedHorizontalHinge(requireActivity()),
onWallpaperPreviewDirty = { activity?.recreate() },
mirrorSurface = mirrorSurface,
)
val darkModeToggleContainerView: FrameLayout =
view.requireViewById(R.id.dark_mode_toggle_container)
val darkModeSectionView =
DarkModeSectionController(
context,
lifecycle,
injector.getDarkModeSnapshotRestorer(requireContext()),
injector.getUserEventLogger(requireContext()),
)
.createView(requireContext())
darkModeSectionView.background = null
darkModeToggleContainerView.addView(darkModeSectionView)
(returnTransition as? Transition)?.doOnStart {
lockScreenView.isVisible = false
homeScreenView.isVisible = false
}
return view
}
private suspend fun loadInitialColors(
wallpaperManager: WallpaperManager,
colorViewModel: WallpaperColorsRepository,
screen: CustomizationSections.Screen,
) {
withContext(Dispatchers.IO) {
val colors =
wallpaperManager.getWallpaperColors(
if (screen == CustomizationSections.Screen.LOCK_SCREEN) {
WallpaperManager.FLAG_LOCK
} else {
WallpaperManager.FLAG_SYSTEM
}
)
withContext(Dispatchers.Main) {
if (screen == CustomizationSections.Screen.LOCK_SCREEN) {
colorViewModel.setLockWallpaperColors(colors)
} else {
colorViewModel.setHomeWallpaperColors(colors)
}
}
}
}
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
binding?.saveInstanceState(savedInstanceState)
}
override fun getDefaultTitle(): CharSequence {
return requireContext().getString(R.string.color_picker_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/color/ui/fragment/ColorPickerFragment.kt | 142366781 |
/*
* 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.color.ui.view
import android.annotation.ColorInt
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
/**
* Draw a color option icon, which is a quadrant circle that can show at most 4 different colors.
*/
class ColorOptionIconView(
context: Context,
attrs: AttributeSet,
) : View(context, attrs) {
private val paint = Paint().apply { style = Paint.Style.FILL }
private val oval = RectF()
private var color0 = DEFAULT_PLACEHOLDER_COLOR
private var color1 = DEFAULT_PLACEHOLDER_COLOR
private var color2 = DEFAULT_PLACEHOLDER_COLOR
private var color3 = DEFAULT_PLACEHOLDER_COLOR
private var w = 0
private var h = 0
/**
* @param color0 the color in the top left quadrant
* @param color1 the color in the top right quadrant
* @param color2 the color in the bottom left quadrant
* @param color3 the color in the bottom right quadrant
*/
fun bindColor(
@ColorInt color0: Int,
@ColorInt color1: Int,
@ColorInt color2: Int,
@ColorInt color3: Int,
) {
this.color0 = color0
this.color1 = color1
this.color2 = color2
this.color3 = color3
invalidate()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
this.w = w
this.h = h
super.onSizeChanged(w, h, oldw, oldh)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// The w and h need to be an even number to avoid tiny pixel-level gaps between the pies
w = w.roundDownToEven()
h = h.roundDownToEven()
val width = w.toFloat()
val height = h.toFloat()
oval.set(0f, 0f, width, height)
canvas.apply {
paint.color = color3
drawArc(
oval,
0f,
90f,
true,
paint,
)
paint.color = color2
drawArc(
oval,
90f,
90f,
true,
paint,
)
paint.color = color0
drawArc(
oval,
180f,
90f,
true,
paint,
)
paint.color = color1
drawArc(
oval,
270f,
90f,
true,
paint,
)
}
}
companion object {
const val DEFAULT_PLACEHOLDER_COLOR = Color.BLACK
fun Int.roundDownToEven(): Int {
return if (this % 2 == 0) this else this - 1
}
}
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/ui/view/ColorOptionIconView.kt | 4269544663 |
/*
* 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.color.ui.view
import android.content.Context
import android.util.AttributeSet
import com.android.wallpaper.picker.SectionView
/**
* The class inherits from {@link SectionView} as the view representing the color section of the
* customization picker. It displays a list of color options and an overflow option.
*/
class ColorSectionView(context: Context, attrs: AttributeSet?) : SectionView(context, attrs)
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/ui/view/ColorSectionView.kt | 1719533186 |
/*
* 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.color.shared.model
import com.android.customization.model.color.ColorOption
/** Models application state for a color option in a picker experience. */
data class ColorOptionModel(
val key: String,
/** Colors for the color option. */
val colorOption: ColorOption,
/** Whether this color option is selected. */
var isSelected: Boolean,
)
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/shared/model/ColorOptionModel.kt | 1377154550 |
/*
* 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.color.shared.model
enum class ColorType {
/** Colors generated based on the current wallpaper */
WALLPAPER_COLOR,
/** Preset colors */
PRESET_COLOR,
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/shared/model/ColorType.kt | 938524516 |
/*
* 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.color.data.repository
import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import com.android.customization.model.ResourceConstants
import com.android.customization.model.color.ColorOptionImpl
import com.android.customization.model.color.ColorOptionsProvider
import com.android.customization.picker.color.shared.model.ColorOptionModel
import com.android.customization.picker.color.shared.model.ColorType
import com.android.systemui.monet.Style
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
class FakeColorPickerRepository(private val context: Context) : ColorPickerRepository {
private val _isApplyingSystemColor = MutableStateFlow(false)
override val isApplyingSystemColor = _isApplyingSystemColor.asStateFlow()
private lateinit var selectedColorOption: ColorOptionModel
private val _colorOptions =
MutableStateFlow(
mapOf<ColorType, List<ColorOptionModel>>(
ColorType.WALLPAPER_COLOR to listOf(),
ColorType.PRESET_COLOR to listOf()
)
)
override val colorOptions: StateFlow<Map<ColorType, List<ColorOptionModel>>> =
_colorOptions.asStateFlow()
init {
setOptions(4, 4, ColorType.WALLPAPER_COLOR, 0)
}
fun setOptions(
wallpaperOptions: List<ColorOptionImpl>,
presetOptions: List<ColorOptionImpl>,
selectedColorOptionType: ColorType,
selectedColorOptionIndex: Int
) {
_colorOptions.value =
mapOf(
ColorType.WALLPAPER_COLOR to
buildList {
for ((index, colorOption) in wallpaperOptions.withIndex()) {
val isSelected =
selectedColorOptionType == ColorType.WALLPAPER_COLOR &&
selectedColorOptionIndex == index
val colorOptionModel =
ColorOptionModel(
key = "${ColorType.WALLPAPER_COLOR}::$index",
colorOption = colorOption,
isSelected = isSelected
)
if (isSelected) {
selectedColorOption = colorOptionModel
}
add(colorOptionModel)
}
},
ColorType.PRESET_COLOR to
buildList {
for ((index, colorOption) in presetOptions.withIndex()) {
val isSelected =
selectedColorOptionType == ColorType.PRESET_COLOR &&
selectedColorOptionIndex == index
val colorOptionModel =
ColorOptionModel(
key = "${ColorType.PRESET_COLOR}::$index",
colorOption = colorOption,
isSelected = isSelected
)
if (isSelected) {
selectedColorOption = colorOptionModel
}
add(colorOptionModel)
}
},
)
}
fun setOptions(
numWallpaperOptions: Int,
numPresetOptions: Int,
selectedColorOptionType: ColorType,
selectedColorOptionIndex: Int
) {
_colorOptions.value =
mapOf(
ColorType.WALLPAPER_COLOR to
buildList {
repeat(times = numWallpaperOptions) { index ->
val isSelected =
selectedColorOptionType == ColorType.WALLPAPER_COLOR &&
selectedColorOptionIndex == index
val colorOption =
ColorOptionModel(
key = "${ColorType.WALLPAPER_COLOR}::$index",
colorOption = buildWallpaperOption(index),
isSelected = isSelected,
)
if (isSelected) {
selectedColorOption = colorOption
}
add(colorOption)
}
},
ColorType.PRESET_COLOR to
buildList {
repeat(times = numPresetOptions) { index ->
val isSelected =
selectedColorOptionType == ColorType.PRESET_COLOR &&
selectedColorOptionIndex == index
val colorOption =
ColorOptionModel(
key = "${ColorType.PRESET_COLOR}::$index",
colorOption = buildPresetOption(index),
isSelected = isSelected,
)
if (isSelected) {
selectedColorOption = colorOption
}
add(colorOption)
}
}
)
}
private fun buildPresetOption(index: Int): ColorOptionImpl {
val builder = ColorOptionImpl.Builder()
builder.lightColors =
intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
builder.darkColors =
intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
builder.index = index
builder.type = ColorType.PRESET_COLOR
builder.source = ColorOptionsProvider.COLOR_SOURCE_PRESET
builder.title = "Preset"
builder
.addOverlayPackage("TEST_PACKAGE_TYPE", "preset_color")
.addOverlayPackage("TEST_PACKAGE_INDEX", "$index")
return builder.build()
}
fun buildPresetOption(style: Style, seedColor: String): ColorOptionImpl {
val builder = ColorOptionImpl.Builder()
builder.lightColors =
intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
builder.darkColors =
intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
builder.type = ColorType.PRESET_COLOR
builder.source = ColorOptionsProvider.COLOR_SOURCE_PRESET
builder.style = style
builder.title = "Preset"
builder
.addOverlayPackage("TEST_PACKAGE_TYPE", "preset_color")
.addOverlayPackage(ResourceConstants.OVERLAY_CATEGORY_SYSTEM_PALETTE, seedColor)
return builder.build()
}
private fun buildWallpaperOption(index: Int): ColorOptionImpl {
val builder = ColorOptionImpl.Builder()
builder.lightColors =
intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
builder.darkColors =
intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
builder.index = index
builder.type = ColorType.WALLPAPER_COLOR
builder.source = ColorOptionsProvider.COLOR_SOURCE_HOME
builder.title = "Dynamic"
builder
.addOverlayPackage("TEST_PACKAGE_TYPE", "wallpaper_color")
.addOverlayPackage("TEST_PACKAGE_INDEX", "$index")
return builder.build()
}
fun buildWallpaperOption(source: String, style: Style, seedColor: String): ColorOptionImpl {
val builder = ColorOptionImpl.Builder()
builder.lightColors =
intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
builder.darkColors =
intArrayOf(Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT, Color.TRANSPARENT)
builder.type = ColorType.WALLPAPER_COLOR
builder.source = source
builder.style = style
builder.title = "Dynamic"
builder
.addOverlayPackage("TEST_PACKAGE_TYPE", "wallpaper_color")
.addOverlayPackage(ResourceConstants.OVERLAY_CATEGORY_SYSTEM_PALETTE, seedColor)
return builder.build()
}
override suspend fun select(colorOptionModel: ColorOptionModel) {
val colorOptions = _colorOptions.value
val wallpaperColorOptions = colorOptions[ColorType.WALLPAPER_COLOR]!!
val newWallpaperColorOptions = buildList {
wallpaperColorOptions.forEach { option ->
add(
ColorOptionModel(
key = option.key,
colorOption = option.colorOption,
isSelected = option.testEquals(colorOptionModel),
)
)
}
}
val basicColorOptions = colorOptions[ColorType.PRESET_COLOR]!!
val newBasicColorOptions = buildList {
basicColorOptions.forEach { option ->
add(
ColorOptionModel(
key = option.key,
colorOption = option.colorOption,
isSelected = option.testEquals(colorOptionModel),
)
)
}
}
_colorOptions.value =
mapOf(
ColorType.WALLPAPER_COLOR to newWallpaperColorOptions,
ColorType.PRESET_COLOR to newBasicColorOptions
)
}
override fun getCurrentColorOption(): ColorOptionModel = selectedColorOption
override fun getCurrentColorSource(): String? =
when ((selectedColorOption.colorOption as ColorOptionImpl).type) {
ColorType.WALLPAPER_COLOR -> ColorOptionsProvider.COLOR_SOURCE_HOME
ColorType.PRESET_COLOR -> ColorOptionsProvider.COLOR_SOURCE_PRESET
else -> null
}
private fun ColorOptionModel.testEquals(other: Any?): Boolean {
if (other == null) {
return false
}
return if (other is ColorOptionModel) {
TextUtils.equals(this.key, other.key)
} else {
false
}
}
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/data/repository/FakeColorPickerRepository.kt | 2313449768 |
/*
* 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.color.data.repository
import android.util.Log
import com.android.customization.model.CustomizationManager
import com.android.customization.model.color.ColorCustomizationManager
import com.android.customization.model.color.ColorOption
import com.android.customization.model.color.ColorOptionImpl
import com.android.customization.picker.color.shared.model.ColorOptionModel
import com.android.customization.picker.color.shared.model.ColorType
import com.android.systemui.monet.Style
import com.android.wallpaper.picker.customization.data.repository.WallpaperColorsRepository
import com.android.wallpaper.picker.customization.shared.model.WallpaperColorsModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.suspendCancellableCoroutine
// TODO (b/262924623): refactor to remove dependency on ColorCustomizationManager & ColorOption
// TODO (b/268203200): Create test for ColorPickerRepositoryImpl
class ColorPickerRepositoryImpl(
wallpaperColorsRepository: WallpaperColorsRepository,
private val colorManager: ColorCustomizationManager,
) : ColorPickerRepository {
private val homeWallpaperColors: StateFlow<WallpaperColorsModel?> =
wallpaperColorsRepository.homeWallpaperColors
private val lockWallpaperColors: StateFlow<WallpaperColorsModel?> =
wallpaperColorsRepository.lockWallpaperColors
private var selectedColorOption: MutableStateFlow<ColorOptionModel> =
MutableStateFlow(getCurrentColorOption())
private val _isApplyingSystemColor = MutableStateFlow(false)
override val isApplyingSystemColor = _isApplyingSystemColor.asStateFlow()
// TODO (b/299510645): update color options on selected option change after restart is disabled
override val colorOptions: Flow<Map<ColorType, List<ColorOptionModel>>> =
combine(homeWallpaperColors, lockWallpaperColors) { homeColors, lockColors ->
homeColors to lockColors
}
.map { (homeColors, lockColors) ->
suspendCancellableCoroutine { continuation ->
if (
homeColors is WallpaperColorsModel.Loading ||
lockColors is WallpaperColorsModel.Loading
) {
continuation.resumeWith(
Result.success(
mapOf(
ColorType.WALLPAPER_COLOR to listOf(),
ColorType.PRESET_COLOR to listOf()
)
)
)
return@suspendCancellableCoroutine
}
val homeColorsLoaded = homeColors as WallpaperColorsModel.Loaded
val lockColorsLoaded = lockColors as WallpaperColorsModel.Loaded
colorManager.setWallpaperColors(
homeColorsLoaded.colors,
lockColorsLoaded.colors
)
colorManager.fetchOptions(
object : CustomizationManager.OptionsFetchedListener<ColorOption?> {
override fun onOptionsLoaded(options: MutableList<ColorOption?>?) {
val wallpaperColorOptions: MutableList<ColorOptionModel> =
mutableListOf()
val presetColorOptions: MutableList<ColorOptionModel> =
mutableListOf()
options?.forEach { option ->
when ((option as ColorOptionImpl).type) {
ColorType.WALLPAPER_COLOR ->
wallpaperColorOptions.add(option.toModel())
ColorType.PRESET_COLOR ->
presetColorOptions.add(option.toModel())
}
}
continuation.resumeWith(
Result.success(
mapOf(
ColorType.WALLPAPER_COLOR to wallpaperColorOptions,
ColorType.PRESET_COLOR to presetColorOptions
)
)
)
}
override fun onError(throwable: Throwable?) {
Log.e(TAG, "Error loading theme bundles", throwable)
continuation.resumeWith(
Result.failure(
throwable ?: Throwable("Error loading theme bundles")
)
)
}
},
/* reload= */ false
)
}
}
override suspend fun select(colorOptionModel: ColorOptionModel) {
_isApplyingSystemColor.value = true
suspendCancellableCoroutine { continuation ->
colorManager.apply(
colorOptionModel.colorOption,
object : CustomizationManager.Callback {
override fun onSuccess() {
_isApplyingSystemColor.value = false
selectedColorOption.value = colorOptionModel
continuation.resumeWith(Result.success(Unit))
}
override fun onError(throwable: Throwable?) {
Log.w(TAG, "Apply theme with error", throwable)
_isApplyingSystemColor.value = false
continuation.resumeWith(
Result.failure(throwable ?: Throwable("Error loading theme bundles"))
)
}
}
)
}
}
override fun getCurrentColorOption(): ColorOptionModel {
val overlays = colorManager.currentOverlays
val styleOrNull = colorManager.currentStyle
val style = styleOrNull?.let {
try {
Style.valueOf(it)
} catch (e: IllegalArgumentException) {
Style.TONAL_SPOT
}
} ?: Style.TONAL_SPOT
val source = colorManager.currentColorSource
val colorOptionBuilder = ColorOptionImpl.Builder()
colorOptionBuilder.source = source
colorOptionBuilder.style = style
for (overlay in overlays) {
colorOptionBuilder.addOverlayPackage(overlay.key, overlay.value)
}
val colorOption = colorOptionBuilder.build()
return ColorOptionModel(
key = "",
colorOption = colorOption,
isSelected = false,
)
}
override fun getCurrentColorSource(): String? {
return colorManager.currentColorSource
}
private fun ColorOptionImpl.toModel(): ColorOptionModel {
return ColorOptionModel(
key = "${this.type}::${this.style}::${this.serializedPackages}",
colorOption = this,
isSelected = isActive(colorManager),
)
}
companion object {
private const val TAG = "ColorPickerRepositoryImpl"
}
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/data/repository/ColorPickerRepositoryImpl.kt | 2583040868 |
/*
* 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.color.data.repository
import com.android.customization.picker.color.shared.model.ColorOptionModel
import com.android.customization.picker.color.shared.model.ColorType
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
/**
* Abstracts access to application state related to functionality for selecting, picking, or setting
* system color.
*/
interface ColorPickerRepository {
/** Whether the system color is in the process of being updated */
val isApplyingSystemColor: StateFlow<Boolean>
/** List of wallpaper and preset color options on the device, categorized by Color Type */
val colorOptions: Flow<Map<ColorType, List<ColorOptionModel>>>
/** Selects a color option with optimistic update */
suspend fun select(colorOptionModel: ColorOptionModel)
/** Returns the current selected color option based on system settings */
fun getCurrentColorOption(): ColorOptionModel
/** Returns the current selected color source based on system settings */
fun getCurrentColorSource(): String?
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/data/repository/ColorPickerRepository.kt | 2160479465 |
/*
* 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.color.domain.interactor
import android.util.Log
import com.android.customization.picker.color.shared.model.ColorOptionModel
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 color picker system. */
class ColorPickerSnapshotRestorer(
private val interactor: ColorPickerInteractor,
) : SnapshotRestorer {
private var snapshotStore: SnapshotStore = SnapshotStore.NOOP
private var originalOption: ColorOptionModel? = null
fun storeSnapshot(colorOptionModel: ColorOptionModel) {
snapshotStore.store(snapshot(colorOptionModel))
}
override suspend fun setUpSnapshotRestorer(
store: SnapshotStore,
): RestorableSnapshot {
snapshotStore = store
originalOption = interactor.getCurrentColorOption()
return snapshot(originalOption)
}
override suspend fun restoreToSnapshot(snapshot: RestorableSnapshot) {
val optionPackagesFromSnapshot: String? = snapshot.args[KEY_COLOR_OPTION_PACKAGES]
originalOption?.let { optionToRestore ->
if (
optionToRestore.colorOption.serializedPackages != optionPackagesFromSnapshot ||
optionToRestore.colorOption.style.toString() !=
snapshot.args[KEY_COLOR_OPTION_STYLE]
) {
Log.wtf(
TAG,
""" Original packages does not match snapshot packages to restore to. The
| current implementation doesn't support undo, only a reset back to the
| original color option."""
.trimMargin(),
)
}
interactor.select(optionToRestore)
}
}
private fun snapshot(colorOptionModel: ColorOptionModel? = null): RestorableSnapshot {
val snapshotMap = mutableMapOf<String, String>()
colorOptionModel?.let {
snapshotMap[KEY_COLOR_OPTION_PACKAGES] = colorOptionModel.colorOption.serializedPackages
snapshotMap[KEY_COLOR_OPTION_STYLE] = colorOptionModel.colorOption.style.toString()
}
return RestorableSnapshot(snapshotMap)
}
companion object {
private const val TAG = "ColorPickerSnapshotRestorer"
private const val KEY_COLOR_OPTION_PACKAGES = "color_packages"
private const val KEY_COLOR_OPTION_STYLE = "color_style"
}
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/domain/interactor/ColorPickerSnapshotRestorer.kt | 988838282 |
/*
* 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.color.domain.interactor
import com.android.customization.picker.color.data.repository.ColorPickerRepository
import com.android.customization.picker.color.shared.model.ColorOptionModel
import javax.inject.Provider
import kotlinx.coroutines.flow.MutableStateFlow
/** Single entry-point for all application state and business logic related to system color. */
class ColorPickerInteractor(
private val repository: ColorPickerRepository,
private val snapshotRestorer: Provider<ColorPickerSnapshotRestorer>,
) {
val isApplyingSystemColor = repository.isApplyingSystemColor
/**
* The newly selected color option for overwriting the current active option during an
* optimistic update, the value is set to null when update fails
*/
val activeColorOption = MutableStateFlow<ColorOptionModel?>(null)
/** List of wallpaper and preset color options on the device, categorized by Color Type */
val colorOptions = repository.colorOptions
suspend fun select(colorOptionModel: ColorOptionModel) {
activeColorOption.value = colorOptionModel
try {
repository.select(colorOptionModel)
snapshotRestorer.get().storeSnapshot(colorOptionModel)
} catch (e: Exception) {
activeColorOption.value = null
}
}
fun getCurrentColorOption(): ColorOptionModel = repository.getCurrentColorOption()
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/color/domain/interactor/ColorPickerInteractor.kt | 2864559832 |
/*
* 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.common.ui.view
import android.graphics.Rect
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView
/** Item spacing used by the RecyclerView. */
class ItemSpacing(
private val itemSpacingDp: Int,
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, itemPosition: Int, parent: RecyclerView) {
val addSpacingToStart = itemPosition > 0
val addSpacingToEnd = itemPosition < (parent.adapter?.itemCount ?: 0) - 1
val isRtl = parent.layoutManager?.layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL
val density = parent.context.resources.displayMetrics.density
val halfItemSpacingPx = itemSpacingDp.toPx(density) / 2
if (!isRtl) {
outRect.left = if (addSpacingToStart) halfItemSpacingPx else 0
outRect.right = if (addSpacingToEnd) halfItemSpacingPx else 0
} else {
outRect.left = if (addSpacingToEnd) halfItemSpacingPx else 0
outRect.right = if (addSpacingToStart) halfItemSpacingPx else 0
}
}
private fun Int.toPx(density: Float): Int {
return (this * density).toInt()
}
companion object {
const val TAB_ITEM_SPACING_DP = 12
const val ITEM_SPACING_DP = 8
}
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/common/ui/view/ItemSpacing.kt | 3808134388 |
/*
* 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.viewmodel
import android.app.WallpaperColors
import android.os.Bundle
import com.android.customization.model.themedicon.domain.interactor.ThemedIconInteractor
import com.android.customization.picker.color.domain.interactor.ColorPickerInteractor
import com.android.wallpaper.model.WallpaperInfo
import com.android.wallpaper.module.CustomizationSections
import com.android.wallpaper.picker.customization.domain.interactor.WallpaperInteractor
import com.android.wallpaper.picker.customization.ui.viewmodel.ScreenPreviewViewModel
import com.android.wallpaper.util.PreviewUtils
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
/** A ThemePicker version of the [ScreenPreviewViewModel] */
class PreviewWithThemeViewModel(
previewUtils: PreviewUtils,
initialExtrasProvider: () -> Bundle? = { null },
wallpaperInfoProvider: suspend (forceReload: Boolean) -> WallpaperInfo?,
onWallpaperColorChanged: (WallpaperColors?) -> Unit = {},
wallpaperInteractor: WallpaperInteractor,
private val themedIconInteractor: ThemedIconInteractor? = null,
colorPickerInteractor: ColorPickerInteractor? = null,
screen: CustomizationSections.Screen,
) :
ScreenPreviewViewModel(
previewUtils,
initialExtrasProvider,
wallpaperInfoProvider,
onWallpaperColorChanged,
wallpaperInteractor,
screen,
) {
override fun workspaceUpdateEvents(): Flow<Boolean>? = themedIconInteractor?.isActivated
private val wallpaperIsLoading = super.isLoading
override val isLoading: Flow<Boolean> =
colorPickerInteractor?.let {
combine(wallpaperIsLoading, colorPickerInteractor.isApplyingSystemColor) {
wallpaperIsLoading,
colorIsLoading ->
wallpaperIsLoading || colorIsLoading
}
}
?: wallpaperIsLoading
}
| android_packages_apps_ThemePicker/src/com/android/customization/picker/preview/ui/viewmodel/PreviewWithThemeViewModel.kt | 1820215122 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.