content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package mohammad.toriq.mymovies.data.source.remote.dto
import mohammad.toriq.mymovies.models.GenresDto
import mohammad.toriq.mymovies.models.MovieDto
import mohammad.toriq.mymovies.models.MoviesDto
import mohammad.toriq.mymovies.models.ReviewsDto
import mohammad.toriq.mymovies.models.VideosDto
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Path
import retrofit2.http.Query
/***
* Created By Mohammad Toriq on 30/11/2023
*/
interface APIService {
companion object {
const val BASE_URL = "https://api.themoviedb.org/3/"
const val IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w185";
const val TOKEN: String = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI3ZDhiZTZlOTE5YTdiMjMwMmM5MjlhYzg3NDIwODM0MSIsInN1YiI6IjY1MmY5MDI2YTgwMjM2MDBmZDJkODdhNCIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.ap13eLyCoYdiBdoxl_NC4zIMqqwDoKoBfuoYBHNWdU8"
}
@GET("movie/{category}")
suspend fun getMovies(
@Path(value = "category", encoded = true) category: String,
@Query(value = "language", encoded = true) language: String,
): MoviesDto
@GET("discover/movie")
suspend fun getDiscoverMovies(
@Query(value = "page", encoded = true) page: Int,
@Query(value = "with_genres", encoded = true) withGenres: String?,
@Query(value = "language", encoded = true) language: String,
): MoviesDto
@GET("genre/movie/list")
suspend fun getGenres(
// @Query(value = "language", encoded = true) language: String,
): GenresDto
@GET("movie/{id}")
suspend fun getDetailMovie(
@Path(value = "id", encoded = true) id: Long,
): MovieDto
@GET("movie/{id}/reviews")
suspend fun getMovieReviews(
@Path(value = "id", encoded = true) id: Long,
@Query(value = "page", encoded = true) page: Int,
): ReviewsDto
@GET("movie/{id}/videos")
suspend fun getMovieVideos(
@Path(value = "id", encoded = true) id: Long,
): VideosDto
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/data/source/APIService.kt | 1058477676 |
package mohammad.toriq.mymovies.data.source.remote
/***
* Created By Mohammad Toriq on 30/11/2023
*/
sealed class Resource<T>(val data: T? = null, val message: String? = null) {
class Loading<T>(data: T? = null) : Resource<T>(data)
class Success<T>(data: T?) : Resource<T>(data)
class Error<T>(message: String, data: T? = null) : Resource<T>(data, message)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/data/source/Resource.kt | 3220659529 |
package mohammad.toriq.mymovies.domain.repository
import kotlinx.coroutines.flow.Flow
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.models.Genres
import mohammad.toriq.mymovies.models.Movie
import mohammad.toriq.mymovies.models.Movies
import mohammad.toriq.mymovies.models.Reviews
import mohammad.toriq.mymovies.models.Videos
/***
* Created By Mohammad Toriq on 30/11/2023
*/
interface Repository {
fun getMovies(
category: String,
language: String,
): Flow<Resource<Movies>>
fun getDiscoverMovies(
page: Int,
withGenres: String?,
language: String,
): Flow<Resource<Movies>>
fun getGenres(
language: String,
): Flow<Resource<Genres>>
fun getDetailMovie(
id: Long,
): Flow<Resource<Movie>>
fun getMovieReviews(
id: Long,
page: Int,
): Flow<Resource<Reviews>>
fun getMovieVideos(
id: Long,
): Flow<Resource<Videos>>
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/repository/Repository.kt | 2143039394 |
package mohammad.toriq.mymovies.models
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class Movie (
var id: Long = 0,
var title: String? = null,
var desc: String? = null,
var originalTitle: String? = null,
var popularity: Double = 0.0,
var imageUrlBackDrop: String? = null,
var imageUrl: String? = null,
var voteAverage: Float = 0f,
var voteCount: Long = 0,
var releaseDate: String? = null,
var runtime: Int = 0,
var budget: Long = 0,
var genres: List<Genre> = listOf(),
var homepage: String? = null,
var status: String? = null,
)
fun Movie.toMovieDto(): MovieDto {
return MovieDto(
id = id,
title = title,
desc = desc,
originalTitle = originalTitle,
popularity = popularity,
imageUrlBackDrop = imageUrlBackDrop,
imageUrl = imageUrl,
voteAverage = voteAverage,
voteCount = voteCount,
releaseDate = releaseDate,
runtime = runtime,
budget = budget,
genres = genres.map { it.toGenreDto() }.toList(),
homepage = homepage,
status = status,
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/model/Movie.kt | 1113069666 |
package mohammad.toriq.mymovies.models
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class Genre(
var id: Long = 0,
var name: String? = null,
)
fun Genre.toGenreDto(): GenreDto {
return GenreDto(
id = id,
name = name,
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/model/Genre.kt | 1111127241 |
package mohammad.toriq.mymovies.models
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class Video (
var iso_639_1: String? = null,
var iso_3166_1: String? = null,
var name: String? = null,
var key: String? = null,
var site: String? = null,
var size: Int = 0,
var type: String? = null,
var official: Boolean? = null,
var publishedAt: String? = null,
var id: String? = null,
)
fun Video.toVideoDto(): VideoDto {
return VideoDto(
iso_639_1 = iso_639_1,
iso_3166_1 = iso_3166_1,
name = name,
key = key,
site = site,
size = size,
type = type,
official = official,
publishedAt = publishedAt,
id = id,
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/model/Video.kt | 546462151 |
package mohammad.toriq.mymovies.models
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class Genres (
var genres : List<Genre> = listOf(),
)
fun Genres.toGenresDto(): GenresDto {
return GenresDto(
genres = genres.map { it.toGenreDto() }.toList(),
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/model/Genres.kt | 1546477478 |
package mohammad.toriq.mymovies.models
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class Videos (
var videos: List<Video> = listOf(),
)
fun Videos.toVideosDto(): VideosDto {
return VideosDto(
videos = videos.map { it.toVideoDto() }.toList(),
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/model/Videos.kt | 4241235737 |
package mohammad.toriq.mymovies.models
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class Reviews (
var page: Long = 0,
var reviews: List<Review> = listOf(),
var totalPages: Long = 0,
var totalResults: Long = 0,
)
fun Reviews.toReviewsDto(): ReviewsDto {
return ReviewsDto(
page = page,
reviews = reviews.map { it.toReviewDto() }.toList(),
totalPages = totalPages,
totalResults = totalResults,
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/model/Reviews.kt | 1475166311 |
package mohammad.toriq.mymovies.models
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class Author(
var name: String? = null,
var username: String? = null,
var avatarPath: String? = null,
var rating: Double? = null,
)
fun Author.toAuthorDto(): AuthorDto {
return AuthorDto(
name = name,
username = username,
avatarPath = avatarPath,
rating = rating,
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/model/Author.kt | 3890182331 |
package mohammad.toriq.mymovies.models
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class Review (
var id: String? = null,
var author: String? = null,
var authorDetails: Author,
var content: String? = null,
var createdAt: String? = null,
var updatedAt: String? = null,
var url: String? = null,
)
fun Review.toReviewDto(): ReviewDto {
return ReviewDto(
id = id,
author = author,
authorDetails = authorDetails.toAuthorDto(),
content = content,
createdAt = createdAt,
updatedAt = updatedAt,
url = url,
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/model/Review.kt | 46302223 |
package mohammad.toriq.mymovies.models
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class Movies (
var page: Long = 0,
var movies: List<Movie> = listOf(),
var totalPages: Long = 0,
var totalResults: Long = 0,
)
fun Movies.toMoviesDto(): MoviesDto {
return MoviesDto(
page = page,
movies = movies.map { it.toMovieDto() }.toList(),
totalPages = totalPages,
totalResults = totalResults,
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/model/Movies.kt | 3542304142 |
package mohammad.toriq.mymovies.domain.usecase
import kotlinx.coroutines.flow.Flow
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.domain.repository.Repository
import mohammad.toriq.mymovies.models.Genres
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class GetGenresUseCase(
private val repository: Repository
) {
operator fun invoke(language: String,
): Flow<Resource<Genres>> {
return repository.getGenres(language)
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/usecase/GetGenresUseCase.kt | 1035186098 |
package mohammad.toriq.mymovies.domain.usecase
import kotlinx.coroutines.flow.Flow
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.domain.repository.Repository
import mohammad.toriq.mymovies.models.Movies
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class GetDiscoverMoviesUseCase(
private val repository: Repository
) {
operator fun invoke(page: Int, withGenres: String?, language: String,
): Flow<Resource<Movies>> {
return repository.getDiscoverMovies(page,withGenres, language)
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/usecase/GetDiscoverMoviesUseCase.kt | 534508289 |
package mohammad.toriq.mymovies.domain.usecase
import kotlinx.coroutines.flow.Flow
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.domain.repository.Repository
import mohammad.toriq.mymovies.models.Reviews
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class GetMovieReviewsUseCase(
private val repository: Repository
) {
operator fun invoke(id: Long, page: Int,
): Flow<Resource<Reviews>> {
return repository.getMovieReviews(id,page)
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/usecase/GetMovieReviewsUseCase.kt | 3019383675 |
package mohammad.toriq.mymovies.domain.usecase
import kotlinx.coroutines.flow.Flow
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.domain.repository.Repository
import mohammad.toriq.mymovies.models.Movie
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class GetDetailMovieUseCase(
private val repository: Repository
) {
operator fun invoke(id: Long,
): Flow<Resource<Movie>> {
return repository.getDetailMovie(id)
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/usecase/GetDetailMovieUseCase.kt | 1457069940 |
package mohammad.toriq.mymovies.domain.usecase
import kotlinx.coroutines.flow.Flow
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.domain.repository.Repository
import mohammad.toriq.mymovies.models.Movies
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class GetMoviesUseCase(
private val repository: Repository
) {
operator fun invoke(category : String,
language:String,
): Flow<Resource<Movies>> {
return repository.getMovies(category,language)
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/usecase/GetMoviesUseCase.kt | 2533567898 |
package mohammad.toriq.mymovies.domain.usecase
import kotlinx.coroutines.flow.Flow
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.domain.repository.Repository
import mohammad.toriq.mymovies.models.Videos
/***
* Created By Mohammad Toriq on 30/11/2023
*/
class GetMovieVideosUseCase(
private val repository: Repository
) {
operator fun invoke(id: Long,
): Flow<Resource<Videos>> {
return repository.getMovieVideos(id)
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/domain/usecase/GetMovieVideosUseCase.kt | 2726484120 |
package mohammad.toriq.mymovies.presentation
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.compose.rememberNavController
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import dagger.hilt.android.AndroidEntryPoint
import mohammad.toriq.mymovies.presentation.navigation.NavGraph
import mohammad.toriq.mymovies.presentation.theme.MyMoviesTheme
import mohammad.toriq.mymovies.R
@AndroidEntryPoint
@ExperimentalComposeUiApi
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyMoviesTheme {
// A surface container using the 'background' color from the theme
SetStatusBarColor(color = colorResource(id = R.color.primary))
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val navController = rememberNavController()
NavGraph(
activity = this,
navController = navController
)
}
}
}
}
}
@Composable
fun SetStatusBarColor(color: Color) {
val systemUiController = rememberSystemUiController()
SideEffect {
systemUiController.setSystemBarsColor(
color = color,
darkIcons = false
)
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/MainActivity.kt | 2411489012 |
package mohammad.toriq.mymovies.presentation.navigation
import androidx.activity.ComponentActivity
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import mohammad.toriq.mymovies.presentation.screen.detailmovie.DetailMovieScreen
import mohammad.toriq.mymovies.presentation.screen.detailmovie.VideoScreen
import mohammad.toriq.mymovies.presentation.screen.genres.GenresScreen
import mohammad.toriq.mymovies.presentation.screen.movies.MoviesScreen
import mohammad.toriq.mymovies.presentation.screen.review.ReviewsScreen
import mohammad.toriq.mymovies.presentation.screen.splash.SplashScreen
/***
* Created By Mohammad Toriq on 30/11/2023
*/
@Composable
fun NavGraph(activity: ComponentActivity, navController: NavHostController) {
NavHost(
navController = navController,
startDestination = Screen.SplashScreen.route
) {
composable(route = Screen.SplashScreen.route) {
SplashScreen(
activity = activity,
navController = navController
)
}
composable(route = Screen.GenresScreen.route) {
GenresScreen(
activity = activity,
navController = navController
)
}
composable(route = Screen.MoviesScreen.route){
var id = it.arguments?.getString("id") ?: "0"
var title = it.arguments?.getString("title") ?: ""
MoviesScreen(activity,navController,id.toLong(),title)
}
composable(route = Screen.DetailMovieScreen.route){
var id = it.arguments?.getString("id") ?: "0"
DetailMovieScreen(activity,navController,id.toLong())
}
composable(route = Screen.ReviewsScreen.route){
var id = it.arguments?.getString("id") ?: "0"
var title = it.arguments?.getString("title") ?: ""
ReviewsScreen(activity,navController,id.toLong(),title)
}
composable(route = Screen.VideoScreen.route){
var id = it.arguments?.getString("id") ?: ""
var title = it.arguments?.getString("title") ?: ""
VideoScreen(activity,navController,id,title)
}
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/navigation/NavGraph.kt | 1918370205 |
package mohammad.toriq.mymovies.presentation.navigation
/***
* Created By Mohammad Toriq on 30/11/2023
*/
sealed class Screen(val route: String) {
object SplashScreen: Screen("splash_screen")
object GenresScreen: Screen("genres_screen")
object MoviesScreen: Screen("movies_screen/{id}/{title}"){
fun sendData(id: String,title: String) = "movies_screen/$id/$title"
}
object DetailMovieScreen: Screen("detail_movie_screen/{id}"){
fun sendData(id: String) = "detail_movie_screen/$id"
}
object ReviewsScreen: Screen("reviews_screen/{id}/{title}"){
fun sendData(id: String, title:String) = "reviews_screen/$id/$title"
}
object VideoScreen: Screen("video_screen/{id}/{title}"){
fun sendData(id: String, title:String) = "video_screen/$id/$title"
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/navigation/Screen.kt | 2598239106 |
package mohammad.toriq.mymovies.presentation.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)
val primary = Color(0xFF032541)
val secondary = Color(0xFF032541)
val tertiary = Color(0xFF032541)
val white = Color(0xFFFFFFFF) | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/theme/Color.kt | 3596871797 |
package mohammad.toriq.mymovies.presentation.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
primary = primary,
secondary = secondary,
tertiary = tertiary
/* 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 MyMoviesTheme(
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 colorScheme = 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
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/theme/Theme.kt | 838179882 |
package mohammad.toriq.mymovies.presentation.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
)
*/
) | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/theme/Type.kt | 4183701514 |
package mohammad.toriq.mymovies.presentation.screen.splash
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
/***
* Created By Mohammad Toriq on 30/11/2023
*/
@HiltViewModel
class SplashViewModel @Inject constructor(
) : ViewModel() {
private val _state = mutableStateOf(SplashUiState())
val state: State<SplashUiState> = _state
init {
loading()
}
fun setState(data:Boolean){
_state.value = state.value.copy(
isLoading = data,
)
}
fun loading() {
viewModelScope.launch {
setState(true)
delay(1000)
setState(false)
}
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/splash/SplashViewModel.kt | 1286169494 |
package mohammad.toriq.mymovies.presentation.screen.splash
/***
* Created By Mohammad Toriq on 30/11/2023
*/
data class SplashUiState (
val isLoading: Boolean = false
) | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/splash/SplashUiState.kt | 2763084031 |
@file:OptIn(ExperimentalMaterial3Api::class)
package mohammad.toriq.mymovies.presentation.screen.splash
import android.annotation.SuppressLint
import android.util.Log
import androidx.activity.ComponentActivity
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.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import mohammad.toriq.mymovies.R
import mohammad.toriq.mymovies.presentation.navigation.Screen
/***
* Created By Mohammad Toriq on 30/11/2023
*/
@Composable
fun SplashScreen (
activity: ComponentActivity,
navController: NavController,
splashViewModel: SplashViewModel = hiltViewModel()
){
val state = splashViewModel.state.value
if(!state.isLoading){
// Toast.makeText(activity,"GenreScreen",Toast.LENGTH_SHORT).show()
splashViewModel.setState(true)
Log.d("OkCheck","GenreScreen")
navController.navigate(Screen.GenresScreen.route){
popUpTo(Screen.SplashScreen.route){
inclusive = true
}
}
}
initSplash()
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun initSplash(modifier: Modifier = Modifier) {
Scaffold(
modifier = Modifier
.fillMaxSize()
) {
Box() {
Column (
modifier = Modifier
.fillMaxSize()
.background(color = colorResource(id = R.color.primary)),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
)
{
Text(
text = stringResource(id = R.string.app_name),
fontSize = 38.sp,
fontWeight = FontWeight.Bold,
color = colorResource(id = R.color.white),
modifier = modifier,
)
}
}
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/splash/SplashScreen.kt | 152201122 |
package mohammad.toriq.mymovies.presentation.screen.genres
import mohammad.toriq.mymovies.models.Genre
/***
* Created By Mohammad Toriq on 30/11/2023
*/
data class GenresUiState (
val genreList: ArrayList<Genre> = ArrayList(),
val isLoading: Boolean = false
) | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/genres/GenresUiState.kt | 640112402 |
package mohammad.toriq.mymovies.presentation.screen.genres
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.domain.usecase.GetGenresUseCase
import mohammad.toriq.mymovies.models.Genre
import javax.inject.Inject
/***
* Created By Mohammad Toriq on 30/11/2023
*/
@HiltViewModel
class GenresViewModel @Inject constructor(
private val getGenresUseCase: GetGenresUseCase
) : ViewModel() {
private val _state = mutableStateOf(GenresUiState())
val state: State<GenresUiState> = _state
var isInit = false
var language = "en-Us"
fun getGenres() {
viewModelScope.launch {
getGenresUseCase(language).onEach { result ->
when (result) {
is Resource.Loading -> {
_state.value = state.value.copy(
genreList = arrayListOf(),
isLoading = true
)
}
is Resource.Success -> {
var list = ArrayList<Genre>()
result.data!!.genres.forEach {
list.add(it)
}
_state.value = state.value.copy(
genreList = list,
isLoading = false
)
}
is Resource.Error -> {
_state.value = state.value.copy(
genreList = arrayListOf(),
isLoading = false
)
}
}
}.launchIn(this)
}
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/genres/GenresViewModel.kt | 2405471915 |
@file:OptIn(ExperimentalMaterial3Api::class)
package mohammad.toriq.mymovies.presentation.screen.genres
import android.annotation.SuppressLint
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowForward
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import mohammad.toriq.mymovies.R
import mohammad.toriq.mymovies.presentation.navigation.Screen
/***
* Created By Mohammad Toriq on 30/11/2023
*/
@Composable
fun GenresScreen (
activity: ComponentActivity,
navController: NavController,
genreViewModel: GenresViewModel = hiltViewModel()
){
if(!genreViewModel.isInit){
genreViewModel.isInit = true
genreViewModel.getGenres()
}
initGenres(
activity,
navController,
genreViewModel)
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun initGenres(
activity: ComponentActivity,
navController: NavController,
genreViewModel: GenresViewModel,
modifier: Modifier = Modifier) {
Scaffold(
modifier = Modifier
.fillMaxSize(),
topBar = {
Surface(
shadowElevation = 3.dp
){
CenterAlignedTopAppBar(
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = colorResource(id = R.color.primary),
titleContentColor = colorResource(id = R.color.white),
),
title = {
Text(
text = "Genres Movie",
fontWeight = FontWeight.SemiBold,
)
},
)
}
},
content = {
var isLoading = genreViewModel.state.value.isLoading
var genres = genreViewModel.state.value.genreList
Box(
modifier = Modifier
.padding(it)
.padding(5.dp)
.fillMaxSize()) {
if(!isLoading){
if(genres.size == 0){
Column(
modifier = Modifier
.fillMaxWidth()
.height(400.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
){
Text(
text = "Genre not Found",
color = colorResource(id = R.color.primary),
fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center,
fontSize = 16.sp,
modifier = Modifier.fillMaxWidth()
)
}
}
else{
LazyVerticalGrid(
columns = GridCells.Adaptive(128.dp),
) {
items(genres.size) { index ->
OutlinedButton(
modifier = Modifier.padding(all = 5.dp),
border = BorderStroke(1.dp, colorResource(id = R.color.primary)),
shape = RoundedCornerShape(4),
onClick = fun(){
Log.d("OKCheck","genre id:"+genres[index].id.toString())
navController.navigate(
Screen.MoviesScreen
.sendData(genres[index].id.toString(),genres[index].name!!)
)
}
){
Row (
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
,
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
){
Text(
text = genres[index].name!!,
fontSize = 14.sp,
color = colorResource(id = R.color.primary),
textAlign = TextAlign.Center,
)
Icon(
Icons.Filled.ArrowForward,
modifier = Modifier.size(20.dp),
tint = colorResource(id = R.color.primary),
contentDescription = "",
)
}
}
}
}
}
}else{
Row(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
CircularProgressIndicator(
color = colorResource(id = R.color.primary)
)
}
}
}
}
)
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/genres/GenresScreen.kt | 668340716 |
package mohammad.toriq.mymovies.presentation.screen.review
import mohammad.toriq.mymovies.models.Review
/***
* Created By Mohammad Toriq on 01/12/2023
*/
data class ReviewsUiState (
val reviewList: ArrayList<Review> = ArrayList(),
val isLoading: Boolean = false,
val errorMessage: String = ""
) | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/review/ReviewsUiState.kt | 818230102 |
@file:OptIn(ExperimentalMaterial3Api::class)
package mohammad.toriq.mymovies.presentation.screen.review
import android.annotation.SuppressLint
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import mohammad.toriq.mymovies.R
import mohammad.toriq.mymovies.data.source.remote.dto.APIService
import mohammad.toriq.mymovies.presentation.navigation.Screen
import mohammad.toriq.mymovies.util.Constants
import mohammad.toriq.mymovies.util.NoRippleInteractionSource
import mohammad.toriq.mymovies.util.Util
/***
* Created By Mohammad Toriq on 30/11/2023
*/
@Composable
fun ReviewsScreen (
activity: ComponentActivity,
navController: NavController,
id: Long,
title: String,
reviewsViewModel: ReviewsViewModel = hiltViewModel()
){
Log.d("OKCheck","id:"+id.toString())
if(!reviewsViewModel.isInit){
reviewsViewModel.isInit = true
reviewsViewModel.id = id
reviewsViewModel.getReviews()
}
initReviews(
activity,
navController,
title,
reviewsViewModel)
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun initReviews(
activity: ComponentActivity,
navController: NavController,
title: String,
reviewsViewModel: ReviewsViewModel,
modifier: Modifier = Modifier) {
BackHandler {
navController.navigateUp()
}
Scaffold(
modifier = Modifier
.fillMaxSize(),
topBar = {
Surface(
shadowElevation = 3.dp
){
CenterAlignedTopAppBar(
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = colorResource(id = R.color.primary),
titleContentColor = colorResource(id = R.color.white),
),
title = {
Text(
text = "Reviews Movie",
fontWeight = FontWeight.SemiBold,
)
},
navigationIcon = {
IconButton(
onClick = {
navController.navigateUp()
}) {
Image(
imageVector = Icons.Filled.ArrowBack,
colorFilter = ColorFilter.tint(colorResource(id = R.color.white)),
contentDescription = "Back"
)
}
},
)
}
},
content = {
var isLoading = reviewsViewModel.state.value.isLoading
var reviews = reviewsViewModel.state.value.reviewList
var isRefreshing = reviewsViewModel.isRefresh
Box(
modifier = Modifier
.padding(it)
.padding(5.dp)
.fillMaxSize()) {
//
if(!isLoading || reviews.size > 0){
val listState = rememberLazyListState()
SwipeRefresh(
modifier = Modifier
.fillMaxWidth(),
state = rememberSwipeRefreshState(isRefreshing = isRefreshing),
onRefresh = {
reviewsViewModel.refresh()
}
) {
if(reviews.size == 0){
Column(
modifier = Modifier
.fillMaxWidth()
.height(400.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
){
Text(
text = "Reviews not Found",
color = colorResource(id = R.color.primary),
fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center,
fontSize = 16.sp,
modifier = Modifier
.fillMaxWidth()
)
}
}else{
LazyColumn(
modifier = Modifier
.fillMaxWidth(),
state = listState,
verticalArrangement = Arrangement.Top
) {
items(reviews.size) { index ->
var review = reviews[index]
var isExpanded by remember { mutableStateOf(false) }
OutlinedButton(
modifier = Modifier
.padding(all = 5.dp),
interactionSource = remember { NoRippleInteractionSource() },
contentPadding = PaddingValues(),
border = BorderStroke(1.dp, colorResource(id = R.color.primary)),
shape = RoundedCornerShape(4.dp),
onClick = fun(){
isExpanded = !isExpanded
}
){
Column(
modifier = Modifier
.padding(all = 5.dp)
.fillMaxWidth()
){
Row(
verticalAlignment = Alignment.CenterVertically
){
if(review.authorDetails.avatarPath!=null){
AsyncImage(
model = APIService.IMAGE_BASE_URL+review.authorDetails.avatarPath!!,
contentDescription = null,
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
modifier = Modifier
.padding(5.dp)
.clip(CircleShape)
.size(35.dp)
)
}else{
var color = colorResource(id = R.color.grey2)
Text(
modifier = Modifier
.padding(15.dp)
.drawBehind {
drawCircle(
color = color,
radius = this.size.maxDimension
)
},
text = review.author!!.substring(0,1),
)
// Spacer(modifier = Modifier.width(5.dp))
}
Column {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(
top = 5.dp,
start = 5.dp,
end = 5.dp
),
text = review.author!!,
fontSize = 14.sp,
fontWeight = FontWeight.Bold,
color = colorResource(id = R.color.primary),
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(
top = 5.dp,
start = 5.dp,
end = 5.dp
),
text = "on "+Util.convertDate(
review.createdAt!!,
Constants.DATE_OUT_FORMAT_DEF1,
Constants.DATE_OUT_FORMAT_DEF4),
fontSize = 12.sp,
color = colorResource(id = R.color.grey),
)
}
}
Text(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp),
text = review.content!!,
fontSize = 12.sp,
color = colorResource(id = R.color.primary),
maxLines = if(isExpanded) Int.MAX_VALUE else 4,
overflow = TextOverflow.Ellipsis,
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 10.dp, horizontal = 5.dp),
text = if(isExpanded) "Sembunyikan" else "Selengkapnya",
fontSize = 12.sp,
textAlign = TextAlign.End,
color = colorResource(id = R.color.blue1),
)
}
}
}
}
listState.OnBottomReached (buffer = 2){
if(!reviewsViewModel.isMax){
reviewsViewModel.loadMore()
}
}
}
}
}else{
Row(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
CircularProgressIndicator(
color = colorResource(id = R.color.primary)
)
}
}
}
}
)
}
@Composable
fun LazyListState.OnBottomReached(
buffer : Int = 0,
loadMore : () -> Unit
){
require(buffer >= 0) { "buffer cannot be negative, but was $buffer" }
val shouldLoadMore = remember {
derivedStateOf {
val lastVisibleItem = layoutInfo.visibleItemsInfo.lastOrNull()
?:
return@derivedStateOf true
lastVisibleItem.index >= layoutInfo.totalItemsCount - 1 - buffer
}
}
LaunchedEffect(shouldLoadMore){
snapshotFlow { shouldLoadMore.value }
.collect { if (it) loadMore() }
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/review/ReviewsScreen.kt | 1209986201 |
package mohammad.toriq.mymovies.presentation.screen.review
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.domain.usecase.GetDetailMovieUseCase
import mohammad.toriq.mymovies.domain.usecase.GetMovieReviewsUseCase
import mohammad.toriq.mymovies.domain.usecase.GetMovieVideosUseCase
import mohammad.toriq.mymovies.models.Video
import javax.inject.Inject
/***
* Created By Mohammad Toriq on 01/12/2023
*/
@HiltViewModel
class ReviewsViewModel @Inject constructor(
private val getMovieReviewsUseCase: GetMovieReviewsUseCase
) : ViewModel() {
private val _state = mutableStateOf(ReviewsUiState())
val state: State<ReviewsUiState> = _state
var id : Long = 0
var page = 1
var isRefresh = false
var isMax = false
var isInit = false
fun getReviews() {
viewModelScope.launch {
getMovieReviewsUseCase(id,page).onEach { result ->
var list = state.value.reviewList
when (result) {
is Resource.Loading -> {
_state.value = state.value.copy(
reviewList = list,
isLoading = true,
errorMessage = ""
)
}
is Resource.Success -> {
if(page == 1){
isInit = true
}
if(result.data?.reviews !=null){
result.data.reviews.forEach {
list.add(it)
}
}
if(page < result.data!!.totalPages){
page++
}else{
isMax = true
}
Log.d("OkCheck","page next:"+page.toString())
_state.value = state.value.copy(
reviewList = list,
isLoading = false,
errorMessage = ""
)
}
is Resource.Error -> {
_state.value = state.value.copy(
reviewList = list,
isLoading = false,
errorMessage = "Failed Connected To API Server"
)
}
}
}.launchIn(this)
}
}
fun loadMore(){
Log.d("OkCheck","loadMore:"+page.toString())
getReviews()
}
fun refresh() {
viewModelScope.launch(Dispatchers.IO) {
Log.d("OkCheck","refresh")
isRefresh = true
isMax = false
page = 1
_state.value = state.value.copy(
reviewList = ArrayList(),
isLoading = false,
errorMessage = ""
)
getReviews()
isRefresh = false
}
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/review/ReviewsViewModel.kt | 3844966881 |
@file:OptIn(ExperimentalMaterial3Api::class)
package mohammad.toriq.mymovies.presentation.screen.movies
import android.annotation.SuppressLint
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import mohammad.toriq.mymovies.R
import mohammad.toriq.mymovies.data.source.remote.dto.APIService
import mohammad.toriq.mymovies.presentation.navigation.Screen
import mohammad.toriq.mymovies.util.Constants
import mohammad.toriq.mymovies.util.Util
/***
* Created By Mohammad Toriq on 30/11/2023
*/
@Composable
fun MoviesScreen (
activity: ComponentActivity,
navController: NavController,
id: Long,
title: String,
moviesViewModel: MoviesViewModel = hiltViewModel()
){
Log.d("OKCheck","id:"+id.toString())
if(!moviesViewModel.isInit){
moviesViewModel.isInit = true
moviesViewModel.genre = id.toString()
moviesViewModel.getMovies()
}
initMovies(
activity,
navController,
title,
moviesViewModel)
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun initMovies(
activity: ComponentActivity,
navController: NavController,
title: String,
moviesViewModel: MoviesViewModel,
modifier: Modifier = Modifier) {
BackHandler {
navController.navigateUp()
}
Scaffold(
modifier = Modifier
.fillMaxSize(),
topBar = {
Surface(
shadowElevation = 3.dp
){
CenterAlignedTopAppBar(
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = colorResource(id = R.color.primary),
titleContentColor = colorResource(id = R.color.white),
),
title = {
Text(
text = title,
fontWeight = FontWeight.SemiBold,
)
},
navigationIcon = {
IconButton(
onClick = {
navController.navigateUp()
}) {
Image(
imageVector = Icons.Filled.ArrowBack,
colorFilter = ColorFilter.tint(colorResource(id = R.color.white)),
contentDescription = "Back"
)
}
},
)
}
},
content = {
var isLoading = moviesViewModel.state.value.isLoading
var movies = moviesViewModel.state.value.movieList
var isRefreshing = moviesViewModel.isRefresh
Box(
modifier = Modifier
.padding(it)
.padding(5.dp)
.fillMaxSize()) {
//
if(!isLoading || movies.size > 0){
val listState = rememberLazyGridState()
SwipeRefresh(
modifier = Modifier
.fillMaxWidth(),
state = rememberSwipeRefreshState(isRefreshing = isRefreshing),
onRefresh = {
moviesViewModel.refresh()
}
) {
if(movies.size == 0){
Column(
modifier = Modifier
.fillMaxWidth()
.height(400.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
){
Text(
text = "Movie not Found",
color = colorResource(id = R.color.primary),
fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center,
fontSize = 16.sp,
modifier = Modifier
.fillMaxWidth()
)
}
}else{
var desiredItemMinHeight by remember {
mutableStateOf(0.dp)
}
val density = LocalDensity.current
LazyVerticalGrid(
modifier = Modifier
.fillMaxWidth(),
columns = GridCells.Adaptive(128.dp),
state = listState,
verticalArrangement = Arrangement.Top
) {
items(movies.size) { index ->
var movie = movies[index]
OutlinedButton(
modifier = Modifier
.padding(all = 3.dp)
.onPlaced {
with(density) {
if (desiredItemMinHeight < it.size.height.toDp()) {
desiredItemMinHeight = it.size.height.toDp()
}
}
}
.defaultMinSize(minHeight = desiredItemMinHeight)
,
contentPadding = PaddingValues(),
border = BorderStroke(0.dp, colorResource(id = R.color.primary)),
shape = RoundedCornerShape(4),
onClick = fun(){
}
){
Column(
modifier = Modifier
.fillMaxWidth()
.clickable(
onClick = fun() {
navController.navigate(
Screen.DetailMovieScreen
.sendData(movies[index].id.toString())
)
}
)
.defaultMinSize(minHeight = desiredItemMinHeight),
){
AsyncImage(
model = APIService.IMAGE_BASE_URL+movie.imageUrl,
contentDescription = null,
contentScale = ContentScale.Crop,
alignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
.height(250.dp)
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 5.dp, vertical = 10.dp),
text = movie.title!!,
fontSize = 14.sp,
color = colorResource(id = R.color.primary),
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp),
text = Util.convertDate(movie.releaseDate,
Constants.DATE_OUT_FORMAT_DEF2,
Constants.DATE_OUT_FORMAT_DEF3),
fontSize = 12.sp,
color = colorResource(id = R.color.grey),
)
}
}
}
}
listState.OnBottomReached (buffer = 2){
if(!moviesViewModel.isMax){
moviesViewModel.loadMore()
}
}
}
}
}else{
Row(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
CircularProgressIndicator(
color = colorResource(id = R.color.primary)
)
}
}
}
}
)
}
@Composable
fun LazyGridState.OnBottomReached(
buffer : Int = 0,
loadMore : () -> Unit
){
require(buffer >= 0) { "buffer cannot be negative, but was $buffer" }
val shouldLoadMore = remember {
derivedStateOf {
val lastVisibleItem = layoutInfo.visibleItemsInfo.lastOrNull()
?:
return@derivedStateOf true
lastVisibleItem.index >= layoutInfo.totalItemsCount - 1 - buffer
}
}
LaunchedEffect(shouldLoadMore){
snapshotFlow { shouldLoadMore.value }
.collect { if (it) loadMore() }
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/movies/MoviesScreen.kt | 980187348 |
package mohammad.toriq.mymovies.presentation.screen.movies
import mohammad.toriq.mymovies.models.Movie
/***
* Created By Mohammad Toriq on 30/11/2023
*/
data class MoviesUiState (
val movieList: ArrayList<Movie> = ArrayList(),
val isLoading: Boolean = false,
val errorMessage : String = ""
) | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/movies/MoviesUiState.kt | 3889314077 |
package mohammad.toriq.mymovies.presentation.screen.movies
import android.util.Log
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.domain.usecase.GetDiscoverMoviesUseCase
import javax.inject.Inject
/***
* Created By Mohammad Toriq on 30/11/2023
*/
@HiltViewModel
class MoviesViewModel @Inject constructor(
private val getDiscoverMoviesUseCase: GetDiscoverMoviesUseCase
) : ViewModel() {
private val _state = mutableStateOf(MoviesUiState())
val state: State<MoviesUiState> = _state
var page = 1
var isRefresh = false
var isMax = false
var isInit = false
var genre:String ?= null
fun getMovies() {
viewModelScope.launch {
getDiscoverMoviesUseCase(page = page,withGenres = genre,"en-Us").onEach { result ->
var list = state.value.movieList
when (result) {
is Resource.Loading -> {
_state.value = state.value.copy(
movieList = list,
isLoading = true,
errorMessage = ""
)
}
is Resource.Success -> {
if(page == 1){
isInit = true
}
if(result.data?.movies !=null){
result.data.movies.forEach {
list.add(it)
}
}
if(page < result.data!!.totalPages){
page++
}else{
isMax = true
}
Log.d("OkCheck","page next:"+page.toString())
_state.value = state.value.copy(
movieList = list,
isLoading = false,
errorMessage = ""
)
}
is Resource.Error -> {
_state.value = state.value.copy(
movieList = list,
isLoading = false,
errorMessage = "Failed Connected To API Server"
)
isMax = true
}
}
}.launchIn(this)
}
}
fun loadMore(){
Log.d("OkCheck","loadMore:"+page.toString())
getMovies()
}
fun refresh() {
viewModelScope.launch(Dispatchers.IO) {
Log.d("OkCheck","refresh")
isRefresh = true
isMax = false
page = 1
_state.value = state.value.copy(
movieList = ArrayList(),
isLoading = false,
errorMessage = ""
)
getMovies()
isRefresh = false
}
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/movies/MoviesViewModel.kt | 3979751136 |
package mohammad.toriq.mymovies.presentation.screen.detailmovie
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import mohammad.toriq.mymovies.data.source.remote.Resource
import mohammad.toriq.mymovies.domain.usecase.GetDetailMovieUseCase
import mohammad.toriq.mymovies.domain.usecase.GetMovieVideosUseCase
import mohammad.toriq.mymovies.models.Video
import javax.inject.Inject
/***
* Created By Mohammad Toriq on 01/12/2023
*/
@HiltViewModel
class DetailMovieViewModel @Inject constructor(
private val getDetailMovieUseCase: GetDetailMovieUseCase,
private val getMovieVideosUseCase: GetMovieVideosUseCase
) : ViewModel() {
private val _state = mutableStateOf(DetailMovieUiState())
val state: State<DetailMovieUiState> = _state
private val _stateVideo = mutableStateOf(DetailMovieVideoUiState())
val stateVideo: State<DetailMovieVideoUiState> = _stateVideo
var id : Long = 0
var isInit = false
fun getDetailMovie() {
viewModelScope.launch {
getDetailMovieUseCase(id).onEach { result ->
when (result) {
is Resource.Loading -> {
_state.value = state.value.copy(
movie = null,
isLoading = true
)
}
is Resource.Success -> {
_state.value = state.value.copy(
movie = result.data,
isLoading = false
)
}
is Resource.Error -> {
_state.value = state.value.copy(
movie = null,
isLoading = false
)
}
}
}.launchIn(this)
}
}
fun getVideo(videos : List<Video>) : Video?{
var types = listOf("Trailer","Teaser","Clip")
var result:Video ?= null
types.forEach {type ->
if(result == null){
videos.forEach { vid ->
if(vid.type!!.contains(type,true)){
result = vid
}
}
}
}
if(result == null){
videos.forEach { vid ->
if(result == null){
result = vid
}
}
}
return result
}
fun getDetailMovieVideos() {
viewModelScope.launch {
getMovieVideosUseCase(id).onEach { result ->
when (result) {
is Resource.Loading -> {
_stateVideo.value = stateVideo.value.copy(
movieVideo = null
)
}
is Resource.Success -> {
var video = getVideo(result.data!!.videos)
_stateVideo.value = stateVideo.value.copy(
movieVideo = video,
)
}
is Resource.Error -> {
_stateVideo.value = stateVideo.value.copy(
movieVideo = null
)
}
}
}.launchIn(this)
}
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/detailmovie/DetailMovieViewModel.kt | 2411477901 |
@file:OptIn(ExperimentalMaterial3Api::class)
package mohammad.toriq.mymovies.presentation.screen.detailmovie
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.PixelFormat
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionContext
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.platform.AbstractComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.window.Dialog
import androidx.fragment.app.Fragment
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.FullscreenListener
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.options.IFramePlayerOptions
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
import mohammad.toriq.mymovies.R
import mohammad.toriq.mymovies.data.source.remote.dto.APIService
import mohammad.toriq.mymovies.presentation.navigation.Screen
import mohammad.toriq.mymovies.util.Constants
import mohammad.toriq.mymovies.util.Util
import mohammad.toriq.mymovies.models.Video
import java.util.UUID
/***
* Created By Mohammad Toriq on 30/11/2023
*/
@Composable
fun DetailMovieScreen (
activity: ComponentActivity,
navController: NavController,
id: Long,
detailMovieViewModel: DetailMovieViewModel = hiltViewModel()
){
Log.d("OKCheck","id:"+id.toString())
if(!detailMovieViewModel.isInit){
detailMovieViewModel.isInit = true
detailMovieViewModel.id = id
detailMovieViewModel.getDetailMovie()
detailMovieViewModel.getDetailMovieVideos()
}
initDetailMovie(
activity,
navController,
detailMovieViewModel)
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun initDetailMovie(
activity: ComponentActivity,
navController: NavController,
detailMovieViewModel: DetailMovieViewModel,
modifier: Modifier = Modifier) {
BackHandler {
navController.navigateUp()
}
val showDialog = remember { mutableStateOf(false) }
var isLoading = detailMovieViewModel.state.value.isLoading
var movie = detailMovieViewModel.state.value.movie
var video = detailMovieViewModel.stateVideo.value.movieVideo
if(showDialog.value){
showDetailMovieVideo(activity = activity, video = video!!,
navController = navController, showDialog)
}
Scaffold(
modifier = Modifier
.fillMaxSize(),
topBar = {
Surface(
shadowElevation = 3.dp
){
CenterAlignedTopAppBar(
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = colorResource(id = R.color.primary),
titleContentColor = colorResource(id = R.color.white),
),
title = {
Text(
text = "Detail Movie",
fontWeight = FontWeight.SemiBold,
)
},
navigationIcon = {
IconButton(
onClick = {
navController.navigateUp()
}) {
Image(
imageVector = Icons.Filled.ArrowBack,
colorFilter = ColorFilter.tint(colorResource(id = R.color.white)),
contentDescription = "Back"
)
}
},
)
}
},
content = {
Box(
modifier = Modifier
.padding(it)
.fillMaxSize()) {
//
if(!isLoading){
if(movie != null) {
Column(
modifier = Modifier,
) {
Row (
modifier = Modifier
.background(color = colorResource(id = R.color.primary2))
){
AsyncImage(
model = APIService.IMAGE_BASE_URL + movie.imageUrl,
contentDescription = null,
alignment = Alignment.Center,
modifier = Modifier.weight(1f)
)
Column (
modifier = Modifier
.weight(2f)
.padding(5.dp)
){
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 5.dp),
text = movie.title!!,
fontSize = 16.sp,
color = colorResource(id = R.color.white),
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(10.dp))
var genre = ""
movie.genres.forEach {
var isComma = true
if(genre.equals("")){
isComma = false
genre = "Genre : "
}
if(isComma){
genre += ", "
}
genre += it.name
}
if(!genre.equals("")){
Text(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp),
text = genre,
fontSize = 13.sp,
color = colorResource(id = R.color.white),
)
}
if(movie.releaseDate != null){
Text(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp),
text = "Release : "+Util.convertDate(movie.releaseDate!!,
Constants.DATE_OUT_FORMAT_DEF2,
Constants.DATE_OUT_FORMAT_DEF4),
fontSize = 13.sp,
color = colorResource(id = R.color.white),
)
}
if(movie.runtime > 0){
Text(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp),
text = "Durasi : "+Util.getShowTime(movie.runtime),
fontSize = 13.sp,
color = colorResource(id = R.color.white),
)
}
if(movie.voteAverage > 0){
Text(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp),
text = "Rating : "+movie.voteAverage,
fontSize = 13.sp,
color = colorResource(id = R.color.white),
)
}
}
}
Text(
modifier = Modifier
.fillMaxWidth()
.padding(
top = 15.dp,
start = 10.dp,
end = 10.dp
),
text = "Description",
fontSize = 18.sp,
color = colorResource(id = R.color.primary),
fontWeight = FontWeight.Bold
)
Text(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp, vertical = 10.dp),
text = movie.desc!!,
fontSize = 14.sp,
color = colorResource(id = R.color.grey),
)
Row (
){
if(video!= null){
Button(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.padding(5.dp),
colors = ButtonDefaults.buttonColors(
containerColor = colorResource(id = R.color.primary2)
),
shape = RoundedCornerShape(10),
onClick = {
showDialog.value = true
},
contentPadding = PaddingValues()
) {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp),
text = "Show "+video.type!!,
fontSize = 14.sp,
color = colorResource(id = R.color.white),
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold
)
}
}
OutlinedButton(
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.padding(5.dp),
shape = RoundedCornerShape(10),
border = BorderStroke(1.dp, colorResource(id = R.color.primary2)),
onClick = {
navController.navigate(
Screen.ReviewsScreen
.sendData(movie.id.toString(), movie.title!!)
)
},
contentPadding = PaddingValues()
) {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp),
text = "Reviews",
fontSize = 14.sp,
color = colorResource(id = R.color.primary2),
textAlign = TextAlign.Center,
fontWeight = FontWeight.Bold
)
}
}
}
}else{
Column(
modifier = Modifier
.fillMaxWidth()
.height(400.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
){
Text(
text = "Detail Movie not Found",
color = colorResource(id = R.color.primary),
fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center,
fontSize = 16.sp,
modifier = Modifier
.fillMaxWidth()
)
}
}
}else{
Row(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
CircularProgressIndicator(
color = colorResource(id = R.color.primary)
)
}
}
}
}
)
}
@Composable
fun LazyGridState.OnBottomReached(
buffer : Int = 0,
loadMore : () -> Unit
){
require(buffer >= 0) { "buffer cannot be negative, but was $buffer" }
val shouldLoadMore = remember {
derivedStateOf {
val lastVisibleItem = layoutInfo.visibleItemsInfo.lastOrNull()
?:
return@derivedStateOf true
lastVisibleItem.index >= layoutInfo.totalItemsCount - 1 - buffer
}
}
LaunchedEffect(shouldLoadMore){
snapshotFlow { shouldLoadMore.value }
.collect { if (it) loadMore() }
}
}
private var isFullscreen = false
@Composable
fun showDetailMovieVideo(
activity: ComponentActivity,
video: Video,
navController: NavController,
openDialogCustom: MutableState<Boolean>) {
Dialog(onDismissRequest = { openDialogCustom.value = false }) {
AndroidView(factory = {
var view = YouTubePlayerView(it)
var fullView = FrameLayout(it)
var youTubePlayerHome: YouTubePlayer?= null
val iFramePlayerOptions = IFramePlayerOptions.Builder()
.controls(1)
.fullscreen(1)
.build()
view.enableAutomaticInitialization = false
isFullscreen = false
view.addFullscreenListener(object : FullscreenListener {
override fun onEnterFullscreen(fullscreenView: View, exitFullscreen: () -> Unit) {
isFullscreen = true
openDialogCustom.value = false
navController.navigate(
Screen.VideoScreen
.sendData(video.key!!, "Video "+video.type!!)
)
}
override fun onExitFullscreen() {
isFullscreen = false
}
})
view.initialize(object : AbstractYouTubePlayerListener() {
override fun onReady(youTubePlayer: YouTubePlayer) {
youTubePlayerHome = youTubePlayer
super.onReady(youTubePlayer)
youTubePlayer.loadVideo(video.key!!, 0f)
}
}, iFramePlayerOptions)
activity.onBackPressedDispatcher.addCallback(
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if (isFullscreen) {
if(youTubePlayerHome!=null){
youTubePlayerHome!!.toggleFullscreen()
}
}
}
}
)
activity.lifecycle.addObserver(view)
view
})
}
} | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/detailmovie/DetailMovieScreen.kt | 3991779816 |
@file:OptIn(ExperimentalMaterial3Api::class)
package mohammad.toriq.mymovies.presentation.screen.detailmovie
import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.navigation.NavController
import com.google.accompanist.systemuicontroller.SystemUiController
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
/***
* Created By Mohammad Toriq on 30/11/2023
*/
@Composable
fun LockScreenOrientation(activity: ComponentActivity,
orientation: Int) {
DisposableEffect(orientation) {
val originalOrientation = activity.requestedOrientation
activity.requestedOrientation = orientation
onDispose {
activity.requestedOrientation = originalOrientation
}
}
}
@Composable
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
fun VideoScreen (
activity: ComponentActivity,
navController: NavController,
id: String,
title: String
){
BackHandler {
navController.navigateUp()
}
val systemUiController: SystemUiController = rememberSystemUiController()
systemUiController.isStatusBarVisible = false // Status bar
systemUiController.isNavigationBarVisible = false // Navigation bar
systemUiController.isSystemBarsVisible = false // Status & Navigation bars
LockScreenOrientation(activity = activity, orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
Scaffold(
modifier = Modifier
.fillMaxSize(),
content = {
Column(
modifier = Modifier
.padding(it)
.background(color = Color.Black)
.fillMaxSize()) {
AndroidView(
modifier = Modifier.padding(50.dp),
factory = {
var view = YouTubePlayerView(it)
view.addYouTubePlayerListener(
object : AbstractYouTubePlayerListener() {
override fun onReady(youTubePlayer: YouTubePlayer) {
super.onReady(youTubePlayer)
youTubePlayer.loadVideo(id, 0f)
}
}
)
view
})
}
}
)
}
| my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/detailmovie/VideoScreen.kt | 2793237266 |
package mohammad.toriq.mymovies.presentation.screen.detailmovie
import mohammad.toriq.mymovies.models.Genre
import mohammad.toriq.mymovies.models.Movie
/***
* Created By Mohammad Toriq on 01/12/2023
*/
data class DetailMovieUiState (
val movie: Movie?= null,
val isLoading: Boolean = false
) | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/detailmovie/DetailMovieUiState.kt | 1723892141 |
package mohammad.toriq.mymovies.presentation.screen.detailmovie
import mohammad.toriq.mymovies.models.Video
/***
* Created By Mohammad Toriq on 01/12/2023
*/
data class DetailMovieVideoUiState (
val movieVideo: Video ?= null,
) | my_movies_jetpack_compose/app/src/main/java/mohammad/toriq/mymovies/presentation/screen/detailmovie/DetailMovieVideoUiState.kt | 850571916 |
package com.example.udemydersleri
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.udemydersleri", appContext.packageName)
}
} | UdemyDersleri/app/src/androidTest/java/com/example/udemydersleri/ExampleInstrumentedTest.kt | 635521067 |
package com.example.udemydersleri
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)
}
} | UdemyDersleri/app/src/test/java/com/example/udemydersleri/ExampleUnitTest.kt | 2102075311 |
package com.example.udemydersleri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | UdemyDersleri/app/src/main/java/com/example/udemydersleri/MainActivity.kt | 3725759499 |
package com.example.udemydersleri
fun main() {
val Ilce = 12.5
val Kita : String = "Antartika"
val faks : Int = 123456789
val sonuc2 = faks.toDouble()
val sonuc1 = Ilce.toInt()
println("$sonuc1\n" +
"$Kita\n" +
"$sonuc2\n" )
} | UdemyDersleri/app/src/main/java/com/example/udemydersleri/IlkOdev.kt | 1702389787 |
package com.example.udemydersleri.genelseyler
fun main() {
for (i in (5 downTo 2) step 1) {
println("$i\n")
}
var sayac = 1
while (sayac < 5){
println("$sayac")
sayac++
}
println("" +
"" +
"" +
"" +
"")
for (a in 1..4){
if (a == 3){
break
}
println("$a")
}
for (a in 1..4){
if (a == 3){
continue
}
println("$a")
}
} | UdemyDersleri/app/src/main/java/com/example/udemydersleri/genelseyler/Donguler.kt | 1257662762 |
package com.example.udemydersleri.genelseyler
fun main() {
val yas = 20
val isim = " asli"
val gun = 8
if (yas >= 20 ){
println(" resit degilsiniz")
}
else {
println(" resitsiniz")
}
when(gun){
1 -> println("pzrts")
2 -> println("sali")
3 -> println("crsmb")
4 -> println("prsmb")
5 -> println("cm")
else -> println(" boyle gun yok")
}
} | UdemyDersleri/app/src/main/java/com/example/udemydersleri/genelseyler/If+When(Switch).kt | 2275817356 |
package com.example.udemydersleri.genelseyler
fun main() {
val a = 38
val b = 30
val c = 16
val d = 50
println("a == b : ${a == b}")
println("a != b : ${a != b}")
println("a > b || c > d ${a > b || c > d}") // veya operatoru true olmasi icin sadece birinin dogru olmasi yeterlidir
println("a > b && c > d ${a > b && c > d}") // ve operatoru true olmasi icin her ikisinin de dogru olmasi gerekir
}
| UdemyDersleri/app/src/main/java/com/example/udemydersleri/genelseyler/KarsilastirmaOperatorleri.kt | 524981182 |
package com.example.udemydersleri.Nesne_Tabanli_programlama
class Araba (renk :String , hiz :Int , CalisiyorMu : Boolean){
var renk: String = renk
var hiz: Int = hiz
var CalisiyorMu: Boolean = CalisiyorMu
} | UdemyDersleri/app/src/main/java/com/example/udemydersleri/Nesne_Tabanli_programlama/Araba.kt | 1352284868 |
package com.example.udemydersleri.Nesne_Tabanli_programlama
fun main() {
// nesne olusturma
val bmw = Araba("beyaz", 29, false)
val citroen = Araba("kirmizi",300,true)
// okuma
println("Rengi : ${bmw.renk}")
println("Hizi : ${bmw.hiz}")
println("Calisiyor mu : ${bmw.CalisiyorMu}")
println("\n")
println("Rengi : ${citroen.renk}")
println("hizi : ${citroen.hiz}")
println("calisiyor mu : ${citroen.CalisiyorMu}")
// veri atama
bmw.renk = "siyah"
bmw.hiz = 28
bmw.CalisiyorMu = true
println("\n")
println("Rengi : ${bmw.renk}")
println("Hizi : ${bmw.hiz}")
println("Calisiyor mu : ${bmw.CalisiyorMu}")
} | UdemyDersleri/app/src/main/java/com/example/udemydersleri/Nesne_Tabanli_programlama/Araba.deneme.kt | 3606229903 |
package com.zhufucdev.currimate
import android.Manifest
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
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.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.OutlinedButton
import androidx.wear.compose.material.Scaffold
import androidx.wear.compose.material.Text
import com.google.android.horologist.compose.layout.ResponsiveTimeText
import com.zhufucdev.currimate.theme.WearAppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
installSplashScreen()
WearAppTheme {
WearApp()
}
setTheme(android.R.style.Theme_DeviceDefault)
}
}
}
@Composable
fun WearApp() {
var calendarPermissionGranted by remember { mutableStateOf<Boolean?>(null) }
val launcher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {
calendarPermissionGranted = it
}
LaunchedEffect(true) {
launcher.launch(Manifest.permission.READ_CALENDAR)
}
Scaffold(
timeText = { ResponsiveTimeText() },
modifier = Modifier.background(MaterialTheme.colors.background)
) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Column {
Text(
text = stringResource(id = R.string.app_name),
style = MaterialTheme.typography.title2,
)
Text(
text = stringResource(
id =
if (calendarPermissionGranted == true) R.string.span_permission_granted
else R.string.span_permission_denied
)
)
if (calendarPermissionGranted == false) {
OutlinedButton(
onClick = { launcher.launch(Manifest.permission.READ_CALENDAR) },
modifier = Modifier.fillMaxWidth()
) {
Text(
text = stringResource(id = R.string.par_grant),
style = MaterialTheme.typography.body2
)
}
}
}
}
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/MainActivity.kt | 755925770 |
package com.zhufucdev.currimate
import android.content.ContentResolver
import android.content.ContentUris
import android.provider.CalendarContract
import android.util.Log
import androidx.wear.provider.WearableCalendarContract
import java.time.Instant
import java.time.ZoneId
import java.time.ZonedDateTime
class CalendarEvents(private val contentResolver: ContentResolver) {
/**
* Query calendar events between a time range (UTC epoch)
* @return [CalendarEvent]s that are guaranteed to be sorted ascendingly
*/
operator fun get(rangeMills: LongRange): List<CalendarEvent> {
val builder = WearableCalendarContract.Instances.CONTENT_URI.buildUpon()
ContentUris.appendId(builder, rangeMills.first)
ContentUris.appendId(builder, rangeMills.last)
return buildList {
try {
contentResolver.query(
builder.build(),
projection,
null,
null
)?.use { cursor ->
while (cursor.moveToNext()) {
add(
CalendarEvent(
id = cursor.getLong(EVENT_ID_INDEX),
beginMills = cursor.getLong(BEGIN_INDEX),
endMills = cursor.getLong(END_INDEX),
title = cursor.getString(TITLE_INDEX),
location = cursor.getString(EVENT_LOCATION_INDEX)
)
)
}
}
} catch (e: SecurityException) {
Log.w("calendar", "Permission denied while querying event instances")
}
}.sorted()
}
}
private val projection = arrayOf(
CalendarContract.Instances.EVENT_ID,
CalendarContract.Instances.TITLE,
CalendarContract.Instances.BEGIN,
CalendarContract.Instances.END,
CalendarContract.Instances.EVENT_LOCATION
)
private const val EVENT_ID_INDEX = 0
private const val TITLE_INDEX = 1
private const val BEGIN_INDEX = 2
private const val END_INDEX = 3
private const val EVENT_LOCATION_INDEX = 4
data class CalendarEvent(
val id: Long,
val title: String,
val beginMills: Long,
val endMills: Long,
val location: String
) : Comparable<CalendarEvent> {
override fun compareTo(other: CalendarEvent): Int = beginMills.compareTo(other.beginMills)
}
operator fun CalendarEvent.contains(time: ZonedDateTime) =
time.toInstant().toEpochMilli() in beginMills until endMills
val CalendarEvent.beginInstant: Instant get() = Instant.ofEpochMilli(beginMills)
val CalendarEvent.endInstant: Instant get() = Instant.ofEpochMilli(endMills)
| Currimate/app/src/main/java/com/zhufucdev/currimate/Calendar.kt | 3066384939 |
package com.zhufucdev.currimate.render
import com.zhufucdev.currimate.CalendarEvent
import com.zhufucdev.currimate.R
import com.zhufucdev.currimate.beginInstant
import com.zhufucdev.currimate.endInstant
import com.zhufucdev.currimate.watchface.WatchFaceCanvasRenderer
import java.time.Duration
import java.time.Instant
fun Renderable.smartTimeString(event: CalendarEvent): String {
val t =
Duration.between(Instant.now(), event.beginInstant).toMinutes().toInt()
return if (t > 0) {
context.resources.getQuantityString(R.plurals.par_in_minutes, t, t)
} else if (t == 0) {
context.getString(R.string.par_at_present)
} else if (t > -10) {
context.resources
.getQuantityString(R.plurals.par_minutes_ago, -t, -t)
} else {
val k = Duration.between(Instant.now(), event.endInstant).toMinutes().toInt() + 1
context.resources
.getQuantityString(R.plurals.par_minutes_remaining, k, k)
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/SmartTimeString.kt | 755320162 |
package com.zhufucdev.currimate.render
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.RectF
import androidx.core.graphics.withRotation
import androidx.wear.watchface.DrawMode
import androidx.wear.watchface.RenderParameters
import com.zhufucdev.currimate.theme.HOUR_HAND_ROUNDNESS
import com.zhufucdev.currimate.theme.HOUR_HAND_WIDTH
import com.zhufucdev.currimate.theme.MINUTE_HAND_ROUNDNESS
import com.zhufucdev.currimate.theme.MINUTE_HAND_WIDTH
import com.zhufucdev.currimate.watchface.UserStyleColors
import java.time.ZonedDateTime
import java.time.temporal.ChronoField
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sqrt
fun drawClock(
canvas: Canvas,
bounds: Rect,
clockCenter: PointF,
zonedDateTime: ZonedDateTime,
renderParameters: RenderParameters,
colorStyleHolder: UserStyleColors
) {
val hourHandLength = 0.5f * (HOUR_HAND_WIDTH / 2 + bounds.bottom - clockCenter.y)
val hourHandRotation =
((zonedDateTime.hour % 12) / 12f + zonedDateTime.minute / 720F) * 360
val hourHandOutline = RectF(
clockCenter.x - HOUR_HAND_WIDTH / 2,
clockCenter.y - HOUR_HAND_WIDTH / 2 - hourHandLength,
clockCenter.x + HOUR_HAND_WIDTH / 2,
clockCenter.y + HOUR_HAND_WIDTH / 2,
)
canvas.withRotation(hourHandRotation, clockCenter.x, clockCenter.y) {
canvas.drawRoundRect(
hourHandOutline,
HOUR_HAND_ROUNDNESS,
HOUR_HAND_ROUNDNESS,
Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = colorStyleHolder.hourHandColor
if (renderParameters.drawMode == DrawMode.AMBIENT) {
strokeWidth = HOUR_HAND_WIDTH * 0.1f
style = Paint.Style.STROKE
}
}
)
}
val minuteHandRotation = (zonedDateTime.minute / 60f + zonedDateTime.second / 3600f) * 360
val minuteHandLength = hourHandLength * 1.8f
canvas.withRotation(minuteHandRotation, clockCenter.x, clockCenter.y) {
canvas.drawRoundRect(
clockCenter.x - MINUTE_HAND_WIDTH / 2,
clockCenter.y - MINUTE_HAND_WIDTH / 2 - minuteHandLength,
clockCenter.x + MINUTE_HAND_WIDTH / 2,
clockCenter.y + MINUTE_HAND_WIDTH / 2,
MINUTE_HAND_ROUNDNESS,
MINUTE_HAND_ROUNDNESS,
Paint(Paint.ANTI_ALIAS_FLAG).apply { color = colorStyleHolder.minuteHandColor }
)
}
if (renderParameters.drawMode != DrawMode.AMBIENT) {
val secondHandRotation =
(zonedDateTime.second / 60f + zonedDateTime[ChronoField.MILLI_OF_SECOND] / 1000f / 60f) * 360
val secondHandLength = run {
val h = bounds.centerY() - clockCenter.y
val t = cos(secondHandRotation / 180 * PI).toFloat()
val r = bounds.width() / 2f
(h * t - sqrt(h * h * t * t - h * h + r * r)) * 0.92f
}
canvas.withRotation(secondHandRotation, clockCenter.x, clockCenter.y) {
canvas.drawLine(
clockCenter.x,
clockCenter.y,
clockCenter.x,
clockCenter.y + secondHandLength,
Paint(Paint.ANTI_ALIAS_FLAG).apply { color = colorStyleHolder.secondHandColor }
)
}
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/DrawClock.kt | 2532286644 |
package com.zhufucdev.currimate.render
import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.Rect
import android.graphics.RectF
import androidx.wear.watchface.RenderParameters
import androidx.wear.watchface.style.CurrentUserStyleRepository
import com.zhufucdev.currimate.theme.TimePaint
import com.zhufucdev.currimate.watchface.UserStyleHolder
import com.zhufucdev.currimate.watchface.WatchFaceCanvasRenderer
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import kotlin.math.PI
abstract class RenderTimeText(
context: Context,
styleHolder: UserStyleHolder,
) : Renderable(context, styleHolder) {
override fun render(
canvas: Canvas,
bounds: Rect,
contentBounds: RectF,
zonedDateTime: ZonedDateTime,
renderParameters: RenderParameters
) {
val radius = minOf(bounds.width(), bounds.height()) * 0.8f / 2f
val timeBounds = RectF(
bounds.width() / 2f - radius,
bounds.height() / 2f - radius,
bounds.width() / 2f + radius,
bounds.height() / 2f + radius
)
val timeString = zonedDateTime.format(DateTimeFormatter.ofPattern("hh:mm"))
val timeTextWidth = TimePaint.measureText(timeString)
val angularOffset = (timeTextWidth / (2 * PI * radius) * 180).toFloat()
val timeTextPath = Path().apply {
addArc(timeBounds, -90f - angularOffset, angularOffset * 2)
}
canvas.drawTextOnPath(
timeString,
timeTextPath,
0f,
0f,
TimePaint
)
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/RenderTimeText.kt | 4027055433 |
package com.zhufucdev.currimate.render
import android.content.Context
import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.RenderNode
import android.graphics.Shader
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.core.graphics.toRect
import androidx.core.graphics.toRectF
import androidx.wear.watchface.DrawMode
import androidx.wear.watchface.RenderParameters
import com.zhufucdev.currimate.CalendarEvent
import com.zhufucdev.currimate.R
import com.zhufucdev.currimate.endInstant
import com.zhufucdev.currimate.theme.LargeTitlePaint
import com.zhufucdev.currimate.theme.ParPaint
import com.zhufucdev.currimate.theme.TextPaint
import com.zhufucdev.currimate.theme.TitlePaint
import com.zhufucdev.currimate.watchface.UserStyleHolder
import java.time.Duration
import java.time.Instant
import java.time.ZonedDateTime
class RenderCurrentAndNext(
context: Context,
styleHolder: UserStyleHolder,
private val current: CalendarEvent,
private val next: CalendarEvent
) : RenderTimeText(context, styleHolder) {
private val nextTitleRenderable = RenderText(next.title, TextPaint, context, styleHolder)
private val currTitleRenderable = RenderText(current.title, TextPaint, context, styleHolder)
private val timerStandIcon =
context.fromDrawable(
R.drawable.ic_timer_sand,
Color.White.copy(alpha = 0.5f),
120,
120
)
private val calendarIcon =
context.fromDrawable(R.drawable.ic_calendar_start_outline, Color.White)
private fun timeRemainingString(event: CalendarEvent): String {
val t = Duration.between(Instant.now(), event.endInstant).toMinutes().toInt()
return context.resources
.getQuantityString(R.plurals.par_minutes_remaining, t, t)
}
override fun render(
canvas: Canvas,
bounds: Rect,
contentBounds: RectF,
zonedDateTime: ZonedDateTime,
renderParameters: RenderParameters
) {
val titlePaint =
if (renderParameters.drawMode == DrawMode.AMBIENT) TextPaint else TitlePaint
val largeTitlePaint =
if (renderParameters.drawMode == DrawMode.AMBIENT) TextPaint else LargeTitlePaint
val currTitleSize = Rect()
titlePaint.getTextBounds(current.title, 0, current.title.length, currTitleSize)
if (currTitleSize.width() >= contentBounds.width()) {
currTitleSize.left = contentBounds.left.toInt()
currTitleSize.right = contentBounds.right.toInt()
}
val currRemainingStr = timeRemainingString(current)
val currRemainingBounds = run {
val t = Rect()
ParPaint.getTextBounds(
currRemainingStr,
0,
currRemainingStr.length,
t
)
t.toRectF().apply {
offsetTo(
(contentBounds.centerX() - currTitleSize.width() / 2f),
(contentBounds.top + currTitleSize.height() + 12),
)
}
}
val nextTitleBounds = run {
val t = Rect()
largeTitlePaint.getTextBounds(next.title, 0, next.title.length, t)
if (t.width() >= contentBounds.width()) {
t.left = contentBounds.left.toInt()
t.right = contentBounds.right.toInt()
}
t.toRectF().apply {
offsetTo(
contentBounds.centerX() + (calendarIcon.width - t.width()) / 2f,
maxOf(currRemainingBounds.bottom + 12f, bounds.exactCenterY() - t.height())
)
}
}
val nextLocationBounds =
next.location.toBottom(of = RectF(nextTitleBounds).apply { left -= calendarIcon.width * 0.618f })
val nextTimeString = smartTimeString(next)
val nextTimeBounds = nextTimeString.toBottom(of = nextLocationBounds, margin = 12f)
if (renderParameters.drawMode != DrawMode.AMBIENT) {
val timerStandIconBounds = RectF(
contentBounds.centerX() - timerStandIcon.width / 2f,
contentBounds.top -
(timerStandIcon.height - currTitleSize.height() - currRemainingBounds.height()) / 2f,
contentBounds.centerX() + timerStandIcon.width / 2f,
contentBounds.top + currTitleSize.bottom +
(timerStandIcon.height - currTitleSize.height() - currRemainingBounds.height()) / 2f
)
val iconMaskPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
isDither = true
shader = LinearGradient(
timerStandIconBounds.centerX(),
timerStandIconBounds.top,
timerStandIconBounds.centerX(),
timerStandIconBounds.bottom,
intArrayOf(
Color.Black.toArgb(),
Color.Transparent.toArgb(),
Color.Transparent.toArgb(),
Color.Black.toArgb()
),
floatArrayOf(0f, 0.4f, 0.6f, 1f),
Shader.TileMode.MIRROR
)
}
canvas.drawBitmap(
timerStandIcon,
timerStandIconBounds.left,
timerStandIconBounds.top,
null
)
canvas.drawRect(timerStandIconBounds, iconMaskPaint)
}
val clockCenter = PointF(bounds.exactCenterX(), nextTimeBounds.centerY() + 40)
drawClock(
canvas,
bounds,
clockCenter,
zonedDateTime,
renderParameters,
styleHolder.colors
)
run {
currTitleRenderable.paint = titlePaint
val node = RenderNode("current event title")
val position = Rect(currTitleSize).apply {
offsetTo(
(contentBounds.centerX() - currTitleSize.width() / 2).toInt(),
contentBounds.top.toInt()
)
bottom += 10
}
node.setPosition(position)
val c = node.beginRecording()
val mapped = Rect(currTitleSize)
mapped.offsetTo(0, 0)
currTitleRenderable.render(
c,
position.apply { offsetTo(0, 0) },
mapped.toRectF(),
zonedDateTime,
renderParameters
)
node.endRecording()
canvas.drawRenderNode(node)
}
canvas.drawText(
currRemainingStr,
currRemainingBounds.left,
currRemainingBounds.bottom,
ParPaint
)
drawFocusedEvent(
next,
nextTitleRenderable,
canvas,
calendarIcon,
nextTimeString,
nextTitleBounds,
zonedDateTime,
renderParameters
)
super.render(canvas, bounds, contentBounds, zonedDateTime, renderParameters)
}
override fun onDestroy() {
calendarIcon.recycle()
timerStandIcon.recycle()
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/RenderCurrentAndNext.kt | 3422175247 |
package com.zhufucdev.currimate.render
import android.content.Context
import androidx.annotation.Px
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.core.graphics.drawable.toBitmap
fun Context.fromDrawable(id: Int, tint: Color, @Px width: Int? = null, @Px height: Int? = null) =
getDrawable(id)!!
.apply { setTint(tint.toArgb()) }.let {
it.toBitmap(
width = width ?: it.intrinsicWidth,
height = height ?: it.intrinsicHeight
)
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/FromDrawable.kt | 3703195001 |
package com.zhufucdev.currimate.render
import android.content.Context
import android.graphics.Canvas
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.RectF
import android.util.Log
import androidx.compose.ui.graphics.Color
import androidx.core.graphics.toRectF
import androidx.wear.watchface.DrawMode
import androidx.wear.watchface.RenderParameters
import com.zhufucdev.currimate.CalendarEvent
import com.zhufucdev.currimate.R
import com.zhufucdev.currimate.theme.LargeTitlePaint
import com.zhufucdev.currimate.theme.TextPaint
import com.zhufucdev.currimate.watchface.UserStyleHolder
import java.time.ZonedDateTime
import kotlin.math.roundToInt
class RenderSoloOngoing(
context: Context,
styleHolder: UserStyleHolder,
private val event: CalendarEvent
) : RenderTimeText(context, styleHolder) {
private val titleRenderable = RenderText(event.title, TextPaint, context, styleHolder)
private val calendarIcon =
context.fromDrawable(R.drawable.ic_calendar_start_outline, Color.White)
override fun render(
canvas: Canvas,
bounds: Rect,
contentBounds: RectF,
zonedDateTime: ZonedDateTime,
renderParameters: RenderParameters
) {
val largeTitlePaint =
if (renderParameters.drawMode == DrawMode.AMBIENT) TextPaint else LargeTitlePaint
val titleBounds = run {
val t = Rect()
largeTitlePaint.getTextBounds(event.title, 0, event.title.length, t)
if (t.width() > contentBounds.width()) {
t.left = contentBounds.left.roundToInt()
t.right = contentBounds.right.roundToInt()
}
t.toRectF().apply {
offsetTo(
contentBounds.centerX() + (calendarIcon.width - t.width()) / 2f,
0f
)
}
}
val locationBounds =
event.location.toBottom(of = RectF(titleBounds).apply { left -= calendarIcon.width * 0.618f })
val timeString = smartTimeString(event)
val timeBounds = timeString.toBottom(of = locationBounds, margin = 12f)
titleBounds.offset(0f, bounds.exactCenterY() - timeBounds.bottom / 2)
drawClock(
canvas,
bounds,
PointF(bounds.exactCenterX(), bounds.exactCenterY()),
zonedDateTime,
renderParameters,
styleHolder.colors
)
drawFocusedEvent(
event,
titleRenderable,
canvas,
calendarIcon,
timeString,
titleBounds,
zonedDateTime,
renderParameters,
)
super.render(canvas, bounds, contentBounds, zonedDateTime, renderParameters)
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/RenderSoloOngoing.kt | 1441699015 |
package com.zhufucdev.currimate.render
import android.content.Context
import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Shader
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.wear.watchface.DrawMode
import androidx.wear.watchface.RenderParameters
import com.zhufucdev.currimate.watchface.UserStyleHolder
import java.time.ZonedDateTime
import kotlin.math.roundToInt
private const val VELOCITY = 50f // pixel per second
private const val MARGIN = 100
class RenderText(
val text: String,
var paint: Paint,
context: Context,
styleHolder: UserStyleHolder,
private val framerate: Int = 60
) :
Renderable(context, styleHolder) {
private var frame = 0
private val textBounds get() = Rect().apply { paint.getTextBounds(text, 0, text.length, this) }
private val frames get() = ((textBounds.width() + MARGIN) / VELOCITY * framerate).roundToInt()
override fun render(
canvas: Canvas,
bounds: Rect,
contentBounds: RectF,
zonedDateTime: ZonedDateTime,
renderParameters: RenderParameters
) {
if (bounds.width() >= textBounds.width()) {
canvas.drawText(
text,
bounds.exactCenterX() - textBounds.width() / 2f,
bounds.exactCenterY() + textBounds.height() / 2f,
paint
)
} else if (renderParameters.drawMode != DrawMode.AMBIENT) {
val leftMaskPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
shader = LinearGradient(
bounds.left.toFloat(),
0f,
bounds.exactCenterX(),
0f,
intArrayOf(
Color.Black.toArgb(),
Color.Transparent.toArgb(),
),
floatArrayOf(0f, 40f / bounds.width()),
Shader.TileMode.MIRROR
)
xfermode = PorterDuffXfermode(PorterDuff.Mode.XOR)
}
val frames = frames
frame = (frame + 1) % frames
val offset = -frame * 1f / frames * (textBounds.width() + MARGIN)
val y = contentBounds.centerY() + textBounds.height() / 2f
canvas.drawText(text, offset + bounds.left, y, paint)
canvas.drawText(text, offset + MARGIN + textBounds.width(), y, paint)
canvas.drawRect(bounds, leftMaskPaint)
} else {
var remaining = bounds.width() * text.length / textBounds.width()
var truncatedText = text.substring(0 until remaining) + "..."
var width = paint.measureText(truncatedText)
while (width >= bounds.width()) {
remaining -= 1
truncatedText = text.substring(0 until remaining) + "..."
width = paint.measureText(truncatedText)
}
canvas.drawText(
truncatedText,
bounds.exactCenterX() - width / 2f,
contentBounds.centerY() + textBounds.height() / 2f,
paint
)
}
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/RenderText.kt | 1104971945 |
package com.zhufucdev.currimate.render
import android.content.Context
import android.graphics.Canvas
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.RectF
import androidx.wear.watchface.RenderParameters
import androidx.wear.watchface.style.CurrentUserStyleRepository
import com.zhufucdev.currimate.watchface.UserStyleHolder
import com.zhufucdev.currimate.watchface.WatchFaceCanvasRenderer
import java.time.ZonedDateTime
class RenderWatchface(
context: Context,
styleHolder: UserStyleHolder
) : Renderable(context, styleHolder) {
override fun render(
canvas: Canvas,
bounds: Rect,
contentBounds: RectF,
zonedDateTime: ZonedDateTime,
renderParameters: RenderParameters
) {
drawClock(
canvas,
bounds,
PointF(bounds.exactCenterX(), bounds.exactCenterY()),
zonedDateTime,
renderParameters,
styleHolder.colors
)
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/RenderWatchface.kt | 1373921512 |
package com.zhufucdev.currimate.render
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.RenderNode
import androidx.core.graphics.toRect
import androidx.wear.watchface.DrawMode
import androidx.wear.watchface.RenderParameters
import com.zhufucdev.currimate.CalendarEvent
import com.zhufucdev.currimate.theme.BodyPaint
import com.zhufucdev.currimate.theme.LargeTitlePaint
import com.zhufucdev.currimate.theme.TextPaint
import java.time.ZonedDateTime
fun drawFocusedEvent(
event: CalendarEvent,
renderable: RenderText,
canvas: Canvas,
calendarIcon: Bitmap,
timeString: String,
titleBounds: RectF,
zonedDateTime: ZonedDateTime,
renderParameters: RenderParameters,
locationBounds: RectF = event.location.toBottom(of = RectF(titleBounds).apply { left -= calendarIcon.width * 0.618f }),
timeBounds: RectF = timeString.toBottom(of = locationBounds, margin = 12f)
) {
val largeTitlePaint =
if (renderParameters.drawMode == DrawMode.AMBIENT) TextPaint else LargeTitlePaint
renderable.paint = largeTitlePaint
val node = RenderNode("event title")
val titleBoundsMapped = RectF(0f, 0f, titleBounds.width(), titleBounds.height())
if (renderParameters.drawMode != DrawMode.AMBIENT) {
val position = titleBounds.toRect().apply { bottom += 10 } // TODO better fix (text baseline)
node.setPosition(position)
val extendedBounds = Rect(position).apply { offsetTo(0, 0) }
val titleCanvas = node.beginRecording()
renderable.render(
canvas = titleCanvas,
bounds = extendedBounds,
contentBounds = titleBoundsMapped,
zonedDateTime = zonedDateTime,
renderParameters = renderParameters
)
node.endRecording()
canvas.drawBitmap(
calendarIcon,
titleBounds.left - calendarIcon.width - 4f,
titleBounds.top + (titleBounds.height() - calendarIcon.height) / 2 + 2f,
largeTitlePaint
)
} else {
val position = Rect(titleBounds.toRect()).apply {
left -= calendarIcon.width / 2
bottom += 10
}
val extendedBounds = Rect(position).apply { offsetTo(0, 0) }
node.setPosition(position)
val titleCanvas = node.beginRecording()
renderable.render(
titleCanvas,
extendedBounds,
titleBoundsMapped,
zonedDateTime,
renderParameters
)
node.endRecording()
}
canvas.drawRenderNode(node)
canvas.drawText(
event.location,
locationBounds.left,
locationBounds.bottom,
BodyPaint
)
canvas.drawText(timeString, timeBounds.left, timeBounds.bottom, BodyPaint)
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/DrawFocusedEvent.kt | 1023625581 |
package com.zhufucdev.currimate.render
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.RectF
import androidx.wear.watchface.RenderParameters
import androidx.wear.watchface.Renderer
import androidx.wear.watchface.style.CurrentUserStyleRepository
import com.zhufucdev.currimate.watchface.UserStyleHolder
import java.time.ZonedDateTime
abstract class Renderable(val context: Context, val styleHolder: UserStyleHolder) {
abstract fun render(
canvas: Canvas,
bounds: Rect,
contentBounds: RectF,
zonedDateTime: ZonedDateTime,
renderParameters: RenderParameters
)
open fun onDestroy() {}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/Renderable.kt | 311649016 |
package com.zhufucdev.currimate.render
import android.content.Context
import android.util.Log
import com.zhufucdev.currimate.CalendarEvent
import com.zhufucdev.currimate.beginInstant
import com.zhufucdev.currimate.contains
import com.zhufucdev.currimate.watchface.UserStyleHolder
import java.time.Duration
import java.time.ZonedDateTime
class RenderableFactory(private val styleHolder: UserStyleHolder, private val context: Context) {
private val renderWatchface = RenderWatchface(context, styleHolder)
private var mCurrNext: Triple<CalendarEvent, CalendarEvent, RenderCurrentAndNext>? = null
private fun renderCurrentAndNext(current: CalendarEvent, next: CalendarEvent) =
mCurrNext?.takeIf { it.first == current && it.second == next }?.third
?: RenderCurrentAndNext(context, styleHolder, current, next)
.also {
mCurrNext?.third?.onDestroy()
mCurrNext = Triple(current, next, it)
}
private var mSolo: Pair<CalendarEvent, RenderSoloOngoing>? = null
private fun renderSoloOngoing(event: CalendarEvent) =
mSolo?.takeIf { it.first == event }?.second
?: RenderSoloOngoing(context, styleHolder, event)
.also {
mSolo?.second?.onDestroy()
mSolo = event to it
}
fun getRenderer(zonedDateTime: ZonedDateTime, events: List<CalendarEvent>): Renderable =
if (events.isEmpty()) {
renderWatchface
} else {
val currentEvent = events.first()
if (zonedDateTime in currentEvent) {
if (events.size < 2
|| Duration.between(
zonedDateTime.toInstant(),
events[1].beginInstant
) > Duration.ofHours(1)
) {
renderSoloOngoing(currentEvent)
} else {
renderCurrentAndNext(currentEvent, events[1])
}
} else if (Duration.between(zonedDateTime.toInstant(), currentEvent.beginInstant)
.let { !it.isNegative && it.toHours() <= 1 }
) {
renderSoloOngoing(currentEvent)
} else {
renderWatchface
}
}
fun onDestroy() {
mCurrNext?.third?.onDestroy()
mSolo?.second?.onDestroy()
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/RenderableFactory.kt | 1727649861 |
package com.zhufucdev.currimate.render
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import androidx.core.graphics.toRectF
import com.zhufucdev.currimate.theme.BodyPaint
fun String.toBottom(of: RectF, margin: Float = 20f, paint: Paint = BodyPaint): RectF {
val t = Rect()
BodyPaint.getTextBounds(this, 0, length, t)
return t.toRectF().apply {
offsetTo(
of.left,
of.bottom + margin
)
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/render/Layout.kt | 1547055388 |
package com.zhufucdev.currimate.watchface
import android.view.SurfaceHolder
import androidx.wear.watchface.CanvasType
import androidx.wear.watchface.ComplicationSlotsManager
import androidx.wear.watchface.WatchFace
import androidx.wear.watchface.WatchFaceService
import androidx.wear.watchface.WatchFaceType
import androidx.wear.watchface.WatchState
import androidx.wear.watchface.style.CurrentUserStyleRepository
import androidx.wear.watchface.style.UserStyleSchema
import androidx.wear.watchface.style.UserStyleSetting
import com.zhufucdev.currimate.R
class CurrimateWatchFaceService : WatchFaceService() {
override suspend fun createWatchFace(
surfaceHolder: SurfaceHolder,
watchState: WatchState,
complicationSlotsManager: ComplicationSlotsManager,
currentUserStyleRepository: CurrentUserStyleRepository
): WatchFace {
val renderer = WatchFaceCanvasRenderer(
context = applicationContext,
surfaceHolder = surfaceHolder,
watchState = watchState,
currentUserStyleRepository = currentUserStyleRepository,
canvasType = CanvasType.HARDWARE
)
return WatchFace(
watchFaceType = WatchFaceType.ANALOG,
renderer = renderer
)
}
override fun createUserStyleSchema() = createUserScheme(this)
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/watchface/CurrimateWatchFaceService.kt | 3775219375 |
package com.zhufucdev.currimate.watchface
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Paint
import android.graphics.Picture
import android.graphics.drawable.Icon
import androidx.annotation.StringRes
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.wear.watchface.style.UserStyleSchema
import androidx.wear.watchface.style.UserStyleSetting
import androidx.wear.watchface.style.WatchFaceLayer
import com.zhufucdev.currimate.R
const val ID_COLOR_SETTINGS = "color_style"
enum class UserStyleColors(
val id: String,
@StringRes val displayNameResourceId: Int,
val hourHandColor: Int,
val minuteHandColor: Int,
val secondHandColor: Int
) {
SALMON(
"salmon", R.string.title_salmon,
Color(204, 110, 69).toArgb(),
Color(181, 181, 181).toArgb(),
Color(107, 53, 30).toArgb()
),
RASPBERRY(
"raspberry", R.string.title_raspberry,
Color(244, 69, 96).toArgb(),
Color(68, 209, 223).toArgb(),
Color(115, 5, 24).toArgb()
),
MAGENTA(
"magenta", R.string.title_magenta,
Color(255, 0, 255).toArgb(),
Color(102, 255, 255).toArgb(),
Color(128, 0, 64).toArgb(),
),
STRAWBERRY(
"strawberry", R.string.title_strawberry,
Color(255, 0, 128).toArgb(),
Color(204, 204, 204).toArgb(),
Color(255, 111, 207).toArgb()
),
TANGERINE(
"tangerine", R.string.title_tangerine,
Color(255, 128, 0).toArgb(),
Color(204, 204, 204).toArgb(),
Color(0, 0, 128).toArgb()
),
AQUA(
"aqua", R.string.title_aqua,
Color(0, 128, 255).toArgb(),
Color(204, 204, 204).toArgb(),
Color(128, 0, 0).toArgb()
),
BLUEBERRY(
"blueberry", R.string.title_blueberry,
Color(0, 0, 255).toArgb(),
Color(255, 102, 102).toArgb(),
Color(64, 0, 128).toArgb()
),
LIME(
"lime", R.string.title_lime,
Color(0, 255, 128).toArgb(),
Color(204, 255, 102).toArgb(),
Color(128, 128, 0).toArgb()
),
SEA_FOAM(
"sea_foam", R.string.title_sea_foam,
Color(0, 255, 0).toArgb(),
Color(0, 128, 128).toArgb(),
Color(128, 0, 64).toArgb()
);
companion object {
fun generateOptionList(context: Context) = entries.map {
UserStyleSetting.ListUserStyleSetting.ListOption(
UserStyleSetting.Option.Id(it.id),
displayNameResourceId = it.displayNameResourceId,
resources = context.resources,
screenReaderNameResourceId = it.displayNameResourceId,
icon = Icon.createWithBitmap(Bitmap.createBitmap(Picture().apply {
val canvas = beginRecording(64, 64)
canvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
Paint().apply { color = it.hourHandColor })
endRecording()
}))
)
}
fun fromOptionId(id: String) = entries.firstOrNull { it.id == id }
}
}
fun createUserScheme(context: Context) = UserStyleSchema(
listOf<UserStyleSetting>(
UserStyleSetting.ListUserStyleSetting(
id = UserStyleSetting.Id(ID_COLOR_SETTINGS),
resources = context.resources,
displayNameResourceId = R.string.title_color,
descriptionResourceId = R.string.par_des_color,
icon = null,
options = UserStyleColors.generateOptionList(context),
affectsWatchFaceLayers = listOf(WatchFaceLayer.BASE)
)
)
)
| Currimate/app/src/main/java/com/zhufucdev/currimate/watchface/CreateUserStyleScheme.kt | 1308063999 |
package com.zhufucdev.currimate.watchface
import androidx.wear.watchface.style.CurrentUserStyleRepository
import androidx.wear.watchface.style.UserStyleSetting
import kotlinx.coroutines.launch
data class UserStyleHolder(var colors: UserStyleColors = UserStyleColors.SALMON)
fun WatchFaceCanvasRenderer.createUserStyleHolder(currentUserStyleRepository: CurrentUserStyleRepository): UserStyleHolder {
val holder = UserStyleHolder()
scope.launch {
currentUserStyleRepository.userStyle.collect {
val option =
it[UserStyleSetting.Id(ID_COLOR_SETTINGS)] as UserStyleSetting.ListUserStyleSetting.ListOption
holder.colors = UserStyleColors.fromOptionId(option.id.value.decodeToString()) ?: error(
"Color ${option.displayName} not implemented"
)
}
}
return holder
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/watchface/UserStyleHolder.kt | 1519810411 |
package com.zhufucdev.currimate.watchface
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Typeface
import android.util.Log
import android.view.SurfaceHolder
import androidx.annotation.Px
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.core.graphics.drawable.toBitmap
import androidx.wear.watchface.RenderParameters
import androidx.wear.watchface.Renderer
import androidx.wear.watchface.WatchState
import androidx.wear.watchface.style.CurrentUserStyleRepository
import androidx.wear.watchface.style.UserStyleSetting
import com.zhufucdev.currimate.CalendarEvent
import com.zhufucdev.currimate.CalendarEvents
import com.zhufucdev.currimate.beginInstant
import com.zhufucdev.currimate.contains
import com.zhufucdev.currimate.render.RenderCurrentAndNext
import com.zhufucdev.currimate.render.RenderSoloOngoing
import com.zhufucdev.currimate.render.RenderWatchface
import com.zhufucdev.currimate.render.RenderableFactory
import java.time.Duration
import java.time.ZonedDateTime
import java.util.Calendar
import java.util.Timer
import java.util.TimerTask
import kotlin.concurrent.timer
import kotlin.concurrent.timerTask
import kotlin.math.sqrt
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
private const val FRAME_PERIOD_EXPECTED = 16L
class WatchFaceCanvasRenderer(
private val context: Context,
surfaceHolder: SurfaceHolder,
watchState: WatchState,
currentUserStyleRepository: CurrentUserStyleRepository,
canvasType: Int
) : Renderer.CanvasRenderer2<WatchFaceCanvasRenderer.CurrimateSharedAssets>(
surfaceHolder,
currentUserStyleRepository,
watchState,
canvasType,
FRAME_PERIOD_EXPECTED,
false
) {
class CurrimateSharedAssets(context: Context) : SharedAssets {
private val delegatedEvents = CalendarEvents(context.contentResolver)
var events: List<CalendarEvent>
private set
private val eventsFetcher: Timer
private fun fetchEvents(): List<CalendarEvent> {
val startMills = Calendar.getInstance().timeInMillis
val endMills = Calendar.getInstance().apply { add(Calendar.DATE, 1) }.timeInMillis
return delegatedEvents[startMills..endMills]
}
init {
events = fetchEvents()
val interval = Duration.ofMinutes(1).toMillis()
eventsFetcher = timer(daemon = true, initialDelay = interval, period = interval) {
events = fetchEvents()
}
}
override fun onDestroy() {
eventsFetcher.cancel()
}
}
override suspend fun createSharedAssets(): CurrimateSharedAssets =
CurrimateSharedAssets(context)
val scope: CoroutineScope =
CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private val styleHolder: UserStyleHolder = createUserStyleHolder(currentUserStyleRepository)
private val renderableFactory = RenderableFactory(styleHolder, context)
override fun renderHighlightLayer(
canvas: Canvas,
bounds: Rect,
zonedDateTime: ZonedDateTime,
sharedAssets: CurrimateSharedAssets
) {
// noop
}
override fun render(
canvas: Canvas,
bounds: Rect,
zonedDateTime: ZonedDateTime,
sharedAssets: CurrimateSharedAssets
) {
canvas.drawRect(bounds, Paint())
val contentBounds = run {
val width = bounds.width() / 4f * sqrt(2f)
val height = bounds.height() / 4f * sqrt(2f)
RectF(
bounds.centerX() - width,
bounds.centerY() - height,
bounds.centerX() + width,
bounds.centerY() + height,
)
}
renderableFactory.getRenderer(zonedDateTime, sharedAssets.events)
.render(canvas, bounds, contentBounds, zonedDateTime, renderParameters)
}
override fun onDestroy() {
scope.cancel("WatchCanvasRenderer scope clear() request")
renderableFactory.onDestroy()
super.onDestroy()
}
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/watchface/WatchFaceCanvasRenderer.kt | 372432676 |
package com.zhufucdev.currimate.theme
import android.graphics.Paint
import android.graphics.Typeface
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
val ParPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.White.toArgb()
textSize = 18f
typeface = Typeface.create(Typeface.DEFAULT, Typeface.ITALIC)
}
val BodyPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.White.toArgb()
textSize = 24f
}
val LargeTitlePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.White.toArgb()
textSize = 48f
typeface = Typeface.DEFAULT_BOLD
}
val TextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.White.toArgb()
textSize = 32f
}
val TimePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.White.toArgb()
textSize = 32f
typeface = Typeface.DEFAULT_BOLD
}
val TitlePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.White.toArgb()
textSize = 42f
typeface = Typeface.DEFAULT_BOLD
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/theme/Text.kt | 4116923820 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zhufucdev.currimate.theme
import androidx.compose.runtime.Composable
import androidx.wear.compose.material.MaterialTheme
@Composable
fun WearAppTheme(
content: @Composable () -> Unit
) {
MaterialTheme(
colors = wearColorPalette,
typography = Typography,
// For shapes, we generally recommend using the default Material Wear shapes which are
// optimized for round and non-round devices.
content = content
)
}
| Currimate/app/src/main/java/com/zhufucdev/currimate/theme/WearAppTheme.kt | 2473758605 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zhufucdev.currimate.theme
import androidx.compose.ui.graphics.Color
import androidx.wear.compose.material.Colors
val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFF6200EE)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
val Red400 = Color(0xFFCF6679)
internal val wearColorPalette: Colors = Colors(
primary = Purple200,
primaryVariant = Purple700,
secondary = Teal200,
secondaryVariant = Teal200,
error = Red400,
onPrimary = Color.Black,
onSecondary = Color.Black,
onError = Color.Black
)
| Currimate/app/src/main/java/com/zhufucdev/currimate/theme/Color.kt | 1394548654 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zhufucdev.currimate.theme
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
import androidx.wear.compose.material.Typography
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
)
| Currimate/app/src/main/java/com/zhufucdev/currimate/theme/Type.kt | 2834940521 |
package com.zhufucdev.currimate.theme
const val HOUR_HAND_WIDTH = 24f
const val HOUR_HAND_ROUNDNESS = 16f
const val MINUTE_HAND_WIDTH = 12f
const val MINUTE_HAND_ROUNDNESS = 8f
| Currimate/app/src/main/java/com/zhufucdev/currimate/theme/Clock.kt | 1859362038 |
package com.example.phonestore
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.phonestore", appContext.packageName)
}
} | Products-Store/app/src/androidTest/java/com/example/phonestore/ExampleInstrumentedTest.kt | 3381673409 |
package com.example.phonestore
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)
}
} | Products-Store/app/src/test/java/com/example/phonestore/ExampleUnitTest.kt | 500741111 |
package com.example.phonestore.ui
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.SearchView.OnQueryTextListener
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider
import com.example.phonestore.adapters.ProductAdapter
import com.example.phonestore.data.retrofit.ProductApi
import com.example.phonestore.databinding.ActivityMainBinding
import com.example.phonestore.viewmodels.MainViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
private lateinit var adapter: ProductAdapter
lateinit var binding: ActivityMainBinding
lateinit var mainViewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
mainViewModel = ViewModelProvider(this)[MainViewModel::class.java]
adapter = ProductAdapter(this)
binding.rvProducts.adapter = adapter
init()
}
private fun init(){
if(isOnline(this)){
val productApi = mainViewModel.getApi()
setList(productApi, mainViewModel.pageNumber) //1..20(0)
onClickListeners()
mainViewModel.listProducts.observe(this) {
adapter.submitList(it)
}
}
else{
createDialogRestart()
}
}
private fun onClickListeners(){
try{
binding.btnNextPage.setOnClickListener{
if(isOnline(this)){
mainViewModel.clickNextPage()
}
else{
createDialogRestart()
}
}
}catch (e : Exception){
Log.i("Button NextPage Exception", e.toString())
}
try{
binding.btnPrevPage.setOnClickListener {
if(isOnline(this)){
mainViewModel.clickPrevPage()
}
else{
createDialogRestart()
}
}
}catch (e: Exception){
Log.i("Button PrevPage Exception", e.toString())
}
try{
if(isOnline(this)){
binding.svSearchProduct.setOnQueryTextListener(object: OnQueryTextListener{
override fun onQueryTextSubmit(p0: String?): Boolean {
if (p0 != null) {
mainViewModel.searchProduct(p0)
}
return true
}
override fun onQueryTextChange(p0: String?): Boolean {
return true
}
})
}
else{
createDialogRestart()
}
}catch (e: Exception){
Log.i("SearchView Exception", e.toString())
}
}
private fun setList(productApi: ProductApi, number: Int){
CoroutineScope(Dispatchers.IO).launch {
val list = productApi.getProducts(number)
runOnUiThread{
binding.apply {
adapter.submitList(list.products)
}
}
}
}
private fun isOnline(context: Context): Boolean {
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val capabilities =
connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
return true
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
return true
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
return true
}
}
return false
}
private fun createDialogRestart(){
val artDialogBuilder = AlertDialog.Builder(this@MainActivity)
artDialogBuilder.setMessage("Мы не можем получить данные. Проверьте интернет соединение")
artDialogBuilder.setCancelable(false)
artDialogBuilder.setPositiveButton("Соединение в норме."){_,_ ->
init()
}
val alertDialogBox = artDialogBuilder.create()
alertDialogBox.show()
}
} | Products-Store/app/src/main/java/com/example/phonestore/ui/MainActivity.kt | 1234998481 |
package com.example.phonestore.ui
import android.app.AlertDialog
import android.content.Context
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.TextView
import com.example.phonestore.R
import com.example.phonestore.data.Product
import com.example.phonestore.utils.GlideApp
class DialogManager {
companion object{
fun showProductDialog(context: Context, product: Product){
val builder = AlertDialog.Builder(context)
val customView = LayoutInflater.from(context).inflate(R.layout.full_product_dialog, null)
builder.setView(customView)
val ivImage = customView.findViewById<ImageView>(R.id.ivProduct)
val tvTitle = customView.findViewById<TextView>(R.id.tvTitle)
val tvPrice = customView.findViewById<TextView>(R.id.tvPrice)
val tvRating = customView.findViewById<TextView>(R.id.tvRating)
val tvDescription = customView.findViewById<TextView>(R.id.tvDescription)
tvTitle.text = product.title
tvPrice.text = "${product.price} ₽"
tvRating.text = "${product.rating}⭐"
tvDescription.text = product.description
GlideApp.with(context)
.load(product.thumbnail)
.into(ivImage)
val dialog = builder.create()
dialog.show()
}
}
} | Products-Store/app/src/main/java/com/example/phonestore/ui/DialogManager.kt | 3255645742 |
package com.example.phonestore.viewmodels
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.phonestore.data.Product
import com.example.phonestore.data.retrofit.ProductApi
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MainViewModel(application: Application): AndroidViewModel(application) {
var pageNumber = 0
val elementsOnPage = 20
var listProducts = MutableLiveData<List<Product>>()
fun getApi(): ProductApi {
return Retrofit.Builder()
.baseUrl("https://dummyjson.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ProductApi::class.java)
}
fun searchProduct(text: String){
viewModelScope.launch{
val list = text.let { getApi().getProductsByName(text) }
listProducts.value = list.products
}
}
fun clickNextPage(){
val buff = pageNumber
if(pageNumber == 0)
pageNumber += 1
pageNumber += 1
viewModelScope.launch {
val list = getApi().getProducts(pageNumber * elementsOnPage - elementsOnPage)
if(list.products.isNotEmpty()){
listProducts.value = list.products
}
else{
pageNumber = buff
}
}
}
fun clickPrevPage(){
val buff = pageNumber
if(pageNumber > 1)
pageNumber -= 1
viewModelScope.launch {
val list = getApi().getProducts(pageNumber * elementsOnPage - elementsOnPage)
if(list.products.isNotEmpty()){
listProducts.value = list.products
}
else{
pageNumber = buff
}
}
}
} | Products-Store/app/src/main/java/com/example/phonestore/viewmodels/MainViewModel.kt | 2019401433 |
package com.example.phonestore.utils
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
@GlideModule
class GlideModuleApp: AppGlideModule() | Products-Store/app/src/main/java/com/example/phonestore/utils/GlideModuleApp.kt | 272960086 |
package com.example.phonestore.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.phonestore.utils.GlideApp
import com.example.phonestore.R
import com.example.phonestore.data.Product
import com.example.phonestore.databinding.ItemListProductBinding
import com.example.phonestore.ui.DialogManager
class ProductAdapter(val context: Context): ListAdapter<Product, ProductAdapter.Holder>(Comparator()){
class Holder(view: View): RecyclerView.ViewHolder(view){
private val binding = ItemListProductBinding.bind(view)
fun bind(product: Product, context: Context) = with(binding){
tvTitle.text = product.title
tvPrice.text = product.price.toString()
tvDescription.text = product.description
GlideApp.with(context)
.load(product.thumbnail)
.into(ivThumbnail)
cvProduct.setOnClickListener {
DialogManager.showProductDialog(context, product)
}
}
}
class Comparator: DiffUtil.ItemCallback<Product>() {
override fun areItemsTheSame(oldItem: Product, newItem: Product): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Product, newItem: Product): Boolean {
return oldItem == newItem
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_list_product, parent, false)
return Holder(view)
}
override fun onBindViewHolder(holder: Holder, position: Int) {
holder.bind(getItem(position), context)
}
} | Products-Store/app/src/main/java/com/example/phonestore/adapters/ProductAdapter.kt | 4014795925 |
package com.example.phonestore.data
data class Product(
val id: Int,
val title: String,
val description: String,
val price: Int,
val discount: Float,
val rating: Float,
val stock: Float,
val brand: String,
val category: String,
val thumbnail: String,
val images: List<String>
)
| Products-Store/app/src/main/java/com/example/phonestore/data/Product.kt | 1222374549 |
package com.example.phonestore.data.retrofit
import com.example.phonestore.data.Product
data class Products(
val products: List<Product>
)
| Products-Store/app/src/main/java/com/example/phonestore/data/retrofit/Products.kt | 3928925298 |
package com.example.phonestore.data.retrofit
import retrofit2.http.GET
import retrofit2.http.Query
interface ProductApi {
@GET("products?limit=20&")
suspend fun getProducts(@Query("skip")id: Int): Products
@GET("products/search")
suspend fun getProductsByName(@Query("q")name: String): Products
} | Products-Store/app/src/main/java/com/example/phonestore/data/retrofit/ProductApi.kt | 686712408 |
package pe.exirium
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.*
import pe.exirium.plugins.*
class ApplicationTest {
@Test
fun testRoot() = testApplication {
application {
configureRouting()
}
client.get("/").apply {
assertEquals(HttpStatusCode.OK, status)
assertEquals("Hello World!", bodyAsText())
}
}
}
| ktor-backend-test/src/test/kotlin/pe/exirium/ApplicationTest.kt | 2946703275 |
package pe.exirium
import io.ktor.server.application.*
import pe.exirium.plugins.*
fun main(args: Array<String>) {
io.ktor.server.netty.EngineMain.main(args)
}
fun Application.module() {
configureSerialization()
configureRouting()
}
| ktor-backend-test/src/main/kotlin/pe/exirium/Application.kt | 1503830311 |
package pe.exirium.plugins
import io.ktor.server.application.*
import io.ktor.server.routing.*
import pe.exirium.routes.customerRouting
import pe.exirium.routes.getOrderRoute
import pe.exirium.routes.listOrdersRoute
import pe.exirium.routes.totalizeOrderRoute
fun Application.configureRouting() {
routing {
customerRouting()
listOrdersRoute()
getOrderRoute()
totalizeOrderRoute()
}
}
| ktor-backend-test/src/main/kotlin/pe/exirium/plugins/Routing.kt | 776453383 |
package pe.exirium.plugins
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
routing {
get("/json/kotlinx-serialization") {
call.respond(mapOf("hello" to "world"))
}
}
}
| ktor-backend-test/src/main/kotlin/pe/exirium/plugins/Serialization.kt | 3138010588 |
package pe.exirium.models
import kotlinx.serialization.Serializable
@Serializable
data class Customer(val id: String, val firstName: String, val lastName: String, val email: String)
val customerStorage = mutableListOf<Customer>() | ktor-backend-test/src/main/kotlin/pe/exirium/models/Customer.kt | 2091924518 |
package pe.exirium.models
import kotlinx.serialization.Serializable
@Serializable
data class Order(val number: String, val contents: List<OrderItem>)
@Serializable
data class OrderItem(val item: String, val amount: Int, val price: Double)
val orderStorage = listOf(Order(
"2020-04-06-01", listOf(
OrderItem("Ham Sandwich", 2, 5.50),
OrderItem("Water", 1, 1.50),
OrderItem("Beer", 3, 2.30),
OrderItem("Cheesecake", 1, 3.75)
)),
Order("2020-04-03-01", listOf(
OrderItem("Cheeseburger", 1, 8.50),
OrderItem("Water", 2, 1.50),
OrderItem("Coke", 2, 1.76),
OrderItem("Ice Cream", 1, 2.35)
))
) | ktor-backend-test/src/main/kotlin/pe/exirium/models/Order.kt | 780731985 |
package pe.exirium.routes
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import pe.exirium.models.Customer
import pe.exirium.models.customerStorage
fun Route.customerRouting() {
route("/customer") {
get {
if (customerStorage.isNotEmpty()) {
call.respond(customerStorage)
} else {
call.respondText("No customers found", status = HttpStatusCode.OK)
}
}
get("{id?}") {
val id = call.parameters["id"] ?: return@get call.respondText(
"Missing id", status = HttpStatusCode.BadRequest
)
val customer = customerStorage.find { it.id == id } ?: return@get call.respondText(
"No customer with id $id", status = HttpStatusCode.NotFound
)
call.respond(customer)
}
post {
val customer = call.receive<Customer>()
customerStorage.add(customer)
call.respondText("Customer stored correctly", status = HttpStatusCode.Created)
}
delete("{id?}") {
val id = call.parameters["id"] ?: return@delete call.respond(HttpStatusCode.BadRequest)
if (customerStorage.removeIf { it.id == id }) {
call.respondText("Customer removed correctly", status = HttpStatusCode.Accepted)
} else {
call.respondText("Not Found", status = HttpStatusCode.NotFound)
}
}
}
} | ktor-backend-test/src/main/kotlin/pe/exirium/routes/CustomerRoutes.kt | 2999659008 |
package pe.exirium.routes
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import pe.exirium.models.orderStorage
fun Route.listOrdersRoute() {
get("/order") {
if (orderStorage.isNotEmpty()) {
call.respond(orderStorage)
}
}
}
fun Route.getOrderRoute() {
get("/order/{id?}") {
val id = call.parameters["id"] ?: return@get call.respondText("Bad Request", status = HttpStatusCode.BadRequest)
val order = orderStorage.find { it.number == id } ?: return@get call.respondText(
"Not Found",
status = HttpStatusCode.NotFound
)
call.respond(order)
}
}
fun Route.totalizeOrderRoute() {
get("/order/{id?}/total") {
val id = call.parameters["id"] ?: return@get call.respondText("Bad Request", status = HttpStatusCode.BadRequest)
val order = orderStorage.find { it.number == id } ?: return@get call.respondText(
"Not Found",
status = HttpStatusCode.NotFound
)
val total = order.contents.sumOf { it.price * it.amount }
call.respond(total)
}
} | ktor-backend-test/src/main/kotlin/pe/exirium/routes/OrderRoutes.kt | 188611811 |
package com.santosgo.mavelheroes
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.santosgo.mavelheroes", appContext.packageName)
}
} | Laboratorio6.6.1/app/src/androidTest/java/com/santosgo/mavelheroes/ExampleInstrumentedTest.kt | 4108082081 |
package com.santosgo.mavelheroes
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)
}
} | Laboratorio6.6.1/app/src/test/java/com/santosgo/mavelheroes/ExampleUnitTest.kt | 962678018 |
package com.santosgo.mavelheroes
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | Laboratorio6.6.1/app/src/main/java/com/santosgo/mavelheroes/MainActivity.kt | 410416655 |
package com.santosgo.mavelheroes
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.santosgo.mavelheroes.databinding.FragmentHeroListBinding
class HeroListFragment : Fragment() {
private var _binding : FragmentHeroListBinding? = null
val binding
get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_binding = FragmentHeroListBinding.inflate(inflater,container,false)
//texto inicial
binding.textView.text = getString(R.string.hero_list)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
} | Laboratorio6.6.1/app/src/main/java/com/santosgo/mavelheroes/HeroListFragment.kt | 3373629760 |
package com.example.phonebook_assignment
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.phonebook_assignment", appContext.packageName)
}
} | phonebook-assignment/app/src/androidTest/java/com/example/phonebook_assignment/ExampleInstrumentedTest.kt | 2074900760 |
package com.example.phonebook_assignment
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)
}
} | phonebook-assignment/app/src/test/java/com/example/phonebook_assignment/ExampleUnitTest.kt | 551695219 |
package com.example.phonebook_assignment.viewmodel
import android.util.Patterns
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.phonebook_assignment.Event
import com.example.phonebook_assignment.db.Contact
import com.example.phonebook_assignment.db.ContactRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class ContactViewModel(private val repository: ContactRepository) : ViewModel() {
private val statusMessage = MutableLiveData<Event<String>>()
val contacts = repository.contacts
val firstName = MutableLiveData<String>()
val lastName = MutableLiveData<String>()
val email = MutableLiveData<String>()
val mobileno = MutableLiveData<String>()
val signUpUsername = MutableLiveData<String>()
val signUpPassword = MutableLiveData<String>()
val loginUsername = MutableLiveData<String>()
val loginPassword = MutableLiveData<String>()
val message: LiveData<Event<String>>
get() = statusMessage
fun saveContact(){
if(validate()) {
val first_name = firstName.value!!
val last_name = lastName.value!!
val user_email = email.value!!
val mobile = mobileno.value!!
insert(Contact(0, first_name, last_name, mobile, user_email))
firstName.value = ""
lastName.value = ""
email.value = ""
mobileno.value = ""
}
}
fun updateContact(id: Int){
if(validate()) {
val first_name = firstName.value!!
val last_name = lastName.value!!
val user_email = email.value!!
val mobile = mobileno.value!!
update(Contact(id, first_name, last_name, mobile, user_email))
firstName.value = ""
lastName.value = ""
email.value = ""
mobileno.value = ""
}
}
fun validate(): Boolean{
var valid = false
if(firstName.value == null || firstName.value == ""){
statusMessage.value = Event("Please enter first name!")
}
else if(lastName.value == null || lastName.value == ""){
statusMessage.value = Event("Please enter last name!")
}
else if(mobileno.value == null || mobileno.value == ""){
statusMessage.value = Event("Please enter phone number!")
}
else if(email.value == null || email.value == ""){
statusMessage.value = Event("Please enter email!")
}
else if(!Patterns.EMAIL_ADDRESS.matcher(email.value!!).matches()){
statusMessage.value = Event("Please enter a correct email address!")
}
else{
statusMessage.value = Event("success")
valid = true
}
return valid
}
fun insert(contact: Contact){
viewModelScope.launch(Dispatchers.IO) {
repository.insert(contact)
}
}
fun update(contact: Contact){
viewModelScope.launch(Dispatchers.IO) {
repository.update(contact)
}
}
fun delete(contact: Contact){
viewModelScope.launch(Dispatchers.IO) {
repository.delete(contact)
}
}
fun deleteAll(){
viewModelScope.launch(Dispatchers.IO) {
repository.deleteAll()
}
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/viewmodel/ContactViewModel.kt | 4199157502 |
package com.example.phonebook_assignment.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.async
class ExitAppViewModel: ViewModel() {
val exit = MutableLiveData<Boolean>(false)
suspend fun getExitValue(): Boolean {
var deferred = viewModelScope.async {
exit.value
}.await()
return deferred!!
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/viewmodel/ExitAppViewModel.kt | 1240427646 |
package com.example.phonebook_assignment
import android.content.SharedPreferences
import android.os.Bundle
import android.text.SpannableString
import android.text.style.UnderlineSpan
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import com.example.phonebook_assignment.databinding.FragmentSignUpBinding
import com.example.phonebook_assignment.db.ContactDatabase
import com.example.phonebook_assignment.db.ContactRepository
import com.example.phonebook_assignment.viewmodel.ContactViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class SignUpFragment : Fragment() {
private lateinit var binding: FragmentSignUpBinding
private lateinit var contactViewModel: ContactViewModel
private lateinit var preferences:SharedPreferencesManager
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_sign_up, container, false)
val dao = ContactDatabase.getInstance(requireContext()).contactDAO
val repository = ContactRepository(dao)
val factory = ContactViewModelFactory(repository)
contactViewModel = ViewModelProvider(this, factory)[ContactViewModel::class.java]
binding.myViewModel = contactViewModel
binding.lifecycleOwner = this
GlobalScope.launch(Dispatchers.IO) {
preferences = SharedPreferencesManager.getInstance([email protected](),"123")
}
val mSpannableString = SpannableString("Login")
mSpannableString.setSpan(UnderlineSpan(), 0, mSpannableString.length, 0)
binding.loginTextView.text = mSpannableString
binding.loginTextView.setOnClickListener{
it.findNavController().navigate(R.id.action_signUpFragment_to_loginFragment)
}
binding.SignUpButton.setOnClickListener {
if(contactViewModel.signUpUsername.value == "" || contactViewModel.signUpPassword.value == ""
|| contactViewModel.signUpUsername.value == null || contactViewModel.signUpPassword.value == null){
Toast.makeText([email protected](),
"Please enter values for the fields!",
Toast.LENGTH_SHORT).show()
}
else{
val name = contactViewModel.signUpUsername.value
val pass = contactViewModel.signUpPassword.value
preferences.saveData(name!!,pass!!)
var bundle = bundleOf("user_name" to name)
AlertDialog.Builder(this.requireContext())
.setMessage("Are you sure you want to create an account?")
.setPositiveButton("Yes") { dialog, which ->
// If the user confirms, go to the home page
it.findNavController().navigate(R.id.action_signUpFragment_to_homeFragment,bundle)
}
.setNegativeButton("No") { dialog, which ->
// go back to ask login page
it.findNavController().navigate(R.id.action_signUpFragment_to_loginFragment)
}
.show()
}
}
return binding.root
}
} | phonebook-assignment/app/src/main/java/com/example/phonebook_assignment/SignUpFragment.kt | 15200909 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.