content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package ru.glassnekeep.dsl.lists
import ru.glassnekeep.dsl.core.ListElement
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import ru.glassnekeep.dsl.multiple.values.Values
import ru.glassnekeep.dsl.multiple.values.toValues
import ru.glassnekeep.parallel.CoroutinesConfig
class AllTag(
private val block: (Int) -> Boolean,
parent: ListElement,
config: CoroutinesConfig
) : ListElement(parent, config) {
override val dispatcher = config.all
private var thenBranch: ((Values) -> List<Int>)? = null
override suspend fun process(input: List<List<Int>>): List<List<Int>> {
val thenBr = thenBranch ?: throw AllClauseInconsistencyException(MISSING_THEN_BRANCH_ERROR_MSG)
val values = input.singleOrNull() ?: throw AllClauseInconsistencyException(
MANY_LISTS_PASSED_AS_PARAMETERS_ERROR_MSG
)
return coroutineScope {
val fit = values.map { value ->
runAsync { block.invoke(value) }
}.awaitAll().none { !it }
val res = if (fit) thenBr(values.toValues()) else values
listOf(res)
}
}
fun ThenDo(block: (Values) -> List<Int>) : ListElement {
thenBranch = block
return this
}
class AllClauseInconsistencyException(msg: String) : Exception(msg)
private companion object {
const val MISSING_THEN_BRANCH_ERROR_MSG = "Missing `Then` branch"
const val MANY_LISTS_PASSED_AS_PARAMETERS_ERROR_MSG = "More than one list passed to `All` operation"
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/lists/AllTag.kt | 1878824043 |
package ru.glassnekeep.dsl.lists
import ru.glassnekeep.dsl.core.ListElement
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import ru.glassnekeep.parallel.CoroutinesConfig
class MapTag(
private val block: (Int) -> Int,
parent: ListElement,
config: CoroutinesConfig
) : ListElement(parent, config) {
override val dispatcher = config.map
override suspend fun process(input: List<List<Int>>): List<List<Int>> {
return coroutineScope {
input.single().map { value ->
runAsync { block.invoke(value) }
}.awaitAll().let(::listOf)
}
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/lists/MapTag.kt | 672245381 |
package ru.glassnekeep.dsl.single
import ru.glassnekeep.dsl.core.Element
import ru.glassnekeep.dsl.core.SingleElement
import ru.glassnekeep.parallel.CoroutinesConfig
class RecurseTag(
private val endCondition: (Int) -> Boolean,
parent: Element,
config: CoroutinesConfig
) : SingleElement(parent, config) {
override val dispatcher = config.rec
private var recurseStep: ((Int) -> Int)? = null
override fun process(input: Int): List<Int> {
val step = recurseStep ?: throw RecurseTagInconsistencyException(MISSING_RECURSE_BRANCH_ERROR_MSG)
var res = input
while (!endCondition(res)) {
res = step(res)
}
return res.let(::listOf)
}
inner class RecurseStep {
fun Recurse(action: (Int) -> Int): SingleElement {
recurseStep = action
return this@RecurseTag
}
}
class RecurseTagInconsistencyException(msg: String) : Exception(msg)
private companion object {
const val MISSING_RECURSE_BRANCH_ERROR_MSG = "Missing 'Recurse' branch"
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/single/RecurseTag.kt | 2481259663 |
package ru.glassnekeep.dsl.single
import ru.glassnekeep.dsl.core.Element
import ru.glassnekeep.dsl.core.SingleElement
import ru.glassnekeep.parallel.CoroutinesConfig
class Apply(
private val block: (Int) -> Int,
parent: Element,
config: CoroutinesConfig
) : SingleElement(parent, config) {
override val dispatcher = config.then
override fun process(input: Int): List<Int> {
return block.invoke(input).let(::listOf)
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/single/Apply.kt | 478929840 |
package ru.glassnekeep.dsl.single.values
import ru.glassnekeep.dsl.core.Element
import ru.glassnekeep.dsl.core.SingleElement
import ru.glassnekeep.parallel.CoroutinesConfig
class ValueSingle(
private val value: Int,
parent: Element,
config: CoroutinesConfig
) : SingleElement(parent, config) {
override val dispatcher = config.default
override fun process(input: Int): List<Int> {
return listOf(value)
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/single/values/ValueSingle.kt | 2352793329 |
package ru.glassnekeep.dsl.single.clauses
import ru.glassnekeep.dsl.core.Element
import ru.glassnekeep.dsl.core.SingleElement
import ru.glassnekeep.parallel.CoroutinesConfig
class IfClause(
private val condition: (Int) -> Boolean,
parent: Element,
config: CoroutinesConfig
) : SingleElement(parent, config) {
override val dispatcher = config.default
private var thenBranch: ((Int) -> Int)? = null
private var elseBranch: ((Int) -> Int)? = null
override fun process(input: Int): List<Int> {
val thenBr = thenBranch ?: throw IfClauseInconsistencyException(MISSING_THEN_BRANCH_ERROR_MSG)
val elseBr = elseBranch ?: throw IfClauseInconsistencyException(MISSING_ELSE_BRANCH_ERROR_MSG)
return if (condition(input)) {
thenBr(input)
} else {
elseBr(input)
}.let(::listOf)
}
fun Then(action: (Int) -> Int): ThenClause {
thenBranch = action
return ThenClause()
}
inner class ThenClause {
fun Else(action: (Int) -> Int): SingleElement {
elseBranch = action
return this@IfClause
}
}
class IfClauseInconsistencyException(msg: String) : Exception(msg)
private companion object {
const val MISSING_THEN_BRANCH_ERROR_MSG = "Missing `Then` branch"
const val MISSING_ELSE_BRANCH_ERROR_MSG = "Missing `Else` branch"
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/single/clauses/IfClause.kt | 695660179 |
package ru.glassnekeep.dsl.single.clauses
import ru.glassnekeep.dsl.core.Element
import ru.glassnekeep.dsl.core.SingleElement
import ru.glassnekeep.parallel.CoroutinesConfig
class SwitchClause(
private val block: (Int) -> Int,
parent: Element,
config: CoroutinesConfig
) : SingleElement(parent, config) {
override val dispatcher = config.default
private val cases = mutableMapOf<Int, (Int) -> Int>()
private var default: ((Int) -> Int)? = null
override fun process(input: Int): List<Int> {
val def = default ?: throw SwitchCaseInconsistencyException(MISSING_DEFAULT_BRANCH_ERROR_MSG)
val action = cases.getOrDefault(block.invoke(input), def)
return action.invoke(input).let(::listOf)
}
fun Case(value: Int, action: (Int) -> Int): CaseClause {
cases[value] = action
return CaseClause(value, action)
}
inner class CaseClause(value: Int, block: (Int) -> Int) {
fun Case(value: Int, action: (Int) -> Int): CaseClause {
cases[value] = action
return CaseClause(value, action)
}
fun Default(action: (Int) -> Int): SingleElement {
default = action
return this@SwitchClause
}
}
class SwitchCaseInconsistencyException(msg: String): Exception(msg)
private companion object {
const val MISSING_DEFAULT_BRANCH_ERROR_MSG = "Missing default branch"
}
} | ru.glassnekeep.parallel-mephi/src/main/kotlin/ru/glassnekeep/dsl/single/clauses/SwitchClause.kt | 3528320210 |
package com.laznaslmi.apicatur
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.laznaslmi.apicatur", appContext.packageName)
}
} | ApiCatur/app/src/androidTest/java/com/laznaslmi/apicatur/ExampleInstrumentedTest.kt | 1797290995 |
package com.laznaslmi.apicatur
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)
}
} | ApiCatur/app/src/test/java/com/laznaslmi/apicatur/ExampleUnitTest.kt | 511704384 |
package com.laznaslmi.apicatur
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.laznaslmi.apicatur.adapter.RVAdapter
import com.laznaslmi.apicatur.databinding.ActivityMainBinding
import com.laznaslmi.apicatur.model.ResponseProgramItem
import com.laznaslmi.apicatur.network.ApiClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
private lateinit var binding: ActivityMainBinding
private lateinit var adapter: RVAdapter
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
adapter = RVAdapter(this@MainActivity, arrayListOf())
binding.rvMain.adapter = adapter
binding.rvMain.setHasFixedSize(true)
remoteGetUsers()
}
fun remoteGetUsers(){
ApiClient.apiService.getProgram().enqueue(object : Callback<ArrayList<ResponseProgramItem>>{
override fun onResponse(
call: Call<ArrayList<ResponseProgramItem>>,
response: Response<ArrayList<ResponseProgramItem>>
) {
if (response.isSuccessful){
val data = response.body()
setDataToAdapter(data!!)
}
}
override fun onFailure(call: Call<ArrayList<ResponseProgramItem>>, t: Throwable) {
Log.d("error", "" + t.stackTraceToString())
}
})
}
fun setDataToAdapter(data: ArrayList<ResponseProgramItem>){
adapter.setData(data)
}
} | ApiCatur/app/src/main/java/com/laznaslmi/apicatur/MainActivity.kt | 2674943439 |
package com.laznaslmi.apicatur.network
import com.laznaslmi.apicatur.model.ResponseProgramItem
import retrofit2.Call
import retrofit2.http.GET
interface ApiService {
@GET("administrasi/api?apikey=123456789")
fun getProgram(): Call<ArrayList<ResponseProgramItem>>
} | ApiCatur/app/src/main/java/com/laznaslmi/apicatur/network/ApiService.kt | 3860687877 |
package com.laznaslmi.apicatur.network
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ApiClient {
val BASE_URL = "http://103.179.216.69/"
val apiService: ApiService
get() {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.addInterceptor(interceptor)
.build()
val retrofit = Retrofit.Builder()
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build()
return retrofit.create(ApiService::class.java)
}
} | ApiCatur/app/src/main/java/com/laznaslmi/apicatur/network/ApiClient.kt | 2264723165 |
package com.laznaslmi.apicatur.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.laznaslmi.apicatur.R
import com.laznaslmi.apicatur.model.ResponseProgramItem
class RVAdapter (
private val context: Context,
private val dataList: ArrayList<ResponseProgramItem>
): RecyclerView.Adapter<RVAdapter.MyViewHolder>(){
class MyViewHolder(val view: View): RecyclerView.ViewHolder(view){
val tvTitle = view.findViewById<TextView>(R.id.tv_title)
val tvReceived = view.findViewById<TextView>(R.id.tv_received)
val tvCountdown = view.findViewById<TextView>(R.id.tv_countdown)
val cvMain = view.findViewById<CardView>(R.id.cvMain)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val itemView = layoutInflater.inflate(R.layout.item_program, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.tvTitle.text = dataList.get(position).title
holder.tvReceived.text = dataList.get(position).received.toString()
holder.tvCountdown.text = dataList.get(position).countdown.toString()
holder.cvMain.setOnClickListener {
Toast.makeText(context, "" + dataList.get(position).title, Toast.LENGTH_SHORT).show()
}
}
override fun getItemCount(): Int = dataList.size
fun setData(data: ArrayList<ResponseProgramItem>){
dataList.clear()
dataList.addAll(data)
notifyDataSetChanged()
}
} | ApiCatur/app/src/main/java/com/laznaslmi/apicatur/adapter/RVAdapter.kt | 458739203 |
package com.laznaslmi.apicatur.model
import com.google.gson.annotations.SerializedName
data class ResponseProgram(
@field:SerializedName("ResponseProgram")
val responseProgram: List<ResponseProgramItem?>? = null
)
data class ResponseProgramItem(
@field:SerializedName("img")
val img: String? = null,
@field:SerializedName("doa")
val doa: List<DoaItem?>? = null,
@field:SerializedName("countdown")
val countdown: Int? = null,
@field:SerializedName("received")
val received: Int? = null,
@field:SerializedName("id")
val id: Int? = null,
@field:SerializedName("office")
val office: String? = null,
@field:SerializedName("title")
val title: String? = null,
@field:SerializedName("category")
val category: String? = null
)
data class DoaItem(
@field:SerializedName("from")
val from: String? = null,
@field:SerializedName("text")
val text: String? = null
)
| ApiCatur/app/src/main/java/com/laznaslmi/apicatur/model/ResponseProgram.kt | 1596757251 |
package com.flad.mapchatapp
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.flad.mapchatapp", appContext.packageName)
}
} | mapchat/app/src/androidTest/java/com/flad/mapchatapp/ExampleInstrumentedTest.kt | 2843147181 |
package com.flad.mapchatapp
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)
}
} | mapchat/app/src/test/java/com/flad/mapchatapp/ExampleUnitTest.kt | 2933493329 |
package com.flad.mapchatapp.ui.composables.homepage
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.flad.mapchatapp.model.source.remote.api.chats.models.Conversation
import com.flad.mapchatapp.ui.composables.login.LoginViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomePage() {
val homePageViewModel: HomePageViewModel = hiltViewModel()
val conversationState by homePageViewModel.uiState.collectAsState()
Scaffold(
topBar = {
TopAppBar(title = { Text("Conversas Recentes") })
}
) { innerPadding ->
ConversationList(conversationState.conversations, Modifier.padding(innerPadding))
}
}
@Composable
fun ConversationList(conversations: List<Conversation>, modifier: Modifier = Modifier) {
LazyColumn(modifier = modifier) {
items(conversations) { conversation ->
ConversationItem(conversation)
}
}
}
@Composable
fun ConversationItem(conversation: Conversation) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(
text = conversation.contactName,
style = MaterialTheme.typography.titleMedium
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = conversation.lastMessage,
style = MaterialTheme.typography.bodyMedium
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = conversation.timestamp,
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.align(Alignment.End)
)
}
}
}
fun SampleData(): List<Conversation> {
return listOf(
Conversation(1, "Amigo 1", "Olá, como vai?", "10:45 AM"),
Conversation(2, "Amigo 2", "Vamos nos encontrar hoje?", "Ontem"),
// Adicione mais conversas aqui
)
} | mapchat/app/src/main/java/com/flad/mapchatapp/ui/composables/homepage/Homepage.kt | 3434235844 |
package com.flad.mapchatapp.ui.composables.homepage
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import com.flad.mapchatapp.base.BaseViewModel
import com.flad.mapchatapp.model.repository.authrepository.AuthRepository
import com.flad.mapchatapp.model.repository.authrepository.eventhandler.AuthEventAndErrorHandler
import com.flad.mapchatapp.model.repository.authrepository.eventhandler.AuthUiEvent
import com.flad.mapchatapp.model.repository.chatsRepository.ChatRepository
import com.flad.mapchatapp.model.source.remote.api.auth.models.AuthenticationResponse
import com.flad.mapchatapp.model.source.remote.api.auth.utils.Response
import com.flad.mapchatapp.model.viewdatainterfaces.IViewEvent
import com.flad.mapchatapp.model.source.remote.api.chats.models.Conversation
import com.flad.mapchatapp.model.source.remote.api.chats.models.ConversationsState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class HomePageViewModel @Inject constructor(
private val authRepositoryMock: AuthRepository,
private val chatRepository: ChatRepository
): BaseViewModel<ConversationsState, AuthUiEvent>() {
var authResponseData = mutableStateOf<AuthenticationResponse?>(null)
private set
override fun createInitialState(): ConversationsState {
return ConversationsState(
conversations = listOf(
Conversation(id = 1, contactName = "Alice", lastMessage = "Oi, como você está?", timestamp = "2022-07-18T12:00:00Z")
))
}
init {
observAuth()
obserMessagesOrError()
loadConversations()
}
private fun observAuth() {
viewModelScope.launch {
authRepositoryMock.authenticationResponse.collect { auth ->
if (auth !== null) {
authResponseData.value = auth
chatRepository.getAllConversations(auth.user)
}
}
}
}
private fun obserMessagesOrError() {
viewModelScope.launch {
AuthEventAndErrorHandler.eventFlow.collect { authUiEvent->
emitEvent(authUiEvent)
}
}
}
private fun loadConversations(){
viewModelScope.launch {
chatRepository.conversations.collect{conversationList->
setState { copy(conversations = conversationList)}
}
}
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/ui/composables/homepage/HomePageViewModel.kt | 1481242502 |
package com.flad.mapchatapp.ui.composables.login
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import com.flad.mapchatapp.base.BaseViewModel
import com.flad.mapchatapp.model.repository.authrepository.AuthRepository
import com.flad.mapchatapp.model.repository.authrepository.eventhandler.AuthEventAndErrorHandler
import com.flad.mapchatapp.model.repository.authrepository.eventhandler.AuthUiEvent
import com.flad.mapchatapp.model.source.remote.api.auth.models.AuthenticationResponse
import com.flad.mapchatapp.model.source.remote.api.auth.utils.Response
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(
private val authRepositoryMock: AuthRepository
): BaseViewModel<AuthenticationResponse, AuthUiEvent>(){
var email = mutableStateOf("")
private set
var password = mutableStateOf("")
private set
var errorMessage = mutableStateOf("")
private set
var signInResponse = mutableStateOf<Response<AuthenticationResponse>>(Response.Idle)
private set
var authResponseData = mutableStateOf<AuthenticationResponse?>(null)
private set
init {
observAuth()
obserMessagesOrError()
}
private fun obserMessagesOrError() {
viewModelScope.launch {
AuthEventAndErrorHandler.eventFlow.collect { authUiEvent->
emitEvent(authUiEvent)
}
}
}
private fun observAuth() {
viewModelScope.launch {
authRepositoryMock.authenticationResponse.collect { auth ->
if (auth !== null) {
authResponseData.value = auth
signInResponse.value = Response.Success(auth)
}
}
}
}
fun signInWithEmailAndPassword() = viewModelScope.launch {
emitEvent(AuthUiEvent.Loading(""))
val emailVal = email.value
val passwordVal = password.value
if (emailVal.isNotEmpty() && passwordVal.isNotEmpty()) {
authRepositoryMock.backEndAuthWithEmailAndPassword(emailVal, passwordVal)
} else {
signInResponse.value =
Response.Failure(IllegalArgumentException("Email and Password cannot be empty."))
}
}
fun signOut(){
//_startDestination.value= NumbersAppScreenBar.LogInScreen
//repo.signOut()
}
fun onEmailChange(newEmail: String) {
email.value = newEmail
}
fun onPasswordChange(newPassword: String) {
password.value = newPassword
}
override fun createInitialState(): AuthenticationResponse {
return AuthenticationResponse()
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/ui/composables/login/LoginViewModel.kt | 3355076652 |
package com.flad.mapchatapp.ui.composables.login
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.flad.mapchatapp.model.repository.authrepository.eventhandler.AuthUiEvent
import androidx.hilt.navigation.compose.hiltViewModel
@Composable
fun LoginScreen(
onSucessNavigate:()->Unit,
){
val loginViewModel: LoginViewModel = hiltViewModel()
val email by loginViewModel.email
val password by loginViewModel.password
val eventHolder by loginViewModel.eventFlow.collectAsState(initial = AuthUiEvent.InitialState(""))
loginViewModel.authResponseData.value.let {
if (it!=null)onSucessNavigate()
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
TextField(
value = email,
onValueChange = loginViewModel::onEmailChange,
label = { Text("Email") },
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(8.dp))
TextField(
value = password,
onValueChange = loginViewModel::onPasswordChange,
label = { Text("Password") },
visualTransformation = PasswordVisualTransformation(),
modifier = Modifier.fillMaxWidth()
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = loginViewModel::signInWithEmailAndPassword,
modifier = Modifier.fillMaxWidth(),
) {
Text("Login")
}
when (eventHolder) {
is AuthUiEvent.Loading -> CircularIndeterminateProgressBar()
is AuthUiEvent.AuthFail -> Text(text = (eventHolder as AuthUiEvent.AuthFail).message, color = Color.Red)
else -> {}
}
}
}
@Composable
fun CircularIndeterminateProgressBar() {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
CircularProgressIndicator()
}
}
| mapchat/app/src/main/java/com/flad/mapchatapp/ui/composables/login/LoginScreen.kt | 3031849541 |
package com.flad.mapchatapp.ui.navigation
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.flad.mapchatapp.ui.composables.homepage.HomePage
import com.flad.mapchatapp.ui.composables.login.LoginScreen
import com.flad.mapchatapp.ui.composables.login.LoginViewModel
@Composable
fun MapchatAppTopLevel(
){
Scaffold {innerPadding->
Nav(
modifier = Modifier.padding(innerPadding)
)
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/ui/navigation/MapChatAppTopLevel.kt | 2884075347 |
package com.flad.mapchatapp.ui.navigation
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navigation
import com.flad.mapchatapp.ui.composables.homepage.HomePage
import com.flad.mapchatapp.ui.composables.login.LoginScreen
import com.flad.mapchatapp.ui.composables.login.LoginViewModel
@Composable
fun Nav(
navController: NavHostController = rememberNavController(),
modifier: Modifier = Modifier
){
NavHost(
navController = navController,
startDestination = MapChatNestedScreansRoutes.AuthRoute.route,
modifier = modifier
){
authGraph(navController = navController)
appGraph(navController = navController)
}
}
| mapchat/app/src/main/java/com/flad/mapchatapp/ui/navigation/Nav.kt | 3406179952 |
package com.flad.mapchatapp.ui.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.navigation
import com.flad.mapchatapp.ui.composables.login.LoginScreen
import com.flad.mapchatapp.ui.composables.login.LoginViewModel
fun NavGraphBuilder.authGraph(
navController: NavHostController
){
navigation(
startDestination = MapChatNestedScreansRoutes.LoginScreen.route,
route = MapChatNestedScreansRoutes.AuthRoute.route)
{
composable(
route = MapChatNestedScreansRoutes.LoginScreen.route
){
LoginScreen(
onSucessNavigate =
{navController.navigate(route = MapChatNestedScreansRoutes.AppRoute.route)}
)
}
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/ui/navigation/AuthNestedGraph.kt | 469740867 |
package com.flad.mapchatapp.ui.navigation
enum class MapChatScreenRoutes {
Login,
Home,
SignUP,
AuthRoute,
AppRoute,
ChatPage
}
sealed class MapChatNestedScreansRoutes(val route: String){
object LoginScreen: MapChatNestedScreansRoutes(route = MapChatScreenRoutes.Login.name)
object SignUp: MapChatNestedScreansRoutes(route = MapChatScreenRoutes.SignUP.name)
object HomePage: MapChatNestedScreansRoutes(route = MapChatScreenRoutes.Home.name)
object ChatPage: MapChatNestedScreansRoutes(route = MapChatScreenRoutes.ChatPage.name)
object AuthRoute: MapChatNestedScreansRoutes(route = MapChatScreenRoutes.AuthRoute.name)
object AppRoute: MapChatNestedScreansRoutes(route = MapChatScreenRoutes.AppRoute.name)
}
| mapchat/app/src/main/java/com/flad/mapchatapp/ui/navigation/MapChatScreenRoutes.kt | 303792511 |
package com.flad.mapchatapp.ui.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.navigation
import com.flad.mapchatapp.ui.composables.homepage.HomePage
import com.flad.mapchatapp.ui.composables.login.LoginViewModel
fun NavGraphBuilder.appGraph(
navController: NavHostController
) {
navigation(
startDestination = MapChatNestedScreansRoutes.HomePage.route,
route = MapChatNestedScreansRoutes.AppRoute.route
) {
composable(route = MapChatNestedScreansRoutes.HomePage.route)
{
HomePage()
}
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/ui/navigation/AppNestedGraph.kt | 3759432857 |
package com.flad.mapchatapp.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | mapchat/app/src/main/java/com/flad/mapchatapp/ui/theme/Color.kt | 1017357831 |
package com.flad.mapchatapp.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun MapChatAppTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | mapchat/app/src/main/java/com/flad/mapchatapp/ui/theme/Theme.kt | 185648668 |
package com.flad.mapchatapp.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | mapchat/app/src/main/java/com/flad/mapchatapp/ui/theme/Type.kt | 1616323563 |
package com.flad.mapchatapp.ui
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class MapChatApplication: Application() {
} | mapchat/app/src/main/java/com/flad/mapchatapp/ui/MapChatApplication.kt | 315198126 |
package com.flad.mapchatapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.flad.mapchatapp.ui.composables.login.LoginViewModel
import com.flad.mapchatapp.ui.navigation.MapchatAppTopLevel
import com.flad.mapchatapp.ui.theme.MapChatAppTheme
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.HiltAndroidApp
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MapChatAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MapchatAppTopLevel()
}
}
}
}
}
| mapchat/app/src/main/java/com/flad/mapchatapp/MainActivity.kt | 2045655887 |
package com.flad.mapchatapp.model.repository.authrepository.di
import com.flad.mapchatapp.model.repository.authrepository.AuthRepository
import com.flad.mapchatapp.model.repository.authrepository.AuthRepositoryMock
import com.flad.mapchatapp.model.source.remote.api.auth.AuthRemoteSource
import com.flad.mapchatapp.model.source.remote.api.auth.AuthRemoteSourceMock
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object authprovider {
@Provides
@Singleton
fun provideAuthRepositoryMock(
authRemoteSource: AuthRemoteSource
): AuthRepository {
// Aqui você deve retornar a implementação de BackEndAuthRepository
return AuthRepositoryMock(authRemoteSource)
}
@Provides
@Singleton
fun provideAuthRemoteSource(): AuthRemoteSource {
return AuthRemoteSourceMock()
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/repository/authrepository/di/authprovider.kt | 3282323451 |
package com.flad.mapchatapp.model.repository.authrepository
import com.flad.mapchatapp.model.repository.authrepository.eventhandler.AuthEventAndErrorHandler
import com.flad.mapchatapp.model.repository.authrepository.eventhandler.AuthUiEvent
import com.flad.mapchatapp.model.source.remote.api.auth.AuthRemoteSource
import com.flad.mapchatapp.model.source.remote.api.auth.models.AuthenticationResponse
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.IOException
class AuthRepositoryMock(
private val authRemoteSource: AuthRemoteSource
): AuthRepository {
private val _authenticationResponse = MutableStateFlow<AuthenticationResponse?>(null)
override val authenticationResponse: StateFlow<AuthenticationResponse?> = _authenticationResponse.asStateFlow()
override suspend fun backEndAuthWithEmailAndPassword(
email: String,
password: String
) {
kotlinx.coroutines.delay(1000L)
try {
authRemoteSource.authenticateWithEmailAndPassword(email = email, password = password).collect{
response->
_authenticationResponse.value=response
}
}catch (exception: IOException){
AuthEventAndErrorHandler.emitEvent(AuthUiEvent.AuthFail("Auth Fail!"))
} catch (exception: RuntimeException){
AuthEventAndErrorHandler.emitEvent(AuthUiEvent.AuthFail("Something Went Wrong!"))
}
}
}
| mapchat/app/src/main/java/com/flad/mapchatapp/model/repository/authrepository/AuthRepositoryMock.kt | 1739733093 |
package com.flad.mapchatapp.model.repository.authrepository
import com.flad.mapchatapp.model.source.remote.api.auth.models.AuthenticationResponse
import kotlinx.coroutines.flow.StateFlow
interface AuthRepository {
val authenticationResponse: StateFlow<AuthenticationResponse?>
suspend fun backEndAuthWithEmailAndPassword(email: String, password: String)
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/repository/authrepository/AuthRepository.kt | 604230713 |
package com.flad.mapchatapp.model.repository.authrepository.eventhandler
import com.flad.mapchatapp.model.viewdatainterfaces.IViewEvent
sealed class AuthUiEvent: IViewEvent {
data class AuthFail(val message: String):AuthUiEvent()
data class Loading(val message: String):AuthUiEvent()
data class InitialState(val message: String):AuthUiEvent()
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/repository/authrepository/eventhandler/AuthUiEvent.kt | 5223094 |
package com.flad.mapchatapp.model.repository.authrepository.eventhandler
import android.util.Log
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
object AuthEventAndErrorHandler {
private val _eventFlow = MutableSharedFlow<AuthUiEvent>()
val eventFlow = _eventFlow.asSharedFlow()
suspend fun emitEvent(event: AuthUiEvent) {
_eventFlow.emit(event)
logEvent(event)
}
private fun logEvent(event: AuthUiEvent) {
when (event) {
is AuthUiEvent.AuthFail -> Log.e(
"EventAndErrorHandle",
"Auth FAiled!: ${event.message}"
)
else -> {}
}
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/repository/authrepository/eventhandler/AuthEventAndErrorHandler.kt | 3659275093 |
package com.flad.mapchatapp.model.repository.chatsRepository
import com.flad.mapchatapp.model.source.remote.api.auth.models.UserDTO
import com.flad.mapchatapp.model.source.remote.api.chats.models.Conversation
import kotlinx.coroutines.flow.StateFlow
interface ChatRepository {
val conversations: StateFlow<List<Conversation>>
suspend fun getAllConversations(userDTO: UserDTO)
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/repository/chatsRepository/ChatRepository.kt | 3415351919 |
package com.flad.mapchatapp.model.repository.chatsRepository.di
import com.flad.mapchatapp.model.repository.authrepository.AuthRepository
import com.flad.mapchatapp.model.repository.authrepository.AuthRepositoryMock
import com.flad.mapchatapp.model.repository.chatsRepository.ChatRepository
import com.flad.mapchatapp.model.repository.chatsRepository.ChatRepositoryMock
import com.flad.mapchatapp.model.source.remote.api.auth.AuthRemoteSource
import com.flad.mapchatapp.model.source.remote.api.auth.AuthRemoteSourceMock
import com.flad.mapchatapp.model.source.remote.api.chats.ConversationRemoteSource
import com.flad.mapchatapp.model.source.remote.api.chats.ConversationRemoteSourceMock
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object chatsprovider {
@Provides
@Singleton
fun providerChatRepositoryMock(
conversationRemoteSource: ConversationRemoteSource
): ChatRepository {
return ChatRepositoryMock(conversationRemoteSource)
}
@Provides
@Singleton
fun provideConversationSource(): ConversationRemoteSource {
return ConversationRemoteSourceMock()
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/repository/chatsRepository/di/chatsprovider.kt | 1040990103 |
package com.flad.mapchatapp.model.repository.chatsRepository
import com.flad.mapchatapp.model.repository.authrepository.eventhandler.AuthEventAndErrorHandler
import com.flad.mapchatapp.model.repository.authrepository.eventhandler.AuthUiEvent
import com.flad.mapchatapp.model.source.remote.api.auth.models.UserDTO
import com.flad.mapchatapp.model.source.remote.api.chats.ConversationRemoteSource
import com.flad.mapchatapp.model.source.remote.api.chats.models.Conversation
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.IOException
class ChatRepositoryMock(
private val convarsationRemoteSource: ConversationRemoteSource
): ChatRepository {
private val _conversations = MutableStateFlow<List<Conversation>>(emptyList())
override val conversations = _conversations.asStateFlow()
override suspend fun getAllConversations(userDTO: UserDTO){
try {
convarsationRemoteSource.getAllConversations(userDTO = userDTO).collect { response ->
_conversations.value = response
}
}catch (exception: IOException){
AuthEventAndErrorHandler.emitEvent(AuthUiEvent.AuthFail("Auth Fail!"))
} catch (exception: RuntimeException){
AuthEventAndErrorHandler.emitEvent(AuthUiEvent.AuthFail("Something Went Wrong!"))
}
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/repository/chatsRepository/ChatRepositoryMock.kt | 93809245 |
package com.flad.mapchatapp.model.source.remote.api.auth.utils
sealed class Response<out T> {
object Loading: Response<Nothing>()
object Idle: Response<Nothing>()
data class Success<out T>(
val data: T
): Response<T>()
data class Failure(
val e: Exception
): Response<Nothing>()
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/source/remote/api/auth/utils/Response.kt | 1297883354 |
package com.flad.mapchatapp.model.source.remote.api.auth.models
import java.util.UUID
data class UserDTO(
val id: UUID,
val email: String
)
| mapchat/app/src/main/java/com/flad/mapchatapp/model/source/remote/api/auth/models/UserDTO.kt | 1790654548 |
package com.flad.mapchatapp.model.source.remote.api.auth.models
import com.flad.mapchatapp.model.viewdatainterfaces.IViewState
import java.util.UUID
data class AuthenticationResponse (
val accessToken: String= "",
val refreshToken: String= "",
val user: UserDTO = UserDTO(id = UUID.randomUUID(), email = "")
): IViewState | mapchat/app/src/main/java/com/flad/mapchatapp/model/source/remote/api/auth/models/AuthenticationResponse.kt | 670673227 |
package com.flad.mapchatapp.model.source.remote.api.auth
import com.flad.mapchatapp.model.source.remote.api.auth.models.AuthenticationResponse
import com.flad.mapchatapp.model.source.remote.api.auth.models.UserDTO
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import java.util.UUID
class AuthRemoteSourceMock: AuthRemoteSource {
override suspend fun authenticateWithEmailAndPassword(email: String, password: String): Flow<AuthenticationResponse> = flow {
// Simula resposta mock
kotlinx.coroutines.delay(500)
emit(
AuthenticationResponse(
accessToken = "mock_access_token_123456",
refreshToken = "mock_refresh_token_123456",
user = UserDTO(id = UUID.randomUUID(), email = "[email protected]")
)
)
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/source/remote/api/auth/AuthRemoteSourceMock.kt | 3403390055 |
package com.flad.mapchatapp.model.source.remote.api.auth
import com.flad.mapchatapp.model.source.remote.api.auth.models.AuthenticationResponse
import kotlinx.coroutines.flow.Flow
interface AuthRemoteSource {
suspend fun authenticateWithEmailAndPassword(email: String, password: String): Flow<AuthenticationResponse>
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/source/remote/api/auth/AuthRemoteSource.kt | 3425019901 |
package com.flad.mapchatapp.model.source.remote.api.auth
import com.flad.mapchatapp.model.source.remote.api.auth.models.AuthenticationResponse
import com.flad.mapchatapp.model.source.remote.api.auth.models.UserDTO
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import java.util.UUID
class AuthRemoteSourceImpl: AuthRemoteSource {
override suspend fun authenticateWithEmailAndPassword(email: String, password: String): Flow<AuthenticationResponse> = flow {
// Simula chamada de rede
kotlinx.coroutines.delay(2000)
emit(
AuthenticationResponse(
accessToken = "real_access_token_123456",
refreshToken = "real_refresh_token_123456",
user = UserDTO(id = UUID.randomUUID(), email = email)
)
)
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/source/remote/api/auth/AuthRemoteSourceImpl.kt | 1685725201 |
package com.flad.mapchatapp.model.source.remote.api.chats
import com.flad.mapchatapp.model.source.remote.api.auth.models.UserDTO
import com.flad.mapchatapp.model.source.remote.api.chats.models.Conversation
import kotlinx.coroutines.flow.Flow
interface ConversationRemoteSource {
suspend fun getAllConversations(userDTO: UserDTO): Flow<List<Conversation>>
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/source/remote/api/chats/ConversationRemoteSource.kt | 3072196614 |
package com.flad.mapchatapp.model.source.remote.api.chats.models
import com.flad.mapchatapp.model.viewdatainterfaces.IViewState
data class ConversationsState(
val conversations: List<Conversation> = emptyList()
): IViewState
| mapchat/app/src/main/java/com/flad/mapchatapp/model/source/remote/api/chats/models/ConversationState.kt | 1447548258 |
package com.flad.mapchatapp.model.source.remote.api.chats.models
import com.flad.mapchatapp.model.viewdatainterfaces.IViewState
data class Conversation(
val id: Int,
val contactName: String,
val lastMessage: String,
val timestamp: String
): IViewState
| mapchat/app/src/main/java/com/flad/mapchatapp/model/source/remote/api/chats/models/Conversation.kt | 3896629040 |
package com.flad.mapchatapp.model.source.remote.api.chats
import com.flad.mapchatapp.model.source.remote.api.auth.models.UserDTO
import com.flad.mapchatapp.model.source.remote.api.chats.models.Conversation
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
class ConversationRemoteSourceMock(
): ConversationRemoteSource {
override suspend fun getAllConversations(userDTO: UserDTO): Flow<List<Conversation>> = flow {
kotlinx.coroutines.delay(500)
val conversations = listOf(
Conversation(id = 1, contactName = "Alice", lastMessage = "Oi, como você está?", timestamp = "2022-07-18T12:00:00Z"),
Conversation(id = 2, contactName = "Bob", lastMessage = "Você viu a minha mensagem?", timestamp = "2022-07-18T15:30:00Z"),
Conversation(id = 3, contactName = "Charlie", lastMessage = "Vamos nos encontrar amanhã?", timestamp = "2022-07-19T09:45:00Z")
)
emit(conversations)
}
} | mapchat/app/src/main/java/com/flad/mapchatapp/model/source/remote/api/chats/ConversationRemoteSourceMock.kt | 1320892912 |
package com.flad.mapchatapp.model.viewdatainterfaces
interface IViewState
interface IViewEvent | mapchat/app/src/main/java/com/flad/mapchatapp/model/viewdatainterfaces/Interfaces.kt | 853422840 |
package com.flad.mapchatapp.base
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.flad.mapchatapp.model.viewdatainterfaces.IViewEvent
import com.flad.mapchatapp.model.viewdatainterfaces.IViewState
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
abstract class BaseViewModel<State : IViewState, Event : IViewEvent> : ViewModel() {
private val initialState: State by lazy { createInitialState() }
abstract fun createInitialState(): State
val currentState: State get() = uiState.value
private val _uiState: MutableStateFlow<State> = MutableStateFlow(initialState)
val uiState: StateFlow<State> = _uiState
private val _eventFlow = MutableSharedFlow<Event>()
val eventFlow = _eventFlow.asSharedFlow()
protected fun emitEvent(event: Event) {
viewModelScope.launch {
_eventFlow.emit(event)
}
}
init {
viewModelScope.launch {
_eventFlow.collect { event ->
onEvent(event)
}
}
}
open suspend fun onEvent(event: Event) {
}
protected fun setState(reduce: State.() -> State) {
val newState = currentState.reduce()
_uiState.value = newState
}
}
| mapchat/app/src/main/java/com/flad/mapchatapp/base/BaseViewModel.kt | 3586331035 |
package com.vinod.cameraxdevelopment
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.vinod.cameraxdevelopment", appContext.packageName)
}
} | CameraX-Impl/app/src/androidTest/java/com/vinod/cameraxdevelopment/ExampleInstrumentedTest.kt | 3746672248 |
package com.vinod.cameraxdevelopment
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)
}
} | CameraX-Impl/app/src/test/java/com/vinod/cameraxdevelopment/ExampleUnitTest.kt | 2866624283 |
package com.vinod.cameraxdevelopment
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Size
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.Camera
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.vinod.cameraxdevelopment.databinding.ActivityMainBinding
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* created by Vinod Kumar 22-Aug-2023
* This Activity is a request result Activity used to capture the image from camera and preview
* on click of ok it will send the image uri result to the Activity which launched it.
*/
class CameraViewActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var isFlashOn = false
private var imageCapture: ImageCapture? = null
private lateinit var outputDirectory: File
private lateinit var cameraExecutor: ExecutorService
private var savedUri: Uri? = null
private var camera: Camera? = null
private var isImageCaptureSuccess: Boolean = false
private var isPermissionScreenOpened: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
isImageCaptureSuccess = false
initViewsForCameraDisplay()
addListeners()
}
/**
* this method responsible for the click listeners and it's behaviours
*/
private fun addListeners() {
binding.tvCaptureButton.setOnClickListener {
captureImage()
}
binding.tvFlashView.setOnClickListener {
toggleFlash()
}
binding.toolbar.setNavigationOnClickListener {
onBackPressed()
}
binding.tvRejectImage.setOnClickListener {
showCameraViews(true)
showPreviewViews(false)
isImageCaptureSuccess = false
}
binding.tvAcceptImage.setOnClickListener {
if (savedUri != null) {
val resultIntent = Intent()
resultIntent.putExtra("imageUri", savedUri)
setResult(RESULT_OK, resultIntent)
Toast.makeText(this, "Thanks \n $savedUri", Toast.LENGTH_SHORT).show()
isImageCaptureSuccess = true
[email protected]()
} else {
Toast.makeText(this, "Please recapture the image", Toast.LENGTH_SHORT).show()
showCameraViews(true)
showPreviewViews(false)
}
}
}
/**
* In this method we check if the permission is granted or not.
* if not we request and start camera action 📷...
*/
override fun onResume() {
super.onResume()
requestCameraPermission()
}
/**
* this method initializes basic views.
*/
private fun initViewsForCameraDisplay() {
intent?.let {
binding.toolbar.title = it.getStringExtra("title") ?: "Camera"
}
if (isPermissionGranted())
setupAndStartCamera()
}
override fun onBackPressed() {
if (!isImageCaptureSuccess){
val resultIntent = Intent()
val uri = Uri.parse("content://empty")
//her passing empty uri instead of null due to web requirements
resultIntent.putExtra("imageUri", uri)
setResult(RESULT_OK, resultIntent)
[email protected]()
}else [email protected]()
}
/**
* this method will setup the camera executor.
*/
private fun setupAndStartCamera() {
outputDirectory = getOutputDirectory()
cameraExecutor = Executors.newSingleThreadExecutor()
startCamera()
}
/**
* helper method
*/
private fun showCameraViews(isIt: Boolean) {
binding.apply {
viewFinder.visibility = if (isIt) View.VISIBLE else View.GONE
tvCaptureButton.visibility = if (isIt) View.VISIBLE else View.GONE
tvFlashView.visibility = if (isIt) View.VISIBLE else View.GONE
}
}
/**
* helper method
*/
private fun showPreviewViews(isIt: Boolean) {
binding.apply {
ivPreview.visibility = if (isIt) View.VISIBLE else View.GONE
tvAcceptImage.visibility = if (isIt) View.VISIBLE else View.GONE
tvRejectImage.visibility = if (isIt) View.VISIBLE else View.GONE
}
}
/**
* this method will start the camera with minimal settings
* with default flash off.
*/
private fun startCamera() {
try {
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({
val cameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder().build().also {
it.setSurfaceProvider(binding.viewFinder.surfaceProvider)
}
imageCapture = ImageCapture.Builder()
.setCaptureMode(CAPTURE_MODE_MINIMIZE_LATENCY)
.setTargetResolution(Size(720, 1080))
.setFlashMode(if (isFlashOn) ImageCapture.FLASH_MODE_ON else ImageCapture.FLASH_MODE_OFF)
.build()
val cameraSelector =
CameraSelector.DEFAULT_BACK_CAMERA //default lens is Back Camera.
try {
cameraProvider.unbindAll()
camera =
cameraProvider.bindToLifecycle(
this,
cameraSelector,
preview,
imageCapture
)
} catch (exc: Exception) {
exc.printStackTrace()
try {
if (camera == null) {
camera = cameraProvider.bindToLifecycle(
this,
CameraSelector.DEFAULT_FRONT_CAMERA,
preview,
imageCapture
)
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
/* Here finishing because if both camera's are not available then
there is no point in showing the camera.
*/
finish()
}
}
}, ContextCompat.getMainExecutor(this))
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
}
/**
* this method responsible for capturing the image and
* storing in the specified directory.
*/
private fun captureImage() {
val imageCapture = imageCapture ?: return
val photoFile = File(
outputDirectory,
SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss-SSS",
Locale.US
).format(System.currentTimeMillis()) + "_damage.jpg"
)
val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
imageCapture.takePicture(
outputOptions,
ContextCompat.getMainExecutor(this),
object : ImageCapture.OnImageSavedCallback {
override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
savedUri = Uri.fromFile(photoFile)
showCameraViews(false)
loadImageToPreview()
if (isFlashOn) {
toggleFlash()
}
}
override fun onError(exception: ImageCaptureException) {
exception.printStackTrace()
}
})
}
/**
* this method will be used to preview the captured image.
*/
private fun loadImageToPreview() {
savedUri?.let {
Glide.with(binding.ivPreview)
.load(it)
.into(binding.ivPreview)
showCameraViews(false)
showPreviewViews(true)
}
}
private fun getOutputDirectory(): File {
val mediaDir = externalMediaDirs.firstOrNull()?.let {
File(it, resources.getString(R.string.app_name)).apply { mkdirs() }
}
return if (mediaDir != null && mediaDir.exists())
mediaDir else filesDir
}
private fun toggleFlash() {
if (isFlashOn)
binding.tvFlashView.setBackgroundResource(R.drawable.baseline_flash_off_24)
else binding.tvFlashView.setBackgroundResource(R.drawable.baseline_flash_on_24)
isFlashOn = !isFlashOn
camera?.let {
it.cameraControl.enableTorch(isFlashOn)
}
}
private fun isPermissionGranted(): Boolean {
return checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
}
private fun requestCameraPermission(): Boolean {
var permissionGranted = false
val cameraPermissionNotGranted =
checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED
if (cameraPermissionNotGranted) {
val permission = arrayOf(Manifest.permission.CAMERA)
requestPermissions(permission, CAMERA_PERMISSION_CODE)
} else permissionGranted = true
return permissionGranted
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == CAMERA_PERMISSION_CODE) {
if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted
setupAndStartCamera()
} else {
// Permission was denied so open app's permission settings page. as of now showing toast as per requirement
if (!isPermissionScreenOpened) {
// navigateToAppSettings()
isPermissionScreenOpened = true
Toast.makeText(this,"Please give camera access",Toast.LENGTH_SHORT).show()
onBackPressed()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PERMISSION_REQUEST_CODE) {
try {
//after the navigating to permission setting screen and redirecting back to app
val cameraPermissionNotGranted =
checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED
if (cameraPermissionNotGranted) onBackPressed() //if still permission is denied
else setupAndStartCamera() // if permission is granted.
} catch (e: java.lang.Exception) {
onBackPressed()
}
}
}
/**
* Open the Application Settings
* To grant permission
*/
private fun navigateToAppSettings() {
val intent = Intent()
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
val uri = Uri.fromParts("package", packageName, null)
intent.data = uri
startActivityForResult(intent, PERMISSION_REQUEST_CODE)
}
companion object {
private const val CAMERA_PERMISSION_CODE = 1010;
const val PERMISSION_REQUEST_CODE = 2003
}
} | CameraX-Impl/app/src/main/java/com/vinod/cameraxdevelopment/CameraViewActivity.kt | 555173555 |
package com.example.relativelayoutpractice
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.relativelayoutpractice", appContext.packageName)
}
} | Random_Colors_with_Relative_View/app/src/androidTest/java/com/example/relativelayoutpractice/ExampleInstrumentedTest.kt | 1573361998 |
package com.example.relativelayoutpractice
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)
}
} | Random_Colors_with_Relative_View/app/src/test/java/com/example/relativelayoutpractice/ExampleUnitTest.kt | 73498817 |
package com.example.relativelayoutpractice
import android.content.Context
import android.graphics.drawable.ColorDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.core.content.ContextCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val boxFirst:TextView = findViewById(R.id.firstBox)
val boxSecond:TextView = findViewById(R.id.secondBox)
val boxThird:TextView = findViewById(R.id.thirdBox)
val buttonChangeColor:Button = findViewById(R.id.changeColor)
fun setBackgroundColor(context:Context, box1: TextView,box2: TextView,box3: TextView,){
val colorArray = arrayOf(
R.color.colorRed, R.color.colorBlue, R.color.colorGreen,
R.color.colorYellow, R.color.colorCyan, R.color.colorMagenta,
R.color.colorOrange, R.color.colorPurple, R.color.colorPink,
R.color.colorTeal, R.color.colorDarkRed, R.color.colorDarkBlue,
R.color.colorDarkGreen, R.color.colorDarkYellow, R.color.colorDarkCyan,
R.color.colorDarkMagenta, R.color.colorDarkOrange, R.color.colorDarkPurple,
R.color.colorDarkPink, R.color.colorDarkTeal
)
val randomIndexNumberBox1 = (0 until colorArray.size ).random()
val randomIndexNumberBox2 = (0 until colorArray.size ).random()
val randomIndexNumberBox3 = (0 until colorArray.size ).random()
val randomColorBox1 = ContextCompat.getColor(context,colorArray[randomIndexNumberBox1])
val randomColorBox2 = ContextCompat.getColor(context,colorArray[randomIndexNumberBox2])
val randomColorBox3 = ContextCompat.getColor(context,colorArray[randomIndexNumberBox3])
box1.background = ColorDrawable(randomColorBox1)
box2.background = ColorDrawable(randomColorBox2)
box3.background = ColorDrawable(randomColorBox3)
}
buttonChangeColor.setOnClickListener{
setBackgroundColor(this,boxFirst,boxSecond,boxThird)
}
}
} | Random_Colors_with_Relative_View/app/src/main/java/com/example/relativelayoutpractice/MainActivity.kt | 617592094 |
package com.gyadam.googleoauthtest
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.gyadam.googleoauthtest", appContext.packageName)
}
} | OauthTestApp/app/src/androidTest/java/com/gyadam/googleoauthtest/ExampleInstrumentedTest.kt | 1678911326 |
package com.gyadam.googleoauthtest
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)
}
} | OauthTestApp/app/src/test/java/com/gyadam/googleoauthtest/ExampleUnitTest.kt | 190350130 |
package com.gyadam.googleoauthtest.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/ui/theme/Color.kt | 291895141 |
package com.gyadam.googleoauthtest.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun GoogleOauthTestTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/ui/theme/Theme.kt | 3013916453 |
package com.gyadam.googleoauthtest.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/ui/theme/Type.kt | 1781385645 |
package com.gyadam.googleoauthtest.ui.screen
sealed class SIgnInEvent {
data class singInWithGoogle(val email: String) : SIgnInEvent()
} | OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/ui/screen/SIgnInEvent.kt | 1278062355 |
package com.gyadam.googleoauthtest.ui.screen
data class SignInState(
val isGoogleSignIn : Boolean = false
)
| OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/ui/screen/SignInState.kt | 4217534587 |
package com.gyadam.googleoauthtest.ui.screen
import androidx.lifecycle.ViewModel
import com.gyadam.googleoauthtest.domain.useCases.GetOauthRequestIntent
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class SignInViewModel @Inject constructor(
private val getOAuthRequestIntent: GetOauthRequestIntent,
) : ViewModel() {
fun onEvent(event: SIgnInEvent) {
when (event) {
is SIgnInEvent.singInWithGoogle -> {
getOAuthRequestIntent(event.email)
}
}
}
} | OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/ui/screen/SignInViewModel.kt | 3375392359 |
package com.gyadam.googleoauthtest.ui.screen
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
@Composable
fun SignInScreen(
viewModel: SignInViewModel = hiltViewModel(),
) {
var email by remember { mutableStateOf("") }
val focusRequester = remember { FocusRequester() }
Surface(color = MaterialTheme.colorScheme.background) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = "Sign In",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(16.dp))
TextField(
value = email,
onValueChange = { email = it },
label = { Text("Email") },
keyboardOptions = KeyboardOptions.Default.copy(
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = { viewModel.onEvent(SIgnInEvent.singInWithGoogle(email)) }
),
singleLine = true,
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester)
)
Spacer(modifier = Modifier.height(16.dp))
ElevatedButton(
onClick = { viewModel.onEvent(SIgnInEvent.singInWithGoogle(email)) },
modifier = Modifier.fillMaxWidth()
) {
Text(text = "Sign In")
}
}
}
DisposableEffect(Unit) {
focusRequester.requestFocus()
onDispose { }
}
}
| OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/ui/screen/SignInScreen.kt | 3197925247 |
package com.gyadam.googleoauthtest
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.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.gyadam.googleoauthtest.ui.screen.SignInScreen
import com.gyadam.googleoauthtest.ui.theme.GoogleOauthTestTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GoogleOauthTestTheme {
// A surface container using the 'background' color from the theme
SignInScreen()
}
}
}
}
| OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/MainActivity.kt | 434226413 |
package com.gyadam.googleoauthtest.module
import com.gyadam.googleoauthtest.data.oauthCore.InMemoryOAuthConfigurationProvider
import com.gyadam.googleoauthtest.data.oauthCore.OAuthConfigurationProvider
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
} | OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/module/AppModule.kt | 474130610 |
package com.gyadam.googleoauthtest.module
import com.gyadam.googleoauthtest.domain.useCases.GetOauthRequestIntent
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import dagger.hilt.android.scopes.ViewModelScoped
@Module
@InstallIn(ViewModelComponent::class)
object UseCaseModule {
@ViewModelScoped
@Provides
fun provideGetOAutheRequestIntentUseCase(): GetOauthRequestIntent = GetOauthRequestIntent()
} | OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/module/UseCaseModule.kt | 2111579500 |
package com.gyadam.googleoauthtest.data.oauthCore
import com.gyadam.googleoauthtest.BuildConfig
class OAuthConfigurationFactoryImpl : OAuthConfigurationFactory {
override fun createConfigurations(): Map<List<String>, OAuthConfiguration> {
return mapOf(
createAolConfiguration(),
createGmailConfiguration(),
createMicrosoftConfiguration(),
createYahooConfiguration(),
)
}
private fun createAolConfiguration(): Pair<List<String>, OAuthConfiguration> {
return listOf("imap.aol.com", "smtp.aol.com") to OAuthConfiguration(
clientId = BuildConfig.OAUTH_AOL_CLIENT_ID,
scopes = listOf("mail-w"),
authorizationEndpoint = "https://api.login.aol.com/oauth2/request_auth",
tokenEndpoint = "https://api.login.aol.com/oauth2/get_token",
redirectUri = "${BuildConfig.APPLICATION_ID}://oauth2redirect",
)
}
private fun createGmailConfiguration(): Pair<List<String>, OAuthConfiguration> {
return listOf(
"imap.gmail.com",
"imap.googlemail.com",
"smtp.gmail.com",
"smtp.googlemail.com",
) to OAuthConfiguration(
clientId = BuildConfig.OAUTH_GMAIL_CLIENT_ID,
scopes = listOf("https://mail.google.com/"),
authorizationEndpoint = "https://accounts.google.com/o/oauth2/v2/auth",
tokenEndpoint = "https://oauth2.googleapis.com/token",
redirectUri = "${BuildConfig.APPLICATION_ID}:/oauth2redirect",
)
}
private fun createMicrosoftConfiguration(): Pair<List<String>, OAuthConfiguration> {
return listOf(
"outlook.office365.com",
"smtp.office365.com",
) to OAuthConfiguration(
clientId = BuildConfig.OAUTH_MICROSOFT_CLIENT_ID,
scopes = listOf(
"https://outlook.office.com/IMAP.AccessAsUser.All",
"https://outlook.office.com/SMTP.Send",
"offline_access",
),
authorizationEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
tokenEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token",
redirectUri = BuildConfig.OAUTH_MICROSOFT_REDIRECT_URI,
)
}
private fun createYahooConfiguration(): Pair<List<String>, OAuthConfiguration> {
return listOf(
"imap.mail.yahoo.com",
"smtp.mail.yahoo.com",
) to OAuthConfiguration(
clientId = BuildConfig.OAUTH_YAHOO_CLIENT_ID,
scopes = listOf("mail-w"),
authorizationEndpoint = "https://api.login.yahoo.com/oauth2/request_auth",
tokenEndpoint = "https://api.login.yahoo.com/oauth2/get_token",
redirectUri = "${BuildConfig.APPLICATION_ID}://oauth2redirect",
)
}
} | OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/data/oauthCore/OAuthConfigurationFactoryImpl.kt | 3718528293 |
package com.gyadam.googleoauthtest.data.oauthCore
fun interface OAuthConfigurationFactory {
fun createConfigurations(): Map<List<String>, OAuthConfiguration>
}
| OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/data/oauthCore/OAuthConfigurationFactory.kt | 128533471 |
package com.gyadam.googleoauthtest.data.oauthCore
data class OAuthConfiguration(
val clientId: String,
val scopes: List<String>,
val authorizationEndpoint: String,
val tokenEndpoint: String,
val redirectUri: String,
)
| OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/data/oauthCore/OAuthConfiguration.kt | 3528822936 |
package com.gyadam.googleoauthtest.data.oauthCore
fun interface OAuthConfigurationProvider {
fun getConfiguration(hostname: String): OAuthConfiguration?
}
| OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/data/oauthCore/OAuthConfigurationProvider.kt | 1989447112 |
package com.gyadam.googleoauthtest.data.oauthCore
internal class InMemoryOAuthConfigurationProvider(
private val configurationFactory: OAuthConfigurationFactory,
) : OAuthConfigurationProvider {
private val hostnameMapping: Map<String, OAuthConfiguration> = buildMap {
for ((hostnames, configuration) in configurationFactory.createConfigurations()) {
for (hostname in hostnames) {
put(hostname.lowercase(), configuration)
}
}
}
override fun getConfiguration(hostname: String): OAuthConfiguration? {
return hostnameMapping[hostname.lowercase()]
}
}
| OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/data/oauthCore/InMemoryOAuthConfigurationProvider.kt | 1257206844 |
package com.gyadam.googleoauthtest.domain.useCases
class GetOauthRequestIntent {
operator fun invoke(email: String) {
println("Sign in with email : $email")
}
} | OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/domain/useCases/GetOauthRequestIntent.kt | 2214856420 |
package com.gyadam.googleoauthtest
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class GoogleOauthTestApp : Application() | OauthTestApp/app/src/main/java/com/gyadam/googleoauthtest/GoogleOauthTestApp.kt | 2664295521 |
fun main(){
println(workersSalary(12, 2300))
println(workersSalary(6,1000))
println(workersSalary(4,500))
}
fun workersSalary(hours :Int, rate : Int ) : Int{
return hours * rate
}
| pip_kotlin/src/main/kotlin/Main.kt | 2992248950 |
package com.example.kitchen
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class KotlinSpringBootKitchenApplicationTests {
@Test
fun contextLoads() {
}
}
| kotlin-spring-boot-kitchen/src/test/kotlin/com/example/kitchen/KotlinSpringBootKitchenApplicationTests.kt | 3868412409 |
package com.example.kitchen
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class KotlinSpringBootKitchenApplication
fun main(args: Array<String>) {
runApplication<KotlinSpringBootKitchenApplication>(*args)
}
| kotlin-spring-boot-kitchen/src/main/kotlin/com/example/kitchen/KotlinSpringBootKitchenApplication.kt | 1353044403 |
package com.example.kitchen
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.kafka.support.KafkaHeaders
import org.springframework.messaging.handler.annotation.Header
import org.springframework.stereotype.Service
@Service
class Kitchen(val kafkaTemplate: KafkaTemplate<String, String>) {
val topic = "kitchen_topic"
@KafkaListener(id = "myConsumer", topics = ["kitchen_topic"], groupId = "spring-boot", autoStartup = "false")
fun listen(value: String,
@Header(KafkaHeaders.RECEIVED_TOPIC) topic: String,
@Header(KafkaHeaders.RECEIVED_KEY) key: String) {
println("Message received: " + value)
prepareMeal()
sendMessage(key, "done")
}
fun sendMessage(key: String, message: String) {
println("Sending message")
kafkaTemplate.send(topic, key, message)
}
fun prepareMeal() {
Thread.sleep(5000)
}
} | kotlin-spring-boot-kitchen/src/main/kotlin/com/example/kitchen/Kitchen.kt | 3951189819 |
package org.redbyte.genom
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("org.redbyte.genom", appContext.packageName)
}
} | genom/app/src/androidTest/java/org/redbyte/genom/ExampleInstrumentedTest.kt | 2137350897 |
package org.redbyte.genom.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | genom/app/src/main/java/org/redbyte/genom/ui/theme/Color.kt | 3896203268 |
package org.redbyte.genom.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun GenomTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | genom/app/src/main/java/org/redbyte/genom/ui/theme/Theme.kt | 2925762416 |
package org.redbyte.genom.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | genom/app/src/main/java/org/redbyte/genom/ui/theme/Type.kt | 1080815192 |
package org.redbyte.genom.settings
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import org.redbyte.genom.R
import org.redbyte.genom.common.data.GameSettings
@Composable
fun SettingsScreen(navController: NavHostController) {
val viewModel: GameSettingsViewModel = viewModel()
val dialogState = remember { mutableStateOf(false) }
var hasPacifists by remember { mutableStateOf(true) }
var hasAggressors by remember { mutableStateOf(false) }
var allowMutations by remember { mutableStateOf(false) }
Surface(color = Color(0xFF1B1B1B)) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
"Выберите типы клеток",
color = Color.Green,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(16.dp))
CheckboxWithText(
text = "Пацифисты",
checked = hasPacifists,
onCheckedChange = { checked ->
if (!checked && !hasAggressors) {
dialogState.value = true
} else {
hasPacifists = checked
}
}
)
CheckboxWithText(
text = "Агрессоры",
checked = hasAggressors,
onCheckedChange = { checked ->
if (!checked && !hasPacifists) {
dialogState.value = true
} else {
hasAggressors = checked
}
}
)
if (hasPacifists && hasAggressors) {
CheckboxWithText(
text = "Разрешить мутации",
checked = allowMutations,
onCheckedChange = { allowMutations = it }
)
}
Spacer(modifier = Modifier.height(16.dp))
Row(
horizontalArrangement = Arrangement.SpaceEvenly,
modifier = Modifier.fillMaxWidth()
) {
Image(
bitmap = ImageBitmap.imageResource(id = R.drawable.ic_biohazard),
contentDescription = "Compose Game",
modifier = Modifier
.weight(1f)
.aspectRatio(1f)
.clickable {
// TODO: release set settings
val gameSettings =
GameSettings(
hasPacifists= hasPacifists,
hasAggressors = hasAggressors,
allowMutations = allowMutations
)
viewModel.setupSettings(gameSettings)
navController.navigate("genomGame")
}
)
Image(
bitmap = ImageBitmap.imageResource(id = R.drawable.ic_biohazard2d),
contentDescription = "OpenGL Game",
modifier = Modifier
.weight(1f)
.aspectRatio(1f)
.clickable { navController.navigate("openGLGame") }
)
}
}
}
if (dialogState.value) {
AlertDialog(
onDismissRequest = { dialogState.value = false },
confirmButton = {
Button(onClick = { dialogState.value = false }) {
Text("ОК")
}
},
text = { Text("Хотя бы один вид клеток должен быть выбран.") }
)
}
}
@Composable
fun CheckboxWithText(text: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = checked,
onCheckedChange = onCheckedChange,
colors = CheckboxDefaults.colors(
checkedColor = Color.Green,
uncheckedColor = Color.DarkGray
)
)
Text(text, color = Color.White)
}
}
| genom/app/src/main/java/org/redbyte/genom/settings/SettingsScreen.kt | 704139290 |
package org.redbyte.genom.settings
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import org.redbyte.genom.common.GameBoard
import org.redbyte.genom.common.data.GameSettings
class GameSettingsViewModel : ViewModel() {
private var gameBoard: GameBoard? = null
private val _settings = MutableLiveData(GameSettings())
val settings: LiveData<GameSettings> = _settings
fun setupSettings(newSettings: GameSettings) {
_settings.value = newSettings
gameBoard = GameBoard(newSettings)
}
fun getGameBoard(): GameBoard = gameBoard ?: GameBoard(
settings.value ?: throw RuntimeException("Game settings cannot be null")
)
}
| genom/app/src/main/java/org/redbyte/genom/settings/GameSettingsViewModel.kt | 2906441521 |
package org.redbyte.genom
import androidx.compose.runtime.Composable
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import org.redbyte.genom.common.GameBoard
import org.redbyte.genom.common.data.GameSettings
import org.redbyte.genom.render.compose.GenomGame
import org.redbyte.genom.settings.SettingsScreen
import org.redbyte.genom.render.opengl.Genom2DGame
@Composable
fun AppNavigation() {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "settingsGame") {
composable("settingsGame") {
SettingsScreen(navController)
}
composable("genomGame") {
GenomGame()
}
composable("openGLGame") {
Genom2DGame()
}
}
}
| genom/app/src/main/java/org/redbyte/genom/AppNavigation.kt | 1289263363 |
package org.redbyte.genom
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.navigation.compose.rememberNavController
import org.redbyte.genom.ui.theme.GenomTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GenomTheme {
AppNavigation()
}
}
}
} | genom/app/src/main/java/org/redbyte/genom/MainActivity.kt | 2099870093 |
package org.redbyte.genom.render.compose
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.detectVerticalDragGestures
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.redbyte.genom.settings.GameSettingsViewModel
@Composable
fun GenomGame() {
val viewModel: GameSettingsViewModel = viewModel()
val gameBoard = viewModel.getGameBoard()
val coroutineScope = rememberCoroutineScope()
var showTopSheet by remember { mutableStateOf(false) }
var isPaused by remember { mutableStateOf(false) }
BoxWithConstraints(Modifier.fillMaxSize()) {
val screenWidth = constraints.maxWidth
val cellSize = screenWidth / gameBoard.settings.width
val aggressiveCount = remember { mutableIntStateOf(0) }
val peacefulCount = remember { mutableIntStateOf(0) }
val cannibalCount = remember { mutableIntStateOf(0) }
val psychoCount = remember { mutableIntStateOf(0) }
val turnNumber = remember { mutableIntStateOf(0) }
var matrix by remember { mutableStateOf(gameBoard.matrix) }
LaunchedEffect(key1 = isPaused, key2 = matrix) {
while (!isPaused) {
psychoCount.intValue =
matrix.sumOf { row -> row.count { it.isAlive && it.genes.contains(4) } }
peacefulCount.intValue =
matrix.sumOf { row -> row.count { it.isAlive && it.genes.contains(6) } }
cannibalCount.intValue =
matrix.sumOf { row -> row.count { it.isAlive && it.genes.contains(7) } }
aggressiveCount.intValue =
gameBoard.matrix.sumOf { row -> row.count { it.isAlive && it.genes.contains(8) } }
turnNumber.intValue++
delay(250)
gameBoard.update()
matrix = gameBoard.matrix.clone()
}
}
Column(modifier = Modifier.pointerInput(Unit) {
detectVerticalDragGestures { _, dragAmount ->
coroutineScope.launch {
if (dragAmount > 0 && !showTopSheet) {
showTopSheet = true
} else if (dragAmount < 0 && showTopSheet) {
showTopSheet = false
}
}
}
}) {
AnimatedVisibility(
visible = showTopSheet,
enter = slideInVertically(),
exit = slideOutVertically()
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text("Ход: ${turnNumber.intValue}")
Text("Агрессоры: ${aggressiveCount.intValue}")
Text("Каннибалы: ${cannibalCount.intValue}")
Text("Пацифисты: ${peacefulCount.intValue}")
Text("Психи: ${psychoCount.intValue}")
Button(onClick = { isPaused = !isPaused }) {
Text(if (isPaused) "Продолжить" else "Пауза")
}
}
}
Canvas(modifier = Modifier.fillMaxSize()) {
matrix.forEachIndexed { i, row ->
row.forEachIndexed { j, cell ->
val color = when {
cell.isAlive && cell.genes.contains(4) -> Color(
android.graphics.Color.parseColor(
"#FFFFC107"
)
)
cell.isAlive && cell.genes.contains(6) -> Color.Green
cell.isAlive && cell.genes.contains(7) -> Color.Blue
cell.isAlive && cell.genes.contains(8) -> Color.Red
else -> Color.White
}
drawCircle(
color,
cellSize / 2f,
center = Offset(
i * cellSize + cellSize / 2f,
j * cellSize + cellSize / 2f
)
)
}
}
}
}
}
}
| genom/app/src/main/java/org/redbyte/genom/render/compose/GenomGame.kt | 427254854 |
package org.redbyte.genom.render.opengl
import android.opengl.GLES20
import android.opengl.GLSurfaceView.Renderer
import android.opengl.Matrix
import org.redbyte.genom.common.GameBoard
import java.nio.ByteBuffer
import java.nio.ByteOrder
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
class GameRenderer(
private val gameBoard: GameBoard,
private val onCellCountUpdate: (Int, Int) -> Unit
) : Renderer {
private var squareShaderProgram: Int = 0
private val projectionMatrix = FloatArray(16)
private var lastUpdateTime = System.nanoTime()
private val updateInterval = 128_000_000
private var turn = 0
// Vertex shader code
private val vertexShaderCode = """
uniform mat4 uMVPMatrix;
attribute vec4 vPosition;
void main() {
gl_Position = uMVPMatrix * vPosition;
}
""".trimIndent()
// Fragment shader code
private val fragmentShaderCode = """
precision mediump float;
uniform vec4 vColor;
void main() {
gl_FragColor = vColor;
}
""".trimIndent()
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
GLES20.glClearColor(0f, 0f, 0.2f, 1.0f)
val vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode)
val fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode)
squareShaderProgram = GLES20.glCreateProgram().also {
GLES20.glAttachShader(it, vertexShader)
GLES20.glAttachShader(it, fragmentShader)
GLES20.glLinkProgram(it)
}
}
override fun onDrawFrame(gl: GL10?) {
val currentTime = System.nanoTime()
val deltaTime = currentTime - lastUpdateTime
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
GLES20.glUseProgram(squareShaderProgram)
val positionHandle = GLES20.glGetAttribLocation(squareShaderProgram, "vPosition")
val colorHandle = GLES20.glGetUniformLocation(squareShaderProgram, "vColor")
val mvpMatrixHandle = GLES20.glGetUniformLocation(squareShaderProgram, "uMVPMatrix")
val vertexStride = COORDS_PER_VERTEX * 4
GLES20.glUniformMatrix4fv(mvpMatrixHandle, 1, false, projectionMatrix, 0)
gameBoard.matrix.forEachIndexed { y, row ->
val aliveColor = floatArrayOf(0.0f, 1.0f, 0.0f, 1.0f)
row.forEachIndexed { x, cell ->
if (cell.isAlive) {
val squareCoords =
calculateSquareCoords(x, y, gameBoard.settings.width, gameBoard.settings.height)
val vertexBuffer = ByteBuffer.allocateDirect(squareCoords.size * 4).run {
order(ByteOrder.nativeOrder())
asFloatBuffer().apply {
put(squareCoords)
position(0)
}
}
GLES20.glEnableVertexAttribArray(positionHandle)
GLES20.glVertexAttribPointer(
positionHandle,
COORDS_PER_VERTEX,
GLES20.GL_FLOAT,
false,
vertexStride,
vertexBuffer
)
GLES20.glUniform4fv(colorHandle, 1, aliveColor, 0)
GLES20.glDrawArrays(
GLES20.GL_TRIANGLE_STRIP,
0,
squareCoords.size / COORDS_PER_VERTEX
)
GLES20.glDisableVertexAttribArray(positionHandle)
}
}
}
if (deltaTime >= updateInterval) {
gameBoard.update()
onCellCountUpdate(gameBoard.countLivingCells(), ++turn)
lastUpdateTime = currentTime
}
}
override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
GLES20.glViewport(0, 0, width, height)
val aspectRatio = if (width >= height) {
// landscape
width.toFloat() / height
} else {
// portrait
height.toFloat() / width
}
if (width >= height) {
Matrix.orthoM(projectionMatrix, 0, -aspectRatio, aspectRatio, -1f, 1f, -1f, 1f)
} else {
Matrix.orthoM(projectionMatrix, 0, -1f, 1f, -aspectRatio, aspectRatio, -1f, 1f)
}
}
private fun loadShader(type: Int, shaderCode: String): Int {
return GLES20.glCreateShader(type).also { shader ->
GLES20.glShaderSource(shader, shaderCode)
GLES20.glCompileShader(shader)
}
}
private fun calculateSquareCoords(x: Int, y: Int, width: Int, height: Int): FloatArray {
val normalizedCellWidth = 2.0f / width
val normalizedCellHeight = 2.0f / height
val normalizedX = -1f + x * normalizedCellWidth
val normalizedY = 1f - y * normalizedCellHeight
return floatArrayOf(
normalizedX, normalizedY,
normalizedX, normalizedY - normalizedCellHeight,
normalizedX + normalizedCellWidth, normalizedY,
normalizedX + normalizedCellWidth, normalizedY - normalizedCellHeight
)
}
companion object {
const val COORDS_PER_VERTEX = 2
}
}
| genom/app/src/main/java/org/redbyte/genom/render/opengl/GameRenderer.kt | 478801099 |
package org.redbyte.genom.render.opengl
import android.opengl.GLSurfaceView
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.viewmodel.compose.viewModel
import org.redbyte.genom.common.GameBoard
import org.redbyte.genom.common.data.GameSettings
import org.redbyte.genom.settings.GameSettingsViewModel
@Composable
fun Genom2DGame() {
val viewModel: GameSettingsViewModel = viewModel()
val gameBoard = viewModel.getGameBoard()
val livingCellsCount = remember { mutableIntStateOf(gameBoard.settings.initialPopulation) }
val turnGame = remember { mutableIntStateOf(0) }
Box(modifier = Modifier.fillMaxSize()) {
AndroidView(
modifier = Modifier.matchParentSize(),
factory = { context ->
GLSurfaceView(context).apply {
setEGLContextClientVersion(2)
setRenderer(GameRenderer(gameBoard) { count, turn ->
livingCellsCount.intValue = count
turnGame.intValue = turn
})
renderMode = GLSurfaceView.RENDERMODE_CONTINUOUSLY
}
}
)
Text(
text = "Количество живых клеток: ${livingCellsCount.intValue}\n" +
"Ход: ${turnGame.intValue}",
color = Color(0xFF009688),
fontSize = 18.sp,
modifier = Modifier
.align(Alignment.TopStart)
.padding(top = 32.dp, start = 16.dp)
)
}
}
| genom/app/src/main/java/org/redbyte/genom/render/opengl/Genom2DGame.kt | 1397912286 |
package org.redbyte.genom.common
import org.redbyte.genom.common.data.Cell
import org.redbyte.genom.common.data.GameSettings
typealias CellMatrix = Array<Array<Cell>>
class GameBoard(val settings: GameSettings) {
val matrix: CellMatrix =
Array(settings.width) { Array(settings.height) { Cell(false, mutableSetOf(6)) } }
private val newMatrix =
Array(settings.width) { Array(settings.height) { Cell(false, mutableSetOf(6)) } }
init {
var populated = 0
val maxCount = matrix.size * matrix[0].size
val pCount =
if (settings.initialPopulation > maxCount) maxCount / 10 else settings.initialPopulation
while (populated < pCount) {
val x = matrix.indices.random()
val y = matrix[0].indices.random()
if (!matrix[x][y].isAlive) {
matrix[x][y].isAlive = true
populated++
}
}
}
fun update() {
for (i in matrix.indices) {
for (j in matrix[0].indices) {
val neighbors = countNeighbors(i, j)
val cell = matrix[i][j]
newMatrix[i][j].isAlive =
if (matrix[i][j].isAlive) neighbors in 2..3 else neighbors == 3
if (newMatrix[i][j].isAlive) {
newMatrix[i][j].turnsLived = cell.turnsLived
newMatrix[i][j].genes = cell.genes
}
}
}
for (i in matrix.indices) {
for (j in matrix[0].indices) {
matrix[i][j] = newMatrix[i][j]
}
}
}
fun countLivingCells() = matrix.flatten().count { it.isAlive }
private fun countNeighbors(x: Int, y: Int): Int {
val directions = arrayOf(
Pair(-1, -1),
Pair(-1, 0),
Pair(-1, 1),
Pair(0, -1),
Pair(0, 1),
Pair(1, -1),
Pair(1, 0),
Pair(1, 1)
)
var neighborCount = 0
for ((dx, dy) in directions) {
val neighborX = x + dx
val neighborY = y + dy
if (neighborX in 0 until settings.height && neighborY in 0 until settings.width) {
if (matrix[neighborY][neighborX].isAlive) {
neighborCount++
}
}
}
return neighborCount
}
}
// TODO: implement logic to game board
//private fun generateWorld(matrix: CellMatrix, initialPopulation: Int) {
// var populated = 0
// val maxAttempts = initialPopulation * 10
// var attempts = 0
//
// while (populated < initialPopulation && attempts < maxAttempts) {
// val x = matrix.indices.random()
// val y = matrix[0].indices.random()
//
// if (!matrix[x][y].isAlive) {
// matrix[x][y].isAlive = true
// when {
// gameSettings.hasAllCells() -> matrix[x][y].genes =
// mutableSetOf(setOf(6, 8).random())
//
// gameSettings.isPacificOnly() -> matrix[x][y].genes = mutableSetOf(6)
// gameSettings.isAggressorsOnly() -> matrix[x][y].genes = mutableSetOf(8)
// }
// populated++
// }
// attempts++
// }
//}
//private fun getNextStatus(matrix: CellMatrix): CellMatrix {
// val newMatrix = Array(matrix.size) { Array(matrix[0].size) { Cell(false, mutableSetOf()) } }
// for (i in matrix.indices) {
// for (j in matrix[0].indices) {
// val cell = matrix[i][j]
// val newCell = newMatrix[i][j]
// newCell.isAlive = newStatus(cell, getNeighbors(matrix, i, j))
// if (newCell.isAlive) {
// newCell.genes = cell.genes
// newCell.turnsLived = cell.turnsLived
// }
// }
// }
// return newMatrix
//}
//
//private fun getNeighbors(matrix: CellMatrix, x: Int, y: Int): List<Cell> {
// val neighbors = mutableListOf<Cell>()
// val ref = arrayOf(
// intArrayOf(-1, -1),
// intArrayOf(-1, 0),
// intArrayOf(-1, 1),
// intArrayOf(0, -1),
// intArrayOf(0, 1),
// intArrayOf(1, -1),
// intArrayOf(1, 0),
// intArrayOf(1, 1)
// )
// for (k in ref.indices) {
// val newX = x + ref[k][0]
// val newY = y + ref[k][1]
// if (newX in matrix.indices && newY in matrix[0].indices) {
// neighbors.add(matrix[newX][newY])
// }
// }
// return neighbors
//}
//
//private fun newStatus(cell: Cell, neighbors: List<Cell>): Boolean {
// val aliveNeighbors = neighbors.count { it.isAlive }
// val peacefulNeighbors = neighbors.filter { it.genes.contains(6) }
// val aggressiveNeighbors = neighbors.filter { it.genes.contains(8) }
// val aggressiveCount = neighbors.count { it.genes.contains(8) }
// val cannibalCount = neighbors.count { it.genes.contains(7) }
// val cannibalNeighbors = neighbors.filter { it.genes.contains(7) }
//
// return when {
// cell.genes.contains(4) -> {
// if (cell.turnsLived < 10) {
// val target = aggressiveNeighbors.ifEmpty { cannibalNeighbors }.firstOrNull()
// target?.isAlive = false
// cell.turnsLived++
// return true
// } else {
// return false // death
// }
// }
//
// cell.genes.contains(6) -> {
// when {
// gameSettings.allowMutations && Random.nextInt(100) < 2 -> {
// cell.genes.remove(6)
// cell.genes.add(4)
// cell.turnsLived = 0
// true
// }
//
// cell.isAlive -> {
// Log.d("_debug", "${aliveNeighbors in 2..3} ");
// aliveNeighbors in 2..3
// }
//
// !cell.isAlive -> {
// aliveNeighbors == 3
// }
//
// else -> false
// }
// }
//
// cell.genes.contains(8) -> {
// val canReproduce =
// peacefulNeighbors.isNotEmpty() || cannibalNeighbors.isNotEmpty() && aggressiveCount in 2..3
// if (gameSettings.allowMutations && canReproduce && Random.nextInt(100) < 5) {
// cell.genes.add(7)
// cell.genes.remove(8)
// }
// canReproduce
// }
//
// cell.genes.contains(7) -> {
// val hasVictims =
// peacefulNeighbors.isNotEmpty() || aggressiveNeighbors.isNotEmpty() && cannibalCount in 2..3
// val surroundedByPeaceful = peacefulNeighbors.size >= 4
// val noNeighbors = neighbors.all { !it.isAlive }
// hasVictims && !surroundedByPeaceful && !noNeighbors
// }
//
// else -> false
// }
//}
| genom/app/src/main/java/org/redbyte/genom/common/GameBoard.kt | 1568791384 |
package org.redbyte.genom.common.data
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class GameSettings(
val width: Int = 32,
val height: Int = 32,
val initialPopulation: Int= 128,
val hasPacifists: Boolean = true,
val hasAggressors: Boolean = false,
val allowMutations: Boolean = false,
) : Parcelable {
fun isPacificOnly(): Boolean = hasPacifists && !hasAggressors
fun isAggressorsOnly(): Boolean = !hasPacifists && hasAggressors
fun hasAllCells(): Boolean = hasPacifists && hasAggressors
}
| genom/app/src/main/java/org/redbyte/genom/common/data/GameSettings.kt | 3989022918 |
package org.redbyte.genom.common.data
data class Cell(var isAlive: Boolean, var genes: MutableSet<Int>, var turnsLived: Int = 0)
| genom/app/src/main/java/org/redbyte/genom/common/data/Cell.kt | 1822067664 |
package org.redbyte
import android.app.Application
class GameApp : Application() {
override fun onCreate() {
super.onCreate()
}
} | genom/app/src/main/java/org/redbyte/GameApp.kt | 118551977 |
package com.example.amsflights
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.amsflights", appContext.packageName)
}
} | NativeAndroid/app/src/androidTest/java/com/example/amsflights/ExampleInstrumentedTest.kt | 3590321902 |
package com.example.amsflights
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)
}
} | NativeAndroid/app/src/test/java/com/example/amsflights/ExampleUnitTest.kt | 2952321001 |
package com.example.amsflights.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | NativeAndroid/app/src/main/java/com/example/amsflights/ui/theme/Color.kt | 2924267163 |
package com.example.amsflights.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun AMSFlightsTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | NativeAndroid/app/src/main/java/com/example/amsflights/ui/theme/Theme.kt | 3470362074 |
package com.example.amsflights.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | NativeAndroid/app/src/main/java/com/example/amsflights/ui/theme/Type.kt | 1378017224 |
package com.example.amsflights
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActionScope
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.example.amsflights.model.Planet
import com.example.amsflights.ui.theme.AMSFlightsTheme
import com.example.amsflights.vm.PlanetViewModel
class MainActivity : ComponentActivity() {
@OptIn(ExperimentalComposeUiApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AMSFlightsTheme {
Column(
modifier = Modifier.fillMaxSize(),
) {
val context = LocalContext.current.applicationContext
val viewModel: PlanetViewModel = viewModel()
var filterText by remember {
mutableStateOf<String?>(null)
}
val planets by viewModel.planetsUiState.collectAsState()
val planet by viewModel.planetUiState.collectAsState()
val keyboard = LocalSoftwareKeyboardController.current
var tempValue by remember {
mutableStateOf("")
}
var isNeedToShow by remember {
mutableStateOf(false)
}
fun onSearch() {
filterText = tempValue
viewModel.getAllPlanets(filterText, context)
keyboard?.hide()
}
fun onClick(id: String){
viewModel.getPlanet(id)
isNeedToShow = true
}
LaunchedEffect(filterText) {
viewModel.getAllPlanets(filterText, context)
}
if (isNeedToShow && planet!=null) {
PlanetCard(planet = planet!!, isFull = true)
BackHandler {
viewModel.getAllPlanets(context = context)
isNeedToShow = false
viewModel.getPlanet((-1).toString())
}
} else {
InputField(
text = tempValue,
onValueChange = { tempValue = it },
label = "Поиск",
onSearch = {
onSearch()
keyboard?.hide()
}
)
PlanetsScreen(planets = planets, onClick = ::onClick)
}
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
AMSFlightsTheme {
Greeting("Android")
}
}
//forcommit
@Composable
fun PlanetCard(
planet: Planet,
modifier: Modifier = Modifier,
backHandle: () -> Unit = {},
isFull: Boolean = false
) {
BackHandler {
backHandle()
}
Column(
verticalArrangement = Arrangement.spacedBy(0.dp, Alignment.Top),
horizontalAlignment = Alignment.Start,
modifier = modifier
.padding(top = 12.dp)
.fillMaxWidth()
.fillMaxHeight(0.98F)
.shadow(
elevation = 200.dp,
ambientColor = Color(0x14000000)
)
.padding(start = 16.dp, end = 16.dp, bottom = 16.dp)
.background(color = Color(0xFFFFFFFF), shape = RoundedCornerShape(size = 16.dp))
) {
AsyncImage(
model = planet.image,
contentDescription = "image description",
contentScale = ContentScale.FillBounds,
modifier = Modifier
.padding(top = 12.dp)
.width(328.dp)
.height(301.dp)
.clip(RoundedCornerShape(30.dp))
)
Text(
text = planet.name,
style = TextStyle(
fontSize = 15.sp,
lineHeight = 20.sp,
fontWeight = FontWeight(400),
color = Color(0xFF000000),
letterSpacing = 0.2.sp,
),
modifier = Modifier.padding(bottom = 16.dp).align(Alignment.CenterHorizontally)
)
if (isFull) {
Text(
text = "Радиус = ${planet.radius}",
style = TextStyle(
fontSize = 15.sp,
lineHeight = 20.sp,
fontWeight = FontWeight(600),
color = Color(0xFF818C99),
letterSpacing = 0.3.sp,
),
modifier = Modifier.padding(start = 16.dp)
)
Text(
text = "Гравитация = ${planet.gravity}",
style = TextStyle(
fontSize = 15.sp,
lineHeight = 20.sp,
fontWeight = FontWeight(600),
color = Color(0xFF818C99),
letterSpacing = 0.3.sp,
),
modifier = Modifier.padding(start = 16.dp)
)
Text(
text = "Тип = ${planet.type}",
style = TextStyle(
fontSize = 15.sp,
lineHeight = 20.sp,
fontWeight = FontWeight(600),
color = Color(0xFF818C99),
letterSpacing = 0.3.sp,
),
modifier = Modifier.padding(start = 16.dp)
)
Text(
text = "Описание: ${planet.description}",
style = TextStyle(
fontSize = 15.sp,
lineHeight = 20.sp,
fontWeight = FontWeight(600),
color = Color(0xFF818C99),
letterSpacing = 0.3.sp,
),
modifier = Modifier.padding(start = 16.dp)
)
}
}
}
@Composable
fun PlanetsScreen(
planets: List<Planet>,
onClick: (String) -> Unit
) {
LazyColumn {
items(planets, key = {it.hashCode()}) {
PlanetCard(
planet = it, modifier = Modifier.clickable(
interactionSource = MutableInteractionSource(),
indication = null,
onClick = { onClick(it.id.toString()) },
)
)
}
}
}
@Composable
fun InputField(
modifier: Modifier = Modifier,
label: String? = null,
text: String = "",
onValueChange: (String) -> Unit,
onSearch: (KeyboardActionScope.() -> Unit)
) {
Column {
if (label != null) {
Text(
text = label,
style = TextStyle(
fontSize = 14.sp,
lineHeight = 18.sp,
fontFamily = FontFamily(Font(R.font.roboto_regular)),
fontWeight = FontWeight(400),
color = Color(0xFF6D7885),
letterSpacing = 0.2.sp,
),
modifier = modifier.padding(start = 16.dp)
)
}
}
Row(
horizontalArrangement = Arrangement.spacedBy(0.dp, Alignment.Start),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.padding(start = 16.dp, bottom = 26.dp, top = 8.dp, end = 16.dp)
.border(
width = 0.5.dp,
color = Color(0x1F000000),
shape = RoundedCornerShape(size = 8.dp)
)
.height(44.dp)
.background(color = Color(0xFFF2F3F5), shape = RoundedCornerShape(size = 8.dp))
.padding(start = 12.dp, top = 12.dp, end = 12.dp, bottom = 12.dp)
) {
BasicTextField(
value = text,
onValueChange = onValueChange,
modifier = Modifier.fillMaxWidth(),
textStyle = TextStyle(
fontSize = 16.sp,
lineHeight = 20.sp,
fontFamily = FontFamily(Font(R.font.roboto_regular)),
fontWeight = FontWeight(400),
color = Color(0xFF303030),
letterSpacing = 0.1.sp,
),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = onSearch)
)
}
} | NativeAndroid/app/src/main/java/com/example/amsflights/MainActivity.kt | 2717699937 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.