content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.avicodes.calorietrackerai.presentation.screens.history
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.avicodes.calorietrackerai.models.Meals
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class HistoryViewModel @Inject constructor() : ViewModel() {
var meals: MutableState<Meals> = mutableStateOf(mapOf())
var dateIsSelected by mutableStateOf(false)
private set
} | AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/screens/history/HistoryViewModel.kt | 2915975510 |
package com.avicodes.calorietrackerai.presentation.screens.history
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.runtime.Composable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.ui.unit.dp
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import com.avicodes.calorietrackerai.models.Meal
import com.avicodes.calorietrackerai.presentation.components.MealHolder
import java.time.LocalDate
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HistoryContent(
paddingValues: PaddingValues,
meals: Map<LocalDate, List<Meal>>,
onClick: (String) -> Unit
) {
if (meals.isNotEmpty()) {
LazyColumn(
modifier = Modifier
.padding(horizontal = 24.dp)
.navigationBarsPadding()
.padding(top = paddingValues.calculateTopPadding())
) {
meals.forEach { (localDate, meal) ->
stickyHeader(key = localDate) {
DateHeader(localDate = localDate)
}
items(
items = meal,
key = { it.id }
) {
MealHolder(meal = it, onClick = onClick)
}
}
}
} else {
EmptyPage()
}
}
@Composable
fun DateHeader(localDate: LocalDate) {
Row(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surface)
.padding(vertical = 14.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(horizontalAlignment = Alignment.End) {
Text(
text = String.format("%02d", localDate.dayOfMonth),
style = TextStyle(
fontSize = MaterialTheme.typography.titleLarge.fontSize,
fontWeight = FontWeight.Light
)
)
Text(
text = localDate.dayOfWeek.toString().take(3),
style = TextStyle(
fontSize = MaterialTheme.typography.bodySmall.fontSize,
fontWeight = FontWeight.Light
)
)
}
Spacer(modifier = Modifier.width(14.dp))
Column(horizontalAlignment = Alignment.Start) {
Text(
text = localDate.month.toString().lowercase()
.replaceFirstChar { it.titlecase() },
style = TextStyle(
fontSize = MaterialTheme.typography.titleLarge.fontSize,
fontWeight = FontWeight.Light
)
)
Text(
text = "${localDate.year}",
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f),
style = TextStyle(
fontSize = MaterialTheme.typography.bodySmall.fontSize,
fontWeight = FontWeight.Light
)
)
}
}
}
@Composable
fun EmptyPage(
title: String = "No Meals!",
subtitle: String = "Start Uploading your diet"
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(all = 24.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = title,
style = TextStyle(
fontSize = MaterialTheme.typography.titleMedium.fontSize,
fontWeight = FontWeight.Medium
)
)
Text(
text = subtitle,
style = TextStyle(
fontSize = MaterialTheme.typography.bodyMedium.fontSize,
fontWeight = FontWeight.Normal
)
)
}
}
@Composable
@Preview(showBackground = true)
fun DateHeaderPreview() {
DateHeader(localDate = LocalDate.now())
} | AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/screens/history/HistoryContent.kt | 4086603810 |
package com.avicodes.calorietrackerai.presentation.screens.upload
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import com.avicodes.calorietrackerai.models.Meal
import com.avicodes.calorietrackerai.presentation.components.DisplayAlertDialog
import com.avicodes.calorietrackerai.presentation.screens.history.BackButton
import com.avicodes.calorietrackerai.presentation.screens.history.DateRangeButton
import com.maxkeppeker.sheets.core.models.base.rememberSheetState
import com.maxkeppeler.sheets.calendar.CalendarDialog
import com.maxkeppeler.sheets.calendar.models.CalendarConfig
import com.maxkeppeler.sheets.calendar.models.CalendarSelection
import com.maxkeppeler.sheets.clock.ClockDialog
import com.maxkeppeler.sheets.clock.models.ClockSelection
import java.time.LocalDate
import java.time.LocalTime
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UploadTopBar(
selectedMeal: Meal?,
mealName: () -> String,
onDateTimeUpdated: (ZonedDateTime) -> Unit,
onDeleteConfirmed: () -> Unit,
onBackPressed: () -> Unit
) {
val dateDialog = rememberSheetState()
val timeDialog = rememberSheetState()
var currentDate by remember { mutableStateOf(LocalDate.now()) }
var currentTime by remember { mutableStateOf(LocalTime.now()) }
val formattedDate = remember(key1 = currentDate) {
DateTimeFormatter
.ofPattern("dd MMM yyyy")
.format(currentDate).uppercase()
}
val formattedTime = remember(key1 = currentTime) {
DateTimeFormatter
.ofPattern("hh:mm a")
.format(currentTime).uppercase()
}
val selectedMealDateTime = remember(selectedMeal) {
if (selectedMeal != null) {
// DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a", Locale.getDefault())
// .withZone(ZoneId.systemDefault())
// .format(selectedMeal.date)
} else "Unknown"
}
var dateTimeUpdated by remember { mutableStateOf(false) }
CenterAlignedTopAppBar(
navigationIcon = {
BackButton { onBackPressed }
},
title = {
Column {
Text(
modifier = Modifier.fillMaxWidth(),
text = mealName(),
style = TextStyle(
fontSize = MaterialTheme.typography.titleLarge.fontSize,
fontWeight = FontWeight.Bold
),
textAlign = TextAlign.Center
)
Text(
modifier = Modifier.fillMaxWidth(),
style = TextStyle(fontSize = MaterialTheme.typography.bodySmall.fontSize),
textAlign = TextAlign.Center,
text = if (selectedMeal != null && dateTimeUpdated) "$formattedDate, $formattedTime"
else if (selectedMeal != null) "$selectedMealDateTime"
else "$formattedDate, $formattedTime",
)
}
},
actions = {
if (dateTimeUpdated) {
IconButton(onClick = {
currentDate = LocalDate.now()
currentTime = LocalTime.now()
dateTimeUpdated = false
onDateTimeUpdated(
ZonedDateTime.of(
currentDate,
currentTime,
ZoneId.systemDefault()
)
)
}) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Close Icon",
tint = MaterialTheme.colorScheme.onSurface
)
}
} else {
DateRangeButton { dateDialog.show() }
}
if (selectedMeal != null) {
DeleteDiaryAction(
onDeleteConfirmed = onDeleteConfirmed
)
}
}
)
CalendarDialog(
state = dateDialog,
selection = CalendarSelection.Date { date: LocalDate ->
currentDate = date
timeDialog.show()
},
config = CalendarConfig(monthSelection = true, yearSelection = true)
)
ClockDialog(
state = dateDialog,
selection = ClockSelection.HoursMinutes { hours, minutes ->
currentTime = LocalTime.of(hours, minutes)
dateTimeUpdated = true
onDateTimeUpdated(
ZonedDateTime.of(
currentDate,
currentTime,
ZoneId.systemDefault()
)
)
},
)
}
@Composable
fun DeleteDiaryAction(
onDeleteConfirmed: () -> Unit
) {
var expanded by remember { mutableStateOf(false) }
var openDialog by remember { mutableStateOf(false) }
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
DropdownMenuItem(
text = {
Text(text = "Delete")
}, onClick = {
openDialog = true
expanded = false
}
)
}
DisplayAlertDialog(
title = "Delete",
message = "Are you sure you want to permanently delete this meal?",
dialogOpened = openDialog,
onDialogClosed = { openDialog = false },
onYesClicked = onDeleteConfirmed
)
IconButton(onClick = { expanded = !expanded }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = "Overflow Menu Icon",
tint = MaterialTheme.colorScheme.onSurface
)
}
} | AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/screens/upload/UploadTopBar.kt | 2073681987 |
package com.avicodes.calorietrackerai.presentation.screens.upload
import android.graphics.Bitmap
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.avicodes.calorietrackerai.BuildConfig
import com.avicodes.calorietrackerai.models.Meal
import com.avicodes.calorietrackerai.models.MealName
import com.avicodes.calorietrackerai.utils.getCurrentMeal
import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.content
import com.google.ai.client.generativeai.type.generationConfig
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import java.time.Instant
import javax.inject.Inject
@HiltViewModel
class UploadViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle,
) : ViewModel() {
private var _uploadUiState: UploadUiState by mutableStateOf(UploadUiState())
val uploadUiState get() = _uploadUiState
private var _calorieGenState: CalorieGenState by mutableStateOf(CalorieGenState.Idle)
val calorieGenState get() = _calorieGenState
private var generativeModel: GenerativeModel
init {
val config = generationConfig {
temperature = 0.1f
}
generativeModel = GenerativeModel(
modelName = "gemini-pro-vision",
apiKey = BuildConfig.gemini_api_key,
generationConfig = config
)
}
fun changeDescription(desc: String) {
_uploadUiState = _uploadUiState.copy(description = desc)
}
fun addPhoto(images: List<Bitmap>) {
val calorie = if (images.isEmpty()) null else _uploadUiState.calories
_uploadUiState = _uploadUiState.copy(images = images, calories = calorie)
}
suspend fun requestCalories(selectedImages: List<Bitmap>) {
_calorieGenState = CalorieGenState.Fetching(startImageLoop(selectedImages))
val prompt =
"Exactly how much calories does this food is? if its a packet, then search the calorie of food according to packet size, if its some utensil container, take that in account to calculate the precise calorie. give the exact calorie count, in numbers, only give me number, no other text"
var output = ""
viewModelScope.launch(Dispatchers.IO) {
try {
val content = content {
for (bitmap in selectedImages) {
image(bitmap)
}
text(prompt)
}
generativeModel.generateContentStream(content).collect { res ->
output += res.text
_uploadUiState = _uploadUiState.copy(calories = output)
_calorieGenState = CalorieGenState.Idle
}
} catch (e: Exception) {
_calorieGenState = CalorieGenState.Error(e.message.toString())
}
}
}
private fun startImageLoop(images: List<Bitmap>): Flow<Bitmap> = flow {
while (_calorieGenState is CalorieGenState.Fetching) {
for (bitmap in images) {
emit(bitmap)
delay(2000)
}
}
}
}
sealed class CalorieGenState {
data class Fetching(var bitmapFlow: Flow<Bitmap>) : CalorieGenState()
data object Idle : CalorieGenState()
data class Error(val message: String) : CalorieGenState()
}
data class UploadUiState(
var calories: String? = null,
var selectedMeal: Meal? = null,
var description: String = "",
val mealName: MealName = getCurrentMeal(),
var images: List<Bitmap> = listOf(),
val updatedDateTime: Instant? = null
)
| AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/screens/upload/UploadViewModel.kt | 1779063751 |
package com.avicodes.calorietrackerai.presentation.screens.upload
import android.graphics.Bitmap
import android.net.Uri
import androidx.compose.animation.AnimatedVisibility
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.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
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.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition
import com.avicodes.calorietrackerai.R
import com.avicodes.calorietrackerai.models.MealName
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.PagerState
import java.time.ZonedDateTime
@OptIn(ExperimentalPagerApi::class)
@Composable
fun UploadScreen(
uiState: UploadUiState,
calorieGenState: CalorieGenState,
pagerState: PagerState,
mealName: () -> String,
onDescriptionChanged: (String) -> Unit,
onDeleteConfirmed: () -> Unit,
onBackPressed: () -> Unit,
onSaveClicked: () -> Unit,
onDateTimeUpdated: (ZonedDateTime) -> Unit,
onImageSelect: (List<Uri>) -> Unit,
onImageDeleteClicked: (Bitmap) -> Unit
) {
var selectedGalleryImage by remember { mutableStateOf<Bitmap?>(null) }
LaunchedEffect(key1 = uiState.mealName) {
pagerState.scrollToPage(MealName.valueOf(uiState.mealName.name).ordinal)
}
Scaffold(
topBar = {
UploadTopBar(
onDeleteConfirmed = onDeleteConfirmed,
selectedMeal = uiState.selectedMeal,
mealName = mealName,
onBackPressed = onBackPressed,
onDateTimeUpdated = onDateTimeUpdated
)
},
content = { paddingValues ->
UploadContent(
uploadUiState = uiState,
pagerState = pagerState,
onDescriptionChanged = onDescriptionChanged,
paddingValues = paddingValues,
onSaveClicked = onSaveClicked,
onImageSelect = onImageSelect,
onImageClicked = { selectedGalleryImage = it }
)
}
)
when (calorieGenState) {
is CalorieGenState.Fetching -> {
val bitmapFlow = calorieGenState.bitmapFlow
val bitmap by bitmapFlow.collectAsState(initial = null)
if (bitmap != null) {
ImageDialog(
isGenerating = true,
selectedGalleryImage = bitmap,
onDismiss = { },
onImageDeleteClicked = { }
)
}
}
else -> {}
}
AnimatedVisibility(visible = selectedGalleryImage != null) {
ImageDialog(
selectedGalleryImage = selectedGalleryImage,
onDismiss = { selectedGalleryImage = null },
onImageDeleteClicked = onImageDeleteClicked
)
}
}
@Composable
fun ImageDialog(
isGenerating: Boolean = false,
selectedGalleryImage: Bitmap?,
onDismiss: () -> Unit,
onImageDeleteClicked: (Bitmap) -> Unit,
) {
Dialog(onDismissRequest = { onDismiss.invoke() }) {
if (selectedGalleryImage != null) {
DisplayImage(
isGenerating = isGenerating,
selectedGalleryImage = selectedGalleryImage,
onCloseClicked = { onDismiss.invoke() },
onDeleteClicked = {
if (selectedGalleryImage != null) {
onImageDeleteClicked(selectedGalleryImage)
onDismiss.invoke()
}
}
)
}
}
}
@Composable
fun DisplayImage(
isGenerating: Boolean,
selectedGalleryImage: Bitmap,
onCloseClicked: () -> Unit,
onDeleteClicked: () -> Unit
) {
Column {
if (!isGenerating) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp)
.padding(top = 24.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Button(onClick = onCloseClicked) {
Icon(imageVector = Icons.Default.Close, contentDescription = "Close Icon")
Text(text = "Close")
}
Button(onClick = onDeleteClicked) {
Icon(imageVector = Icons.Default.Delete, contentDescription = "Delete Icon")
Text(text = "Delete")
}
}
}
Box(
modifier = Modifier
) {
AsyncImage(
modifier = Modifier
.padding(40.dp)
.fillMaxSize(),
model = ImageRequest.Builder(LocalContext.current)
.data(selectedGalleryImage)
.crossfade(true)
.build(),
contentScale = ContentScale.Fit,
contentDescription = "Gallery Image"
)
if (isGenerating) {
val animationFoodComposition by rememberLottieComposition(
spec = LottieCompositionSpec.RawRes(R.raw.animation_scanning)
)
LottieAnimation(
composition = animationFoodComposition,
iterations = LottieConstants.IterateForever,
modifier = Modifier.fillMaxSize()
)
}
}
}
} | AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/screens/upload/UploadScreen.kt | 1130157439 |
package com.avicodes.calorietrackerai.presentation.screens.upload
import android.graphics.Bitmap
import android.net.Uri
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Shapes
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.avicodes.calorietrackerai.models.GalleryImage
import com.avicodes.calorietrackerai.models.GalleryState
import com.avicodes.calorietrackerai.models.Meal
import com.avicodes.calorietrackerai.models.MealName
import com.avicodes.calorietrackerai.presentation.components.GalleryUploader
import kotlinx.coroutines.launch
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.PagerState
@OptIn(ExperimentalPagerApi::class)
@Composable
fun UploadContent(
uploadUiState: UploadUiState,
pagerState: PagerState,
onDescriptionChanged: (String) -> Unit,
paddingValues: PaddingValues,
onSaveClicked: () -> Unit,
onImageSelect: (List<Uri>) -> Unit,
onImageClicked: (Bitmap) -> Unit
) {
val scrollState = rememberScrollState()
val context = LocalContext.current
val focusManager = LocalFocusManager.current
LaunchedEffect(key1 = scrollState.maxValue) {
scrollState.scrollTo(scrollState.maxValue)
}
Column(
modifier = Modifier
.fillMaxSize()
.imePadding()
.navigationBarsPadding()
.padding(top = paddingValues.calculateTopPadding())
.padding(bottom = 24.dp)
.padding(horizontal = 24.dp),
verticalArrangement = Arrangement.SpaceBetween
) {
Column(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.verticalScroll(state = scrollState)
) {
Spacer(modifier = Modifier.height(30.dp))
HorizontalPager(
state = pagerState,
count = MealName.entries.size
) { page ->
AsyncImage(
modifier = Modifier.size(120.dp),
model = ImageRequest.Builder(LocalContext.current)
.data(MealName.entries[page].icon)
.crossfade(true)
.build(),
contentDescription = "Meal Image"
)
}
Spacer(modifier = Modifier.height(30.dp))
if(uploadUiState.calories != null) {
Card(
modifier = Modifier
.padding(vertical = 16.dp)
.fillMaxWidth(),
shape = MaterialTheme.shapes.medium,
) {
Text(
text = "${uploadUiState.calories} Calories",
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
textAlign = TextAlign.Center
)
}
}
TextField(
modifier = Modifier.fillMaxWidth(),
value = uploadUiState.description,
onValueChange = onDescriptionChanged,
placeholder = { Text(text = "Tell me about it.") },
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Unspecified,
disabledIndicatorColor = Color.Unspecified,
unfocusedIndicatorColor = Color.Unspecified,
focusedPlaceholderColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f),
unfocusedPlaceholderColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
),
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Next
),
keyboardActions = KeyboardActions(
onNext = {
focusManager.clearFocus()
}
)
)
}
Column(verticalArrangement = Arrangement.Bottom) {
Spacer(modifier = Modifier.height(12.dp))
GalleryUploader(
images = uploadUiState.images,
onAddClicked = {
focusManager.clearFocus()
},
onImageSelect = onImageSelect,
onImageClicked = onImageClicked
)
Spacer(modifier = Modifier.height(12.dp))
Button(
modifier = Modifier
.fillMaxWidth()
.height(54.dp),
onClick = {
if (uploadUiState.calories != null && uploadUiState.description.isNotEmpty()) {
onSaveClicked()
} else {
Toast.makeText(
context,
"Fields cannot be empty.",
Toast.LENGTH_SHORT
).show()
}
},
shape = Shapes().small
) {
Text(text = "Save")
}
}
}
} | AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/screens/upload/UploadContent.kt | 3453305964 |
package com.avicodes.calorietrackerai.presentation.components
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.text.font.FontWeight
@Composable
fun DisplayAlertDialog(
title: String,
message: String,
dialogOpened: Boolean,
onDialogClosed: () -> Unit,
onYesClicked: () -> Unit,
) {
if (dialogOpened) {
AlertDialog(
title = {
Text(
text = title,
fontSize = MaterialTheme.typography.headlineSmall.fontSize,
fontWeight = FontWeight.Bold
)
},
text = {
Text(
text = message,
fontSize = MaterialTheme.typography.bodyMedium.fontSize,
fontWeight = FontWeight.Normal
)
},
confirmButton = {
Button(
onClick = {
onYesClicked()
onDialogClosed()
})
{
Text(text = "Yes")
}
},
dismissButton = {
OutlinedButton(onClick = onDialogClosed)
{
Text(text = "No")
}
},
onDismissRequest = onDialogClosed
)
}
} | AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/components/AlertDialog.kt | 2774081613 |
package com.avicodes.calorietrackerai.presentation.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
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.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
fun RowScope.CalorieTitleValueColumn(
title: String,
value: String
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.weight(1f)
) {
Text(
text = title,
color = MaterialTheme.colorScheme.primary,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Bold
)
Text(
text = value,
style = MaterialTheme.typography.headlineSmall,
modifier = Modifier.padding(vertical = 8.dp),
fontWeight = FontWeight.Bold
)
}
}
@Composable
fun CalorieProgressInfo() {
Row(
modifier = Modifier
.fillMaxWidth()
.height(IntrinsicSize.Min)
) {
CalorieTitleValueColumn(title = "CURRENT", value = "200")
VerticalDivider()
CalorieTitleValueColumn(title = "GOAL", value = "1000")
}
} | AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/components/InfoColumn.kt | 3530153806 |
package com.avicodes.calorietrackerai.presentation.components
import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CornerBasedShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Shapes
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.avicodes.calorietrackerai.models.GalleryImage
import com.avicodes.calorietrackerai.models.GalleryState
import com.avicodes.calorietrackerai.ui.theme.Elevation
import kotlin.math.max
@Composable
fun Gallery(
modifier: Modifier = Modifier,
images: List<Uri>,
imageSize: Dp = 40.dp,
spaceBetween: Dp = 10.dp,
imageShape: CornerBasedShape = Shapes().small
) {
BoxWithConstraints(modifier = modifier) {
val numberOfVisibleImages = remember {
derivedStateOf {
max(
a = 0,
b = this.maxWidth.div(spaceBetween + imageSize).toInt().minus(1)
)
}
}
val remainingImages =
remember { derivedStateOf { images.size - numberOfVisibleImages.value } }
Row {
images.take(numberOfVisibleImages.value).forEach { image ->
AsyncImage(
modifier = Modifier
.clip(imageShape)
.size(imageSize),
model = ImageRequest.Builder(LocalContext.current)
.data(image)
.crossfade(true)
.build(),
contentScale = ContentScale.Crop,
contentDescription = "Gallery Image"
)
Spacer(modifier = Modifier.width(spaceBetween))
}
if (remainingImages.value > 0) {
LastImageOverlay(
imageSize = imageSize,
imageShape = imageShape,
remainingImages = remainingImages.value
)
}
}
}
}
@Composable
fun GalleryUploader(
modifier: Modifier = Modifier,
images: List<Bitmap>,
imageSize: Dp = 60.dp,
imageShape: CornerBasedShape = Shapes().medium,
spaceBetween: Dp = 12.dp,
onAddClicked: () -> Unit,
onImageSelect: (List<Uri>) -> Unit,
onImageClicked: (Bitmap) -> Unit,
) {
BoxWithConstraints(modifier = modifier) {
val numberOfVisibleImages = remember(images) {
derivedStateOf {
max(
a = 0,
b = this.maxWidth.div(spaceBetween + imageSize).toInt().minus(2)
)
}
}
val remainingImages = remember(images) {
derivedStateOf {
images.size - numberOfVisibleImages.value
}
}
Log.e("Avneet", "${images.size.toString()} $numberOfVisibleImages $remainingImages")
Row {
AddImageButton(
onImageSelect = onImageSelect,
imageSize = imageSize,
imageShape = imageShape,
onAddClicked = onAddClicked,
images = images
)
Spacer(modifier = Modifier.width(spaceBetween))
images.take(numberOfVisibleImages.value).forEach { galleryImage ->
AsyncImage(
modifier = Modifier
.clip(imageShape)
.size(imageSize)
.clickable { onImageClicked(galleryImage) },
model = ImageRequest.Builder(LocalContext.current)
.data(galleryImage)
.crossfade(true)
.build(),
contentScale = ContentScale.Crop,
contentDescription = "Gallery Image"
)
Spacer(modifier = Modifier.width(spaceBetween))
}
if (remainingImages.value > 0) {
LastImageOverlay(
imageSize = imageSize,
imageShape = imageShape,
remainingImages = remainingImages.value
)
}
}
}
}
@Composable
fun AddImageButton(
onImageSelect: (List<Uri>) -> Unit,
images: List<Bitmap>,
imageSize: Dp,
imageShape: CornerBasedShape,
onAddClicked: () -> Unit
) {
val multiplePhotoPicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickMultipleVisualMedia(maxItems = 8),
) { images ->
onImageSelect(images)
}
Surface(
modifier = Modifier
.size(imageSize)
.clip(shape = imageShape),
onClick = {
if(images.isEmpty()) {
onAddClicked()
multiplePhotoPicker.launch(
PickVisualMediaRequest(
ActivityResultContracts.PickVisualMedia.ImageOnly
)
)
} else {
onImageSelect(listOf())
onAddClicked()
}
},
tonalElevation = Elevation.Level1
) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Icon(
imageVector = if(images.isEmpty()) Icons.Default.Add else Icons.Default.Close,
contentDescription = "Add Icon",
)
}
}
}
@Composable
fun LastImageOverlay(
imageSize: Dp,
imageShape: CornerBasedShape,
remainingImages: Int
) {
Box(contentAlignment = Alignment.Center) {
Surface(
modifier = Modifier
.clip(imageShape)
.size(imageSize),
color = MaterialTheme.colorScheme.primaryContainer
) {}
Text(
text = "+$remainingImages",
style = TextStyle(
fontSize = MaterialTheme.typography.bodyLarge.fontSize,
fontWeight = FontWeight.Medium
),
color = MaterialTheme.colorScheme.onPrimaryContainer
)
}
} | AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/components/Gallery.kt | 1559197516 |
package com.avicodes.calorietrackerai.presentation.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun VerticalDivider() {
Box(
modifier = Modifier
.fillMaxHeight()
.background(color = MaterialTheme.colorScheme.primary)
.width(1.dp)
)
} | AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/components/VerticalDivider.kt | 3100703692 |
package com.avicodes.calorietrackerai.presentation.components
import android.net.Uri
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.material3.MaterialTheme
import androidx.compose.material3.Shapes
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
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.clip
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.avicodes.calorietrackerai.models.Meal
import com.avicodes.calorietrackerai.models.MealName
import com.avicodes.calorietrackerai.ui.theme.Elevation
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
@Composable
fun MealHolder(meal: Meal, onClick: (String) -> Unit) {
val localDensity = LocalDensity.current
var galleryOpened by remember { mutableStateOf(false) }
var galleryLoading by remember { mutableStateOf(false) }
val downloadedImages = remember { mutableStateListOf<Uri>() }
var componentHeight by remember { mutableStateOf(0.dp) }
val context = LocalContext.current
Row(modifier = Modifier
.clickable(
indication = null,
interactionSource = remember {
MutableInteractionSource()
}
) { onClick(meal.id) }
) {
Spacer(modifier = Modifier.width(14.dp))
Surface(
modifier = Modifier
.width(2.dp)
.height(componentHeight + 14.dp),
tonalElevation = Elevation.Level1
) {}
Spacer(modifier = Modifier.width(20.dp))
Surface(
modifier = Modifier
.clip(shape = Shapes().medium)
.onGloballyPositioned {
componentHeight = with(localDensity) { it.size.height.toDp() }
},
tonalElevation = Elevation.Level1
) {
Column(modifier = Modifier.fillMaxWidth()) {
DiaryHeader(mealName = meal.mealName, time = Instant.now())
Text(
modifier = Modifier.padding(all = 14.dp),
text = meal.description,
style = TextStyle(fontSize = MaterialTheme.typography.bodyLarge.fontSize),
maxLines = 4,
overflow = TextOverflow.Ellipsis
)
if (meal.images.isNotEmpty()) {
ShowGalleryButton(
galleryOpened = galleryOpened,
onClick = {
galleryOpened = !galleryOpened
},
galleryLoading = galleryLoading
)
}
AnimatedVisibility(
visible = galleryOpened && !galleryLoading,
enter = fadeIn() + expandVertically(
animationSpec = spring(
dampingRatio = Spring.DampingRatioMediumBouncy,
stiffness = Spring.StiffnessLow
)
)
) {
Column(modifier = Modifier.padding(all = 14.dp)) {
Gallery(images = downloadedImages)
}
}
}
}
}
}
@Composable
fun DiaryHeader(mealName: String, time: Instant) {
val mood by remember { mutableStateOf(MealName.valueOf(mealName)) }
val formatter = remember {
DateTimeFormatter.ofPattern("hh:mm a", Locale.getDefault())
.withZone(ZoneId.systemDefault())
}
Row(
modifier = Modifier
.fillMaxWidth()
.background(mood.containerColor)
.padding(horizontal = 14.dp, vertical = 7.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Image(
modifier = Modifier.size(18.dp),
painter = painterResource(id = mood.icon),
contentDescription = "Mood Icon",
)
Spacer(modifier = Modifier.width(7.dp))
Text(
text = mood.name,
color = mood.contentColor,
style = TextStyle(fontSize = MaterialTheme.typography.bodyMedium.fontSize)
)
}
Text(
text = formatter.format(time),
color = mood.contentColor,
style = TextStyle(fontSize = MaterialTheme.typography.bodyMedium.fontSize)
)
}
}
@Composable
fun ShowGalleryButton(
galleryOpened: Boolean,
galleryLoading: Boolean,
onClick: () -> Unit
) {
TextButton(onClick = onClick) {
Text(
text = if (galleryOpened)
if (galleryLoading) "Loading" else "Hide Gallery"
else "Show Gallery",
style = TextStyle(fontSize = MaterialTheme.typography.bodySmall.fontSize)
)
}
}
| AI-CalorieTracker/app/src/main/java/com/avicodes/calorietrackerai/presentation/components/MealHolder.kt | 1230802071 |
package uk.co.jatra.sheets
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("uk.co.jatra.sheets", appContext.packageName)
}
} | Sheets/app/src/androidTest/java/uk/co/jatra/sheets/ExampleInstrumentedTest.kt | 1826678314 |
package uk.co.jatra.sheets
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)
}
} | Sheets/app/src/test/java/uk/co/jatra/sheets/ExampleUnitTest.kt | 2767511620 |
package uk.co.jatra.sheets.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) | Sheets/app/src/main/java/uk/co/jatra/sheets/ui/theme/Color.kt | 2473318957 |
package uk.co.jatra.sheets.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 SheetsTheme(
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
)
} | Sheets/app/src/main/java/uk/co/jatra/sheets/ui/theme/Theme.kt | 3228068724 |
package uk.co.jatra.sheets.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
)
*/
) | Sheets/app/src/main/java/uk/co/jatra/sheets/ui/theme/Type.kt | 1837321805 |
package uk.co.jatra.sheets
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import uk.co.jatra.sheets.ui.theme.SheetsTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val sheetVisible = remember { mutableStateOf(false) }
SheetsTheme {
Box(modifier = Modifier.fillMaxSize()) {
mainContent(sheetVisible, name = "BottomSheet play")
bottomSheet(
sheetVisible = sheetVisible,
modifier = Modifier
.align(Alignment.BottomCenter)
)
}
}
}
}
@Composable
private fun bottomSheet(sheetVisible: MutableState<Boolean>, modifier: Modifier) {
AnimatedVisibility(
visible = sheetVisible.value,
enter = slideInVertically(
animationSpec = tween(500),
initialOffsetY = { it },
),
exit = slideOutVertically(animationSpec = tween(500),
targetOffsetY = { it }
),
modifier = modifier,
) {
Box(
modifier = modifier
.fillMaxWidth()
.height(300.dp)
.background(MaterialTheme.colorScheme.primary)
.offset(y = ((-300).dp).coerceAtLeast(0.dp)) // Anchor to bottom
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = modifier
.fillMaxSize()
.background(color = Color.Red)
) {
Text(text = "Hello, I'm a bottom sheet")
Button(onClick = {
sheetVisible.value = !sheetVisible.value
}) {
Text("Hide")
}
}
}
}
}
@Composable
private fun mainContent(sheetVisible: MutableState<Boolean>,
name: String,
modifier: Modifier = Modifier) {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.secondary
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(
text = "Hello $name!",
modifier = modifier
)
Button(onClick = {
sheetVisible.value = !sheetVisible.value
}) {
Text(if (sheetVisible.value) "Hide" else "Show")
}
}
}
}
} | Sheets/app/src/main/java/uk/co/jatra/sheets/MainActivity.kt | 855213872 |
package com.internshipavito
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.internshipavito", appContext.packageName)
}
} | InternshipAvito/app/src/androidTest/java/com/internshipavito/ExampleInstrumentedTest.kt | 1041693471 |
package com.internshipavito
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)
}
} | InternshipAvito/app/src/test/java/com/internshipavito/ExampleUnitTest.kt | 2539381666 |
package com.internshipavito
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.fragment_container)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
} | InternshipAvito/app/src/main/java/com/internshipavito/MainActivity.kt | 87753537 |
package com.internshipavito.framework
import android.app.Application
import com.facebook.drawee.backends.pipeline.Fresco
class KinopoiskApplication: Application() {
override fun onCreate() {
super.onCreate()
Fresco.initialize(this )
}
} | InternshipAvito/app/src/main/java/com/internshipavito/framework/KinopoiskApplication.kt | 1074208888 |
package com.internshipavito.data.network
import okhttp3.Interceptor
import okhttp3.Response
class MovieInterceptor: Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request().newBuilder()
.addHeader("accept", "application/json")
.addHeader("X-API-KEY", API_KEY)
.build()
return chain.proceed(request)
}
private companion object {
private const val API_KEY = "indicate_your_api_key_here"
}
} | InternshipAvito/app/src/main/java/com/internshipavito/data/network/MovieInterceptor.kt | 3092881963 |
package com.internshipavito.data.network
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.Path
class RetrofitClient {
private val okHttpClient = OkHttpClient.Builder()
.addInterceptor(MovieInterceptor())
.build()
private val retrofit: Retrofit = Retrofit.Builder()
.baseUrl("https://api.kinopoisk.dev/v1.4/")
.addConverterFactory(MoshiConverterFactory.create())
.client(okHttpClient)
.build()
private fun getApi(): KinopoiskApi {
return retrofit.create(KinopoiskApi::class.java)
}
suspend fun fetchMovies(page: Int, limit: Int): List<GalleryItem> = getApi().fetchMovies(page, limit).movies
suspend fun fetchMovie(@Path("movieId") movieId: String): GalleryItem = getApi().fetchMovie(movieId)
suspend fun findMoviesById(@Path("movieName") movieName: String): List<GalleryItem> = getApi().findMovieById(movieName).movies
} | InternshipAvito/app/src/main/java/com/internshipavito/data/network/RetrofitClient.kt | 3164334600 |
package com.internshipavito.data.network
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class GalleryItem(
val id: String,
val name: String,
val description: String,
val rating: Rating,
val poster: Poster,
val year: String
)
@JsonClass(generateAdapter = true)
data class Poster(
@Json(name = "previewUrl") val url: String
)
@JsonClass(generateAdapter = true)
data class Rating(
val kp: String,
val imdb: String,
val filmCritics: String
)
@JsonClass(generateAdapter = true)
data class MoviesResponse(
@Json(name = "docs")val movies: List<GalleryItem>
) | InternshipAvito/app/src/main/java/com/internshipavito/data/network/MovieResponse.kt | 3368518475 |
package com.internshipavito.data.network
import androidx.paging.PagingSource
import androidx.paging.PagingState
class MoviePagingSource(
private val retrofitClient: RetrofitClient
) : PagingSource<Int, GalleryItem>() {
override fun getRefreshKey(state: PagingState<Int, GalleryItem>): Int? {
val anchorPosition = state.anchorPosition ?: return null
val anchorPage = state.closestPageToPosition(anchorPosition) ?: return null
return anchorPage.prevKey?.plus(1) ?: anchorPage.nextKey?.minus(1) }
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, GalleryItem> {
val page = params.key ?: 1
val limit = params.loadSize.coerceAtMost(20)
val response = retrofitClient.fetchMovies(page, limit)
val nextKey = if (response.size < limit) null else page + 1
val prevKey = if (page == 1) null else page - 1
return LoadResult.Page(response, prevKey, nextKey)
}
} | InternshipAvito/app/src/main/java/com/internshipavito/data/network/MoviePagingSource.kt | 3842850106 |
package com.internshipavito.data.network
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
interface KinopoiskApi {
@GET("movie?")
suspend fun fetchMovies(
@Query("page") page: Int,
@Query("limit") limit: Int
): MoviesResponse
@GET("movie/{movieId}")
suspend fun fetchMovie(
@Path("movieId") movieId: String
): GalleryItem
@GET("movie/search")
suspend fun findMovieById(
@Query("query") name: String
): MoviesResponse
}
| InternshipAvito/app/src/main/java/com/internshipavito/data/network/KinopoiskApi.kt | 4160178166 |
package com.internshipavito.presentation.gridFeature
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.internshipavito.data.network.GalleryItem
import com.internshipavito.data.network.MoviePagingSource
import com.internshipavito.data.network.RetrofitClient
import kotlinx.coroutines.flow.Flow
class MovieGalleryViewModel(private val retrofitClient: RetrofitClient): ViewModel() {
val getMovies: Flow<PagingData<GalleryItem>> = Pager(
config = PagingConfig(pageSize = PAGE_SIZE, enablePlaceholders = false),
pagingSourceFactory = { MoviePagingSource(retrofitClient) }
).flow
suspend fun findMoviesById(query: String): List<GalleryItem> {
return retrofitClient.findMoviesById(query)
}
companion object {
private const val PAGE_SIZE = 20
}
class MovieViewModelFactory(private val retrofitClient: RetrofitClient) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(MovieGalleryViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return MovieGalleryViewModel(retrofitClient) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
} | InternshipAvito/app/src/main/java/com/internshipavito/presentation/gridFeature/MovieGalleryViewModel.kt | 71609640 |
package com.internshipavito.presentation.gridFeature
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.findNavController
import androidx.paging.PagingData
import androidx.recyclerview.widget.GridLayoutManager
import com.internshipavito.data.network.RetrofitClient
import com.internshipavito.databinding.FragmentMovieGalleryBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
class MovieGalleryFragment: Fragment() {
private var _binding: FragmentMovieGalleryBinding? = null
private val binding
get() = checkNotNull(_binding){
"Cannot access binding because it is null"
}
private var searchJob: Job? = null
private val retrofitClient = RetrofitClient()
private val movieGalleryViewModel: MovieGalleryViewModel by viewModels { MovieGalleryViewModel.MovieViewModelFactory(retrofitClient) }
private val movieGridAdapter = MovieGridAdapter()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMovieGalleryBinding.inflate(inflater, container, false)
binding.movieGrid.layoutManager = GridLayoutManager(context, 2)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.movieGrid.adapter = movieGridAdapter
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
movieGalleryViewModel.getMovies.collectLatest { pagingData ->
movieGridAdapter.submitData(pagingData)
}
}
}
binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
searchJob = CoroutineScope(Dispatchers.Main).launch {
delay(1000)
if (!newText.isNullOrBlank()) {
searchMovie(newText)
} else {
movieGalleryViewModel.getMovies.collectLatest { pagingData ->
movieGridAdapter.submitData(pagingData)
}
}
}
return true
}
})
movieGridAdapter.setOnItemClickListener {
val direction = MovieGalleryFragmentDirections.showMovieDetails(it.id)
findNavController().navigate(direction)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun searchMovie(query: String) {
viewLifecycleOwner.lifecycleScope.launch {
try {
val foundMovies = movieGalleryViewModel.findMoviesById(query)
movieGridAdapter.submitData(PagingData.from(foundMovies))
} catch (ex: Exception) {
Log.e("MovieGalleryFragment", "Error searching for movies: $ex")
}
}
}
} | InternshipAvito/app/src/main/java/com/internshipavito/presentation/gridFeature/MovieGalleryFragment.kt | 2785677040 |
package com.internshipavito.presentation.gridFeature
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.internshipavito.data.network.GalleryItem
import com.internshipavito.databinding.GridItemBinding
class MovieGridAdapter : PagingDataAdapter<GalleryItem, MovieGridAdapter.MovieViewHolder>(MOVIE_COMPARATOR) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
val binding = GridItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return MovieViewHolder(binding)
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
val movieItem = getItem(position)
movieItem?.let {
holder.bind(it)
}
}
inner class MovieViewHolder(private val binding: GridItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(movie: GalleryItem) {
binding.itemMovieView.setImageURI(movie.poster.url)
binding.root.setOnClickListener {
onItemClickListener?.let {
it(movie)
}
}
}
}
private var onItemClickListener: ((GalleryItem) -> Unit)? = null
fun setOnItemClickListener(listener: (GalleryItem) -> Unit) {
onItemClickListener = listener
}
companion object {
private val MOVIE_COMPARATOR = object : DiffUtil.ItemCallback<GalleryItem>() {
override fun areItemsTheSame(oldItem: GalleryItem, newItem: GalleryItem): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: GalleryItem, newItem: GalleryItem): Boolean =
oldItem == newItem
}
}
} | InternshipAvito/app/src/main/java/com/internshipavito/presentation/gridFeature/MovieAdapter.kt | 2186367448 |
package com.internshipavito.presentation.detailFeature
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.navArgs
import com.internshipavito.R
import com.internshipavito.data.network.GalleryItem
import com.internshipavito.databinding.FragmentMovieDetailBinding
import kotlinx.coroutines.launch
class MovieDetailFragment: Fragment() {
private val args: MovieDetailFragmentArgs by navArgs()
private val movieDetailViewmodel: MovieDetailViewmodel by viewModels{
MovieDetailViewModelFactory(args.movieId)
}
private var _binding: FragmentMovieDetailBinding? = null
private val binding
get() = checkNotNull(_binding) {
"Cannot access binding because it is null"
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMovieDetailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
movieDetailViewmodel.galleryItem.collect { movie ->
movie?.let { updateUi(it) }
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
@SuppressLint("SetTextI18n")
private fun updateUi(movie: GalleryItem) {
binding.apply {
moviePoster.setImageURI(movie.poster.url)
movieName.text = movie.name
movieYear.text = getString(R.string.production_year) + " " + movie.year
movieDescription.text = movie.description
movieRatingKp.text = if (movie.rating.kp == "0") getString(R.string.movie_rating_stub) else "Кинопоиск: ${movie.rating.kp}"
movieRatingImdb.text = if (movie.rating.imdb == "0") getString(R.string.movie_rating_stub) else "Imdb: ${movie.rating.imdb}"
movieRatingFc.text = if (movie.rating.filmCritics == "0") getString(R.string.movie_rating_stub) else "FilmCritics: ${movie.rating.filmCritics}"
}
}
} | InternshipAvito/app/src/main/java/com/internshipavito/presentation/detailFeature/MovieDetailFragment.kt | 4141883311 |
package com.internshipavito.presentation.detailFeature
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.internshipavito.data.network.GalleryItem
import com.internshipavito.data.network.RetrofitClient
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
class MovieDetailViewmodel(movieId: String) : ViewModel() {
private val retrofitClient = RetrofitClient()
private val _galleryItem: MutableStateFlow<GalleryItem?> = MutableStateFlow(null)
val galleryItem: StateFlow<GalleryItem?>
get() = _galleryItem.asStateFlow()
init {
viewModelScope.launch {
_galleryItem.value = retrofitClient.fetchMovie(movieId)
}
}
}
class MovieDetailViewModelFactory(
private val movieId: String
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return MovieDetailViewmodel(movieId) as T
}
}
| InternshipAvito/app/src/main/java/com/internshipavito/presentation/detailFeature/MovieDetailViewmodel.kt | 1392111216 |
class GlobalMarketMonitorAdapter {
} | covest-news/GlobalMarketMonitorAdapter.kt | 3207981627 |
package com.covest.news
import com.covest.news.adapter.GlobalMonitorNewsAdapter
import com.covest.news.adapter.TelegramAdapter
import io.github.cdimascio.dotenv.dotenv
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import java.time.LocalDateTime
suspend fun main() {
val env = dotenv()
val client = HttpClient(CIO) {
install(ContentNegotiation) {
json()
}
}
val adapter = GlobalMonitorNewsAdapter(client)
val telegramAdapter = TelegramAdapter(client, env["TELEGRAM_TOKEN"]!!, env["TELEGRAM_CHAT_ID"]!!)
val titleAndDate = adapter.getAllNewsHeadline().map { it.title + " - " + it.updatedAt }
val message = titleAndDate.joinToString(
prefix = "\n=====================\n",
separator = "\n=====================\n",
)
println(telegramAdapter.send(message))
println(message)
/*
TODO
1. 중복알림 제거하기 -> 아마 디비를 써야하지 않을까?
2. 토큰 값 외부 주입받기 (for 보안)
3. 서버에 올려두고 주기적으로 뉴스보내도록 하기
4. 해드라인 정보로 공부할만한 키워드 추출하기 with gpt
*/
}
data class NewsHeadline(
val id: String,
val title: String,
val updatedAt: LocalDateTime,
val writer: String,
val source: String
)
| covest-news/src/main/kotlin/com/covest/news/Application.kt | 1439286784 |
package com.covest.news.serialize
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
@Serializer(forClass = LocalDateTime::class)
object LocalDateTimeSerializer : KSerializer<LocalDateTime> {
private val formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
override fun serialize(encoder: Encoder, value: LocalDateTime) {
encoder.encodeString(value.format(formatter))
}
/*
descriptor는 직렬화 대상 타입의 구조와 형식을 설명하는 메타데이터를 제공합니다.
커스텀 LocalDateTime 직렬화기에서 descriptor는 주로 문자열 타입을 나타내는 데 사용됩니다.
PrimitiveSerialDescriptor를 사용하여 LocalDateTime 타입이 문자열 형식으로 직렬화될 것임을 나타냅니다.
PrimitiveSerialDescriptor의 첫 번째 인자는 해당 직렬화기의 이름으로 사용되며,
두 번째 인자는 직렬화되는 데이터의 종류를 나타내는 PrimitiveKind입니다. 이 경우 LocalDateTime은 문자열 형태로 직렬화되므로 PrimitiveKind.STRING을 사용합니다.
이렇게 descriptor를 정의함으로써, 직렬화 라이브러리는 이 커스텀 직렬화기가 어떤 타입의 데이터를 어떻게 처리할지에 대한 정보를 갖게 됩니다.
이는 직렬화 및 역직렬화 과정에서 타입 안정성을 보장하고, 직렬화 체계의 일관성을 유지하는 데 도움이 됩니다.
*/
override val descriptor: SerialDescriptor =
PrimitiveSerialDescriptor("LocalDateTime", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): LocalDateTime {
return LocalDateTime.parse(decoder.decodeString(), formatter)
}
}
| covest-news/src/main/kotlin/com/covest/news/serialize/LocalDateTimeSerializer.kt | 3939236163 |
package com.covest.news.adapter
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
class TelegramAdapter(
private val client: HttpClient,
private val token: String,
private val chatId: String
) {
companion object {
const val BASE_URL = "https://api.telegram.org/bot"
const val SEND_MESSAGE = "/sendMessage"
}
suspend fun send(message: String): String {
return client.post(BASE_URL + token + SEND_MESSAGE) {
contentType(ContentType.Application.Json)
setBody(mapOf("chat_id" to chatId, "text" to message))
}.bodyAsText() // TODO: 코틀린 철학을 살려서... 리턴까지 응답을 내보내지 않고 status code를 logging 할 수 있을까?
}
} | covest-news/src/main/kotlin/com/covest/news/adapter/TelegramAdapter.kt | 3560506627 |
package com.covest.news.adapter
import com.covest.news.NewsHeadline
import com.covest.news.serialize.LocalDateTimeSerializer
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.time.LocalDateTime
class GlobalMonitorNewsAdapter(
private val httpClient: HttpClient
) {
companion object {
const val GET_ALL = "http://globalmonitor.einfomax.co.kr/apis/usa/news/getnewsall"
const val GET_ONE = "https://globalmonitor.einfomax.co.kr/apis/usa/news/getnewsone"
}
suspend fun getAllNewsHeadline(): List<com.covest.news.NewsHeadline> {
return httpClient
.post(GET_ALL)
.body<NewsHeadlineResponse>()
.data
.map { NewsHeadline(it.id, it.title, it.updateDateTime, it.writer, it.source) }
}
suspend fun getOne(id: String): String {
return httpClient.post(GET_ONE) {
contentType(ContentType.Application.Json)
setBody(mapOf("id" to id))
}.bodyAsText()
}
@Serializable
data class NewsHeadlineResponse(
val total: Int,
val data: List<NewsHeadline>
)
@Serializable
data class NewsHeadline(
@SerialName("_id")
val id: String,
@SerialName("SendDateTime")
val sendDateTime: String,
@SerialName("Credit")
val credit: String? = null,
@SerialName("Category.@name")
val categoryName: String,
@SerialName("Title")
val title: String,
@SerialName("viewcount")
val viewCount: Int = 0,
@SerialName("UpdateDateTime")
@Serializable(with = LocalDateTimeSerializer::class)
val updateDateTime: LocalDateTime,
@SerialName("Writer")
val writer: String,
@SerialName("Source")
val source: String
)
} | covest-news/src/main/kotlin/com/covest/news/adapter/GlobalMonitorNewsAdapter.kt | 3438100442 |
package com.example.myapplication
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.myapplication", appContext.packageName)
}
} | user_list-CRUD/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
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)
}
} | user_list-CRUD/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var pos = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val userList = ArrayList<Users>()
userList.add(Users("pedro", "gremio123"))
userList.add(Users("elen", "inter123"))
userList.add(Users("gato", "miau123"))
val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, userList)
binding.listView.adapter = adapter
binding.listView.setOnItemClickListener { _, _, position, _ ->
binding.editUsername.setText(userList.get(position).username)
binding.editPassword.setText(userList.get(position).password)
pos = position
}
binding.buttonAdd.setOnClickListener {
val username = binding.editUsername.text.toString().trim()
val password = binding.editPassword.text.toString().trim()
if (username.isEmpty() && password.isEmpty()) {
Toast.makeText(applicationContext, "No username and/or password informed.", Toast.LENGTH_LONG)
.show()
} else {
userList.add(Users(username, password))
adapter.notifyDataSetChanged()
cleanFields()
pos = -1
}
}
binding.buttonEdit.setOnClickListener {
val username = binding.editUsername.text.toString().trim()
val password = binding.editPassword.text.toString().trim()
if (pos >= 0) {
if (username.isNotEmpty() && password.isNotEmpty()) {
userList.get(pos).username = username
userList.get(pos).password = password
adapter.notifyDataSetChanged()
cleanFields()
pos = -1
}
}
}
binding.buttonDelete.setOnClickListener {
if (pos >= 0) {
userList.removeAt(pos)
adapter.notifyDataSetChanged()
cleanFields()
pos = -1
}
}
binding.buttonClear.setOnClickListener {
userList.clear()
adapter.notifyDataSetChanged()
cleanFields()
}
}
private fun cleanFields() {
binding.editUsername.setText("")
binding.editPassword.setText("")
}
} | user_list-CRUD/app/src/main/java/com/example/myapplication/MainActivity.kt | 3151224956 |
package com.example.myapplication
class Users(var username: String, var password: String) {
override fun toString(): String {
return username
}
} | user_list-CRUD/app/src/main/java/com/example/myapplication/Users.kt | 3160473902 |
import com.acmerobotics.roadrunner.geometry.Pose2d
import trajectorysequence.sequencesegment.SequenceSegment
/**
* The type of non-movement action performed by the robot
*
* @param duration: The time it takes to perform the certain action
* @param distanceDropped: The distance in front of the robot the pixel is dropped in inches;
* Only applicable to DROP_PIXEL
* TODO: Find the actual duration and distance dropped values
**/
enum class Action(val duration: Double, val distanceDropped: Double?) {
DROP_PIXEL(3.0, 2.5),
DROP_PIXEL_ON_BOARD(4.9, null)
}
class ActionSegment(val action: Action, pose: Pose2d) : SequenceSegment(action.duration, pose, pose, emptyList())
| ftcsim/src/main/kotlin/ActionSegment.kt | 185150899 |
import javafx.scene.control.ComboBox
import javafx.scene.control.TableCell
/**
* A cell with a ComboBox in it. Meant for the action column.
*/
class ActionCell(private var combo: ComboBox<FXAction>) : TableCell<FXTrajectory, FXAction>() {
override fun updateItem(act: FXAction?, empty: Boolean) {
super.updateItem(act, empty)
graphic = if (empty) {
null
} else {
combo.value = act
combo
}
}
}
| ftcsim/src/main/kotlin/ActionCell.kt | 2583088813 |
import com.acmerobotics.roadrunner.geometry.Pose2d
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import kotlinx.serialization.Serializable
import kotlin.math.cos
/**
* An action to be performed by the robot. Meant to be used for the GUI.
*
* @property text: The text to render in the GUI table
* @property exportableFunction: The 'function' representation of the action for
* when we want to export our trajectory
*/
enum class FXAction(private val text: String, val exportableFunction: String) {
FORWARD("Forward", "forward"),
BACKWARD("Backward", "backward"),
STRAFE_LEFT("Strafe Left", "strafeLeft"),
STRAFE_RIGHT("Strafe Right", "strafeRight"),
TURN("Turn", "turn"),
SPLINE_TO("Spline To", "splineTo"),
LINE_TO("Line To", "lineTo"),
DROP_PIXEL("Drop Pixel (Field)", "dropPixel"),
DROP_PIXEL_ON_BOARD("Drop Pixel (Board)", "dropPixelOnBoard");
override fun toString() = text
fun toSerialize() = super.toString()
}
/**
* A singular movement in the overall trajectory. Meant to be used by the GUI to represent
* the movement with all of its parameters in the table.
*
* @property a: The action performed by the movement
* @property q: The amount of the action (eg. 42in or 69deg)
* @property mV: The maximum velocity of the movement ("-" means default)
* @property mAV: The maximum angular velocity of the movement
* @property mA: The maximum acceleration of the movement
*/
@Serializable
data class FXTrajectory(
val a: FXAction,
val q: String,
val mV: String = "-",
val mAV: String = "-",
val mA: String = "-"
) {
@Serializable(with = SOPSerializer::class)
private val action = SimpleObjectProperty(a)
@Serializable(with = SSPSerializer::class)
private val quantification = SimpleStringProperty(q)
@Serializable(with = SSPSerializer::class)
private val maxVel = SimpleStringProperty(mV)
@Serializable(with = SSPSerializer::class)
private val maxAngVel = SimpleStringProperty(mAV)
@Serializable(with = SSPSerializer::class)
private val maxAccel = SimpleStringProperty(mA)
fun newAction(a: FXAction) = this.copy(a = a)
fun newQuantification(q: String) = this.copy(q = q)
fun newMaxVel(mV: String) = this.copy(mV = mV)
fun newMaxAngVel(mAV: String) = this.copy(mAV = mAV)
fun newMaxAccel(mA: String) = this.copy(mA = mA)
// The get functions may seem unused outside of this class, but they are used internally by JavaFX
fun getAction(): FXAction = action.get()
fun getQuantification(): String = quantification.get()
fun getMaxVel(): String = maxVel.get()
fun getMaxAngVel(): String = maxAngVel.get()
fun getMaxAccel(): String = maxAccel.get()
fun actionProperty() = action
/**
* Returns the exportable representation of the action as a string
*/
fun exportable(startPose: Pose2d) = when (val action = getAction()) {
FXAction.TURN -> "${action.exportableFunction}(${getQuantification()})"
FXAction.LINE_TO -> {
val (fmV, fmAV, fmA) = getFormattedMaxes()
val specs = getQuantification().split(",", ", ", " ,", " , ").map { it.toDouble() }
val newHeading =
if (startPose.heading == 0.0) specs[2] else (startPose.heading.toDegrees - specs[2]) % startPose.heading.toDegrees
("${action.exportableFunction}(" +
"${cos(startPose.heading) * (specs[0] - startPose.x)}, " +
"${cos(startPose.heading) * (specs[1] - startPose.y)}, " +
// THIS IS JANKY SHIT AND WILL NOT SCALE
"${newHeading}, " +
"${fmV}, ${fmAV}, ${fmA}, trackWidth)")
}
FXAction.DROP_PIXEL, FXAction.DROP_PIXEL_ON_BOARD -> "${action.exportableFunction}()"
else -> {
val (fmV, fmAV, fmA) = getFormattedMaxes()
"${action.exportableFunction}(${getQuantification()}, ${fmV}, ${fmAV}, ${fmA}, trackWidth)"
}
}
private fun getFormattedMaxes(): Triple<String, String, String> {
return Triple(
getMaxVel().isOrElse("-", "maxVelocity"),
getMaxAngVel().isOrElse("-", "maxAngularVelocity"),
getMaxAccel().isOrElse("-", "maxAcceleration")
)
}
private fun String.isOrElse(cond: String, newValue: String) = if (this == cond) newValue else this
}
| ftcsim/src/main/kotlin/FXTrajectory.kt | 4078563879 |
import com.acmerobotics.roadrunner.geometry.Pose2d
import javafx.geometry.Rectangle2D
import javafx.scene.canvas.GraphicsContext
import javafx.scene.image.Image
import javafx.scene.transform.Rotate
import kotlin.math.pow
import kotlin.math.sqrt
/**
* Helper class meant to represent the Robot on the canvas. Takes care of rendering it and
* detecting collisions with other objects on the field.
*
* @property image: The robot's image
* @property fieldDimPixels: The size of the field image in pixels
* @param startPose: The starting position of the robot (x:pixels, y:pixels, heading:degrees)
*/
class Robot(private val image: Image, private val fieldDimPixels: Double, startPose: Pose2d) {
var x = startPose.x
set(value) {
field = value.coerceIn(0.0, fieldDimPixels) // Ensures that the robot stays within the field
}
var y = -startPose.y
set(value) {
field = value.coerceIn(0.0, fieldDimPixels) // Ensures that the robot stays within the field
}
var rotation = startPose.heading // degrees
val asRectangle2D get() = Rectangle2D(x, y, image.width, image.height)
private val centerPointX get() = x + image.width / 2
private val centerPointY get() = y + image.height / 2
/**
* Renders the robot on the canvas taking care of position and rotation.
*/
fun render(gc: GraphicsContext) {
gc.save()
// Rotation about pivot point
val r = Rotate(-rotation, centerPointX, centerPointY)
gc.setTransform(r.mxx, r.myx, r.mxy, r.myy, r.tx, r.ty)
gc.drawImage(image, x, y)
gc.restore()
}
fun moveTo(pose: Pose2d) {
x = pose.x
y = -pose.y
rotation = pose.heading
}
/**
* Identifies if the robot is colliding with another object
*/
fun collision(other: Rectangle2D) = other.intersects(asRectangle2D)
/**
* Simple pythagorean formula to determine the distance ot another object
*/
fun distanceTo(other: Rectangle2D) =
sqrt((centerPointX - other.centerPointX).pow(2) + (centerPointY - other.centerPointY).pow(2))
}
| ftcsim/src/main/kotlin/Robot.kt | 3099014378 |
import com.acmerobotics.roadrunner.geometry.Pose2d
import com.acmerobotics.roadrunner.geometry.Vector2d
import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint
import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint
import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint
import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint
import javafx.animation.KeyFrame
import javafx.animation.Timeline
import javafx.application.Application
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.geometry.Rectangle2D
import javafx.geometry.VPos
import javafx.scene.Scene
import javafx.scene.canvas.Canvas
import javafx.scene.canvas.GraphicsContext
import javafx.scene.control.*
import javafx.scene.control.cell.PropertyValueFactory
import javafx.scene.control.cell.TextFieldTableCell
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.input.*
import javafx.scene.layout.GridPane
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import javafx.scene.paint.Color
import javafx.scene.text.Font
import javafx.scene.text.TextAlignment
import javafx.stage.FileChooser
import javafx.stage.Stage
import javafx.util.Duration
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import trajectorysequence.TrajectorySequence
import trajectorysequence.TrajectorySequenceBuilder
import trajectorysequence.TrajectoryType
import trajectorysequence.sequencesegment.SequenceSegment
import trajectorysequence.sequencesegment.TrajectorySegment
import trajectorysequence.sequencesegment.TurnSegment
import trajectorysequence.sequencesegment.WaitSegment
import java.io.File
import kotlin.math.cos
import kotlin.math.min
import kotlin.math.sin
/**
* The simulator GUI. If you aren't maintaining this codebase, the changes you make will most likely be to the
* constants (marked below). The simulator works as follows:
* 1. All the GUI elements are initialized
* 2. `Simulator.simulationLoop(...)` is called `fps` times per second
* 3. This renders the canvas and animates the robot's movements
* Notes:
* - When modifying code here, it is easy to forget to convert to pixels or inches
*/
class Simulator : Application() {
/*****************
* CONSTANTS
*****************/
private val fps = 60 // Frames per second
private val numberSamples = 50 // Number of samples when drawing the trajectory
private var startPose = Pose2d(0.0, -24.0 * 4 - 6.681 + 2, 180.0.toRadians) // x, y, angle
private val fieldDimPixels = 640.0 // 640px x 640px
private val fieldDimReal = 144.0 // 144in x 144in
private val robotWidth = 18.0 // 17.995in (rear to intake tip)
private val robotLength = 17.5 // 17.319in (side to side)
private val trackWidth = 12.7 // Distance between wheels
// Drive Constants
private val maxVel = 60.0 // mph
private val maxAccel = 60.0 // mph
private val maxAngVel = 5.528055275836724 // rad/sec
private val maxAngAccel = 5.528055275836724 // rad/sec^2
// Default constants specified for the autonomous programs (e.g. BlueClose.java)
private var specifiedMaxVel = 55.0
private var specifiedMaxAngVel = 1.75
private var specifiedMaxAccel = 100.0
/*****************
* COLLISION
*****************/
// All the following values are in pixels
private val leftBackdrop = Rectangle2D(105.0, 0.0, 110.0, 55.0)
private val rightBackdrop = Rectangle2D(425.0, 0.0, 110.0, 55.0)
private val trussLeg1 = Rectangle2D(0.0, 321.0, 3.0, 105.0)
private val trussLeg2 = Rectangle2D(105.0, 321.0, 3.0, 105.0)
private val trussLeg3 = Rectangle2D(212.0, 321.0, 3.0, 105.0)
private val trussLeg4 = Rectangle2D(425.0, 321.0, 3.0, 105.0)
private val trussLeg5 = Rectangle2D(637.0, 321.0, 3.0, 105.0)
private val fixedObjects = arrayOf(
leftBackdrop,
rightBackdrop,
trussLeg1,
trussLeg2,
trussLeg3,
trussLeg4,
trussLeg5
)
/*****************
* IMAGES
*****************/
private val field = Image("/field.png")
private val pixel = Image("/pixel_ftc.png")
private val robot = Robot(
Image("/robot_ftc.png", robotWidth.in2px, robotLength.in2px, false, false),
fieldDimPixels,
startPose.in2px
)
/*****************
* CURRENT STATE
*****************/
// Whether the simulation should run or not
private var simulate = false
// The number of pixels stacked on the left backdrop (to render)
private var leftBackDropScore = 0
// The number of pixels stacked on the right backdrop (to render)
private var rightBackDropScore = 0
// Positions of all the pixels in the format (x:pixel, y:pixel)
private var pixelPositions = mutableListOf<Pair<Double, Double>>()
// Internally used when creating trajectories
private var prevPose = startPose
private val velocityConstraint = createVelocityConstraint(maxVel, maxAngVel)
private val accelerationConstraint = createAccelerationConstraint(maxAccel)
// The time when the simulation was started
private var startTime = Double.NaN
// The table of movement paths
private val trajectoryTable = TableView<FXTrajectory>()
// The sequence of movements
private var sequence = getTrajectorySequence()
// The current movement segment being animated
private var segmentIndex = 0
// The duration of each movement segment
private var trajectoryDurations = sequence.sequenceList?.map { it.duration } ?: emptyList()
// The total trajectory duration
private var totalDuration = trajectoryDurations.sum()
/*****************
* CONVERSIONS
*****************/
private val Double.in2px get() = this * fieldDimPixels / fieldDimReal
// Silently converts the heading to degrees
private val Pose2d.in2px get() = Pose2d(this.x.in2px, this.y.in2px, heading.toDegrees)
/*****************
* UI
*****************/
private val windowWidth = field.width + 600
private val windowHeight = field.height + 50
// For drag and drop of rows in the table
private val serializedMimeType = DataFormat("application/x-java-serialized-object")
private val selections = mutableListOf<FXTrajectory>()
// Has the overall trajectory been modified?
private var trajectoriesModified = false
private val root = HBox()
private val canvas = Canvas(field.width, field.height)
// The right side of the GUI
private val builder = VBox()
private lateinit var timeline: Timeline
private val timer = ProgressBar(0.0)
private val timeCount = Label("- / -")
// When the robot collides with a fixed object on the field
private val collisionError = Alert(
Alert.AlertType.ERROR,
"ur skill issue got the opps ded crying",
ButtonType.OK
)
// When an invalid non-double (or in some cases non-positive) value is supplied
private val expectedDoubleError = Alert(
Alert.AlertType.ERROR,
"why tf would u not put a decimal bruh",
ButtonType.OK
)
// The options for the combo boxes in the action column of the table
private val actionOptions =
FXCollections.observableList(
listOf(
FXAction.FORWARD,
FXAction.BACKWARD,
FXAction.STRAFE_LEFT,
FXAction.STRAFE_RIGHT,
FXAction.SPLINE_TO,
FXAction.LINE_TO,
FXAction.TURN,
FXAction.DROP_PIXEL,
FXAction.DROP_PIXEL_ON_BOARD
)
)
/**
* The first function run. Initializes the entire GUI and canvas.
*/
override fun start(stage: Stage) {
// Styling
root.padding = Insets(25.0)
builder.padding = Insets(0.0, 0.0, 0.0, 25.0)
builder.spacing = 25.0
HBox.setHgrow(builder, Priority.ALWAYS)
// Initialize the GUI elements
initLogo()
initTrajectoryTable()
// Requires the stage to create the file dialogs for save/open
initButtons(stage)
initTimer()
initErrors()
stage.title = "FTCSIM"
stage.isResizable = false
// If this isn't set, the images look like shit
canvas.graphicsContext2D.isImageSmoothing = false
// Initialize the canvas rendering
timeline = Timeline(KeyFrame(
Duration.millis(1000.0 / fps),
{ simulationLoop(canvas.graphicsContext2D) }
))
timeline.cycleCount = Timeline.INDEFINITE
root.children.addAll(canvas, builder)
stage.scene = Scene(root, windowWidth, windowHeight)
stage.show()
timeline.play()
}
private fun initErrors() {
collisionError.title = null
collisionError.headerText = "Invalid collision with fixed object"
expectedDoubleError.title = null
expectedDoubleError.headerText = "Expected a decimal value for the specified field"
}
private fun initTimer() {
val timerUnit = HBox()
HBox.setHgrow(timer, Priority.ALWAYS)
timer.maxWidth = Double.MAX_VALUE
timerUnit.spacing = 5.0
timerUnit.children.addAll(timer, timeCount)
builder.children.add(timerUnit)
}
/**
* Creates the toolbar of buttons and adds their functionality.
*/
private fun initButtons(stage: Stage) {
val buttonBar = HBox()
val add = Button("Add")
val remove = Button("Remove")
val run = Button("Run")
val stop = Button("Stop")
val save = Button("Save")
val open = Button("Open")
val export = Button("Export")
val settings = Button("Settings")
val flip = Button("Flip")
buttonBar.spacing = 4.0
setupImageButton(add, "/add.png")
setupImageButton(remove, "/remove.png")
setupImageButton(run, "/run.png")
setupImageButton(stop, "/stop.png")
setupImageButton(save, "/save.png")
setupImageButton(open, "/open.png")
setupImageButton(export, "/export.png")
setupImageButton(settings, "/settings.png")
flip.setPrefSize(60.0, 30.0)
add.setOnAction {
// Default segment is Forward 10
trajectoryTable.items.add(FXTrajectory(FXAction.FORWARD, "10"))
trajectoriesModified = true
}
remove.setOnAction { removeSelectedTrajectories() }
run.setOnAction {
if (trajectoriesModified) stopSimulation()
timeline.play()
simulate = true
}
stop.setOnAction { stopSimulation() }
save.setOnAction { saveTrajectory(stage) }
open.setOnAction { openTrajectory(stage) }
export.setOnAction { exportTrajectory() }
settings.setOnAction { openSettings() }
flip.setOnAction { flipTrajectories() }
buttonBar.children.addAll(add, remove, run, stop, save, open, export, settings, flip)
builder.children.add(buttonBar)
}
/**
* Helper function to create each column in the table with a TextField. Unless you know what you're
* doing, you probably don't want to mess with this function.
*
* @param col: The column to be initialized
* @param propertyName: The 'internal name' of the column to be referred to by JavaFX. JavaFX uses
* reflection to dynamically call `FXTrajectory::get{propertyName}`, which is
* why privatizing those functions (which seems doable) will break things
* @param sideEffect: The new value to put into the trajectory table when a change is made to a
* cell in the column
*/
private fun initTextColumn(
col: TableColumn<FXTrajectory, String>,
propertyName: String,
sideEffect: (FXTrajectory, String) -> FXTrajectory
) {
col.style = "-fx-alignment: CENTER-LEFT;"
col.cellValueFactory = PropertyValueFactory(propertyName)
col.cellFactory = TextFieldTableCell.forTableColumn()
col.setOnEditCommit { t ->
val value = t.newValue.toDoubleOrNull()
val prevValue = trajectoryTable.items[t.tablePosition.row]
// Note that turns are currently allowed to have negative values
// if ((value != null && (value > 0 || prevValue.getAction() == FXAction.TURN)) || t.newValue == "-") {
val position = t.tablePosition.row
val prevTrajectory = trajectoryTable.items[position]
// To whoever is maintaining this code, I DARE YOU to simplify these two lines; Even if you're smart,
// and replace it with trajectoryTable.refresh(), it's not going to refresh the table internally
trajectoryTable.items.removeAt(position)
trajectoryTable.items.add(position, sideEffect(prevTrajectory, t.newValue))
trajectoriesModified = true
// } else expectedDoubleError.showAndWait()
}
col.isSortable = false
col.isReorderable = false
}
/**
* Initializes the entire trajectory table. Unless you know what you're doing, you probably
* don't want to mess with this function.
* Hints:
* - `column.setCellValueFactory` is the function to run when JavaFX wants to read
* the `FXTrajectory`
* - `column.setCellFactory` is how the cell is made
*/
private fun initTrajectoryTable() {
val actionColumn = TableColumn<FXTrajectory, FXAction>("Action")
val quantificationColumn = TableColumn<FXTrajectory, String>("in/deg")
val maxVelColumn = TableColumn<FXTrajectory, String>("vₘₐₓ")
val maxAngVelColumn = TableColumn<FXTrajectory, String>("ωₘₐₓ")
val maxAccelColumn = TableColumn<FXTrajectory, String>("aₘₐₓ")
initTextColumn(quantificationColumn, "Quantification", FXTrajectory::newQuantification)
initTextColumn(maxVelColumn, "MaxVel", FXTrajectory::newMaxVel)
initTextColumn(maxAngVelColumn, "MaxAngVel", FXTrajectory::newMaxAngVel)
initTextColumn(maxAccelColumn, "MaxAccel", FXTrajectory::newMaxAccel)
actionColumn.minWidth = 90.0
actionColumn.setCellValueFactory { cellData -> cellData.value.actionProperty() }
actionColumn.setCellFactory {
val combo: ComboBox<FXAction> = ComboBox(actionOptions)
val cell = ActionCell(combo)
combo.setOnAction {
val newTrajectory = trajectoryTable.items[cell.index].copy(a = combo.value)
trajectoryTable.items.removeAt(cell.index)
trajectoryTable.items.add(cell.index, newTrajectory)
trajectoriesModified = true
}
cell
}
actionColumn.isSortable = false
actionColumn.isReorderable = false
// To make the table rows draggable
trajectoryTable.setRowFactory {
val row: TableRow<FXTrajectory> = TableRow()
row.setOnDragDetected { event ->
if (!row.isEmpty) {
val index = row.index
selections.clear()
val items = trajectoryTable.selectionModel.selectedItems
items.forEach { selections.add(it) }
val db = row.startDragAndDrop(TransferMode.MOVE)
db.dragView = row.snapshot(null, null)
val cc = ClipboardContent()
cc[serializedMimeType] = index
db.setContent(cc)
event.consume()
}
}
row.setOnDragOver { event ->
val db = event.dragboard
if (db.hasContent(serializedMimeType) && row.index != db.getContent(serializedMimeType) as Int) {
event.acceptTransferModes(*TransferMode.COPY_OR_MOVE)
event.consume()
}
}
row.setOnDragDropped { event ->
val db = event.dragboard
if (db.hasContent(serializedMimeType)) {
var dI: FXTrajectory? = null
var dropIndex = if (row.isEmpty) {
trajectoryTable.items.size
} else {
dI = trajectoryTable.items[row.index]
row.index
}
var delta = 0
if (dI != null) while (selections.contains(dI)) {
delta = 1
--dropIndex
if (dropIndex < 0) {
dI = null
dropIndex = 0
break
}
dI = trajectoryTable.items[dropIndex]
}
selections.forEach { trajectoryTable.items.remove(it) }
if (dI != null) dropIndex = trajectoryTable.items.indexOf(dI) + delta
else if (dropIndex != 0) dropIndex = trajectoryTable.items.size
trajectoryTable.selectionModel.clearSelection()
selections.forEach {
trajectoryTable.items.add(dropIndex, it)
trajectoryTable.selectionModel.select(dropIndex)
dropIndex++
}
event.isDropCompleted = true
selections.clear()
event.consume()
}
}
row
}
// Register backspace and delete to delete selected items in the table
// trajectoryTable.addEventFilter(KeyEvent.KEY_PRESSED) { event ->
// if (event.code in listOf(KeyCode.DELETE, KeyCode.BACK_SPACE)) {
// removeSelectedTrajectories()
// event.consume()
// }
// }
// Trajectory table is initialized with Forward 10
trajectoryTable.items.add(FXTrajectory(FXAction.FORWARD, "10"))
trajectoryTable.columns.addAll(
actionColumn,
quantificationColumn,
maxVelColumn,
maxAngVelColumn,
maxAccelColumn
)
trajectoryTable.selectionModel.selectionMode = SelectionMode.MULTIPLE
// Allows the columns to expand and take up space
trajectoryTable.columnResizePolicy = TableView.CONSTRAINED_RESIZE_POLICY
trajectoryTable.isEditable = true
// If the table is empty
trajectoryTable.placeholder = Label("No trajectories added")
builder.children.add(trajectoryTable)
}
private fun initLogo() {
val topLabel = HBox()
val ftcLogo = ImageView("/ftc_logo.png")
val ftcsimText = Label("FTCSIM")
ftcsimText.font = Font("Arial Bold Italic", 72.0)
ftcLogo.fitWidth = 150.0
ftcLogo.isPreserveRatio = true
topLabel.children.addAll(ftcLogo, ftcsimText)
topLabel.alignment = Pos.CENTER
builder.children.add(topLabel)
}
/**
* Serializes the current trajectory, and then saves it to the user's choice of file
*/
private fun saveTrajectory(stage: Stage) {
// We serialize the entire state of the simulator, not just the trajectory
val serialized = Json.encodeToString(
SerializeQuintuple(
trajectoryTable.items.toList(),
startPose,
specifiedMaxVel,
specifiedMaxAngVel,
specifiedMaxAccel
)
)
val fileChooser = FileChooser()
fileChooser.title = "Save"
fileChooser.initialFileName = "trajectory.ftcsim"
val selectedFile = fileChooser.showSaveDialog(stage)
if (selectedFile != null)
File(selectedFile.toPath().toString()).printWriter().use { out -> out.println(serialized) }
}
/**
* Opens a file containing the serialized trajectory, and then loads it into the table
*/
private fun openTrajectory(stage: Stage) {
val fileChooser = FileChooser()
fileChooser.title = "Open"
val selectedFile = fileChooser.showOpenDialog(stage)
if (selectedFile != null) {
val text = File(selectedFile.toPath().toString()).readText()
// TODO: Verify the text is in fact valid and deserializable
val (deserialized, sP, sMV, sMAV, sMA) = Json.decodeFromString<SerializeQuintuple>(text)
// TODO: Add prompt asking "are you sure you want to delete the current trajectories"
trajectoryTable.items.clear()
trajectoryTable.items.addAll(deserialized)
startPose = sP
specifiedMaxVel = sMV
specifiedMaxAngVel = sMAV
specifiedMaxAccel = sMA
}
stopSimulation()
}
/**
* Exports the trajectory to a format that can be copy-pasted into the autonomous code
*/
private fun exportTrajectory() {
val body = trajectoryTable.items.joinToString(separator = "\n ") { it.exportable(startPose) + ";" }
val export = "private void movement() {\n $body\n resetArm();\n stop();\n}"
val popup = Stage()
val copyableField = TextArea()
copyableField.setPrefSize(600.0, 400.0)
copyableField.isEditable = false
copyableField.text = export
popup.scene = Scene(copyableField)
popup.show()
}
/**
* Creates a popup containing the modifiable configuration of the robot and roadrunner.
*/
private fun openSettings() {
val popup = Stage()
val grid = GridPane()
grid.vgap = 4.0
grid.hgap = 10.0
val fields = listOf(
Triple("Start Pose (x)", TextField(startPose.x.toString()), "in"),
Triple("Start Pose (y)", TextField(startPose.y.toString()), "in"),
Triple("Start Pose (heading)", TextField(startPose.heading.toDegrees.toString()), "deg"),
Triple("Specified Max Velocity", TextField(specifiedMaxVel.toString()), "mph"),
Triple("Specified Max Angular Velocity", TextField(specifiedMaxAngVel.toString()), "rad/sec"),
Triple("Specified Max Acceleration", TextField(specifiedMaxAccel.toString()), "mph^2")
)
// There is not forEachIndexed for maps, so we are doing this instead
var row = 0
fields.forEach { (label, field, units) ->
grid.add(Label(label), 0, row)
grid.add(field, 1, row)
grid.add(Label(units), 2, row)
row++
}
val saveButton = Button("Save")
saveButton.setOnAction {
fields[0].second.text.toDoubleOrNull()?.let { startPose = startPose.copy(x = it) }
?: expectedDoubleError.show()
fields[1].second.text.toDoubleOrNull()?.let { startPose = startPose.copy(y = it) }
?: expectedDoubleError.show()
fields[2].second.text.toDoubleOrNull()?.let { startPose = startPose.copy(heading = it.toRadians) }
?: expectedDoubleError.show()
fields[3].second.text.toDoubleOrNull()?.let { specifiedMaxVel = it } ?: expectedDoubleError.show()
fields[4].second.text.toDoubleOrNull()?.let { specifiedMaxAngVel = it } ?: expectedDoubleError.show()
fields[5].second.text.toDoubleOrNull()?.let { specifiedMaxAccel = it } ?: expectedDoubleError.show()
popup.close()
stopSimulation()
}
val box = VBox()
box.padding = Insets(15.0)
box.spacing = 7.0
box.children.addAll(grid, saveButton)
popup.scene = Scene(box)
popup.show()
}
private fun flipTrajectories() {
startPose = startPose.copy(x = 126 - startPose.x, heading = 180.0.toRadians - startPose.heading)
// JANKY AS SHIT
trajectoryTable.items.toList().forEachIndexed { i, it ->
val newTrajectory = when (it.getAction()) {
FXAction.STRAFE_LEFT -> it.newAction(FXAction.STRAFE_RIGHT)
FXAction.STRAFE_RIGHT -> it.newAction(FXAction.STRAFE_LEFT)
FXAction.TURN -> it.newQuantification("-" + it.getQuantification())
FXAction.SPLINE_TO -> TODO()
FXAction.LINE_TO -> {
val specs = it.getQuantification().split(",", ", ", " ,", " , ").map { it.toDouble() }
val newX = fieldDimReal - 18.0 - specs[0]
val newY = specs[1]
val newHeading = specs[2]
it.newQuantification("$newX, $newY, $newHeading")
}
FXAction.FORWARD, FXAction.BACKWARD, FXAction.DROP_PIXEL, FXAction.DROP_PIXEL_ON_BOARD -> it
}
trajectoryTable.items.removeAt(i)
trajectoryTable.items.add(i, newTrajectory)
}
stopSimulation()
}
/**
* Removes all the trajectories currently selected in the table.
*/
private fun removeSelectedTrajectories() {
// We sort the indices in ascending order, and THEN remove the values from the table to
// avoid shifting the other indices out of their position
trajectoryTable.selectionModel.selectedIndices.sorted().reversed()
.forEach { trajectoryTable.items.removeAt(it) }
trajectoriesModified = true
}
/**
* The guts of the simulator. Responsible for robot animation. Called every frame.
*/
private fun simulationLoop(gc: GraphicsContext) {
// If the trajectories have been modified, we want to stop running through the trajectories
if (trajectoriesModified) stopSimulation()
gc.drawImage(field, 0.0, 0.0)
if (simulate) {
when (val segment = sequence.get(segmentIndex)) {
is TrajectorySegment -> updateRobotMove(segment)
is TurnSegment -> updateRobotTurn(segment)
is ActionSegment -> updateRobotAction(segment)
is WaitSegment -> TODO()
}
}
// Render everything
robot.render(gc)
// Draw the robot's trajectory
sequence.sequenceList?.forEach { drawTrajectory(gc, it) }
// Draw the backboard score
gc.textAlign = TextAlignment.CENTER
gc.textBaseline = VPos.CENTER
gc.font = Font("Arial Bold", 30.0)
gc.fill = Color.WHITE
gc.fillText(
leftBackDropScore.toString(),
leftBackdrop.centerPointX,
leftBackdrop.centerPointY - 7
)
gc.fillText(
rightBackDropScore.toString(),
rightBackdrop.centerPointX,
rightBackdrop.centerPointY - 7
)
// Draw the pixels placed on the field
pixelPositions.forEach { (x, y) -> gc.drawImage(pixel, x - pixel.width / 2, y - pixel.height / 2) }
// handleCollisions()
// Stop the animation once we finish the final segment
if (segmentIndex == sequence.size()) {
timeline.stop()
resetValues()
}
}
/**
* Stops the simulation by resetting all the state values and moving the robot back the
* starting position.
*/
private fun stopSimulation() {
simulate = false
timer.progress = 0.0
resetValues()
robot.moveTo(startPose.in2px)
timeline.play()
}
/**
* Resets the simulator's current state.
*/
private fun resetValues() {
leftBackDropScore = 0
rightBackDropScore = 0
pixelPositions = mutableListOf()
prevPose = startPose
startTime = Double.NaN
sequence = getTrajectorySequence()
trajectoryDurations = sequence.sequenceList?.map { it.duration } ?: emptyList()
totalDuration = trajectoryDurations.sum()
timeCount.text = "- / %.1fs".format(totalDuration)
segmentIndex = 0
trajectoriesModified = false
}
/**
* Detects whether a collision has occurred using the robot and object's bounding boxes, and raises an error
* if a collision has occurred.
*/
private fun handleCollisions() {
fixedObjects.forEach { obj ->
if (robot.collision(obj)) {
// Stop the entire simulation
timeline.stop()
collisionError.show()
}
}
}
/**
* For each simple movement of the robot (this DOES NOT include turns), this function renders the robots
* position at that time. It works by measuring the time since the simulation has started, and what the
* trajectory passed in as a parameter says it should be at the measured time. The function
* `updateRobotTurn` works analogously.
*
* @param segment: The trajectory piece that is currently being animated. Contains all the information
* for the robots position at all times throughout the segment's run time. This stays constant until
* the entire segment piece has been animated.
*/
private fun updateRobotMove(segment: TrajectorySegment) {
val trajectory = segment.trajectory
val profileTime = getProfileTime()
if (profileTime >= segment.duration) segmentIndex++
val (x, y, angle) = trajectory[profileTime].in2px
robot.x = x
robot.y = -y
robot.rotation = angle
}
/**
* Animates the robot's turns. Works the same way as `updateRobotMovement`.
*/
private fun updateRobotTurn(segment: TurnSegment) {
val motion = segment.motionProfile
val profileTime = getProfileTime()
if (profileTime >= segment.duration) segmentIndex++
val angle = motion[profileTime].x
val (x, y, _) = segment.startPose.in2px
robot.x = x
robot.y = -y
robot.rotation = angle.toDegrees
}
/**
* The animation function ran when the robot is performing either:
* - Dropping a pixel on the field
* - Dropping a pixel on the backdrop
* When dropped on the field, it calculates the canvas position to render the pixel. When dropped on the
* backdrop, it waits for the specified amount of time before incrementing the closest backdrop's pixel
* count.
*/
private fun updateRobotAction(segment: ActionSegment) {
when (val action = segment.action) {
Action.DROP_PIXEL -> {
if (getProfileTime() >= segment.duration) {
val rect = robot.asRectangle2D
val rotation = robot.rotation.toRadians
// Some trig to calculate the position the pixel should be at
pixelPositions.add(
Pair(
rect.centerPointX + (action.distanceDropped!!.in2px + rect.height / 2) * cos(rotation),
rect.centerPointY - (action.distanceDropped.in2px + rect.height / 2) * sin(rotation)
)
)
}
}
// Drop the pixel on the closes backboard AFTER the entire segment time is up
Action.DROP_PIXEL_ON_BOARD ->
if (robot.distanceTo(leftBackdrop) < robot.distanceTo(rightBackdrop)
&& getProfileTime() >= segment.duration
) leftBackDropScore++
else if (robot.distanceTo(leftBackdrop) > robot.distanceTo(rightBackdrop)
&& getProfileTime() >= segment.duration
) rightBackDropScore++
}
if (getProfileTime() >= segment.duration) segmentIndex++
}
/**
* Draws out the trajectory the robot will be taking.
*/
private fun drawTrajectory(gc: GraphicsContext, segment: SequenceSegment) {
if (segment is TrajectorySegment) {
gc.lineWidth = 7.0
gc.stroke = Color.BLUE
gc.fill = Color.BLUE
val path = segment.trajectory.path
val samplePoints = Array(numberSamples) { it * (path.length() / (numberSamples - 1)) }
val pathPoints = samplePoints.map { point -> path[point].in2px.vec() }
arrayOf(pathPoints.first(), pathPoints.last()).forEach {
gc.fillOval(
it.x + robotWidth.in2px / 2 - 5,
-it.y + robotLength.in2px / 2 - 5,
10.0,
10.0
)
}
// We want the path to be slightly transparent
gc.globalAlpha = 0.6
gc.strokePolyline(
pathPoints.map { it.x + robotWidth.in2px / 2 }.toDoubleArray(),
pathPoints.map { -it.y + robotLength.in2px / 2 }.toDoubleArray(),
numberSamples
)
gc.globalAlpha = 1.0
}
}
/**
* Converts the GUI trajectory table's items into a sequence for roadrunner.
*/
private fun getTrajectorySequence(): TrajectorySequence {
return TrajectorySequence(trajectoryTable.items.map { (action, q, mV, mAV, mA) ->
// TODO: Make this dung pile better, no nulls please
val amount: Double? = q.toDoubleOrNull()
// "-" represents a default
val maxVel = if (mV == "-") specifiedMaxVel else mV.toDouble()
val maxAngVel = if (mAV == "-") specifiedMaxAngVel else mAV.toDouble()
val maxAccel = if (mA == "-") specifiedMaxAccel else mA.toDouble()
when (action) {
FXAction.FORWARD -> forward(amount!!, maxVel, maxAngVel, maxAccel)
FXAction.BACKWARD -> backward(amount!!, maxVel, maxAngVel, maxAccel)
FXAction.STRAFE_LEFT -> strafeLeft(amount!!, maxVel, maxAngVel, maxAccel)
FXAction.STRAFE_RIGHT -> strafeRight(amount!!, maxVel, maxAngVel, maxAccel)
FXAction.SPLINE_TO -> {
val spline = q.split(",", ", ", " ,", " , ").map { it.toDoubleOrNull() }
splineTo(
spline.getOrNull(0),
spline.getOrNull(1),
spline.getOrNull(2)?.toRadians,
maxVel,
maxAngVel,
maxAccel
)
}
FXAction.LINE_TO -> {
val line = q.split(",", ", ", " ,", " , ").map { it.toDoubleOrNull() }
lineTo(
line.getOrNull(0),
line.getOrNull(1),
line.getOrNull(2)?.toRadians,
maxVel,
maxAngVel,
maxAccel
)
}
FXAction.TURN -> turn(amount!!.toRadians)
FXAction.DROP_PIXEL -> dropPixel()
FXAction.DROP_PIXEL_ON_BOARD -> dropPixelOnBoard()
}
})
}
private fun forward(distance: Double, maxVel: Double, maxAngVel: Double, maxAccel: Double): TrajectorySegment {
val velConst = createVelocityConstraint(maxVel, maxAngVel)
val accelConst = createAccelerationConstraint(maxAccel)
val segment = newBuilder(prevPose).forward(distance, velConst, accelConst).build()[0] as TrajectorySegment
segment.trajectoryType = TrajectoryType.FORWARD
prevPose = segment.endPose
return segment
}
private fun backward(distance: Double, maxVel: Double, maxAngVel: Double, maxAccel: Double): TrajectorySegment {
val velConst = createVelocityConstraint(maxVel, maxAngVel)
val accelConst = createAccelerationConstraint(maxAccel)
val segment = newBuilder(prevPose).back(distance, velConst, accelConst).build()[0] as TrajectorySegment
segment.trajectoryType = TrajectoryType.BACKWARD
prevPose = segment.endPose
return segment
}
private fun strafeLeft(distance: Double, maxVel: Double, maxAngVel: Double, maxAccel: Double): TrajectorySegment {
val velConst = createVelocityConstraint(maxVel, maxAngVel)
val accelConst = createAccelerationConstraint(maxAccel)
val segment = newBuilder(prevPose).strafeLeft(distance, velConst, accelConst).build()[0] as TrajectorySegment
segment.trajectoryType = TrajectoryType.STRAFE_LEFT
prevPose = segment.endPose
return segment
}
private fun strafeRight(distance: Double, maxVel: Double, maxAngVel: Double, maxAccel: Double): TrajectorySegment {
val velConst = createVelocityConstraint(maxVel, maxAngVel)
val accelConst = createAccelerationConstraint(maxAccel)
val segment = newBuilder(prevPose).strafeRight(distance, velConst, accelConst).build()[0] as TrajectorySegment
segment.trajectoryType = TrajectoryType.STRAFE_RIGHT
prevPose = segment.endPose
return segment
}
private fun splineTo(
x: Double?,
y: Double?,
endTangent: Double?,
maxVel: Double,
maxAngVel: Double,
maxAccel: Double
): SequenceSegment {
val velConst = createVelocityConstraint(maxVel, maxAngVel)
val accelConst = createAccelerationConstraint(maxAccel)
val segment = newBuilder(prevPose).splineTo(
Vector2d(x ?: prevPose.x, y ?: prevPose.y),
endTangent ?: 0.0,
velConst,
accelConst
)
.build()[0] as SequenceSegment
prevPose = segment.endPose
return segment
}
private fun lineTo(
x: Double?,
y: Double?,
heading: Double?,
maxVel: Double,
maxAngVel: Double,
maxAccel: Double
): SequenceSegment {
val velConst = createVelocityConstraint(maxVel, maxAngVel)
val accelConst = createAccelerationConstraint(maxAccel)
val segment = newBuilder(prevPose).lineToLinearHeading(
Pose2d(x ?: prevPose.x, y ?: prevPose.y, heading ?: prevPose.heading),
velConst,
accelConst
)
.build()[0] as SequenceSegment
prevPose = segment.endPose
return segment
}
private fun turn(angle: Double): SequenceSegment {
val segment = newBuilder(prevPose).turn(angle).build()[0]
prevPose = segment.endPose
return segment
}
private fun dropPixel() = ActionSegment(Action.DROP_PIXEL, prevPose)
private fun dropPixelOnBoard() = ActionSegment(Action.DROP_PIXEL_ON_BOARD, prevPose)
private fun newBuilder(pose: Pose2d) = TrajectorySequenceBuilder(
pose,
velocityConstraint,
accelerationConstraint,
maxAngVel,
maxAngAccel
)
/**
* The current time in seconds
*/
private fun currentTime() = System.currentTimeMillis() / 1000.0
/**
* Returns the elapsed time along the trajectory currently running. In addition, it also updates
* the timer bar.
*/
private fun getProfileTime(): Double {
// If the simulation has been reset or has not been run yet
if (startTime.isNaN()) startTime = currentTime()
val prevTrajectoryDuration = trajectoryDurations.subList(0, segmentIndex).sum()
val time = currentTime()
val deltaTime = time - startTime
timer.progress = deltaTime / totalDuration
timeCount.text = "%.1fs / %.1fs".format(min(deltaTime, totalDuration), totalDuration)
return deltaTime - prevTrajectoryDuration
}
private fun createVelocityConstraint(maxVel: Double, maxAngVel: Double) =
MinVelocityConstraint(
listOf(
AngularVelocityConstraint(maxAngVel),
MecanumVelocityConstraint(
maxVel,
trackWidth
)
)
)
private fun createAccelerationConstraint(maxAccel: Double) = ProfileAccelerationConstraint(maxAccel)
private fun setupImageButton(button: Button, imagePath: String) {
val image = ImageView(imagePath)
button.setPrefSize(30.0, 30.0)
image.isPreserveRatio = true
image.fitWidth = button.prefWidth
button.graphic = image
button.contentDisplay = ContentDisplay.GRAPHIC_ONLY
}
}
val Double.toRadians get() = Math.toRadians(this)
val Double.toDegrees get() = Math.toDegrees(this)
val Rectangle2D.centerPointX get() = this.minX + this.width / 2
val Rectangle2D.centerPointY get() = this.minY + this.height / 2
fun main(args: Array<String>) {
Application.launch(Simulator::class.java, *args)
}
| ftcsim/src/main/kotlin/Main.kt | 2833952371 |
import com.acmerobotics.roadrunner.geometry.Pose2d
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.DoubleArraySerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.*
/**
* Tuple containing the entire state of the simulator when the trajectory is saved.
*/
@Serializable
data class SerializeQuintuple(
val trajectory: List<FXTrajectory>,
@Serializable(with = Pose2dSerializer::class) val startPose: Pose2d,
val specifiedMaxVel: Double,
val specifiedMaxAngVel: Double,
val specifiedMaxAccel: Double
)
/**
* Serializer for the `SimpleObjectProperty` class of `FXAction`. Simply serializes/deserializes the
* string form of the `FXAction`.
*/
object SOPSerializer : KSerializer<SimpleObjectProperty<FXAction>> {
override val descriptor = PrimitiveSerialDescriptor("SimpleObjectProperty", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: SimpleObjectProperty<FXAction>) {
encoder.encodeString(value.get().toSerialize())
}
override fun deserialize(decoder: Decoder): SimpleObjectProperty<FXAction> {
return SimpleObjectProperty(FXAction.valueOf(decoder.decodeString()))
}
}
/**
* Serializer for the `SimpleStringProperty`. Simply serializes/deserializes its string parameter.
*/
object SSPSerializer : KSerializer<SimpleStringProperty> {
override val descriptor = PrimitiveSerialDescriptor("SimpleObjectProperty", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: SimpleStringProperty) {
encoder.encodeString(value.get())
}
override fun deserialize(decoder: Decoder): SimpleStringProperty {
return SimpleStringProperty(decoder.decodeString())
}
}
/**
* Serializer for `Pose2d`. Since `Pose2d` is a data class, it should be possible to simply annotate it with
* `@Serializable`, however it is contained in the roadrunner library which we shouldn't modify, so instead
* we explicitly create a serializer for it.
*/
object Pose2dSerializer : KSerializer<Pose2d> {
private val delegateSerializer = DoubleArraySerializer()
override val descriptor = PrimitiveSerialDescriptor("Pose2d", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Pose2d) {
encoder.encodeSerializableValue(delegateSerializer, doubleArrayOf(value.x, value.y, value.heading))
}
override fun deserialize(decoder: Decoder): Pose2d {
val array = decoder.decodeSerializableValue(delegateSerializer)
return Pose2d(array[0], array[1], array[2])
}
}
| ftcsim/src/main/kotlin/SerializeUtils.kt | 3704797002 |
package com.github.prosonit.mytestplugin
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.openapi.components.service
import com.intellij.psi.xml.XmlFile
import com.intellij.testFramework.TestDataPath
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.PsiErrorElementUtil
import com.github.prosonit.mytestplugin.services.MyProjectService
@TestDataPath("\$CONTENT_ROOT/src/test/testData")
class MyPluginTest : BasePlatformTestCase() {
fun testXMLFile() {
val psiFile = myFixture.configureByText(XmlFileType.INSTANCE, "<foo>bar</foo>")
val xmlFile = assertInstanceOf(psiFile, XmlFile::class.java)
assertFalse(PsiErrorElementUtil.hasErrors(project, xmlFile.virtualFile))
assertNotNull(xmlFile.rootTag)
xmlFile.rootTag?.let {
assertEquals("foo", it.name)
assertEquals("bar", it.value.text)
}
}
fun testRename() {
myFixture.testRename("foo.xml", "foo_after.xml", "a2")
}
fun testProjectService() {
val projectService = project.service<MyProjectService>()
assertNotSame(projectService.getRandomNumber(), projectService.getRandomNumber())
}
override fun getTestDataPath() = "src/test/testData/rename"
}
| MyTestPlugin/src/test/kotlin/com/github/prosonit/mytestplugin/MyPluginTest.kt | 1662222994 |
package com.github.prosonit.mytestplugin.toolWindow
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBPanel
import com.intellij.ui.content.ContentFactory
import com.github.prosonit.mytestplugin.MyBundle
import com.github.prosonit.mytestplugin.services.MyProjectService
import javax.swing.JButton
class MyToolWindowFactory : ToolWindowFactory {
init {
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
val myToolWindow = MyToolWindow(toolWindow)
val content = ContentFactory.getInstance().createContent(myToolWindow.getContent(), null, false)
toolWindow.contentManager.addContent(content)
}
override fun shouldBeAvailable(project: Project) = true
class MyToolWindow(toolWindow: ToolWindow) {
private val service = toolWindow.project.service<MyProjectService>()
fun getContent() = JBPanel<JBPanel<*>>().apply {
val label = JBLabel(MyBundle.message("randomLabel", "?"))
add(label)
add(JButton(MyBundle.message("shuffle")).apply {
addActionListener {
label.text = MyBundle.message("randomLabel", service.getRandomNumber())
}
})
}
}
}
| MyTestPlugin/src/main/kotlin/com/github/prosonit/mytestplugin/toolWindow/MyToolWindowFactory.kt | 1369537233 |
package com.github.prosonit.mytestplugin
import com.intellij.DynamicBundle
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
@NonNls
private const val BUNDLE = "messages.MyBundle"
object MyBundle : DynamicBundle(BUNDLE) {
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
getMessage(key, *params)
@Suppress("unused")
@JvmStatic
fun messagePointer(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) =
getLazyMessage(key, *params)
}
| MyTestPlugin/src/main/kotlin/com/github/prosonit/mytestplugin/MyBundle.kt | 305388958 |
package com.github.prosonit.mytestplugin.listeners
import com.intellij.openapi.application.ApplicationActivationListener
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.wm.IdeFrame
internal class MyApplicationActivationListener : ApplicationActivationListener {
override fun applicationActivated(ideFrame: IdeFrame) {
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
}
| MyTestPlugin/src/main/kotlin/com/github/prosonit/mytestplugin/listeners/MyApplicationActivationListener.kt | 2865474767 |
package com.github.prosonit.mytestplugin.services
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.openapi.project.Project
import com.github.prosonit.mytestplugin.MyBundle
@Service(Service.Level.PROJECT)
class MyProjectService(project: Project) {
init {
thisLogger().info(MyBundle.message("projectService", project.name))
thisLogger().warn("Don't forget to remove all non-needed sample code files with their corresponding registration entries in `plugin.xml`.")
}
fun getRandomNumber() = (1..100).random()
}
| MyTestPlugin/src/main/kotlin/com/github/prosonit/mytestplugin/services/MyProjectService.kt | 4154795285 |
package com.assignment.findit
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.assignment.findit", appContext.packageName)
}
} | FindIt/app/src/androidTest/java/com/assignment/findit/ExampleInstrumentedTest.kt | 2184675990 |
package com.assignment.findit
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)
}
} | FindIt/app/src/test/java/com/assignment/findit/ExampleUnitTest.kt | 4049064616 |
package com.assignment.findit
import SellUploadClass
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.AppCompatButton
import com.bumptech.glide.Glide
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class SingleProductSell : AppCompatActivity() {
lateinit var imgView: ImageView
lateinit var soldby: TextView
lateinit var price: TextView
lateinit var location: TextView
lateinit var phno: TextView
lateinit var sellerid: TextView
lateinit var buybtn: AppCompatButton
lateinit var database: FirebaseDatabase
lateinit var productRef: DatabaseReference
lateinit var productList: ArrayList<HashMap<String, Any>> // Store products as Maps
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_product_sell)
imgView = findViewById(R.id.imageView3)
soldby = findViewById(R.id.soldbytv)
price = findViewById(R.id.pricetv)
phno = findViewById(R.id.phnotv)
location = findViewById(R.id.loctv)
sellerid = findViewById(R.id.idtv)
buybtn = findViewById(R.id.buybtn)
productList = ArrayList<HashMap<String, Any>>()
// Retrieve product details from intent
val productImgUrl = intent.getStringExtra("productimg")
val soldBy = intent.getStringExtra("soldby")
val iprice = intent.getIntExtra("price", 0) // Use getIntExtra for price
val ilocation = intent.getStringExtra("location")
val sellerId = intent.getStringExtra("sellerid")
val iphno = intent.getStringExtra("phno")
val uid = intent.getStringExtra("uid")
Toast.makeText(this, uid, Toast.LENGTH_SHORT).show()
// Set product details to the views
Glide.with(this).load(productImgUrl).into(imgView) // Use Glide for image loading
soldby.text = "Sold By: $soldBy"
price.text = "Price: $iprice"
phno.text = "Phone Number: $iphno"
location.text = "Location: $ilocation"
sellerid.text = "Seller ID: $sellerId"
val backBtn = findViewById<AppCompatButton>(R.id.backBtn)
backBtn.setOnClickListener {
finishAfterTransition()
}
buybtn.setOnClickListener {
database = FirebaseDatabase.getInstance()
val reference = database.getReference("FindIt/allSold")
database = FirebaseDatabase.getInstance()
Toast.makeText(applicationContext, "Are you sure you want to buy this product?", Toast.LENGTH_SHORT).show()
buybtn.setOnClickListener {
val currentUserId = getCurrentUserId()
// Construct a reference to the specific product using uid
val productRef = database.getReference("FindIt/allSold").child(uid!!)
productRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val product = snapshot.getValue(SellUploadClass::class.java)!!
// Check if sellerId matches and product isn't already bought or pending
if (product.sellerId == sellerId && product.isBought == "no") {
// Set isBought to "pending" and buyer ID
product.isBought = "pending"
product.boughtBy = currentUserId
// Update the product data in Firebase
snapshot.ref.setValue(product)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(
applicationContext,
"Purchase request sent!",
Toast.LENGTH_SHORT
).show()
// (Optional) Handle successful purchase request (e.g., navigate to a different screen)
} else {
Toast.makeText(
applicationContext,
"Failed to request purchase",
Toast.LENGTH_SHORT
).show()
// Handle update failure (e.g., log the error)
}
}
} else {
// Handle scenario where product is not found, already bought, or pending
Toast.makeText(
applicationContext,
"Product not found, already bought, or pending",
Toast.LENGTH_SHORT
).show()
}
} else {
// Handle scenario where the product with the given uid doesn't exist
Toast.makeText(
applicationContext,
"Product not found",
Toast.LENGTH_SHORT
).show()
}
}
override fun onCancelled(error: DatabaseError) {
// Handle database errors here
}
})
}
}
}
private fun getCurrentUserId(): String {
val currentUser = FirebaseAuth.getInstance().currentUser
return if (currentUser != null) {
currentUser.uid
} else {
// Handle the case where there's no logged-in user
""
}
}
}
| FindIt/app/src/main/java/com/assignment/findit/SingleProductSell.kt | 1564943442 |
package com.assignment.findit
import SellUploadClass
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class ProcessingSell : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var productList: ArrayList<SellUploadClass>
private lateinit var adapter: ProcessingAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_processing_sell)
recyclerView = findViewById(R.id.processrecview) // Assuming ID for recycler view
recyclerView.layoutManager = LinearLayoutManager(this)
productList = ArrayList()
adapter = ProcessingAdapter(this, productList)
recyclerView.adapter = adapter
// Get Firebase Database instance
val database = FirebaseDatabase.getInstance()
// Fetch pending products
val currentUserId = FirebaseAuth.getInstance().currentUser!!.uid
val reference = database.getReference("FindIt/allSold")
.orderByChild("sellerId") // Query for products based on seller ID
.equalTo(currentUserId)
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
productList.clear()
for (dataSnapshot in snapshot.children) {
val product = dataSnapshot.getValue(SellUploadClass::class.java)!!
// Filter for pending products only
if (product.isBought == "pending") {
productList.add(product)
}
}
adapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
// Handle database errors
}
})
}
}
| FindIt/app/src/main/java/com/assignment/findit/ProcessingSell.kt | 623413402 |
package com.assignment.findit
import SellUploadClass
import android.app.ActivityOptions
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import com.google.android.gms.tasks.OnCompleteListener
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.Button
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SwitchCompat
import androidx.core.widget.ContentLoadingProgressBar
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class MainActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var productList: ArrayList<SellUploadClass>
lateinit var adapter: RecyclerView.Adapter<*>
private lateinit var btn: Button
private lateinit var btnProcess: Button
private lateinit var btnAdd: Button
private lateinit var layoutSwitch: SwitchCompat
private lateinit var planeLoad: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView = findViewById(R.id.recview)
productList = ArrayList()
adapter = ProductAdapter(this, productList)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
planeLoad = findViewById(R.id.planeLoad)
layoutSwitch = findViewById(R.id.switchbtn)
layoutSwitch.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
// Switch to grid layout
adapter = ProductAdapterGrid(this, productList)
recyclerView.layoutManager = GridLayoutManager(this, 2)
} else {
// Switch to linear layout
adapter = ProductAdapter(this, productList)
recyclerView.layoutManager = LinearLayoutManager(this)
}
recyclerView.adapter = adapter
}
val subButtonAnimationHorizontal = AnimationUtils.loadAnimation(this, R.anim.sub_button_animation_horizontal)
val subButtonAnimationVertical = AnimationUtils.loadAnimation(this, R.anim.sub_button_animation_vertical)
val subButtonAnimationDiagonal = AnimationUtils.loadAnimation(this, R.anim.sub_button_animation_diagonal)
val logOutEntry = AnimationUtils.loadAnimation(this, R.anim.sub_button_logout_entry)
val floatingActionButton = findViewById<LottieAnimationView>(R.id.floatingActionButton)
val fabSubBtn1 = findViewById<FloatingActionButton>(R.id.personFab)
val fabSubBtn2 = findViewById<FloatingActionButton>(R.id.pendingFab)
val fabSubBtn3 = findViewById<FloatingActionButton>(R.id.addtoinventoryFab)
val logOutFab = findViewById<FloatingActionButton>(R.id.logoutFab)
var isRotated = false
floatingActionButton.setOnClickListener {
val anim = RotateAnimation(
0f,
45f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f
)
anim.duration = 200
anim.fillAfter = true
anim.interpolator = LinearInterpolator()
val reverseAnim = RotateAnimation(
70f, // Start from 45 degrees (reversed)
0f, // Rotate to 0 degrees
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f
)
reverseAnim.duration = 200
reverseAnim.fillAfter = true
reverseAnim.interpolator = LinearInterpolator()
fabSubBtn1.setOnClickListener {
val profileIntent = Intent(this, Buy::class.java)
val options = ActivityOptions.makeSceneTransitionAnimation(this)
startActivity(profileIntent, options.toBundle())
}
fabSubBtn3.setOnClickListener {
val historyIntent = Intent(this, Sell::class.java)
val options = ActivityOptions.makeSceneTransitionAnimation(this)
startActivity(historyIntent, options.toBundle())
}
fabSubBtn2.setOnClickListener {
val exploreIntent = Intent(this, ProcessingSell::class.java)
val options = ActivityOptions.makeSceneTransitionAnimation(this)
startActivity(exploreIntent, options.toBundle())
}
logOutFab.setOnClickListener {
// Inflate the custom layout for the dialog
val view = LayoutInflater.from(this).inflate(R.layout.custom_layout_dialog, null)
// Create an AlertDialog builder
val builder = AlertDialog.Builder(this)
// Set the custom view for the dialog
builder.setView(view)
// Find the buttons from the custom layout
val yesButton = view.findViewById<Button>(R.id.yesButton)
// Set positive (Yes) button click listener
yesButton.setOnClickListener {
// User clicked "Yes", proceed with logout
val firebaseAuth = FirebaseAuth.getInstance()
firebaseAuth.signOut()
val profileIntent = Intent(this, Login::class.java)
val options = ActivityOptions.makeSceneTransitionAnimation(this)
startActivity(profileIntent, options.toBundle())
}
// Create and show the alert dialog
val dialog = builder.create()
dialog.show()
}
if (isRotated) {
floatingActionButton.startAnimation(reverseAnim) // Use reverseAnim for reversed rotation
isRotated = false
isRotated = false
fabSubBtn1.visibility = View.GONE
fabSubBtn2.visibility = View.GONE
fabSubBtn3.visibility = View.GONE
logOutFab.visibility = View.GONE
fabSubBtn1.startAnimation(
AnimationUtils.loadAnimation(
this,
R.anim.sub_button_animation_vertical_back
)
)
fabSubBtn2.startAnimation(
AnimationUtils.loadAnimation(
this,
R.anim.sub_button_animation_diagonal_back
)
)
fabSubBtn3.startAnimation(
AnimationUtils.loadAnimation(
this,
R.anim.sub_button_animation_horizantal_back
)
)
logOutFab.startAnimation(
AnimationUtils.loadAnimation(
this,
R.anim.sub_button_logout_exit
)
)
} else {
floatingActionButton.startAnimation(anim)
fabSubBtn1.visibility = View.VISIBLE
fabSubBtn2.visibility = View.VISIBLE
fabSubBtn3.visibility = View.VISIBLE
logOutFab.visibility = View.VISIBLE
fabSubBtn1.startAnimation(subButtonAnimationVertical)
fabSubBtn2.startAnimation(subButtonAnimationDiagonal)
fabSubBtn3.startAnimation(subButtonAnimationHorizontal)
logOutFab.startAnimation(logOutEntry)
isRotated = true
}
}
// Fetch products from Firebase
fetchProducts()
}
private fun fetchProducts() {
val currentUserId = FirebaseAuth.getInstance().currentUser!!.uid
val database = FirebaseDatabase.getInstance()
val reference = database.getReference("FindIt/allSold")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
productList.clear()
for (dataSnapshot in snapshot.children) {
val product = dataSnapshot.getValue(SellUploadClass::class.java)!!
if (product.isBought == "no" && product.sellerId != currentUserId) {
productList.add(product)
}
}
// Hide loading animation after data is fetched
planeLoad.visibility = View.GONE
adapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
// Handle database errors here
planeLoad.visibility = View.GONE // Hide loading animation on error
}
})
}
}
| FindIt/app/src/main/java/com/assignment/findit/MainActivity.kt | 2225199700 |
package com.assignment.findit
import SellUploadClass // Assuming your product data class
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class DonateAdapter(val context: Context, val productList: ArrayList<SellUploadClass>) :
RecyclerView.Adapter<DonateAdapter.DonateViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DonateViewHolder {
val view = LayoutInflater.from(context)
.inflate(R.layout.donate_card, parent, false) // Assuming item layout ID
return DonateViewHolder(view)
}
override fun onBindViewHolder(holder: DonateViewHolder, position: Int) {
val product = productList[position]
holder.productNameTv.text = product.sellerName
holder.locationTv.text = "Location: ${product.location}"
// Load product image using Glide (optional)
// Glide.with(context).load(product.productImgUrl).into(holder.productIv)
}
override fun getItemCount(): Int {
return productList.size
}
class DonateViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
// val productIv: ImageView = itemView.findViewById(R.id.donate_item_image) // Assuming ID
val productNameTv: TextView = itemView.findViewById(R.id.donatename) // Assuming ID
val locationTv: TextView = itemView.findViewById(R.id.donateloc) // Assuming ID
}
}
| FindIt/app/src/main/java/com/assignment/findit/DonateAdapter.kt | 2270682257 |
package com.assignment.findit
import SellUploadClass
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class ProductAdapterGrid(val context: Context, val productList: ArrayList<SellUploadClass>) :
RecyclerView.Adapter<ProductAdapterGrid.ProductViewHolder>() {
inner class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val productImage: ImageView = itemView.findViewById(R.id.imageViewGrid)
val price: TextView = itemView.findViewById(R.id.tvGridPrice)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.main_page_all_sold_card_grid, parent, false)
return ProductViewHolder(view)
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
val product = productList[position]
holder.price.text = "Price: "
Glide.with(context)
.load(product.imageUrl) // Load image URL from SellUploadClass
.into(holder.productImage)
holder.itemView.setOnClickListener {
navigateToProductDetails(product) // Call a new method to handle click
}
}
private fun navigateToProductDetails(product: SellUploadClass) {
val intent = Intent(context, SingleProductSell::class.java)
intent.putExtra("productimg", product.imageUrl) // Replace with actual image logic
intent.putExtra("soldby", product.sellerName)
intent.putExtra("location", product.location)
intent.putExtra("sellerid", product.sellerId)
intent.putExtra("phno", product.phno)
intent.putExtra("uid", product.uid)
context.startActivity(intent)
}
override fun getItemCount(): Int {
return productList.size
}
}
| FindIt/app/src/main/java/com/assignment/findit/ProductAdapterGrid.kt | 3650431501 |
package com.assignment.findit
import SellUploadClass
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.AppCompatButton
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
class ProcessingAdapter(val context: Context, val productList: ArrayList<SellUploadClass>) :
RecyclerView.Adapter<PendingViewHolder>() {
val database: FirebaseDatabase = FirebaseDatabase.getInstance()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PendingViewHolder {
val view: View = LayoutInflater.from(context)
.inflate(R.layout.pending_product_item_layout, parent, false)
return PendingViewHolder(view)
}
override fun onBindViewHolder(holder: PendingViewHolder, position: Int) {
val product = productList[position]
holder.sellerNameTv.text = "Sold By: ${product.sellerName}"
holder.productNameTv.text = product.productName
holder.locationTv.text = "Location: ${product.location}"
holder.phoneNoTv.text = "Phone Number: ${product.phno}"
// Handle button visibility and functionality based on isBought
if (product.isBought == "pending") {
holder.agreeBtn.visibility = View.VISIBLE
holder.leaveBtn.visibility = View.VISIBLE
holder.agreeBtn.setOnClickListener {
handleAgreeAction(product)
}
holder.leaveBtn.setOnClickListener {
handleLeaveAction(product)
}
} else {
holder.agreeBtn.visibility = View.GONE
holder.leaveBtn.visibility = View.GONE
}
}
private fun handleAgreeAction(product: SellUploadClass) {
val reference = database.getReference("FindIt/allSold").child(product.uid)
reference.setValue(product.apply {
isBought = "yes"
})
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// Update buyer's "buy" node to include the product information (optional, implement based on your data structure)
removeFromPending(product) // Delete from seller's pending
// (Optional) Show a success message or update UI
} else {
// Handle update failure (e.g., log the error)
}
}
}
private fun handleLeaveAction(product: SellUploadClass) {
val reference = database.getReference("FindIt/allSold").child(product.uid) // Assuming uid is unique identifier for the product in "allSold"
reference.setValue(product.apply {
isBought = "no"
boughtBy = ""
// Set other relevant fields back to their original values (if needed)
})
.addOnCompleteListener { task ->
if (task.isSuccessful) {
removeFromPending(product) // Delete from seller's pending
// (Optional) Show a confirmation message or update UI
} else {
// Handle update failure (e.g., log the error)
}
}
}
private fun removeFromPending(product: SellUploadClass) {
val sellerId = FirebaseAuth.getInstance().currentUser!!.uid
val pendingRef = database.getReference("FindIt/users/$sellerId/pending").child(product.uid) // Assuming uid is used in pending node as well
pendingRef.removeValue()
}
override fun getItemCount(): Int {
return productList.size
}
}
class PendingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val sellerNameTv: TextView = itemView.findViewById(R.id.sellerNameTv)
val productNameTv: TextView = itemView.findViewById(R.id.productNameTv)
val locationTv: TextView = itemView.findViewById(R.id.locationTv)
val priceTv: TextView = itemView.findViewById(R.id.priceTv)
val phoneNoTv: TextView = itemView.findViewById(R.id.phoneNoTv)
val agreeBtn: AppCompatButton = itemView.findViewById(R.id.buttonAgree)
val leaveBtn: AppCompatButton = itemView.findViewById(R.id.buttonLeave)
}
| FindIt/app/src/main/java/com/assignment/findit/ProcessingAdapter.kt | 1913519818 |
class SellUploadClass(
val sellerName: String,
val productName: String,
val location: String,
val sellerId: String,
var isBought: String,
var boughtBy: String,
val phno: String,
val uid: String,
var isBoughtByCurrentUser: Boolean = false,
val imageUrl: String = ""
) {
// Primary constructor with arguments
// Add an empty secondary constructor for Firebase
constructor() : this("", "", "", "", "no", "", "", "", false, "") {
// Empty implementation for the no-argument constructor
}
}
| FindIt/app/src/main/java/com/assignment/findit/SellUploadClass.kt | 2909561241 |
package com.assignment.findit
import android.app.ActivityOptions
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.transition.Slide
import android.view.Gravity
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.widget.AppCompatButton
import com.google.firebase.auth.FirebaseAuth
class Login : AppCompatActivity() {
lateinit var emailEdt: EditText
lateinit var passEdt: EditText
lateinit var logInBtn: AppCompatButton
lateinit var signUpBtn: AppCompatButton
lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.enterTransition = Slide(Gravity.LEFT)
setContentView(R.layout.activity_login)
auth = FirebaseAuth.getInstance()
emailEdt = findViewById(R.id.editTextText)
passEdt = findViewById(R.id.editTextText3)
signUpBtn = findViewById(R.id.button2)
signUpBtn.setOnClickListener {
val profileIntent = Intent(this, Signup::class.java)
val options = ActivityOptions.makeSceneTransitionAnimation(this)
startActivity(profileIntent, options.toBundle())
}
logInBtn = findViewById(R.id.button)
logInBtn.setOnClickListener {
auth.signInWithEmailAndPassword(emailEdt.text.toString(), passEdt.text.toString()).addOnSuccessListener {
Toast.makeText(this, "Logged in", Toast.LENGTH_SHORT).show()
val profileIntent = Intent(this, MainActivity::class.java)
val options = ActivityOptions.makeSceneTransitionAnimation(this)
startActivity(profileIntent, options.toBundle())
}
.addOnFailureListener {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show()
}
}
}
} | FindIt/app/src/main/java/com/assignment/findit/Login.kt | 3304600116 |
package com.assignment.findit
import SellUploadClass
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import android.Manifest
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.service.autofill.UserData
import androidx.annotation.RequiresApi
import com.google.firebase.storage.FirebaseStorage
import java.io.ByteArrayOutputStream
import kotlin.random.Random
class Sell : AppCompatActivity() {
lateinit var mAuth: FirebaseAuth
lateinit var uidEdt: String
private lateinit var imageView: ImageView
private val REQUEST_IMAGE_CAPTURE = 101
lateinit var database: FirebaseDatabase
lateinit var userRef: DatabaseReference
lateinit var auth: FirebaseAuth
lateinit var sellerName: String
lateinit var phno: String
lateinit var location: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sell)
// Get Firebase Authentication instance
mAuth = FirebaseAuth.getInstance()
uidEdt = Random.nextInt(1, 1001).toString().trim()
val productNameEdt = findViewById<EditText>(R.id.productNameEdt)
val sellBtn = findViewById<Button>(R.id.sellBtn)
imageView = findViewById(R.id.imgView)
// Fab clicking - image capture
val fab = findViewById<FloatingActionButton>(R.id.camera_fab) // Assuming ID for FAB
fab.setOnClickListener {
if (checkCameraPermission()) {
// Open camera intent
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
if (takePictureIntent.resolveActivity(packageManager) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
}
} else {
// Explain permission and guide to settings (can't directly open permission screen)
Toast.makeText(this, "Camera permission is required to capture an image. Please grant permission in your app settings.", Toast.LENGTH_LONG).show()
// Optionally, open the system settings app (might not lead to direct permission screen)
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
val uri = Uri.fromParts("package", packageName, null)
intent.data = uri
startActivity(intent)
}
}
val backBtn = findViewById<AppCompatButton>(R.id.backBtn)
backBtn.setOnClickListener {
finishAfterTransition()
}
// Set up button click listener
sellBtn.setOnClickListener {
val productName = productNameEdt.text.toString().trim()
if (TextUtils.isEmpty(productName)) {
productNameEdt.requestFocus()
return@setOnClickListener
}
// **Data retrieval and writing:**
val currentUserId = getCurrentUserId()
database = FirebaseDatabase.getInstance()
auth = FirebaseAuth.getInstance()
val userId = auth.currentUser?.uid
if (userId != null) {
userRef = database.getReference("FindIt/UserDetails/$userId")
userRef.addListenerForSingleValueEvent(object : ValueEventListener {
@RequiresApi(Build.VERSION_CODES.P)
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val userData = snapshot.value as? Map<*, *>
userData?.let {
val name = it["name"] as? String
val address = it["address"] as? String
val phone = it["phone"] as? String
Toast.makeText(applicationContext, "$name, $address, $phone", Toast.LENGTH_SHORT).show()
location = address.toString()
sellerName = name.toString()
phno = phone.toString()
}
}
}
override fun onCancelled(error: DatabaseError) {
// Handle database error
}
})
}
// Check for existing ID before adding
checkForExistingId(uidEdt, currentUserId) { isUnique ->
if (isUnique) {
val capturedImage = imageView.drawable
if (capturedImage != null) {
val bitmap = (capturedImage as BitmapDrawable).bitmap
uploadImageToFirebase(bitmap) { imageUrl ->
val sellUploadClass = SellUploadClass(
sellerName,
productName,
location,
currentUserId,
"no",
"",
phno,
uidEdt,
false,
imageUrl
)
writeToDatabaseForGlobal(sellUploadClass)
writeToDatabase(sellUploadClass)
productNameEdt.setText("")
imageView.setImageDrawable(null) // Clear image view after upload
}
} else {
// No image captured, proceed without image
val sellUploadClass = SellUploadClass(
sellerName,
productName,
location,
currentUserId,
"no",
"",
phno,
uidEdt,
false,
""// No image URL if not captured
)
writeToDatabaseForGlobal(sellUploadClass)
writeToDatabase(sellUploadClass)
productNameEdt.setText("")
}
} else {
Toast.makeText(this, "This unique ID is already used!", Toast.LENGTH_SHORT).show()
}
}
}
}
fun checkCameraPermission(): Boolean {
return ContextCompat.checkSelfPermission(
this,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
}
fun requestCameraPermission() {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.CAMERA),
REQUEST_IMAGE_CAPTURE
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
val bitmap = data?.extras?.get("data") as Bitmap
imageView.setImageBitmap(bitmap)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted, proceed with camera intent
Toast.makeText(this, "Camera permission granted!", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Camera permission required to capture image!", Toast.LENGTH_SHORT).show()
// You may also want to explain to the user why your app needs camera access and guide them to settings if they choose to deny permission.
}
}
}
private fun writeToDatabaseForGlobal(sellUploadClass: SellUploadClass) {
val database = FirebaseDatabase.getInstance()
val rootRef = database.reference.child("FindIt").child("allSold").child(uidEdt.toString()) // Use push() for unique key
rootRef.setValue(sellUploadClass)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// Toast message can be removed if you prefer
Toast.makeText(this, "Data Uploaded to allSold", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show()
}
}
}
private fun uploadImageToFirebase(bitmap: Bitmap, callback: (String) -> Unit) {
val storageRef = FirebaseStorage.getInstance().reference
val imageRef = storageRef.child("images/${System.currentTimeMillis()}.jpg") // Create unique image name
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val imageData = baos.toByteArray()
val uploadTask = imageRef.putBytes(imageData)
uploadTask.addOnSuccessListener {
it.storage.downloadUrl.addOnSuccessListener { uri ->
val imageUrl = uri.toString()
callback(imageUrl)
}
}.addOnFailureListener { exception ->
Toast.makeText(this, "Image upload failed: ${exception.message}", Toast.LENGTH_SHORT).show()
}
}
private fun writeToDatabase(sellUploadClass: SellUploadClass) {
val database = FirebaseDatabase.getInstance()
val rootRef = database.reference.child("FindIt").child("users")
val userRef = rootRef.child(sellUploadClass.sellerId).child("sell")
userRef.push().setValue(sellUploadClass)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Toast.makeText(this, "Data Uploaded", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show()
}
}
}
private fun getCurrentUserId(): String {
val currentUser = FirebaseAuth.getInstance().currentUser
return if (currentUser != null) {
currentUser.uid!!
} else {
return ""
}
}
private fun checkForExistingId(uniqueId: String, currentUserId: String, callback: (Boolean) -> Unit) {
val database = FirebaseDatabase.getInstance()
val userRef = database.reference.child("FindIt").child("users").child(currentUserId).child("sell")
userRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
var isUnique = true
for (child in dataSnapshot.children) {
val existingId = child.child("uid").getValue(String::class.java) ?: ""
if (existingId == uniqueId) {
isUnique = false
break
}
}
callback(isUnique)
}
override fun onCancelled(databaseError: DatabaseError) {
// Handle database errors (optional)
Toast.makeText(this@Sell, "Error checking ID", Toast.LENGTH_SHORT).show()
}
})
}
} | FindIt/app/src/main/java/com/assignment/findit/Sell.kt | 1934311750 |
package com.assignment.findit
import SellUploadClass // Assuming your product data class
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class Donate : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var productList: ArrayList<SellUploadClass>
private lateinit var adapter: DonateAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_donate)
recyclerView = findViewById(R.id.donateRecView) // Assuming ID for RecyclerView
recyclerView.layoutManager = LinearLayoutManager(this)
productList = ArrayList()
adapter = DonateAdapter(this, productList)
recyclerView.adapter = adapter
// Fetch products from Firebase
fetchDonateProducts()
}
private fun fetchDonateProducts() {
val database = FirebaseDatabase.getInstance()
val reference = database.getReference("FindIt/allSold")
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
productList.clear()
for (dataSnapshot in snapshot.children) {
val product = dataSnapshot.getValue(SellUploadClass::class.java)!!
}
adapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
// Handle database errors here
}
})
}
}
| FindIt/app/src/main/java/com/assignment/findit/Donate.kt | 4234095479 |
package com.assignment.findit
import SellUploadClass
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class Buy : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var productList: ArrayList<SellUploadClass>
private lateinit var adapter: BoughtProductAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_buy)
val backBtn = findViewById<AppCompatButton>(R.id.backBtn)
backBtn.setOnClickListener {
finishAfterTransition()
}
recyclerView = findViewById(R.id.buyrecview)
recyclerView.layoutManager = LinearLayoutManager(this)
productList = ArrayList()
adapter = BoughtProductAdapter(this, productList)
recyclerView.adapter = adapter
fetchBoughtProducts()
}
private fun fetchBoughtProducts() {
val database = FirebaseDatabase.getInstance()
val currentUserId = FirebaseAuth.getInstance().currentUser!!.uid // Assuming user is logged in
val reference = database.getReference("FindIt/allSold")
.orderByChild("boughtBy")
.equalTo(currentUserId)
reference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
productList.clear()
for (dataSnapshot in snapshot.children) {
val product = dataSnapshot.getValue(SellUploadClass::class.java)!!
if(product.isBought == "yes") {
productList.add(product)
}
}
adapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
// Handle database errors here
Toast.makeText(applicationContext, "Error fetching bought products", Toast.LENGTH_SHORT).show()
}
})
}
}
| FindIt/app/src/main/java/com/assignment/findit/Buy.kt | 882584664 |
package com.assignment.findit
import SellUploadClass
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class BoughtProductAdapter(val context: Context, val productList: ArrayList<SellUploadClass>) :
RecyclerView.Adapter<ProductViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
val view: View = LayoutInflater.from(context)
.inflate(R.layout.buy_custom_layout, parent, false)
return ProductViewHolder(view)
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
val product = productList[position]
holder.sellerNameTv.text = "Sold By: ${product.sellerName}"
holder.productNameTv.text = product.productName
holder.locationTv.text = "Location: ${product.location}"
holder.phoneNoTv.text = "Phone Number: ${product.phno}"
// Load image using Glide
Glide.with(context)
.load(product.imageUrl) // Load image URL from SellUploadClass
.into(holder.productIv)
}
override fun getItemCount(): Int {
return productList.size
}
override fun getItemViewType(position: Int): Int {
return if (productList[position].isBoughtByCurrentUser) 1 else 0
}
}
class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val productIv: ImageView = itemView.findViewById(R.id.product_image)
val sellerNameTv: TextView = itemView.findViewById(R.id.seller_name_tv)
val productNameTv: TextView = itemView.findViewById(R.id.product_name_tv)
val locationTv: TextView = itemView.findViewById(R.id.location_tv)
val priceTv: TextView = itemView.findViewById(R.id.price_tv)
val phoneNoTv: TextView = itemView.findViewById(R.id.phone_no_tv)
}
| FindIt/app/src/main/java/com/assignment/findit/BoughtProductAdapter.kt | 1570717794 |
package com.assignment.findit
import android.app.ActivityOptions
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.transition.Slide
import android.view.Gravity
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.widget.AppCompatButton
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
class Signup : AppCompatActivity() {
lateinit var auth: FirebaseAuth
lateinit var emailEdt: EditText
lateinit var passEdt: EditText
lateinit var confPassEdt: EditText
lateinit var nameEdt: EditText // New EditText for name
lateinit var phoneEdt: EditText // New EditText for phone number
lateinit var addressEdt: EditText // New EditText for address
lateinit var signupBtn: AppCompatButton
lateinit var logInBtn: AppCompatButton
lateinit var database: FirebaseDatabase // Added for database access
lateinit var userRef: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.enterTransition = Slide(Gravity.LEFT)
setContentView(R.layout.activity_signup)
auth = FirebaseAuth.getInstance()
emailEdt = findViewById(R.id.editTextText4)
passEdt = findViewById(R.id.editTextText5)
confPassEdt = findViewById(R.id.editTextText6)
nameEdt = findViewById(R.id.nameSignUpEdt) // Reference new EditText
phoneEdt = findViewById(R.id.phnoSignUpEdt) // Reference new EditText
addressEdt = findViewById(R.id.addressSignUpEdt) // Reference new EditText
signupBtn = findViewById(R.id.button3)
logInBtn = findViewById(R.id.button4)
database = FirebaseDatabase.getInstance()
signupBtn.setOnClickListener {
val email = emailEdt.text.toString()
val password = passEdt.text.toString()
val confirmPassword = confPassEdt.text.toString()
val name = nameEdt.text.toString().trim() // Get name with trim()
val phone = phoneEdt.text.toString().trim() // Get phone number with trim()
val address = addressEdt.text.toString().trim() // Get address with trim()
// Check for empty fields
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword) || TextUtils.isEmpty(name) || TextUtils.isEmpty(phone) || TextUtils.isEmpty(address)) {
Toast.makeText(this, "Please fill all fields", Toast.LENGTH_SHORT).show()
} else {
// All fields are filled, proceed with signup
if (password == confirmPassword) {
auth.createUserWithEmailAndPassword(email, password)
.addOnSuccessListener {
val userId = auth.currentUser?.uid // Get current user ID
// Create a User data object (optional, modify if needed)
val userData = hashMapOf(
"name" to name,
"phone" to phone,
"address" to address
)
// Write user data to database under the specified path
if (userId != null) {
val userPath = "FindIt/UserDetails/$userId" // Modified path
database.getReference(userPath).setValue(userData)
.addOnSuccessListener {
Toast.makeText(this, "Account created successfully", Toast.LENGTH_SHORT).show()
val profileIntent = Intent(this, Login::class.java)
val options = ActivityOptions.makeSceneTransitionAnimation(this)
startActivity(profileIntent, options.toBundle())
Toast.makeText(this, "Log In", Toast.LENGTH_SHORT).show()
}
.addOnFailureListener { exception ->
Toast.makeText(this, "Failed to add user data: $exception", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Failed to create account", Toast.LENGTH_SHORT).show()
}
}
.addOnFailureListener { exception ->
Toast.makeText(this, "Signup failed: $exception", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Passwords do not match", Toast.LENGTH_SHORT).show()
}
}
}
logInBtn = findViewById(R.id.button4)
logInBtn.setOnClickListener {
finishAfterTransition()
}
}
} | FindIt/app/src/main/java/com/assignment/findit/Signup.kt | 512245988 |
package com.assignment.findit
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
class SplashScreen : AppCompatActivity() {
lateinit var imageView: ImageView
lateinit var progressBar: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
progressBar = findViewById(R.id.progressBar2) // Assuming "progressBar2" is the progress bar ID
imageView = findViewById(R.id.imageView)
// imageView.startAnimation(AnimationUtils.loadAnimation(applicationContext, R.anim.blink))
// Simulate progress bar filling in 3 seconds
val handler = Handler()
val runnable: Runnable = object : Runnable {
var progress = 0
override fun run() {
if (progress < 100) {
progress += 10
progressBar.progress = progress
handler.postDelayed(this, 500) // Update every 300 milliseconds
} else {
val firebaseAuth = FirebaseAuth.getInstance()
val currentUser = firebaseAuth.currentUser
if (currentUser == null) {
startActivity(Intent(this@SplashScreen, Login::class.java))
} else {
startActivity(Intent(this@SplashScreen, MainActivity::class.java))
}
finish() // Finish the splash screen after navigation
}
}
}
handler.post(runnable)
}
}
| FindIt/app/src/main/java/com/assignment/findit/SplashScreen.kt | 1781168559 |
package com.assignment.findit
import SellUploadClass
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
class ProductAdapter(val context: Context, val productList: ArrayList<SellUploadClass>) :
RecyclerView.Adapter<ProductAdapter.ProductViewHolder>() {
inner class ProductViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val productImage: ImageView = itemView.findViewById(R.id.imageView2)
val productName: TextView = itemView.findViewById(R.id.tv1)
val price: TextView = itemView.findViewById(R.id.textView4)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.main_page_all_sold_card_list, parent, false)
return ProductViewHolder(view)
}
override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
val product = productList[position]
// Set product details to the views (replace with your logic)
//holder.productImage.setImageResource(R.drawable.your_product_image) // Replace with image loading logic based on product data
holder.productName.text = "Sold By: "+product.sellerName
holder.price.text = "Price: "
Glide.with(context)
.load(product.imageUrl) // Load image URL from SellUploadClass
.into(holder.productImage)
holder.itemView.setOnClickListener {
navigateToProductDetails(product) // Call a new method to handle click
}
}
private fun navigateToProductDetails(product: SellUploadClass) {
val intent = Intent(context, SingleProductSell::class.java)
intent.putExtra("productimg", product.imageUrl) // Replace with actual image logic
intent.putExtra("soldby", product.sellerName)
intent.putExtra("location", product.location)
intent.putExtra("sellerid", product.sellerId)
intent.putExtra("phno", product.phno)
intent.putExtra("uid", product.uid)
context.startActivity(intent)
}
override fun getItemCount(): Int {
return productList.size
}
}
| FindIt/app/src/main/java/com/assignment/findit/ProductAdapter.kt | 188988572 |
package com.example.planetresources
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.planetresources", appContext.packageName)
}
} | PlanetResources/app/src/androidTest/java/com/example/planetresources/ExampleInstrumentedTest.kt | 1773437491 |
package com.example.planetresources
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)
}
} | PlanetResources/app/src/test/java/com/example/planetresources/ExampleUnitTest.kt | 2665622358 |
package com.example.planetresources.models
class Nave(val usedTo: String) {
//quita un valor de recurso
fun extractResource() : Int{
return -1
}
override fun toString(): String {
return "Nave($usedTo)"
}
} | PlanetResources/app/src/main/java/com/example/planetresources/models/Nave.kt | 1987157729 |
package com.example.planetresources.models
class Mineral(val name: String, val elapseTime: Int) {
var quantity = 0
fun addResource(){
quantity++
}
override fun toString(): String {
return "Mineral($name,$elapseTime)"
}
} | PlanetResources/app/src/main/java/com/example/planetresources/models/Mineral.kt | 3718592195 |
package com.example.planetresources.view
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.MutableLiveData
import com.example.planetresources.databinding.ActivityMainBinding
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
lateinit var jobPicoMetal : Job
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//crear channel metal
val metalChannel = Channel<Int>(3)
var metalQty = 0
val metalQtyLiveData = MutableLiveData<Int>(0)
//crear channel cristal
val cristalChannel = Channel<Int>(3)
val cristalQtyLiveData = MutableLiveData<Int>(0)
//crear channel deuterio
val deuterioChannel = Channel<Int>(3)
//var deuterioQty = 0
val deuterioQtyLiveData = MutableLiveData<Int>(0)
//METAL
jobPicoMetal = startNewJob(binding.picoMetalIv)
metalQtyLiveData.observe(this){
if (metalQtyLiveData.value!! >= 3) {
jobPicoMetal.cancel()
binding.picoMetalIv.visibility = View.GONE
}
else{
if(!jobPicoMetal.isActive) {
binding.picoMetalIv.visibility = View.VISIBLE
jobPicoMetal = startNewJob(binding.picoMetalIv)
}
}
}
CoroutineScope(Dispatchers.Default).launch {
while (true) {
withContext(Dispatchers.Main) {
binding.cantMetalTv.text = metalQtyLiveData.value!!.toString()
}
metalChannel.send(metalQtyLiveData.value!!)
delay(1000)
if (metalQtyLiveData.value!! < 3 ) {
metalQtyLiveData.postValue(metalQtyLiveData.value!! + 1)
}
}
}
binding.naveMetalIv.setOnClickListener {
CoroutineScope(Dispatchers.Default).launch {
metalChannel.receive()
if (metalQtyLiveData.value!! > 0 ) metalQtyLiveData.postValue(metalQtyLiveData.value!! - 1)
withContext(Dispatchers.Main) {
binding.cantMetalTv.text = metalQtyLiveData.value!!.toString()
rotateNave(binding.naveMetalIv)
/*while (binding.naveMetalIv.y > 682.0) {
delay(500)
binding.naveMetalIv.y -= 50
}
binding.cantMetalTv.text = metalQty.toString()
metalChannel.receive()
if (metalQty > 0 ) metalQty--
while (binding.naveMetalIv.y < 822.0) {
delay(500)
binding.naveMetalIv.y += 50
}*/
//println(binding.naveMetalIv.y)//822.0
}
}
}
//CRISTAL
var jobPicoCristal = startNewJob(binding.picoCristalIv)
cristalQtyLiveData.observe(this){
binding.cantCristalTv.text = cristalQtyLiveData.value!!.toString()
if (cristalQtyLiveData.value!! >= 3) {
jobPicoCristal.cancel()
binding.picoCristalIv.visibility = View.GONE
}else{
if (!jobPicoCristal.isActive) {
binding.picoCristalIv.visibility = View.VISIBLE
jobPicoCristal = startNewJob(binding.picoCristalIv)
}
}
}
CoroutineScope(Dispatchers.IO).launch {
while (true){
withContext(Dispatchers.Main){
//binding.cantCristalTv.text = cristalQtyLiveData.value!!.toString()
}
cristalChannel.send(cristalQtyLiveData.value!!)
delay(2000)
if (cristalQtyLiveData.value!! < 3 ) cristalQtyLiveData.postValue(cristalQtyLiveData.value!! + 1)
}
}
binding.naeCristalIv.setOnClickListener {
CoroutineScope(Dispatchers.IO).launch {
cristalChannel.receive()
if (cristalQtyLiveData.value!! > 0 ) cristalQtyLiveData.postValue(cristalQtyLiveData.value!! - 1)
withContext(Dispatchers.Main){
//binding.cantCristalTv.text = cristalQtyLiveData.value!!.toString()
rotateNave(binding.naeCristalIv)
}
}
}
//DEUTERIO
var jobPicoDeuterio = startNewJob(binding.picoDeuterioIv)
deuterioQtyLiveData.observe(this){
binding.cantDeuterioTv.text = deuterioQtyLiveData.value!!.toString()
if (deuterioQtyLiveData.value!! >= 3) {
jobPicoDeuterio.cancel()
binding.picoDeuterioIv.visibility = View.GONE
}else{
if (!jobPicoDeuterio.isActive) {
binding.picoDeuterioIv.visibility = View.VISIBLE
jobPicoDeuterio = startNewJob(binding.picoDeuterioIv)
}
}
}
CoroutineScope(Dispatchers.IO).launch {
while (true){
/*withContext(Dispatchers.Main){
//binding.cantDeuterioTv.text = deuterioQty.toString()
binding.cantDeuterioTv.text = deuterioQtyLiveData.value!!.toString()
}*/
//deuterioChannel.send(deuterioQty)
deuterioChannel.send(deuterioQtyLiveData.value!!)
delay(3000)
//if (deuterioQty < 3 ) deuterioQty++
if (deuterioQtyLiveData.value!! < 3)
deuterioQtyLiveData.postValue(deuterioQtyLiveData.value!! + 1)
}
}
binding.naveDeuterioIv.setOnClickListener {
CoroutineScope(Dispatchers.IO).launch {
deuterioChannel.receive()
//if (deuterioQty > 0 ) deuterioQty--
if (deuterioQtyLiveData.value!! > 0)
deuterioQtyLiveData.postValue(deuterioQtyLiveData.value!! - 1)
withContext(Dispatchers.Main){
//binding.cantDeuterioTv.text = deuterioQty.toString()
binding.cantDeuterioTv.text = deuterioQtyLiveData.value!!.toString()
rotateNave(binding.naveDeuterioIv)
}
}
}
}
private fun startNewJob(picoIv: ImageView): Job {
return CoroutineScope(Dispatchers.Main).launch {
while (true){
picoIv.rotation = 40f
delay(200)
picoIv.rotation = 0f
delay(200)
}
}
}
private suspend fun rotateNave(naveIv: ImageView) {
naveIv.rotation = 90f
delay(50)
naveIv.rotation = 180f
delay(50)
naveIv.rotation = 270f
delay(50)
naveIv.rotation = 360f
}
} | PlanetResources/app/src/main/java/com/example/planetresources/view/MainActivity.kt | 682525684 |
package com.gulehri.androidtask
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.gulehri.androidtask", appContext.packageName)
}
} | Shah-Saud-JB-Task/app/src/androidTest/java/com/gulehri/androidtask/ExampleInstrumentedTest.kt | 890048615 |
package com.gulehri.androidtask
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)
}
} | Shah-Saud-JB-Task/app/src/test/java/com/gulehri/androidtask/ExampleUnitTest.kt | 1160078313 |
package com.gulehri.androidtask.ads
import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.facebook.shimmer.ShimmerFrameLayout
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdLoader
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.VideoOptions
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdOptions
import com.google.android.gms.ads.nativead.NativeAdView
import com.gulehri.androidtask.R
import com.gulehri.androidtask.utils.Extensions
class ExtraSmallNativeAdsHelper(private val activity: Context) {
private var nativeAdExtraSmall: NativeAd? = null
private var isAdLoaded: Boolean = false
fun setNativeAdSmall(
shimmerContainer: ShimmerFrameLayout?,
frameLayout: FrameLayout, layoutId: Int,
onFail: ((String?) -> Unit)? = null,
onLoad: ((NativeAd?) -> Unit)? = null,
) {
if (Extensions.isNetworkAvailable(activity)) {
if (isAdLoaded) {
// Ad is already loaded, populate the ad without loading it again
populateAdView(frameLayout, layoutId)
} else {
shimmerContainer?.startShimmer()
val builder =
AdLoader.Builder(
activity,
activity.getString(R.string.natives)
)
builder.forNativeAd { unifiedNativeAd: NativeAd ->
if (nativeAdExtraSmall != null) {
nativeAdExtraSmall?.destroy()
}
nativeAdExtraSmall = unifiedNativeAd
isAdLoaded = true // Mark ad as loaded
populateAdView(frameLayout, layoutId)
onLoad?.invoke(nativeAdExtraSmall!!)
}
val videoOptions = VideoOptions.Builder().setStartMuted(true).build()
val adOptions =
NativeAdOptions.Builder().setAdChoicesPlacement(NativeAdOptions.ADCHOICES_TOP_LEFT)
.setVideoOptions(videoOptions).build()
builder.withNativeAdOptions(adOptions)
val adLoader = builder
.withAdListener(object : AdListener() {
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
Log.e("Add Failed", loadAdError.message + "-ECode " + loadAdError.code)
super.onAdFailedToLoad(loadAdError)
nativeAdExtraSmall?.let {
Log.e("Native Error", "Error")
onFail?.invoke(loadAdError.message)
}
}
override fun onAdLoaded() {
super.onAdLoaded()
shimmerContainer?.stopShimmer()
shimmerContainer?.visibility = View.GONE
Log.e("Add Loaded", "LOda")
}
})
.withNativeAdOptions(adOptions)
.build()
adLoader.loadAd(AdRequest.Builder().build())
}
} else {
frameLayout.visibility = View.GONE
}
}
private fun populateAdView(frameLayout: FrameLayout, layoutId: Int) {
val adView =
(activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(
layoutId,
null
) as NativeAdView
populateUnifiedNativeAdSmallView(nativeAdExtraSmall!!, adView)
frameLayout.removeAllViews()
frameLayout.addView(adView)
}
private fun populateUnifiedNativeAdSmallView(nativeAd: NativeAd, adView: NativeAdView) {
adView.headlineView = adView.findViewById(R.id.ad_headline)
adView.callToActionView = adView.findViewById(R.id.ad_call_to_action)
adView.iconView = adView.findViewById(R.id.ad_app_icon)
if (nativeAd.headline != null) (adView.headlineView as TextView).text = nativeAd.headline
if (nativeAd.callToAction == null) {
adView.callToActionView?.visibility = View.GONE
} else {
adView.callToActionView?.visibility = View.VISIBLE
(adView.callToActionView as Button).text = nativeAd.callToAction
}
if (nativeAd.icon != null) {
adView.iconView?.visibility = View.VISIBLE
(adView.iconView as ImageView).setImageDrawable(nativeAd.icon?.drawable)
} else adView.iconView?.visibility = View.GONE
adView.setNativeAd(nativeAd)
}
}
| Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/ads/ExtraSmallNativeAdsHelper.kt | 3393463336 |
package com.gulehri.androidtask.ads
import android.app.Activity
import android.util.Log
import androidx.annotation.StringRes
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import com.gulehri.androidtask.R
import com.gulehri.androidtask.ui.MainActivity
import com.gulehri.androidtask.utils.Extensions
import com.gulehri.androidtask.utils.INTER_AD_CAPPING
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.util.concurrent.TimeUnit
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
object InterstitialHelper {
private var TAG = "inter_ad_log"
private var mInterstitialAd: InterstitialAd? = null
private var isAdShowing = false
private var isAdLoading = false
private var lastInterstitialAdDismissTime = 0L
private var adCappingBetweenInterstitialAndAppOpenAd = 0L
private var job: CoroutineScope = CoroutineScope(Dispatchers.Main)
fun loadInterAd(
activity: Activity,
@StringRes adId: Int = R.string.interstitial
) {
if (Extensions.isNetworkAvailable(activity)) {
try {
isAdLoading = true
Log.d(TAG, "loadInterAd: is Called ${activity.getString(adId)}")
val adRequest = AdRequest.Builder().build()
InterstitialAd.load(
activity, activity.getString(adId), adRequest,
object : InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(error: LoadAdError) {
super.onAdFailedToLoad(error)
mInterstitialAd = null
isAdLoading = false
Log.d(TAG, "Failed to load")
}
override fun onAdLoaded(interAd: InterstitialAd) {
super.onAdLoaded(interAd)
mInterstitialAd = interAd
isAdLoading = false
Log.d(TAG, "Ad is loaded ${activity.getString(adId)}")
}
})
} catch (e: IOException) {
mInterstitialAd = null
isAdLoading = false
}
}
}
fun showAndLoadInterAd(
activity: Activity,
canLoadNext: Boolean = false,
onDismiss: () -> Unit
) {
if (!isAdLoading /*&& isTimeOfNextInterAd()*/ && mInterstitialAd != null
&& Extensions.isNetworkAvailable(activity) && !MainActivity.isActivityPause
) {
job.launch {
LoadingDialog.showLoadingDialog(activity)
withContext(Dispatchers.IO) {
delay(1500.milliseconds)
}
LoadingDialog.hideLoadingDialog(activity)
if (!MainActivity.isActivityPause)
mInterstitialAd?.show(activity)
}.invokeOnCompletion {
if (it == null) {
mInterstitialAd?.fullScreenContentCallback =
object : FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
Log.d(TAG, "Ad is Dismissed")
mInterstitialAd = null
isAdShowing = false
lastInterstitialAdDismissTime = System.currentTimeMillis()
fetchAnother(canLoadNext, activity)
}
override fun onAdFailedToShowFullScreenContent(p0: AdError) {
super.onAdFailedToShowFullScreenContent(p0)
isAdShowing = false
mInterstitialAd = null
isAdLoading = false
onDismiss()
fetchAnother(canLoadNext, activity)
}
override fun onAdImpression() {
isAdShowing = true
isAdLoading = false
onDismiss()
}
override fun onAdShowedFullScreenContent() {
isAdShowing = true
isAdLoading = false
}
}
} else {
onDismiss()
}
}
} else {
onDismiss()
}
}
private fun fetchAnother(next: Boolean, activity: Activity) {
if (next) {
job.launch {
withContext(Dispatchers.IO) {
delay(5.seconds)
}
loadInterAd(activity, R.string.interstitial)
}
}
}
fun getCurrentInterAd(): InterstitialAd? = mInterstitialAd
fun isInterAdShowing(): Boolean = isAdShowing
fun isInterAdLoading(): Boolean = isAdLoading
private fun isTimeOfNextInterAd(): Boolean =
timeDifference(lastInterstitialAdDismissTime) >= (INTER_AD_CAPPING - 10)
private fun timeDifference(adLoadedTime: Long): Int {
val current = System.currentTimeMillis()
val elapsedTime = current - adLoadedTime
return TimeUnit.MILLISECONDS.toSeconds(elapsedTime).toInt()
}
fun destroyAll(activity: Activity) {
LoadingDialog.hideLoadingDialog(activity = activity)
isAdShowing = false
mInterstitialAd = null
lastInterstitialAdDismissTime = 0L
job.cancel()
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/ads/InterstitialHelper.kt | 1894969037 |
package com.gulehri.androidtask.ads
import android.app.Activity
import android.app.Dialog
import android.view.Window
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import com.gulehri.androidtask.R
object LoadingDialog {
var dialog: Dialog? = null
@JvmStatic
fun showLoadingDialog(context: Activity, @StringRes title: Int? = R.string.loadingAds) {
if (!context.isFinishing && !context.isDestroyed) {
if (dialog == null) {
try {
dialog = Dialog(context)
dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog?.window?.setBackgroundDrawable(
ContextCompat.getDrawable(
context,
R.drawable.loading_dialog_bg
)
)
dialog?.setCancelable(false)
dialog?.setContentView(R.layout.dialog_loading)
val textView = dialog?.findViewById<TextView>(R.id.progress_text)
if (title != null) {
textView?.text = context.getString(title)
}
dialog?.show()
} catch (_: Exception) {
} catch (_: java.lang.Exception) {
} catch (_: IllegalArgumentException) {
}
} else dialog?.show()
}
}
@JvmStatic
fun hideLoadingDialog(activity: Activity) {
try {
if (!activity.isFinishing && !activity.isDestroyed && dialog != null) {
dialog?.dismiss()
}
} catch (_: Exception) {
} catch (_: java.lang.Exception){}
}
}
| Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/ads/LoadingDialog.kt | 1267062314 |
package com.gulehri.androidtask.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.gulehri.androidtask.ads.InterstitialHelper
import com.gulehri.androidtask.databinding.ActivityMainBinding
import com.gulehri.androidtask.screenshort.Actions
import com.gulehri.androidtask.screenshort.ScreenShortService
import com.gulehri.androidtask.utils.Extensions.isMyServiceRunning
import com.gulehri.androidtask.utils.PermissionUtils
class MainActivity : AppCompatActivity() {
companion object {
var isActivityPause = false
}
private lateinit var binding: ActivityMainBinding
private val mediaProjectionManager: MediaProjectionManager by lazy {
application.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Request permission to capture the screen
if (!this.isMyServiceRunning(ScreenShortService::class.java)) {
startActivityForResult(
mediaProjectionManager.createScreenCaptureIntent(),
77
)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
PermissionUtils.checkAndRequestPermissions(this) {
if (data != null) {
startScreenShortService(resultCode, data)
}
}
}
}
private fun startScreenShortService(code: Int, data: Intent?) {
if (!this.isMyServiceRunning(ScreenShortService::class.java)) {
startService(Intent(this, ScreenShortService::class.java).apply {
action = Actions.START.toString()
putExtra("code", code)
putExtra("data", data)
})
}
}
override fun onResume() {
super.onResume()
isActivityPause = false
}
override fun onPause() {
super.onPause()
isActivityPause = true
}
override fun onDestroy() {
super.onDestroy()
InterstitialHelper.destroyAll(this)
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/ui/MainActivity.kt | 3659410335 |
package com.gulehri.androidtask.ui.adapters
import android.content.Context
import android.provider.Settings.Global.getString
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil.load
import coil.transform.RoundedCornersTransformation
import com.gulehri.androidtask.R
import com.gulehri.androidtask.ads.ExtraSmallNativeAdsHelper
import com.gulehri.androidtask.databinding.NativeAdsContainerBinding
import com.gulehri.androidtask.databinding.SingleImageBinding
import com.gulehri.androidtask.model.Image
class ScreenshotsAdapter(private val context: Context, private val onItemClick: (Image, View) -> Unit) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var itemList: MutableList<Image> = mutableListOf()
companion object{
const val VIEW_TYPE_IMAGE = 0
const val VIEW_TYPE_AD = 1
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return when (viewType) {
VIEW_TYPE_IMAGE -> {
val binding = SingleImageBinding.inflate(inflater, parent, false)
ImageViewHolder(binding)
}
VIEW_TYPE_AD -> {
val binding = NativeAdsContainerBinding.inflate(inflater, parent, false)
AdViewHolder(binding)
}
else -> throw IllegalArgumentException("Invalid view type")
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when(holder){
is ImageViewHolder ->{
holder.bind(image = itemList[position])
}
is AdViewHolder ->{
holder.bind()
}
}
}
override fun getItemCount(): Int {
return itemList.size
}
override fun getItemViewType(position: Int): Int {
Log.d("getItemViewType", "")
return itemList[position].view_type
}
fun updateData(newList: MutableList<Image>) {
itemList.clear()
itemList = newList
notifyDataSetChanged()
}
// ViewHolder for image items
inner class ImageViewHolder(private val binding: SingleImageBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(image: Image) {
//LoadReal Image
// binding.img.load(image.path)
binding.img.load(image.path) {
transformations(RoundedCornersTransformation(10f))
}
binding.btnMenu.setOnClickListener {
onItemClick(image, it)
}
}
}
// ViewHolder for ad items
class AdViewHolder(private val binding: NativeAdsContainerBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind() {
ExtraSmallNativeAdsHelper(binding.root.context).setNativeAdSmall(
binding.nativeAdIncludeSmall.splashShimmer,
binding.nativeAdIncludeSmall.adFrame,
R.layout.extra_small_native,
)
// val nativeHelper = NativeHelper(binding.root.context)
// nativeHelper.populateUnifiedNativeAdView(
// NativeHelper.adMobNativeAd,
// binding.nativeContainer,
// binding.adPlaceHolder, 110
// ) {}
//
// binding.nativeContainer.show()
}
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/ui/adapters/ScreenshotsAdapter.kt | 3030299606 |
package com.gulehri.androidtask.ui.vm
import android.os.Environment
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.gulehri.androidtask.model.Image
import kotlinx.coroutines.launch
import java.io.File
class ImageViewModel : ViewModel() {
private val _imageList = MutableLiveData<List<Image>>()
val imageList: LiveData<List<Image>> get() = _imageList
fun loadImages() {
viewModelScope.launch {
val directory =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
val taskDirectory = File(directory, "Shah Saud Task")
if (taskDirectory.exists() && taskDirectory.isDirectory) {
val images = taskDirectory.listFiles { file -> file.isFile }?.map { file ->
Image(file.absolutePath)
} ?: emptyList()
_imageList.postValue(images)
}
}
}
fun deleteFile(imagePath: String) {
viewModelScope.launch {
File(imagePath).deleteRecursively()
loadImages()
}
}
}
| Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/ui/vm/ImageViewModel.kt | 2799195532 |
package com.gulehri.androidtask.ui
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.PopupMenu
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.gulehri.androidtask.R
import com.gulehri.androidtask.ads.InterstitialHelper
import com.gulehri.androidtask.ui.adapters.ScreenshotsAdapter
import com.gulehri.androidtask.databinding.FragmentMainBinding
import com.gulehri.androidtask.utils.Extensions
import com.gulehri.androidtask.model.Image
import com.gulehri.androidtask.ui.vm.ImageViewModel
import com.gulehri.androidtask.utils.Extensions.hide
import com.gulehri.androidtask.utils.Extensions.show
class MainFragment : Fragment() {
private var _binding: FragmentMainBinding? = null
private val binding get() = _binding!!
private var _adapter: ScreenshotsAdapter? = null
val adapter get() = _adapter!!
private val imageViewModel by viewModels<ImageViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMainBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
loadImages()
//PreLoadInterAd
if (Extensions.isNetworkAvailable(view.context))
activity?.let { InterstitialHelper.loadInterAd(it) }
binding.swipeRefreshLayout.setOnRefreshListener {
loadImages()
}
}
private fun loadImages() {
// Observe the LiveData
imageViewModel.imageList.observe(viewLifecycleOwner) { images ->
val updatedImageList = mutableListOf<Image>()
for ((index, image) in images.withIndex()) {
updatedImageList.add(image)
// Add an ad item after every 6 images
if ((index + 1) % 6 == 0 && index + 1 < images.size) {
val adItem = Image(path = "ad", view_type = 1) // Assuming view_type 1 is for ad items
updatedImageList.add(adItem)
}
}
Log.d("loadImages", "$updatedImageList")
adapter.updateData(updatedImageList)
binding.swipeRefreshLayout.isRefreshing = false
if (updatedImageList.isEmpty()) {
binding.noDataPlaceHolder.show()
} else {
binding.noDataPlaceHolder.hide()
}
}
imageViewModel.loadImages()
}
private fun setupRecyclerView() {
val layoutManager = GridLayoutManager(requireContext(), 3)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return if (adapter.getItemViewType(position) == ScreenshotsAdapter.VIEW_TYPE_AD) {
layoutManager.spanCount
} else {
1
}
}
}
binding.recView.layoutManager = layoutManager
_adapter = ScreenshotsAdapter(requireContext(),::menuClick)
binding.recView.adapter = adapter
}
private fun menuClick(image: Image, anchorView: View) {
val popupMenu = PopupMenu(requireContext(), anchorView)
popupMenu.inflate(R.menu.menu)
popupMenu.setOnMenuItemClickListener { item: MenuItem ->
when (item.itemId) {
R.id.menu_open -> {
navigateToNext(image)
true
}
R.id.menu_share -> {
activity?.let {
Extensions.shareImage(it, image.path)
}
true
}
R.id.menu_delete -> {
imageViewModel.deleteFile(image.path)
true
}
else -> false
}
}
popupMenu.show()
}
private fun navigateToNext(image: Image) {
activity?.let {
InterstitialHelper.showAndLoadInterAd(it, true) {
if (findNavController().currentDestination?.id == R.id.mainFragment) {
findNavController().navigate(
R.id.action_mainFragment_to_detailFragment,
bundleOf("image" to image)
)
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_adapter = null
_binding = null
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/ui/MainFragment.kt | 3769119527 |
package com.gulehri.androidtask.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import coil.load
import com.gulehri.androidtask.databinding.FragmentDetailBinding
import com.gulehri.androidtask.model.Image
import com.gulehri.androidtask.ui.vm.ImageViewModel
class DetailFragment : Fragment() {
private var _binding: FragmentDetailBinding? = null
private val binding get() = _binding!!
fun image() = arguments?.getParcelable<Image>("image")
private val imageViewModel by viewModels<ImageViewModel>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
_binding = FragmentDetailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.imageView3.load(image()?.path)
binding.toolbar.setNavigationOnClickListener {
findNavController().popBackStack()
}
binding.btnDel.setOnClickListener {
image()?.let { it1 -> imageViewModel.deleteFile(it1.path) }
findNavController().popBackStack()
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/ui/DetailFragment.kt | 2591001740 |
package com.gulehri.androidtask
import android.app.Application
import android.app.NotificationManager
import android.os.Build
import com.google.firebase.FirebaseApp
import com.gulehri.androidtask.utils.Extensions.createNotificationChannel
/*
* Created by Shah Saud on 12/24/2023.
*/
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
init()
}
private fun init() {
FirebaseApp.initializeApp(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel(this, getSystemService(NotificationManager::class.java))
}
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/MyApp.kt | 1064176610 |
package com.gulehri.androidtask.utils
import android.app.Activity
import android.app.ActivityManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.content.FileProvider
import com.gulehri.androidtask.R
import java.io.File
object Extensions {
fun Any?.debug() {
Log.d("find", "$this")
}
fun infoLog(tag: String, message: String) = Log.i(tag, message)
fun isNetworkAvailable(context: Context): Boolean {
var result = false
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
cm?.run {
cm.getNetworkCapabilities(cm.activeNetwork)?.run {
result = when {
hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
}
}
return result
}
@RequiresApi(26)
fun createNotificationChannel(context: Context, notificationManager: NotificationManager) {
val notificationChannel = NotificationChannel(
CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH
)
notificationChannel.apply {
description = context.getString(R.string.notification)
enableVibration(true)
}
notificationManager.createNotificationChannel(notificationChannel)
}
fun Context.isMyServiceRunning(serviceClass: Class<*>): Boolean {
val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager?
for (service in manager!!.getRunningServices(Int.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
return true
}
}
return false
}
fun View.hide() {
visibility = View.GONE
}
fun View.show() {
visibility = View.VISIBLE
}
fun appDirectory(): String {
val myDirectory =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
.toString() + File.separator + "Shah Saud Task"
val myDir = File(myDirectory)
if (!myDir.exists()) {
try {
myDir.mkdirs()
} catch (e: Exception) {
myDir.mkdir()
}
}
return myDirectory
}
fun shareImage(context: Activity, path: String?) {
path?.let {
val contentUri =
FileProvider.getUriForFile(context, context.packageName + ".provider", File(path))
if (contentUri != null) {
Intent().also {
it.action = Intent.ACTION_SEND
it.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.app_name))
it.putExtra(Intent.EXTRA_TEXT, context.getString(R.string.follow_for_more))
it.type = "image/*"
it.putExtra(Intent.EXTRA_STREAM, contentUri)
it.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
}.also {
context.startActivity(it)
}
}
} ?: Toast.makeText(context, R.string.something_went_wrong, Toast.LENGTH_SHORT).show()
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/utils/Extensions.kt | 2758591191 |
package com.gulehri.androidtask.utils
import android.Manifest
import android.os.Build
import com.gulehri.androidtask.ui.MainActivity
import com.permissionx.guolindev.PermissionX
object PermissionUtils {
fun checkAndRequestPermissions(activity: MainActivity, onGrant: () -> Unit) {
val hasStoragePermission =
PermissionX.isGranted(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
val hasMediaImagesPermission =
PermissionX.isGranted(activity, Manifest.permission.READ_MEDIA_IMAGES)
val hasWritePermission =
PermissionX.isGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
val hasNotificationPermission =
PermissionX.isGranted(activity, Manifest.permission.POST_NOTIFICATIONS)
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> {
if (!hasMediaImagesPermission && !hasNotificationPermission) {
PermissionX.init(activity).permissions(
Manifest.permission.READ_MEDIA_IMAGES,
Manifest.permission.POST_NOTIFICATIONS,
).onExplainRequestReason { scope, deniedList ->
scope.showRequestReasonDialog(
deniedList,
"Allow these Permission for the App to work Properly.",
"OK",
"Cancel"
)
}.onForwardToSettings { scope, deniedList ->
scope.showForwardToSettingsDialog(
deniedList,
"You need to allow necessary permissions in Settings manually",
"OK",
"Cancel"
)
}.request { allGranted, grantedList, deniedList ->
if (allGranted) {
onGrant()
}
}
} else onGrant()
}
Build.VERSION.SDK_INT < Build.VERSION_CODES.R -> {
if (!hasWritePermission && !hasStoragePermission) {
PermissionX.init(activity).permissions(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
).onExplainRequestReason { scope, deniedList ->
scope.showRequestReasonDialog(
deniedList,
"Allow these Permission for the App to work Properly.",
"OK",
"Cancel"
)
}.onForwardToSettings { scope, deniedList ->
scope.showForwardToSettingsDialog(
deniedList,
"You need to allow necessary permissions in Settings manually",
"OK",
"Cancel"
)
}.request { allGranted, grantedList, deniedList ->
if (allGranted) {
onGrant()
}
}
} else onGrant()
}
else -> {
if (!hasStoragePermission) {
PermissionX.init(activity)
.permissions(
Manifest.permission.READ_EXTERNAL_STORAGE
).onExplainRequestReason { scope, deniedList ->
scope.showRequestReasonDialog(
deniedList,
"Allow these Permission for the App to work Properly.",
"OK",
"Cancel"
)
}
.onForwardToSettings { scope, deniedList ->
scope.showForwardToSettingsDialog(
deniedList,
"You need to allow necessary permissions in Settings manually",
"OK",
"Cancel"
)
}
.request { allGranted, grantedList, deniedList ->
if (allGranted) {
onGrant()
}
}
} else onGrant()
}
}
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/utils/PermissionUtils.kt | 899394447 |
package com.gulehri.androidtask.utils;
/*
* Created by Shah Saud on 12/24/2023.
*/
const val CHANNEL_NAME = "Screen Short"
const val CHANNEL_ID = "98"
const val INTER_AD_CAPPING = 5 //5Seconds | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/utils/Constants.kt | 1220811038 |
package com.gulehri.androidtask.model
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Image(
val path: String,
val view_type: Int = 0
) : Parcelable
| Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/model/Image.kt | 1946395521 |
package com.gulehri.androidtask.screenshort
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.widget.Toast
/*
* Created by Shah Saud on 12/24/2023.
*/
class ScreenShortService : Service() {
companion object {
var code: Int = 0
var data: Intent? = null
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
Actions.START.toString() -> {
code = intent.getIntExtra("code", 0)
data = intent.getParcelableExtra("data")
startForeground(79, NotificationHelper.getNotification(this))
}
Actions.SCREENSHOT.toString() -> {
data?.let { ScreenshotHelper(context = this).captureAndSaveScreenshot(code, it) }
}
Actions.CANCEL.toString() -> stopSelf()
}
return START_NOT_STICKY
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/screenshort/ScreenShortService.kt | 1568780441 |
package com.gulehri.androidtask.screenshort
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.gulehri.androidtask.utils.Extensions.debug
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class MyNotificationReceiver : BroadcastReceiver() {
@SuppressLint("MissingPermission")
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Actions.CANCEL.toString() -> {
context.startService(Intent(context, ScreenShortService::class.java).apply {
action = Actions.CANCEL.toString()
})
}
Actions.SCREENSHOT.toString() -> {
CoroutineScope(Dispatchers.IO).launch {
delay(2000)
withContext(Dispatchers.Default) {
context.startService(Intent(context, ScreenShortService::class.java).apply {
action = Actions.SCREENSHOT.toString()
})
}
}
try {
val it = Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
context.sendBroadcast(it)
} catch (e: Exception) {
e.debug()
}
}
}
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/screenshort/MyNotificationReceiver.kt | 1835201975 |
package com.gulehri.androidtask.screenshort
enum class Actions {
START, CANCEL, SCREENSHOT
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/screenshort/Actions.kt | 1194212035 |
package com.gulehri.androidtask.screenshort
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.hardware.display.DisplayManager
import android.media.ImageReader
import android.media.MediaPlayer
import android.media.MediaScannerConnection
import android.media.projection.MediaProjectionManager
import android.util.DisplayMetrics
import android.view.WindowManager
import android.widget.Toast
import com.gulehri.androidtask.R
import com.gulehri.androidtask.utils.Extensions
import com.gulehri.androidtask.utils.Extensions.debug
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.UUID
class ScreenshotHelper(private val context: Context) {
fun captureAndSaveScreenshot(
code: Int, intent: Intent
) {
CoroutineScope(Dispatchers.IO).launch {
delay(500)
withContext(Dispatchers.Main) {
val mediaProjectionManager =
context.applicationContext.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
val windowManager =
context.applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val mediaProjection = mediaProjectionManager.getMediaProjection(code, intent)
val display = windowManager.defaultDisplay
val displayMetrics = DisplayMetrics()
display.getMetrics(displayMetrics)
// Create an ImageReader to capture the screen content
val imageReader = ImageReader.newInstance(
displayMetrics.widthPixels,
displayMetrics.heightPixels,
android.graphics.PixelFormat.RGBA_8888,
2
)
// Create a virtual display
val virtualDisplay = mediaProjection?.createVirtualDisplay(
"Screenshot",
displayMetrics.widthPixels,
displayMetrics.heightPixels,
displayMetrics.densityDpi,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
imageReader.surface,
null,
null
)
imageReader.setOnImageAvailableListener({
try {
val image = it.acquireLatestImage()
val planes = image.planes
val buffer = planes[0].buffer.rewind()
val pixelStride = planes[0].pixelStride
val rowStride = planes[0].rowStride
val rowPadding: Int = rowStride - pixelStride * displayMetrics.widthPixels
// create bitmap
val bitmap = Bitmap.createBitmap(
displayMetrics.widthPixels + rowPadding / pixelStride,
displayMetrics.heightPixels,
Bitmap.Config.ARGB_8888
)
bitmap.copyPixelsFromBuffer(buffer)
saveScreenshot(bitmap)
mediaProjection?.stop()
virtualDisplay?.release()
it.close()
} catch (e: Exception) {
e.localizedMessage.debug()
}
}, null)
}
}
}
private fun saveScreenshot(bitmap: Bitmap) {
val myPath: File?
val directory = Extensions.appDirectory()
myPath = File(directory, "${UUID.randomUUID()}.png")
kotlin.runCatching {
FileOutputStream(myPath).use {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)
}
bitmap.recycle()
}.onFailure {
try {
bitmap.recycle()
} catch (e: IOException) {
e.message.toString().debug()
}
}.onSuccess {
MediaScannerConnection.scanFile(context, arrayOf(myPath.absolutePath), null) { _, _ -> }
playSaveSound()
Toast.makeText(context, "Image Saved", Toast.LENGTH_SHORT).show()
}
}
private fun playSaveSound() {
try {
val mediaPlayer = MediaPlayer.create(context, R.raw.camera)
mediaPlayer.setOnCompletionListener {
it.release()
}
mediaPlayer.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
| Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/screenshort/ScreenshotHelper.kt | 3630268404 |
package com.gulehri.androidtask.screenshort
import android.annotation.SuppressLint
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import com.gulehri.androidtask.R
import com.gulehri.androidtask.utils.CHANNEL_ID
object NotificationHelper {
@SuppressLint("MissingPermission")
fun getNotification(context: Context): Notification {
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.baseline_notifications_24)
.setContentTitle("Your SS Buddy")
.setContentText("The task is running")
.setOnlyAlertOnce(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.addAction(
R.drawable.baseline_power_settings_new_24,
"Cancel",
createActionIntent(context, Actions.CANCEL.toString())
)
.addAction(
R.drawable.round_add_24,
"Screenshot",
createActionIntent(context, Actions.SCREENSHOT.toString())
)
.setAutoCancel(true)
return builder.build()
}
private fun createActionIntent(context: Context, action: String): PendingIntent {
val intent = Intent(context, MyNotificationReceiver::class.java)
intent.action = action
return PendingIntent.getBroadcast(
context,
0,
intent,
PendingIntent.FLAG_IMMUTABLE
)
}
} | Shah-Saud-JB-Task/app/src/main/java/com/gulehri/androidtask/screenshort/NotificationHelper.kt | 742937352 |
package com.sopt.now
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.sopt.now", appContext.packageName)
}
} | youjin-park/app/src/androidTest/java/com/sopt/now/ExampleInstrumentedTest.kt | 2298658867 |
package com.sopt.now
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)
}
} | youjin-park/app/src/test/java/com/sopt/now/ExampleUnitTest.kt | 2409944037 |
package com.sopt.now
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | youjin-park/app/src/main/java/com/sopt/now/MainActivity.kt | 2747365946 |
package ch.epfl.skysync.viewmodel
import androidx.compose.ui.test.junit4.createComposeRule
import ch.epfl.skysync.Repository
import ch.epfl.skysync.database.DatabaseSetup
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.tables.BalloonTable
import ch.epfl.skysync.database.tables.BasketTable
import ch.epfl.skysync.database.tables.FlightTable
import ch.epfl.skysync.database.tables.FlightTypeTable
import ch.epfl.skysync.database.tables.VehicleTable
import ch.epfl.skysync.models.UNSET_ID
import ch.epfl.skysync.models.calendar.TimeSlot
import ch.epfl.skysync.models.flight.PlannedFlight
import ch.epfl.skysync.models.flight.Role
import ch.epfl.skysync.models.flight.RoleType
import ch.epfl.skysync.models.flight.Team
import java.time.LocalDate
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class FlightsViewModelTest {
private val db = FirestoreDatabase(useEmulator = true)
private val dbSetup = DatabaseSetup()
private val flightTable = FlightTable(db)
private val basketTable = BasketTable(db)
private val balloonTable = BalloonTable(db)
private val flightTypeTable = FlightTypeTable(db)
private val vehicleTable = VehicleTable(db)
private val repository = Repository(db)
// adding this rule should set the test dispatcher and should
// enable us to use advanceUntilIdle(), but it seems advanceUntilIdle
// cancel the coroutine instead of waiting for it to finish
// instead use the .join() for the moment
// @ExperimentalCoroutinesApi @get:Rule var mainCoroutineRule = MainCoroutineRule()
@get:Rule val composeTestRule = createComposeRule()
lateinit var viewModel: FlightsViewModel
lateinit var defaultFlight1: PlannedFlight
@Before
fun setUp() = runTest {
defaultFlight1 =
PlannedFlight(
nPassengers = 2,
team =
Team(
roles =
listOf(
Role(RoleType.PILOT, dbSetup.pilot1),
Role(RoleType.CREW, dbSetup.crew1))),
flightType = dbSetup.flightType1,
balloon = dbSetup.balloon1,
basket = dbSetup.basket2,
date = LocalDate.of(2024, 8, 12),
timeSlot = TimeSlot.AM,
vehicles = listOf(dbSetup.vehicle1),
id = UNSET_ID)
dbSetup.clearDatabase(db)
dbSetup.fillDatabase(db)
composeTestRule.setContent { viewModel = FlightsViewModel.createViewModel(repository) }
}
@Test
fun fetchesCurrentFlightsIsNullOnInit() {
runTest {
viewModel.refreshCurrentFlights().join()
val currentFlights = viewModel.currentFlights.value
assertEquals(1, currentFlights?.size)
}
}
@Test
fun fetchesCurrentFlights() =
runTest() {
var flight1 =
PlannedFlight(
nPassengers = 2,
team =
Team(
roles =
listOf(
Role(RoleType.PILOT, dbSetup.pilot1),
Role(RoleType.CREW, dbSetup.crew1))),
flightType = dbSetup.flightType2,
balloon = dbSetup.balloon1,
basket = dbSetup.basket2,
date = LocalDate.of(2024, 8, 12),
timeSlot = TimeSlot.AM,
vehicles = listOf(dbSetup.vehicle1),
id = UNSET_ID)
var flight2 =
PlannedFlight(
nPassengers = 2,
team =
Team(
roles =
listOf(
Role(RoleType.PILOT, dbSetup.pilot1),
Role(RoleType.CREW, dbSetup.crew1))),
flightType = dbSetup.flightType1,
balloon = dbSetup.balloon1,
basket = dbSetup.basket2,
date = LocalDate.of(2024, 8, 12),
timeSlot = TimeSlot.AM,
vehicles = listOf(dbSetup.vehicle1),
id = UNSET_ID)
flight1 = flight1.copy(id = flightTable.add(flight1, onError = { assertNull(it) }))
flight2 = flight2.copy(id = flightTable.add(flight2, onError = { assertNull(it) }))
viewModel.refreshCurrentFlights().join()
assertEquals(3, viewModel.currentFlights.value?.size)
}
@Test
fun addsFlight() = runTest {
var flight1 =
PlannedFlight(
nPassengers = 2,
team =
Team(
roles =
listOf(
Role(RoleType.PILOT, dbSetup.pilot1),
Role(RoleType.CREW, dbSetup.crew1))),
flightType = dbSetup.flightType2,
balloon = dbSetup.balloon1,
basket = dbSetup.basket2,
date = LocalDate.of(2024, 8, 12),
timeSlot = TimeSlot.AM,
vehicles = listOf(dbSetup.vehicle1),
id = UNSET_ID)
viewModel.addFlight(flight1).join()
viewModel.refreshCurrentFlights().join()
assertEquals(2, viewModel.currentFlights.value?.size)
}
@Test
fun deletesFlight() = runTest {
var flight1 =
PlannedFlight(
nPassengers = 2,
team =
Team(
roles =
listOf(
Role(RoleType.PILOT, dbSetup.pilot1),
Role(RoleType.CREW, dbSetup.crew1))),
flightType = dbSetup.flightType2,
balloon = dbSetup.balloon1,
basket = dbSetup.basket2,
date = LocalDate.of(2024, 8, 12),
timeSlot = TimeSlot.AM,
vehicles = listOf(dbSetup.vehicle1),
id = UNSET_ID)
var flight2 =
PlannedFlight(
nPassengers = 2,
team =
Team(
roles =
listOf(
Role(RoleType.PILOT, dbSetup.pilot1),
Role(RoleType.CREW, dbSetup.crew1))),
flightType = dbSetup.flightType1,
balloon = dbSetup.balloon1,
basket = dbSetup.basket2,
date = LocalDate.of(2024, 8, 12),
timeSlot = TimeSlot.AM,
vehicles = listOf(dbSetup.vehicle1),
id = UNSET_ID)
viewModel.refreshCurrentFlights().join()
val initFlights = viewModel.currentFlights.value
assertEquals(1, initFlights?.size)
flight1 = flight1.copy(id = flightTable.add(flight1, onError = { assertNull(it) }))
flight2 = flight2.copy(id = flightTable.add(flight2, onError = { assertNull(it) }))
viewModel.refreshCurrentFlights().join()
val withFlightsAdded = viewModel.currentFlights.value
assertEquals(3, withFlightsAdded?.size)
viewModel.deleteFlight(flight1.id).join()
viewModel.refreshCurrentFlights().join()
val withOneFlightDeleted = viewModel.currentFlights.value
assertEquals(2, withOneFlightDeleted?.size)
assertTrue(withOneFlightDeleted?.contains(flight2) ?: false)
assertFalse(withOneFlightDeleted?.contains(flight1) ?: true)
}
@Test
fun modifyFlight() = runTest {
var flight1 =
PlannedFlight(
nPassengers = 2,
team =
Team(
roles =
listOf(
Role(RoleType.PILOT, dbSetup.pilot1),
Role(RoleType.CREW, dbSetup.crew1))),
flightType = dbSetup.flightType2,
balloon = dbSetup.balloon1,
basket = dbSetup.basket2,
date = LocalDate.of(2024, 8, 12),
timeSlot = TimeSlot.AM,
vehicles = listOf(dbSetup.vehicle1),
id = UNSET_ID)
flight1 = flight1.copy(id = flightTable.add(flight1, onError = { assertNull(it) }))
// we first need to refresh as otherwise the view model doesn't know about the flight
// also it doesn't make sense to modify a flight you didn't load in the first place
viewModel.refreshCurrentFlights().join()
val modifiedFlight = flight1.copy(nPassengers = 3)
viewModel.modifyFlight(modifiedFlight).join()
viewModel.getFlight("dummy")
viewModel.refreshCurrentFlights().join()
assertEquals(2, viewModel.currentFlights.value?.size)
assertTrue(viewModel.currentFlights.value?.contains(modifiedFlight) ?: false)
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/viewmodel/FlightsViewModelTest.kt | 3643219225 |
package ch.epfl.skysync.viewmodel
import androidx.compose.material.Text
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.test.ext.junit.runners.AndroidJUnit4
import ch.epfl.skysync.database.DatabaseSetup
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.tables.AvailabilityTable
import ch.epfl.skysync.database.tables.UserTable
import ch.epfl.skysync.models.calendar.AvailabilityStatus
import ch.epfl.skysync.models.calendar.TimeSlot
import java.time.LocalDate
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class CalendarViewModelTest {
@get:Rule val composeTestRule = createComposeRule()
private val db = FirestoreDatabase(useEmulator = true)
private val dbs = DatabaseSetup()
private val userTable = UserTable(db)
private val availabilityTable = AvailabilityTable(db)
private lateinit var calendarViewModel: CalendarViewModel
@Before
fun testSetup() = runTest {
dbs.clearDatabase(db)
dbs.fillDatabase(db)
composeTestRule.setContent {
calendarViewModel =
CalendarViewModel.createViewModel(dbs.admin1.id, userTable, availabilityTable)
val uiState = calendarViewModel.uiState.collectAsStateWithLifecycle()
Text(text = uiState.value.user?.firstname ?: "Bob")
}
}
@Test
fun testSaveAvailabilities() = runTest {
calendarViewModel.refresh().join()
val availabilityCalendar = calendarViewModel.uiState.value.availabilityCalendar
assertEquals(
AvailabilityStatus.NO,
availabilityCalendar.getAvailabilityStatus(
dbs.availability3.date, dbs.availability3.timeSlot))
assertEquals(
AvailabilityStatus.OK,
availabilityCalendar.getAvailabilityStatus(
dbs.availability4.date, dbs.availability4.timeSlot))
val newDate = LocalDate.of(2024, 8, 11)
// create a new availability using nextAvailabilityStatus
var status = availabilityCalendar.nextAvailabilityStatus(newDate, TimeSlot.AM)
assertEquals(AvailabilityStatus.OK, status)
// delete an availability using nextAvailabilityStatus
status = availabilityCalendar.nextAvailabilityStatus(dbs.availability3.date, TimeSlot.AM)
assertEquals(AvailabilityStatus.UNDEFINED, status)
calendarViewModel.saveAvailabilities().join()
val user = userTable.get(dbs.admin1.id, onError = { assertNull(it) })
assertNotNull(user)
assertEquals(
AvailabilityStatus.OK, user!!.availabilities.getAvailabilityStatus(newDate, TimeSlot.AM))
assertEquals(
AvailabilityStatus.UNDEFINED,
user!!.availabilities.getAvailabilityStatus(dbs.availability3.date, TimeSlot.AM))
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/viewmodel/CalendarViewModelTest.kt | 3953569742 |
package ch.epfl.skysync.database.tables
import androidx.test.ext.junit.runners.AndroidJUnit4
import ch.epfl.skysync.database.DatabaseSetup
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.database.ListenerUpdate
import ch.epfl.skysync.models.message.Message
import java.time.Instant
import java.util.Date
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MessageGroupTest {
private val db = FirestoreDatabase(useEmulator = true)
private val dbs = DatabaseSetup()
private val messageGroupTable = MessageGroupTable(db)
private val messageTable = MessageTable(db)
@Before
fun testSetup() = runTest {
dbs.clearDatabase(db)
dbs.fillDatabase(db)
}
@Test
fun getTest() = runTest {
val messageGroup = messageGroupTable.get(dbs.messageGroup1.id, onError = { assertNull(it) })
assertNotNull(messageGroup)
assertEquals(
listOf(dbs.admin2.id, dbs.pilot1.id, dbs.crew1.id).sorted(),
messageGroup!!.userIds.sorted())
val messages = messageGroupTable.retrieveMessages(messageGroup.id, onError = { assertNull(it) })
assertNotNull(messageGroup)
assertTrue(listOf(dbs.message1, dbs.message2).containsAll(messages))
}
@Test
fun listenerTest() = runTest {
var listenerUpdates: MutableList<ListenerUpdate<Message>> = mutableListOf()
val listener =
messageGroupTable.addGroupListener(dbs.messageGroup1.id) { update ->
listenerUpdates.add(update)
}
var newMessage1 =
Message(userId = dbs.crew1.id, date = Date.from(Instant.now()), content = "New")
newMessage1 = newMessage1.copy(id = messageTable.add(dbs.messageGroup1.id, newMessage1))
messageTable.delete(newMessage1.id)
var newMessage2 =
Message(userId = dbs.crew1.id, date = Date.from(Instant.now()), content = "New again")
newMessage2 = newMessage2.copy(id = messageTable.add(dbs.messageGroup1.id, newMessage2))
assertEquals(4, listenerUpdates.size)
assertEquals(true, listenerUpdates[0].isFirstUpdate)
// the listener is triggered to fetch query from the database a first time
// this will however (because this is a test) not to be the first update as it needs to wait
// for a requests and is not a coroutine (it is not blocking as it is executed by the listener)
assertEquals(
ListenerUpdate(
isFirstUpdate = false,
isLocalUpdate = true,
adds = listOf(dbs.message2, dbs.message1),
updates = listOf(),
deletes = listOf()),
listenerUpdates[1])
assertEquals(
ListenerUpdate(
isFirstUpdate = true,
isLocalUpdate = true,
adds = listOf(newMessage1),
updates = listOf(),
deletes = listOf()),
listenerUpdates[0])
assertEquals(
ListenerUpdate(
isFirstUpdate = false,
isLocalUpdate = false,
adds = listOf(),
updates = listOf(),
deletes = listOf(newMessage1)),
listenerUpdates[2])
assertEquals(
ListenerUpdate(
isFirstUpdate = false,
isLocalUpdate = true,
adds = listOf(newMessage2),
updates = listOf(),
deletes = listOf()),
listenerUpdates[3])
listener.remove()
}
@Test
fun deleteTest() = runTest {
messageGroupTable.delete(dbs.messageGroup1.id, onError = { assertNull(it) })
val messageGroups = messageGroupTable.getAll(onError = { assertNull(it) })
assertEquals(listOf(dbs.messageGroup2), messageGroups)
val messages = messageTable.getAll(onError = { assertNull(it) })
assertEquals(listOf(dbs.message3), messages)
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/database/tables/MessageGroupTest.kt | 1698669026 |
package ch.epfl.skysync.database.tables
import androidx.test.ext.junit.runners.AndroidJUnit4
import ch.epfl.skysync.database.FirestoreDatabase
import ch.epfl.skysync.models.calendar.Availability
import ch.epfl.skysync.models.calendar.AvailabilityStatus
import ch.epfl.skysync.models.calendar.TimeSlot
import java.time.LocalDate
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
// sleep to let the db requests the time to be done
const val DB_SLEEP_TIME = 3000L
@RunWith(AndroidJUnit4::class)
class AvailabilityTableUnitTest {
private val table = AvailabilityTable(FirestoreDatabase(useEmulator = true))
@Before
fun testSetup() {
runTest { table.deleteTable() }
}
/**
* Test the AvailabilityTable as one integration test as it is mostly a wrapper of the
* FirestoreDatabase class (it has no relations) and the FirestoreDatabase has no mock class,
* instead we use an emulator, meaning we can not test the `add` method in isolation for example.
*/
@Test
fun integrationTest() {
runTest {
val userId = "userId"
val availability =
Availability(
status = AvailabilityStatus.MAYBE, timeSlot = TimeSlot.PM, date = LocalDate.now())
// add an availability
val id = table.add(userId, availability)
// retrieve the added availability
var getAvailability = table.get(id)
// the added then retrieved availability should be the same as the initial one
assertEquals(availability.copy(id = id), getAvailability)
val updateAvailability =
Availability(
id = id,
status = AvailabilityStatus.OK,
timeSlot = TimeSlot.PM,
date = LocalDate.now())
table.update(userId, id, updateAvailability)
getAvailability = table.get(id)
// the updated availability should be the same as the initial one
assertEquals(updateAvailability, getAvailability)
// delete the availability
table.delete(id)
// get all the availabilities
val availabilities = table.getAll()
// there should not be any availabilities left
assertEquals(0, availabilities.size)
}
}
}
| skysync/app/src/androidTest/java/ch/epfl/skysync/database/tables/AvailabilityTableUnitTest.kt | 358864419 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.