path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/BindingAdapters.kt
1813625294
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.marsphotos import android.view.View import android.widget.ImageView import androidx.core.net.toUri import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.RecyclerView import coil.load import com.example.android.marsphotos.network.MarsPhoto import com.example.android.marsphotos.overview.MarsApiStatus import com.example.android.marsphotos.overview.PhotoGridAdapter /** * Updates the data shown in the [RecyclerView]. */ @BindingAdapter("listData") fun bindRecyclerView(recyclerView: RecyclerView, data: List<MarsPhoto>?) { val adapter = recyclerView.adapter as PhotoGridAdapter adapter.submitList(data) } /** * Uses the Coil library to load an image by URL into an [ImageView] */ @BindingAdapter("imageUrl") fun bindImage(imgView: ImageView, imgUrl: String?) { imgUrl?.let { val imgUri = imgUrl.toUri().buildUpon().scheme("https").build() imgView.load(imgUri) { placeholder(R.drawable.loading_animation) error(R.drawable.ic_broken_image) } } } /** * This binding adapter displays the [MarsApiStatus] of the network request in an image view. When * the request is loading, it displays a loading_animation. If the request has an error, it * displays a broken image to reflect the connection error. When the request is finished, it * hides the image view. */ @BindingAdapter("marsApiStatus") fun bindStatus(statusImageView: ImageView, status: MarsApiStatus) { when (status) { MarsApiStatus.LOADING -> { statusImageView.visibility = View.VISIBLE statusImageView.setImageResource(R.drawable.loading_animation) } MarsApiStatus.ERROR -> { statusImageView.visibility = View.VISIBLE statusImageView.setImageResource(R.drawable.ic_connection_error) } MarsApiStatus.DONE -> { statusImageView.visibility = View.GONE } } }
csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/network/MarsApiService.kt
4201349311
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.marsphotos.network import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.GET private const val BASE_URL = "https://android-kotlin-fun-mars-server.appspot.com/" /** * Build the Moshi object that Retrofit will be using, making sure to add the Kotlin adapter for * full Kotlin compatibility. */ private val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() /** * Use the Retrofit builder to build a retrofit object using a Moshi converter with our Moshi * object. */ private val retrofit = Retrofit.Builder() .addConverterFactory(MoshiConverterFactory.create(moshi)) .baseUrl(BASE_URL) .build() /** * A public interface that exposes the [getPhotos] method */ interface MarsApiService { /** * Returns a [List] of [MarsPhoto] and this method can be called from a Coroutine. * The @GET annotation indicates that the "photos" endpoint will be requested with the GET * HTTP method */ @GET("photos") suspend fun getPhotos(): List<MarsPhoto> } /** * A public Api object that exposes the lazy-initialized Retrofit service */ object MarsApi { val retrofitService: MarsApiService by lazy { retrofit.create(MarsApiService::class.java) } }
csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/network/MarsPhoto.kt
3722717877
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.marsphotos.network import com.squareup.moshi.Json /** * This data class defines a Mars photo which includes an ID, and the image URL. * The property names of this data class are used by Moshi to match the names of values in JSON. */ data class MarsPhoto( val id: String, // used to map img_src from the JSON to imgSrcUrl in our class @Json(name = "img_src") val imgSrcUrl: String )
csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/overview/OverviewFragment.kt
89015591
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.marsphotos.overview import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.example.android.marsphotos.databinding.FragmentOverviewBinding /** * This fragment shows the the status of the Mars photos web services transaction. */ class OverviewFragment : Fragment() { private val viewModel: OverviewViewModel by viewModels() /** * Inflates the layout with Data Binding, sets its lifecycle owner to the OverviewFragment * to enable Data Binding to observe LiveData, and sets up the RecyclerView with an adapter. */ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentOverviewBinding.inflate(inflater) // Allows Data Binding to Observe LiveData with the lifecycle of this Fragment binding.lifecycleOwner = this // Giving the binding access to the OverviewViewModel binding.viewModel = viewModel // Sets the adapter of the photosGrid RecyclerView binding.photosGrid.adapter = PhotoGridAdapter() return binding.root } }
csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/overview/PhotoGridAdapter.kt
2297339626
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.marsphotos.overview import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.android.marsphotos.databinding.GridViewItemBinding import com.example.android.marsphotos.network.MarsPhoto /** * This class implements a [RecyclerView] [ListAdapter] which uses Data Binding to present [List] * data, including computing diffs between lists. */ class PhotoGridAdapter : ListAdapter<MarsPhoto, PhotoGridAdapter.MarsPhotosViewHolder>(DiffCallback) { /** * The MarsPhotosViewHolder constructor takes the binding variable from the associated * GridViewItem, which nicely gives it access to the full [MarsPhoto] information. */ class MarsPhotosViewHolder( private var binding: GridViewItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(marsPhoto: MarsPhoto) { binding.photo = marsPhoto // This is important, because it forces the data binding to execute immediately, // which allows the RecyclerView to make the correct view size measurements binding.executePendingBindings() } } /** * Allows the RecyclerView to determine which items have changed when the [List] of * [MarsPhoto] has been updated. */ companion object DiffCallback : DiffUtil.ItemCallback<MarsPhoto>() { override fun areItemsTheSame(oldItem: MarsPhoto, newItem: MarsPhoto): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: MarsPhoto, newItem: MarsPhoto): Boolean { return oldItem.imgSrcUrl == newItem.imgSrcUrl } } /** * Create new [RecyclerView] item views (invoked by the layout manager) */ override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): MarsPhotosViewHolder { return MarsPhotosViewHolder( GridViewItemBinding.inflate(LayoutInflater.from(parent.context)) ) } /** * Replaces the contents of a view (invoked by the layout manager) */ override fun onBindViewHolder(holder: MarsPhotosViewHolder, position: Int) { val marsPhoto = getItem(position) holder.bind(marsPhoto) } }
csm3123-lab6/Lab6_MarsPhotoDisplayImage-master/app/src/main/java/com/example/android/marsphotos/overview/OverviewViewModel.kt
236331125
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.marsphotos.overview import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.android.marsphotos.network.MarsApi import com.example.android.marsphotos.network.MarsPhoto import kotlinx.coroutines.launch enum class MarsApiStatus { LOADING, ERROR, DONE } /** * The [ViewModel] that is attached to the [OverviewFragment]. */ class OverviewViewModel : ViewModel() { // The internal MutableLiveData that stores the status of the most recent request private val _status = MutableLiveData<MarsApiStatus>() // The external immutable LiveData for the request status val status: LiveData<MarsApiStatus> = _status // Internally, we use a MutableLiveData, because we will be updating the List of MarsPhoto // with new values private val _photos = MutableLiveData<List<MarsPhoto>>() // The external LiveData interface to the property is immutable, so only this class can modify val photos: LiveData<List<MarsPhoto>> = _photos /** * Call getMarsPhotos() on init so we can display status immediately. */ init { getMarsPhotos() } /** * Gets Mars photos information from the Mars API Retrofit service and updates the * [MarsPhoto] [List] [LiveData]. */ private fun getMarsPhotos() { viewModelScope.launch { _status.value = MarsApiStatus.LOADING try { _photos.value = MarsApi.retrofitService.getPhotos() _status.value = MarsApiStatus.DONE } catch (e: Exception) { _status.value = MarsApiStatus.ERROR _photos.value = listOf() } } } }
csm3123-lab6/Lab6_MarsPhotosRetrieveData-master/app/src/main/java/com/example/android/marsphotos/MainActivity.kt
892584274
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.marsphotos import android.os.Bundle import androidx.appcompat.app.AppCompatActivity /** * MainActivity sets the content view activity_main, a fragment container that contains * overviewFragment. */ class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
csm3123-lab6/Lab6_MarsPhotosRetrieveData-master/app/src/main/java/com/example/android/marsphotos/network/MarsApiService.kt
3765231990
package com.example.android.marsphotos.network import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.GET private const val BASE_URL = "https://android-kotlin-fun-mars-server.appspot.com" /** * Build the Moshi object with Kotlin adapter factory that Retrofit will be using. */ private val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() /** * The Retrofit object with the Moshi converter. */ private val retrofit = Retrofit.Builder() .addConverterFactory(MoshiConverterFactory.create(moshi)) .baseUrl(BASE_URL) .build() /** * A public interface that exposes the [getPhotos] method */ interface MarsApiService { /** * Returns a [List] of [MarsPhoto] and this method can be called from a Coroutine. * The @GET annotation indicates that the "photos" endpoint will be requested with the GET * HTTP method */ @GET("photos") suspend fun getPhotos() : List<MarsPhoto> } /** * A public Api object that exposes the lazy-initialized Retrofit service */ object MarsApi { val retrofitService: MarsApiService by lazy { retrofit.create(MarsApiService::class.java) } }
csm3123-lab6/Lab6_MarsPhotosRetrieveData-master/app/src/main/java/com/example/android/marsphotos/network/MarsPhoto.kt
4026924341
package com.example.android.marsphotos.network import com.squareup.moshi.Json /** * This data class defines a Mars photo which includes an ID, and the image URL. * The property names of this data class are used by Moshi to match the names of values in JSON. */ data class MarsPhoto( val id: String, @Json(name = "img_src") val imgSrcUrl: String )
csm3123-lab6/Lab6_MarsPhotosRetrieveData-master/app/src/main/java/com/example/android/marsphotos/overview/OverviewFragment.kt
3155813697
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.marsphotos.overview import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import com.example.android.marsphotos.databinding.FragmentOverviewBinding /** * This fragment shows the the status of the Mars photos web services transaction. */ class OverviewFragment : Fragment() { private val viewModel: OverviewViewModel by viewModels() /** * Inflates the layout with Data Binding, sets its lifecycle owner to the OverviewFragment * to enable Data Binding to observe LiveData, and sets up the RecyclerView with an adapter. */ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = FragmentOverviewBinding.inflate(inflater) // Allows Data Binding to Observe LiveData with the lifecycle of this Fragment binding.lifecycleOwner = this // Giving the binding access to the OverviewViewModel binding.viewModel = viewModel return binding.root } }
csm3123-lab6/Lab6_MarsPhotosRetrieveData-master/app/src/main/java/com/example/android/marsphotos/overview/OverviewViewModel.kt
3910161745
/* * Copyright (C) 2021 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.marsphotos.overview import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.android.marsphotos.network.MarsApi import kotlinx.coroutines.launch /** * The [ViewModel] that is attached to the [OverviewFragment]. */ class OverviewViewModel : ViewModel() { // The internal MutableLiveData that stores the status of the most recent request private val _status = MutableLiveData<String>() // The external immutable LiveData for the request status val status: LiveData<String> = _status /** * Call getMarsPhotos() on init so we can display status immediately. */ init { getMarsPhotos() } /** * Gets Mars photos information from the Mars API Retrofit service and updates the * [MarsPhoto] [List] [LiveData]. */ private fun getMarsPhotos() { viewModelScope.launch { try { val listResult = MarsApi.retrofitService.getPhotos() _status.value = "Success: ${listResult.size} Mars photos retrieved" } catch (e: Exception) { _status.value = "Failure: ${e.message}" } } } }
Add-User/app/src/androidTest/java/com/example/learnmvp/ExampleInstrumentedTest.kt
764863305
package com.example.learnmvp 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.learnmvp", appContext.packageName) } }
Add-User/app/src/androidTest/java/com/example/learnmvp/MainActivityTest.kt
4288106713
package com.example.learnmvp import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.example.learnmvp.view.alluser.MainActivity import com.example.learnmvp.view.random.RandomImageActivity import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class MainActivityTest { @get:Rule val mainActivity = ActivityScenarioRule(MainActivity::class.java) @Test fun testGotoRandomPage() { onView(withId(R.id.randomImage)).perform(click()) onView(withId(R.id.randomImageLayout)).check(matches(isDisplayed())) } }
Add-User/app/src/test/java/com/example/learnmvp/ExampleUnitTest.kt
2745523028
package com.example.learnmvp 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) } }
Add-User/app/src/test/java/com/example/learnmvp/MainPresenterTest.kt
1984383859
package com.example.learnmvp import com.example.learnmvp.data.local.dao.UserDao import com.example.learnmvp.data.local.entity.UserEntity import com.example.learnmvp.data.local.repository.UserRepository import com.example.learnmvp.data.local.repository.UserRepositoryImpl import com.example.learnmvp.data.remote.repository.RemoteRepository import com.example.learnmvp.view.alluser.MainPresenter import com.example.learnmvp.view.alluser.MainView import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runBlockingTest import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.mock import org.mockito.Mockito.`when` import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class MainPresenterTest { @Mock private lateinit var view : MainView.AllUserView private lateinit var presenter: MainPresenter lateinit var userDao: UserDao private lateinit var repository: UserRepositoryImpl @Before fun setup(){ userDao = mock(UserDao::class.java) repository = UserRepositoryImpl(userDao) presenter = MainPresenter(view, repository) } @Test fun `Test Get User`() = runTest { val listUser = listOf(UserEntity("jhoan", "[email protected]"), UserEntity("herlina", "panjaitan")) `when`( userDao.getAllUsers() ).thenReturn(listUser) val result = repository.getUsers() assertEquals(listUser, result) } }
Add-User/app/src/main/java/com/example/learnmvp/di/CacheModule.kt
568039503
package com.example.learnmvp.di import android.content.Context import com.example.learnmvp.data.local.dabase.UserDatabase import com.example.learnmvp.data.local.dao.UserDao import com.example.learnmvp.data.local.repository.UserRepository import com.example.learnmvp.data.local.repository.UserRepositoryImpl import com.example.learnmvp.data.remote.repository.RemoteRepository import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class CacheModule { @Provides @Singleton fun provideUserDatabase (@ApplicationContext context: Context) : UserDatabase { return UserDatabase.getDatabase(context) } @Provides @Singleton fun provideDao(userDatabase: UserDatabase) : UserDao { return userDatabase.userDao() } @Provides @Singleton fun provideRepository(userDao: UserDao) : UserRepository { return UserRepositoryImpl(userDao) } }
Add-User/app/src/main/java/com/example/learnmvp/di/NetworkModule.kt
1590235882
package com.example.learnmvp.di import com.example.learnmvp.data.remote.apiservice.ApiService import com.example.learnmvp.data.remote.repository.RemoteRepository import com.example.learnmvp.data.remote.repository.RemoteRepositoryImpl import com.google.gson.Gson import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class NetworkModule { val BASE_URL = "https://dog.ceo/api/" @Provides @Singleton fun provideHttpClient() : OkHttpClient { return OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build() } @Provides @Singleton fun provideRetrofit( httpClient: OkHttpClient ) : Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .client(httpClient) .addConverterFactory(GsonConverterFactory.create()) .build() } @Provides @Singleton fun provideApiService(retrofit: Retrofit) : ApiService { return retrofit.create(ApiService::class.java) } @Provides @Singleton fun providerRepository( apiService: ApiService ) : RemoteRepository { return RemoteRepositoryImpl(apiService) } }
Add-User/app/src/main/java/com/example/learnmvp/model/DataModel.kt
3738654821
package com.example.learnmvp.model data class DataModel( var name: String, val id: String, )
Add-User/app/src/main/java/com/example/learnmvp/view/alluser/MainActivity.kt
2865997308
package com.example.learnmvp.view.alluser import android.app.Activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.recyclerview.widget.LinearLayoutManager import com.example.learnmvp.data.local.dabase.UserDatabase import com.example.learnmvp.data.local.entity.UserEntity import com.example.learnmvp.data.local.repository.UserRepository import com.example.learnmvp.data.local.repository.UserRepositoryImpl import com.example.learnmvp.databinding.ActivityMainBinding import com.example.learnmvp.view.formuser.FormUserActivity import com.example.learnmvp.view.random.RandomImageActivity import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class MainActivity : AppCompatActivity(), MainView.AllUserView { lateinit var presenter: MainView.Presenter lateinit var binding: ActivityMainBinding lateinit var userAdapter: MainAdapter @Inject lateinit var userRepository: UserRepository lateinit var result: ActivityResultLauncher<Intent> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) initView() bindPresenter() } private fun initView(){ result = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if(result.resultCode == 123) { println("yes, it return 123") presenter.loadDataUser() } } presenter = MainPresenter(this, userRepository) presenter.loadDataUser() userAdapter = MainAdapter(object: MainAdapter.MainListener{ }) presenter.loadDataUser() } private fun bindPresenter() { binding.btnChangeData.setOnClickListener { presenter.goToInsertForm() } binding.randomImage.setOnClickListener { startActivity(Intent(this, RandomImageActivity::class.java)) } } override fun showListUser(users: List<UserEntity>) { binding.rvUsers.apply { adapter = userAdapter layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.VERTICAL, false) itemAnimator = null } userAdapter.updateUser(users) } override fun goToInsertPage() { val intent = Intent(this, FormUserActivity::class.java) result.launch(intent) } }
Add-User/app/src/main/java/com/example/learnmvp/view/alluser/MainAdapter.kt
1217464005
package com.example.learnmvp.view.alluser import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.learnmvp.data.local.entity.UserEntity import com.example.learnmvp.databinding.ItemUserBinding class MainAdapter (private val listener : MainListener) : RecyclerView.Adapter<MainAdapter.ViewHolder>() { private var listUser = mutableListOf<UserEntity>() fun updateUser(listUser: List<UserEntity>) { this.listUser = listUser as MutableList<UserEntity> notifyDataSetChanged() } class ViewHolder (private val binding: ItemUserBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(user: UserEntity){ binding.tvId.text = user.id.toString() binding.tvName.text = user.name binding.tvEmail.text = user.email } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val inflater = LayoutInflater.from(parent.context) val view = ItemUserBinding.inflate(inflater, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return listUser.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(listUser[position]) holder.itemView.setOnLongClickListener{ toggleSelection(position) true } } private fun toggleSelection(position: Int) { } interface MainListener { } }
Add-User/app/src/main/java/com/example/learnmvp/view/alluser/MainPresenter.kt
2267364769
package com.example.learnmvp.view.alluser import com.example.learnmvp.data.local.repository.UserRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject class MainPresenter @Inject constructor( private val allUserView: MainView.AllUserView, private val userRepository: UserRepository ) : MainView.Presenter { override fun loadDataUser() { CoroutineScope(Dispatchers.IO).launch { try { val data = userRepository.getUsers() withContext(Dispatchers.Main) { allUserView.showListUser(data) } } catch (e: java.lang.Exception) { e.printStackTrace() } } } override fun goToInsertForm() { allUserView.goToInsertPage() } }
Add-User/app/src/main/java/com/example/learnmvp/view/alluser/MainView.kt
364955085
package com.example.learnmvp.view.alluser import com.example.learnmvp.data.local.entity.UserEntity interface MainView { interface AllUserView { fun showListUser(users: List<UserEntity>) fun goToInsertPage() } interface Presenter { fun loadDataUser() fun goToInsertForm() } }
Add-User/app/src/main/java/com/example/learnmvp/view/random/RandomImageActivity.kt
3090430885
package com.example.learnmvp.view.random import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.bumptech.glide.Glide import com.example.learnmvp.data.remote.model.ApiResponse import com.example.learnmvp.data.remote.repository.RemoteRepository import com.example.learnmvp.databinding.ActivityRandomImageBinding import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class RandomImageActivity : AppCompatActivity(), RandomImage.RandomImageView { lateinit var binding : ActivityRandomImageBinding lateinit var presenter: RandomImage.Presenter @Inject lateinit var remoteRepository: RemoteRepository override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRandomImageBinding.inflate(layoutInflater) setContentView(binding.root) initView() } private fun initView() { presenter = RandomImagePresenter(remoteRepository, this) presenter.loadImage() } override fun showImage(response: ApiResponse?) { Glide.with(this) .load(response?.message) .into(binding.imgRandom) } override fun failedLoadImage() { Toast.makeText(this, "Failed To Load Image", Toast.LENGTH_SHORT).show() } override fun showLoading(b: Boolean) { if(b){ binding.pbItem.visibility = View.VISIBLE } else binding.pbItem.visibility = View.GONE } }
Add-User/app/src/main/java/com/example/learnmvp/view/random/RandomImagePresenter.kt
1888162378
package com.example.learnmvp.view.random import com.example.learnmvp.data.remote.repository.NetworkResult import com.example.learnmvp.data.remote.repository.RemoteRepository import kotlinx.coroutines.* import kotlinx.coroutines.flow.collect import javax.inject.Inject class RandomImagePresenter @Inject constructor( private val remoteRepository: RemoteRepository, private val view: RandomImage.RandomImageView ) : RandomImage.Presenter { override fun loadImage() { view.showLoading(true) CoroutineScope(Dispatchers.IO).launch { remoteRepository.getRandom().collect{ result -> when(result){ is NetworkResult.ErrorResponse -> { withContext(Dispatchers.Main){ view.showLoading(false) view.failedLoadImage() } } is NetworkResult.Success -> { withContext(Dispatchers.Main){ view.showLoading(false) view.showImage(result.data) } } } } } } }
Add-User/app/src/main/java/com/example/learnmvp/view/random/RandomImage.kt
1987085915
package com.example.learnmvp.view.random import com.example.learnmvp.data.remote.model.ApiResponse interface RandomImage { interface RandomImageView { fun showImage(response: ApiResponse?) fun failedLoadImage() fun showLoading(b: Boolean) } interface Presenter { fun loadImage() } }
Add-User/app/src/main/java/com/example/learnmvp/view/formuser/FormUserActivity.kt
1227636264
package com.example.learnmvp.view.formuser import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ActionMenuView import android.widget.Toast import com.example.learnmvp.R import com.example.learnmvp.data.local.dabase.UserDatabase import com.example.learnmvp.data.local.dao.UserDao import com.example.learnmvp.data.local.entity.UserEntity import com.example.learnmvp.data.local.repository.UserRepository import com.example.learnmvp.data.local.repository.UserRepositoryImpl import com.example.learnmvp.databinding.ActivityFormUserBinding import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class FormUserActivity : AppCompatActivity(), FormUser.UserView { lateinit var formUserPresenter: FormUserPresenter lateinit var binding: ActivityFormUserBinding @Inject lateinit var userRepository: UserRepository override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityFormUserBinding.inflate(layoutInflater) setContentView(binding.root) initView() initFields() initPresenter() } private fun initView() { formUserPresenter = FormUserPresenter(this, userRepository) } private fun initFields() { binding.btnInputUser.setOnClickListener { formUserPresenter.createUser(binding.name.text.toString(), binding.email.text.toString()) } } private fun initPresenter() { } override fun showError() { } override fun showLoading() { } override fun successAddUser() { Toast.makeText(this, "Success Add User", Toast.LENGTH_SHORT).show() setResult(123) finish() } override fun failedAddUser() { Toast.makeText(this, "Failed Add User", Toast.LENGTH_SHORT).show() } }
Add-User/app/src/main/java/com/example/learnmvp/view/formuser/FormUserPresenter.kt
214739608
package com.example.learnmvp.view.formuser import com.example.learnmvp.data.local.entity.UserEntity import com.example.learnmvp.data.local.repository.UserRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class FormUserPresenter( private val view: FormUser.UserView, private val repository: UserRepository ) : FormUser.UserPresenter { override fun insertUser(user: UserEntity) { CoroutineScope(Dispatchers.IO) .launch { try { repository.insertUser(user) withContext(Dispatchers.Main) { view.successAddUser() } } catch (e: java.lang.Exception) { e.printStackTrace() withContext(Dispatchers.Main) { view.failedAddUser() } } } } fun createUser(name: String, email: String) { val user = UserEntity(name, email) CoroutineScope(Dispatchers.IO) .launch { try { repository.insertUser(user) withContext(Dispatchers.Main) { view.successAddUser() } } catch (e: Exception) { e.printStackTrace() view.failedAddUser() } } } }
Add-User/app/src/main/java/com/example/learnmvp/view/formuser/FormUser.kt
3089522410
package com.example.learnmvp.view.formuser import com.example.learnmvp.data.local.entity.UserEntity interface FormUser { interface UserView { fun showError() fun showLoading() fun successAddUser() fun failedAddUser() } interface UserPresenter { fun insertUser(user: UserEntity) } }
Add-User/app/src/main/java/com/example/learnmvp/data/local/repository/UserRepository.kt
1515593274
package com.example.learnmvp.data.local.repository import com.example.learnmvp.data.local.dao.UserDao import com.example.learnmvp.data.local.entity.UserEntity interface UserRepository { suspend fun getUsers() : List<UserEntity> suspend fun insertUser(user: UserEntity) suspend fun deleteUser(id: String) }
Add-User/app/src/main/java/com/example/learnmvp/data/local/repository/UserRepositoryImpl.kt
3994149812
package com.example.learnmvp.data.local.repository import com.example.learnmvp.data.local.dao.UserDao import com.example.learnmvp.data.local.entity.UserEntity import javax.inject.Inject class UserRepositoryImpl @Inject constructor(private val userDao: UserDao) : UserRepository { override suspend fun getUsers(): List<UserEntity> { return userDao.getAllUsers() } override suspend fun insertUser(user: UserEntity) { return userDao.insertUser(user) } override suspend fun deleteUser(id: String) { return userDao.deleteUser(id) } }
Add-User/app/src/main/java/com/example/learnmvp/data/local/dabase/UserDatabase.kt
2787128254
package com.example.learnmvp.data.local.dabase import android.content.Context import android.service.autofill.UserData import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.learnmvp.data.local.dao.UserDao import com.example.learnmvp.data.local.entity.UserEntity @Database(entities = [UserEntity::class], version = 1, exportSchema = false) abstract class UserDatabase : RoomDatabase(){ abstract fun userDao(): UserDao companion object { @Volatile private var INSTANCE : UserDatabase? = null fun getDatabase(context: Context): UserDatabase { return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, UserDatabase::class.java, "my_app_database" ).build() INSTANCE = instance instance } } } }
Add-User/app/src/main/java/com/example/learnmvp/data/local/entity/UserEntity.kt
704647921
package com.example.learnmvp.data.local.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "users") data class UserEntity( @ColumnInfo(name = "name") val name: String, @ColumnInfo(name = "email") val email: String, ) { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Int = 0 }
Add-User/app/src/main/java/com/example/learnmvp/data/local/dao/UserDao.kt
846030611
package com.example.learnmvp.data.local.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import com.example.learnmvp.data.local.entity.UserEntity @Dao interface UserDao { @Query("SELECT * FROM users") suspend fun getAllUsers() : List<UserEntity> @Insert suspend fun insertUser(user: UserEntity) @Query("DELETE FROM users WHERE id = :userId") suspend fun deleteUser(userId: String) }
Add-User/app/src/main/java/com/example/learnmvp/data/remote/repository/RemoteRepositoryImpl.kt
1143363867
package com.example.learnmvp.data.remote.repository import android.view.KeyEvent.DispatcherState import com.example.learnmvp.data.remote.apiservice.ApiService import com.example.learnmvp.data.remote.model.ApiResponse import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.withContext import javax.inject.Inject class RemoteRepositoryImpl @Inject constructor(private val apiService: ApiService) : RemoteRepository { override fun getRandom(): Flow<NetworkResult<ApiResponse>> { return flow { try { val response = apiService.getRandomDog() if(response.isSuccessful) { emit(NetworkResult.Success<ApiResponse>(response.body())) } else{ emit(NetworkResult.ErrorResponse("Failed get Image")) } }catch (e: java.lang.Exception){ throw e } }.catch { e -> emit(NetworkResult.ErrorResponse(e.message.orEmpty())) }.flowOn(Dispatchers.IO) } }
Add-User/app/src/main/java/com/example/learnmvp/data/remote/repository/NetworkResult.kt
2509548164
package com.example.learnmvp.data.remote.repository import com.example.learnmvp.data.remote.model.ApiResponse sealed class NetworkResult<out T> { class Success<out T>(val data : ApiResponse? = null) : NetworkResult<T>() class ErrorResponse(val message: String ?= null): NetworkResult<Nothing>() }
Add-User/app/src/main/java/com/example/learnmvp/data/remote/repository/RemoteRepository.kt
1294940396
package com.example.learnmvp.data.remote.repository import com.example.learnmvp.data.remote.model.ApiResponse import kotlinx.coroutines.flow.Flow interface RemoteRepository{ fun getRandom() : Flow<NetworkResult<ApiResponse>> }
Add-User/app/src/main/java/com/example/learnmvp/data/remote/model/ApiResponse.kt
3319207011
package com.example.learnmvp.data.remote.model import com.google.gson.annotations.SerializedName data class ApiResponse ( @SerializedName("message") val message: String, @SerializedName("status") val success: String, )
Add-User/app/src/main/java/com/example/learnmvp/data/remote/apiservice/ApiService.kt
1683242684
package com.example.learnmvp.data.remote.apiservice import com.example.learnmvp.data.remote.model.ApiResponse import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Url interface ApiService { @GET("breeds/image/random") suspend fun getRandomDog() : Response<ApiResponse> }
Add-User/app/src/main/java/com/example/learnmvp/LearnApplication.kt
4042645640
package com.example.learnmvp import android.app.Activity import android.app.Application import android.os.Bundle import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class LearnApplication : Application(), Application.ActivityLifecycleCallbacks{ override fun onActivityCreated(p0: Activity, p1: Bundle?) { println(" on activity crated") } override fun onActivityStarted(p0: Activity) { println("on activity started") } override fun onActivityResumed(p0: Activity) { println("on activityResumed") } override fun onActivityPaused(p0: Activity) { println("on activity paused") } override fun onActivityStopped(p0: Activity) { println("on activity stopped") } override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) { println("on activity saveInstance") } override fun onActivityDestroyed(p0: Activity) { println("on activity destroyed") } }
Upcoming-Movies/app/src/androidTest/java/com/samueljuma/upcomingmovies/ExampleInstrumentedTest.kt
1743107209
package com.samueljuma.upcomingmovies 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.samueljuma.upcomingmovies", appContext.packageName) } }
Upcoming-Movies/app/src/test/java/com/samueljuma/upcomingmovies/ExampleUnitTest.kt
857797672
package com.samueljuma.upcomingmovies 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) } }
Upcoming-Movies/app/src/main/java/com/samueljuma/upcomingmovies/MainActivity.kt
2714411482
package com.samueljuma.upcomingmovies import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_main) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } } }
Android-Architectures/MVIApp/app/src/androidTest/java/com/example/mviapp/ExampleInstrumentedTest.kt
2121896536
package com.example.mviapp 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.mviapp", appContext.packageName) } }
Android-Architectures/MVIApp/app/src/test/java/com/example/mviapp/ExampleUnitTest.kt
2961496136
package com.example.mviapp 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) } }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/ui/theme/Color.kt
1603509236
package com.example.mviapp.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)
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/ui/theme/Theme.kt
1995623631
package com.example.mviapp.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 MVIAppTheme( 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 ) }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/ui/theme/Type.kt
3321522997
package com.example.mviapp.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 ) */ )
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/MainActivity.kt
2378851943
package com.example.mviapp import android.os.Bundle import android.widget.Toast import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModelProviders import androidx.lifecycle.lifecycleScope import coil.compose.rememberImagePainter import com.example.mviapp.api.AnimalService import com.example.mviapp.model.Animal import com.example.mviapp.ui.theme.MVIAppTheme import com.example.mviapp.view.MainIntent import com.example.mviapp.view.MainState import com.example.mviapp.view.MainViewModel import com.example.mviapp.view.ViewModelFactory import kotlinx.coroutines.launch class MainActivity : FragmentActivity() { private lateinit var mainViewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mainViewModel = ViewModelProviders .of(this, ViewModelFactory(AnimalService.api)) .get(MainViewModel::class.java) val onButtonClick: () -> Unit = { lifecycleScope.launch { mainViewModel.userIntent.send(MainIntent.FetchAnimal) } } setContent { MVIAppTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { MainScreen(viewModel = mainViewModel, onButtonClick = onButtonClick) } } } } } @Composable fun MainScreen(viewModel: MainViewModel, onButtonClick: () -> Unit) { val state = viewModel.state.value when (state) { is MainState.Idle -> IdleScreen(onButtonClick = onButtonClick) is MainState.Loading -> LoadingScreen() is MainState.Animals -> AnimalList(animals = state.animals) is MainState.Error -> { IdleScreen(onButtonClick = onButtonClick) Toast.makeText(LocalContext.current, state.error, Toast.LENGTH_SHORT).show() } } } @Composable fun IdleScreen(onButtonClick: () -> Unit) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Button(onClick = onButtonClick) { Text(text = "Fetch Animals") } } } @Composable fun LoadingScreen() { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { CircularProgressIndicator() } } @Composable fun AnimalList(animals: List<Animal>) { LazyColumn { items(items = animals) { AnimalItem(animal = it) Divider(color = Color.LightGray, modifier = Modifier.padding(vertical = 4.dp)) } } } @Composable fun AnimalItem(animal: Animal) { Row( modifier = Modifier .fillMaxWidth() .height(100.dp) ) { val url = AnimalService.BASE_URL + animal.image val painter = rememberImagePainter(data = url) Image( painter = painter, contentDescription = null, modifier = Modifier.size(100.dp), contentScale = ContentScale.FillHeight ) Column( modifier = Modifier .fillMaxSize() .padding(start = 4.dp) ) { Text(text = animal.name, fontWeight = FontWeight.Bold) Text(text = animal.location) } } }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/model/Animal.kt
1103851502
package com.example.mviapp.model data class Animal( val name: String = "", val location: String = "", val image: String = "" )
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/view/MainViewModel.kt
3501329836
package com.example.mviapp.view import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.mviapp.api.AnimalRepository import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.launch class MainViewModel(private val animalRepository: AnimalRepository) : ViewModel() { val userIntent = Channel<MainIntent>(Channel.UNLIMITED) var state = mutableStateOf<MainState>(MainState.Idle) private set init { handleIntent() } private fun handleIntent() { viewModelScope.launch { userIntent.consumeAsFlow().collect { collector -> when (collector) { is MainIntent.FetchAnimal -> fetchAnimals() } } } } private fun fetchAnimals() { viewModelScope.launch { state.value = MainState.Loading state.value = try { MainState.Animals(animalRepository.getAnimals()) } catch (e: Exception) { e.printStackTrace() MainState.Error(e.localizedMessage) } } } }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/view/MainState.kt
407557533
package com.example.mviapp.view import com.example.mviapp.model.Animal sealed class MainState { data object Idle : MainState() data object Loading : MainState() data class Animals(val animals: List<Animal>) : MainState() data class Error(val error: String?) : MainState() }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/view/ViewModelFactory.kt
2493094996
package com.example.mviapp.view import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.mviapp.api.AnimalApi import com.example.mviapp.api.AnimalRepository class ViewModelFactory(private val api: AnimalApi) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MainViewModel::class.java)) { return MainViewModel(AnimalRepository(api)) as T } throw IllegalArgumentException("Unknown class name") } }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/view/MainIntent.kt
958450864
package com.example.mviapp.view sealed class MainIntent { data object FetchAnimal : MainIntent() }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/api/AnimalService.kt
2624634530
package com.example.mviapp.api import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object AnimalService { const val BASE_URL = "https://raw.githubusercontent.com/CatalinStefan/animalApi/master/" private fun getRetrofit() = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() val api: AnimalApi = getRetrofit().create(AnimalApi::class.java) }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/api/AnimalApi.kt
2268741462
package com.example.mviapp.api import com.example.mviapp.model.Animal import retrofit2.http.GET interface AnimalApi { @GET("animals.json") suspend fun getAnimals(): List<Animal> }
Android-Architectures/MVIApp/app/src/main/java/com/example/mviapp/api/AnimalRepository.kt
2792167888
package com.example.mviapp.api import com.example.mviapp.model.Animal class AnimalRepository(private val api: AnimalApi) { suspend fun getAnimals(): List<Animal> = api.getAnimals() }
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/ui/theme/Color.kt
1258427492
package com.alperen.statesamancioglu.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)
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/ui/theme/Theme.kt
4223095565
package com.alperen.statesamancioglu.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 StateSamanciogluTheme( 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 ) }
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/ui/theme/Type.kt
2295007732
package com.alperen.statesamancioglu.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 ) */ )
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/MainActivity.kt
542241386
package com.alperen.statesamancioglu 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.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.alperen.statesamancioglu.ui.theme.StateSamanciogluTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { StateSamanciogluTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val navController = rememberNavController() NavHost(navController = navController, startDestination ="firstScreen" ) { composable(route = "firstScreen") { val viewModel = viewModel<FirstScreenVM>() val time by viewModel.counter.collectAsStateWithLifecycle() //bu lifecycle'a saygı duyar. //.collectAsState() //lifecycle awareness değil. FirstScreen(time = time, onButtonClicked = { navController.navigate("secondScreen") } ) } composable(route= "secondScreen") { SecondScreen() } } } } } } }
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/FirstScreenVM.kt
3858069072
package com.alperen.statesamancioglu import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.stateIn class FirstScreenVM:ViewModel() { private var count = 0 val counter = flow { while (true) { delay(1000L) println("Running Flow") emit(count++) } }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(10000),0) }
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/secondScreen.kt
4170756210
package com.alperen.statesamancioglu import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun SecondScreen(){ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) { Text(text = "Second Screen", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Center, modifier = Modifier.padding(2.dp) ) } }
stateSamancioglu/app/src/main/java/com/alperen/statesamancioglu/FirstScreen.kt
4258706048
package com.alperen.statesamancioglu import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun FirstScreen(time: Int, onButtonClicked:()->Unit){ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) { Text(text = time.toString(), style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.primary, textAlign = TextAlign.Center, modifier = Modifier.padding(2.dp).clickable(onClick = onButtonClicked) ) } }
kotlin-fabric-mod-template/src/main/kotlin/net/projecttl/mod/example/mixin/ExampleMixin.kt
3833756619
package net.projecttl.mod.example.mixin import net.minecraft.client.gui.screen.TitleScreen import org.spongepowered.asm.mixin.Mixin import org.spongepowered.asm.mixin.injection.At import org.spongepowered.asm.mixin.injection.Inject import org.spongepowered.asm.mixin.injection.callback.CallbackInfo @Mixin(TitleScreen::class) class ExampleMixin { @Inject(at = [At("HEAD")], method = ["init()V"]) private fun init(info: CallbackInfo) { println("This line is printed by an example mod mixin!") } }
kotlin-fabric-mod-template/src/main/kotlin/net/projecttl/mod/example/ExampleMod.kt
3847905308
package net.projecttl.mod.example import net.fabricmc.api.ModInitializer import org.slf4j.LoggerFactory class ExampleMod : ModInitializer { val logger = LoggerFactory.getLogger("ExampleMod") override fun onInitialize() { TODO("Not yet implemented") } }
pivot-control/app/src/androidTest/java/com/example/controlpivot/ExampleInstrumentedTest.kt
931896525
package com.example.controlpivot 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.controlpivot", appContext.packageName) } }
pivot-control/app/src/test/java/com/example/controlpivot/ExampleUnitTest.kt
3631547911
package com.example.controlpivot 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) } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/viewmodel/SplashViewModel.kt
2448980935
package com.example.controlpivot.ui.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.controlpivot.data.repository.SessionRepository import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Job import kotlinx.coroutines.launch class SplashViewModel(private val sessionRepository: SessionRepository): ViewModel() { private val _isLogged = MutableLiveData<Boolean?>(null) val isLogged: LiveData<Boolean?> = _isLogged var job: Job? = null fun checkLogin(){ job?.cancel() job = viewModelScope.launch{ when(val result = sessionRepository.getSession()){ is Resource.Error -> _isLogged.postValue(false) is Resource.Success -> { _isLogged.postValue(true) } } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/viewmodel/PivotMachineViewModel.kt
649942019
package com.example.controlpivot.ui.viewmodel import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.controlpivot.ConnectivityObserver import com.example.controlpivot.NetworkConnectivityObserver import com.example.controlpivot.R import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.data.local.model.MachinePendingDelete import com.example.controlpivot.data.local.model.PivotMachineEntity import com.example.controlpivot.data.remote.datasource.PivotMachineRemoteDatasource import com.example.controlpivot.data.repository.MachinePendingDeleteRepository import com.example.controlpivot.data.repository.PivotMachineRepository import com.example.controlpivot.data.repository.SessionRepository import com.example.controlpivot.domain.usecase.DeletePendingMachineUseCase import com.example.controlpivot.ui.screen.createpivot.PivotMachineEvent import com.example.controlpivot.ui.screen.createpivot.PivotMachineState import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class PivotMachineViewModel( private val connectivityObserver: NetworkConnectivityObserver, private val pivotMachineRepository: PivotMachineRepository, private val sessionRepository: SessionRepository, private val pendingDeleteUseCase: DeletePendingMachineUseCase, private val machinePendingDeleteRepository: MachinePendingDeleteRepository, private val pivotMachineRemoteDatasource: PivotMachineRemoteDatasource, ) : ViewModel() { private var session: Session? = null private var _networkStatus = ConnectivityObserver.Status.Available private var getCurrentMachineJob: Job? = null private var deleteMachineJob: Job? = null private var getMachinesByNameJob: Job? = null private var registerMachineJob: Job? = null private var getSessionJob: Job? = null private var refreshDataJob: Job? = null private var networkObserverJob: Job? = null private val _state = MutableStateFlow(PivotMachineState()) val state = _state.asStateFlow() private val _event = MutableSharedFlow<Event>() val event = _event.asSharedFlow() sealed class Event() { class ShowMessage(val message: Message) : Event() data object PivotMachineCreated : Event() } init { loadSession() getPivotMachineByName() observeNetworkChange() refreshData() } fun onEvent(event: PivotMachineEvent) { when (event) { is PivotMachineEvent.DeleteMachine -> { deleteMachine(event.machineId) } is PivotMachineEvent.ResetDataMachine -> { _state.update { it.copy(currentMachine = PivotMachineEntity()) } } is PivotMachineEvent.SelectMachine -> { getCurrentMachine(event.id) } is PivotMachineEvent.CreateMachine -> { registerPivotMachine(event.machine) } is PivotMachineEvent.SearchMachine -> { getPivotMachineByName(event.query) } } } fun refreshData() { refreshDataJob?.cancel() refreshDataJob = viewModelScope.launch(Dispatchers.IO) { _state.update { it.copy(isLoading = true) } if (isNetworkAvailable()) { pivotMachineRepository.registerPendingMachines() pendingDeleteUseCase() if (pivotMachineRepository.arePendingPivotMachines()) reloadPivotMachines() } _state.update { it.copy(isLoading = false) } } } private suspend fun reloadPivotMachines() { val result = pivotMachineRepository.fetchPivotMachine() if (result is Resource.Error) _event.emit(Event.ShowMessage(result.message)) } private fun loadSession() { getSessionJob?.cancel() getSessionJob = viewModelScope.launch(Dispatchers.IO) { when (val result = sessionRepository.getSession()) { is Resource.Error -> { _event.emit(Event.ShowMessage(result.message)) } is Resource.Success -> session = result.data } } } private fun registerPivotMachine(machine: PivotMachineEntity) { registerMachineJob?.cancel() registerMachineJob = viewModelScope.launch(Dispatchers.IO) { if (machine.name == "" || machine.location == "" || machine.endowment == 0.0 || machine.flow == 0.0 || machine.pressure == 0.0 || machine.area == 0.0 || machine.length == 0.0 || machine.power == 0.0 || machine.efficiency == 0.0 || machine.speed == 0.0 ) { _event.emit( Event.ShowMessage(Message.StringResource(R.string.values_are_required))) return@launch } else { when (val result = pivotMachineRepository.upsertPivotMachine(machine)) { is Resource.Error -> _event.emit(Event.ShowMessage(result.message)) is Resource.Success -> { _event.emit(Event.PivotMachineCreated) if (isNetworkAvailable()) { when (val response = pivotMachineRepository.savePivotMachine(result.data)) { is Resource.Error -> _event.emit(Event.ShowMessage(response.message)) is Resource.Success -> {} } } } } } } } private suspend fun isNetworkAvailable(): Boolean { if (_networkStatus != ConnectivityObserver.Status.Available) { _event.emit( Event.ShowMessage(Message.StringResource(R.string.internet_error))) return false } return true } private fun getPivotMachineByName(query: String = "") { getMachinesByNameJob?.cancel() getMachinesByNameJob = viewModelScope.launch(Dispatchers.IO) { pivotMachineRepository.getAllPivotMachines(query).collectLatest { result -> when (result) { is Resource.Error -> _event.emit(Event.ShowMessage(result.message)) is Resource.Success -> _state.update { it.copy(machines = result.data) } } } } } private fun getCurrentMachine(id: Int) { getCurrentMachineJob?.cancel() getCurrentMachineJob = viewModelScope.launch(Dispatchers.IO) { pivotMachineRepository.getPivotMachineAsync(id).onEach { result -> when (result) { is Resource.Error -> _event.emit(Event.ShowMessage(result.message)) is Resource.Success -> _state.update { it.copy(currentMachine = result.data) } } }.collect() } } private fun deleteMachine(machineId: Int) { deleteMachineJob?.cancel() deleteMachineJob = viewModelScope.launch(Dispatchers.IO) { when (val response = pivotMachineRepository.getPivotMachine(machineId)) { is Resource.Error -> _event.emit(Event.ShowMessage(response.message)) is Resource.Success -> { val result = pivotMachineRepository.deletePivotMachine(machineId) if (result is Resource.Error) _event.emit(Event.ShowMessage(result.message)) else { if (response.data.isSave) { val machinePendingDelete = when (val result = machinePendingDeleteRepository.getPendingDelete()) { is Resource.Error -> MachinePendingDelete() is Resource.Success -> result.data } if (isNetworkAvailable()) { pivotMachineRemoteDatasource.deletePivotMachine(response.data.remoteId) } else { val listId = machinePendingDelete.listId.toMutableList() listId.add(response.data.remoteId) when (val resultDelete = machinePendingDeleteRepository.savePendingDelete( MachinePendingDelete(listId) )) { is Resource.Error -> _event.emit( Event.ShowMessage(resultDelete.message) ) is Resource.Success -> { } } } } _event.emit( Event.ShowMessage( Message.StringResource(R.string.machine_deleted) ) ) } } } } } private fun observeNetworkChange() { networkObserverJob?.cancel() networkObserverJob = viewModelScope.launch(Dispatchers.IO) { connectivityObserver.observe().collectLatest { status -> _networkStatus = status } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/viewmodel/LoginViewModel.kt
2759395208
package com.example.controlpivot.ui.viewmodel import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.controlpivot.ConnectivityObserver import com.example.controlpivot.NetworkConnectivityObserver import com.example.controlpivot.R import com.example.controlpivot.data.common.model.Session import com.example.controlpivot.data.repository.SessionRepository import com.example.controlpivot.ui.screen.login.Credentials import com.example.controlpivot.ui.screen.login.LoginEvent import com.example.controlpivot.ui.screen.login.LoginState import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class LoginViewModel( private val sessionRepository: SessionRepository, private val connectivityObserver: NetworkConnectivityObserver ) : ViewModel() { private var loginJob: Job? = null private var networkObserverJob: Job? = null private var changeCredentialsJob: Job? = null private var getSessionJob: Job? = null private val _state = MutableStateFlow(LoginState()) val state = _state.asStateFlow() private val _message = MutableSharedFlow<Message>() val message = _message.asSharedFlow() private val _isLogged = MutableLiveData(false) val isLogged: LiveData<Boolean> = _isLogged private var _networkStatus = ConnectivityObserver.Status.Available private var session: Session? = null init { loadSession() observeNetworkChange() } fun onEvent(event: LoginEvent) { when (event) { is LoginEvent.Login -> login(event.credentials) is LoginEvent.ChangeCredentials -> changeCredentials(event.credentials) } } private fun changeCredentials(credentials: Credentials) { changeCredentialsJob?.cancel() changeCredentialsJob = viewModelScope.launch(Dispatchers.IO) { credentials.validate().let { result -> if (result is Resource.Error) { _message.emit(result.message) return@launch } } if (!isNetworkAvalible()) return@launch _state.update { it.copy(isLoading = true) } when (val result = sessionRepository.updateSession( credentials )) { is Resource.Error -> { _state.update { it.copy(isLoading = false) } _message.emit(result.message) } is Resource.Success -> { _isLogged.postValue(true) _message.emit(Message.StringResource(R.string.update_success)) } } } } fun login(credentials: Credentials) { loginJob?.cancel() loginJob = viewModelScope.launch(Dispatchers.IO) { credentials.validate().let { result -> if (result is Resource.Error) { _message.emit(result.message) return@launch } } if (!isNetworkAvalible()) return@launch _state.update { it.copy(isLoading = true) } when (val result = sessionRepository.fetchSession( credentials )) { is Resource.Error -> { _state.update { it.copy(isLoading = false) } _message.emit(result.message) } is Resource.Success -> { _isLogged.postValue(true) } } } } private suspend fun isNetworkAvalible(): Boolean { if (_networkStatus != ConnectivityObserver.Status.Available) { _message.emit(Message.StringResource(R.string.internet_error)) return false } return true } private fun observeNetworkChange() { networkObserverJob?.cancel() networkObserverJob = viewModelScope.launch(Dispatchers.IO) { connectivityObserver.observe().collectLatest { status -> _networkStatus = status } } } fun loadSession() { getSessionJob?.cancel() getSessionJob = viewModelScope.launch(Dispatchers.IO) { when (val result = sessionRepository.getSession()) { is Resource.Error -> { _message.emit(result.message) } is Resource.Success -> { Log.d("LOG", result.data.toString()) _state.update { it.copy(session = result.data) }} } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/viewmodel/ClimateViewModel.kt
3131310096
package com.example.controlpivot.ui.viewmodel import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.controlpivot.ConnectivityObserver import com.example.controlpivot.NetworkConnectivityObserver import com.example.controlpivot.R import com.example.controlpivot.data.repository.ClimateRepository import com.example.controlpivot.domain.usecase.GetIdPivotNameUseCase import com.example.controlpivot.ui.screen.climate.ClimateEvent import com.example.controlpivot.ui.screen.climate.ClimateState import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import java.time.LocalDateTime import java.time.format.DateTimeFormatter class ClimateViewModel( private val climateRepository: ClimateRepository, private val connectivityObserver: NetworkConnectivityObserver, private val getIdPivotNameUseCase: GetIdPivotNameUseCase, ) : ViewModel() { private var _networkStatus = ConnectivityObserver.Status.Available private var networkObserverJob: Job? = null private var selectByIdPivotJob: Job? = null private var getClimatesJob: Job? = null private var getIdPivotNameListJob: Job? = null private var refreshDataJob: Job? = null private val _state = MutableStateFlow(ClimateState()) val state = _state.asStateFlow() private val _message = MutableSharedFlow<Message>() val message = _message.asSharedFlow() init { getClimates() getIdPivotNameList() observeNetworkChange() } @RequiresApi(Build.VERSION_CODES.O) fun onEvent(event: ClimateEvent) { when (event) { is ClimateEvent.SelectClimateByIdPivot -> selectByIdPivot(event.id) } } private fun getIdPivotNameList(query: String = "") { getIdPivotNameListJob?.cancel() getIdPivotNameListJob = viewModelScope.launch(Dispatchers.IO) { getIdPivotNameUseCase(query).collectLatest { result -> when (result) { is Resource.Error -> _message.emit(result.message) is Resource.Success -> _state.update { it.copy(idPivotList = result.data) } } } } } @RequiresApi(Build.VERSION_CODES.O) private fun selectByIdPivot(id: Int) { selectByIdPivotJob?.cancel() selectByIdPivotJob = viewModelScope.launch(Dispatchers.IO) { when (val result = climateRepository.getClimatesById(id)) { is Resource.Error -> {} is Resource.Success -> _state.update { climateState -> val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val listTime = result.data.map { LocalDateTime.parse(it.timestamp, formatter) } val timeMostRecently = listTime.maxByOrNull { it } val climate = result.data.find { it.timestamp == timeMostRecently!!.format(formatter) } climateState.copy(currentClimate = climate) } } Log.d("OneClimate", _state.value.currentClimate.toString()) } } fun refreshData() { refreshDataJob?.cancel() refreshDataJob = viewModelScope.launch(Dispatchers.IO) { _state.update { it.copy(isLoading = true) } if (isNetworkAvailable()) { getClimates() } _state.update { it.copy(isLoading = false) } } } private fun getClimates() { getClimatesJob?.cancel() getClimatesJob = viewModelScope.launch(Dispatchers.IO) { if (climateRepository.fetchClimate() is Resource.Success) { climateRepository.getAllClimates("").collectLatest { result -> when (result) { is Resource.Error -> _message.emit(result.message) is Resource.Success -> { _state.update { it.copy(climates = result.data) } } } } } } } private suspend fun isNetworkAvailable(): Boolean { if (_networkStatus != ConnectivityObserver.Status.Available) { _message.emit(Message.StringResource(R.string.internet_error)) return false } return true } private fun observeNetworkChange() { networkObserverJob?.cancel() networkObserverJob = viewModelScope.launch(Dispatchers.IO) { connectivityObserver.observe().collectLatest { status -> _networkStatus = status } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/viewmodel/PivotControlViewModel.kt
3502989793
package com.example.controlpivot.ui.viewmodel import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.controlpivot.ConnectivityObserver import com.example.controlpivot.NetworkConnectivityObserver import com.example.controlpivot.R import com.example.controlpivot.data.local.model.PivotControlEntity import com.example.controlpivot.data.local.model.SectorControl import com.example.controlpivot.data.repository.PivotControlRepository import com.example.controlpivot.domain.usecase.GetIdPivotNameUseCase import com.example.controlpivot.domain.usecase.GetPivotControlsWithSectorsUseCase import com.example.controlpivot.ui.screen.pivotcontrol.ControlEvent import com.example.controlpivot.ui.screen.pivotcontrol.ControlState import com.example.controlpivot.utils.Message import com.example.controlpivot.utils.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class PivotControlViewModel( private val connectivityObserver: NetworkConnectivityObserver, private val controlRepository: PivotControlRepository, private val getIdPivotNameUseCase: GetIdPivotNameUseCase, private val getPivotControlsWithSectorsUseCase: GetPivotControlsWithSectorsUseCase, ) : ViewModel() { private var _networkStatus = ConnectivityObserver.Status.Available private var saveControlsJob: Job? = null private var saveSectorsJob: Job? = null private var networkObserverJob: Job? = null private var selectByIdPivotJob: Job? = null private var getIdPivotNameListJob: Job? = null private var getPivotControls: Job? = null private var showMessageJob: Job? = null private var refreshDataJob: Job? = null private val _state = MutableStateFlow(ControlState()) val state = _state.asStateFlow() private val _message = MutableSharedFlow<Message>() val message = _message.asSharedFlow() init { observeNetworkChange() getIdPivotNameList() getPivotControls() refreshData() } fun onEvent(event: ControlEvent) { when (event) { is ControlEvent.SaveControls -> saveControls(event.controls) is ControlEvent.SaveSectors -> saveSectors(event.sectors) is ControlEvent.SelectControlByIdPivot -> selectByIdPivot(event.id) is ControlEvent.ShowMessage -> showMessage(event.string) } } private fun refreshData() { refreshDataJob?.cancel() refreshDataJob = viewModelScope.launch(Dispatchers.IO) { if (isNetworkAvailable()) { while (true) { getPivotControls() delay(1000) } } } } private fun showMessage(string: Int) { showMessageJob?.cancel() showMessageJob = viewModelScope.launch(Dispatchers.IO) { _message.emit(Message.StringResource(string)) } } private fun getPivotControls() { getPivotControls?.cancel() getPivotControls = viewModelScope.launch(Dispatchers.IO) { val resource = controlRepository.fetchPivotControl() if (resource is Resource.Error) { _message.emit(resource.message) } } } private fun getIdPivotNameList(query: String = "") { getIdPivotNameListJob?.cancel() getIdPivotNameListJob = viewModelScope.launch(Dispatchers.IO) { getIdPivotNameUseCase(query).collectLatest { result -> when (result) { is Resource.Error -> _message.emit(result.message) is Resource.Success -> _state.update { it.copy(idPivotList = result.data) } } } } } private fun selectByIdPivot(id: Int, query: String = "") { selectByIdPivotJob?.cancel() selectByIdPivotJob = viewModelScope.launch(Dispatchers.IO) { getPivotControlsWithSectorsUseCase(query).collectLatest { result -> when (result) { is Resource.Error -> _message.emit(result.message) is Resource.Success -> { _state.update { controlState -> controlState.copy(controls = result.data.find { it.id == id } ?: state.value.controls) } Log.d("CONTROLS", _state.value.toString()) } } } } } private fun saveControls(controls: PivotControlEntity) { saveControlsJob?.cancel() saveControlsJob = viewModelScope.launch(Dispatchers.IO) { val result = controlRepository.addPivotControl(controls) _state.update { it.copy( controls = it.controls.copy( id = controls.id, idPivot = controls.idPivot, progress = controls.progress, isRunning = controls.isRunning, stateBomb = controls.stateBomb, wayToPump = controls.wayToPump, turnSense = controls.turnSense, ) ) } if (result is Resource.Error) { _message.emit(result.message) } } } private fun saveSectors(sectors: SectorControl) { saveSectorsJob?.cancel() saveSectorsJob = viewModelScope.launch(Dispatchers.IO) { val result = controlRepository.upsertSectorControl(sectors) selectByIdPivot(sectors.sector_control_id) if (result is Resource.Error) _message.emit(result.message) } } private suspend fun isNetworkAvailable(): Boolean { if (_networkStatus != ConnectivityObserver.Status.Available) { _message.emit(Message.StringResource(R.string.internet_error)) _state.update { it.copy(networkStatus = false) } return false } _state.update { it.copy(networkStatus = true) } return true } private fun observeNetworkChange() { networkObserverJob?.cancel() networkObserverJob = viewModelScope.launch(Dispatchers.IO) { connectivityObserver.observe().collectLatest { status -> _networkStatus = status } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/activity/LoginActivity.kt
3545299348
package com.example.controlpivot.ui.activity import android.content.Intent 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.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import com.example.controlpivot.MainActivity import com.example.controlpivot.toast import com.example.controlpivot.ui.screen.login.LoginScreen import com.example.controlpivot.ui.theme.ControlPivotTheme import com.example.controlpivot.ui.viewmodel.LoginViewModel import kotlinx.coroutines.flow.collectLatest import org.koin.androidx.viewmodel.ext.android.viewModel class LoginActivity: ComponentActivity() { private val loginViewModel by viewModel<LoginViewModel>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ControlPivotTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val state by loginViewModel.state.collectAsState() LoginScreen(state = state, onEvent = loginViewModel::onEvent) LaunchedEffect(Unit) { loginViewModel.isLogged.observe(this@LoginActivity) { if (it) { startActivity(Intent(this@LoginActivity, MainActivity::class.java)) finish() } } loginViewModel.message.collectLatest { message -> [email protected](message) } } } } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/activity/SplashActivity.kt
2221237678
package com.example.controlpivot.ui.activity import android.content.Intent import android.os.Bundle import android.util.Log 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.ui.Modifier import com.example.controlpivot.MainActivity import com.example.controlpivot.ui.screen.SplashScreen import com.example.controlpivot.ui.theme.ControlPivotTheme import com.example.controlpivot.ui.viewmodel.SplashViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class SplashActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ControlPivotTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { val splashViewModel by viewModel<SplashViewModel>() SplashScreen () splashViewModel.checkLogin() splashViewModel.isLogged.observe(this) { if (it == null) return@observe if (it) startActivity(Intent(this, MainActivity::class.java)) else startActivity(Intent(this, LoginActivity::class.java)) finish() } } } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/navigation/BottomNavBarAnimated.kt
4248438515
package com.example.controlpivot.ui.navigation import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue 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.navigation.NavController import androidx.navigation.NavGraph.Companion.findStartDestination import androidx.navigation.compose.currentBackStackEntryAsState import com.example.controlpivot.ui.screen.createpivot.BottomNavScreen @OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class) @Composable fun BottomNavBarAnimation( navController: NavController, ) { val screens = listOf( BottomNavScreen.PivotMachines, BottomNavScreen.Climate, BottomNavScreen.Control, BottomNavScreen.Settings ) val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route ElevatedCard( Modifier .height(75.dp), shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp), colors = CardDefaults.cardColors( containerColor = Color.White ) ) { Row( Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically, ) { screens.forEach { screen -> val isSelected = currentRoute?.contains(screen.route) ?: false val animatedWeight by animateFloatAsState( targetValue = if (isSelected) 1.5f else .5f, label = "" ) Box( modifier = Modifier.weight(animatedWeight), contentAlignment = Alignment.Center, ) { val interactionSource = remember { MutableInteractionSource() } BottomNavItem( modifier = Modifier.clickable( interactionSource = interactionSource, indication = null ) { navController.navigate(screen.route) { popUpTo(navController.graph.findStartDestination().id) { saveState = true } launchSingleTop = true restoreState = true } }, screen = screen, isSelected = isSelected ) } } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/navigation/BottomNavItem.kt
1084265905
package com.example.controlpivot.ui.navigation import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.spring import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.shadow import androidx.compose.ui.unit.dp import com.example.controlpivot.ui.screen.createpivot.BottomNavScreen import com.example.controlpivot.ui.theme.GreenLow @Composable fun BottomNavItem( modifier: Modifier = Modifier, screen: BottomNavScreen, isSelected: Boolean, ) { val animatedHeight by animateDpAsState( targetValue = if (isSelected) 50.dp else 40.dp, label = "" ) val animatedElevation by animateDpAsState( targetValue = if (isSelected) 15.dp else 0.dp, label = "" ) val animatedAlpha by animateFloatAsState( targetValue = if (isSelected) 1f else .5f, label = "" ) val animatedIconSize by animateDpAsState( targetValue = if (isSelected) 28.dp else 28.dp, animationSpec = spring( stiffness = Spring.StiffnessLow, dampingRatio = Spring.DampingRatioMediumBouncy ), label = "" ) val animatedColor by animateColorAsState( targetValue = if (isSelected) GreenLow else MaterialTheme.colorScheme.background, label = "" ) Box( modifier = modifier .background(color = MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center, ) { Row( modifier = Modifier .height(animatedHeight) .shadow( elevation = 0.dp, shape = RoundedCornerShape(20.dp) ) .background( color = animatedColor, shape = RoundedCornerShape(20.dp) ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, ) { FlipIcon( modifier = Modifier .align(Alignment.CenterVertically) .fillMaxHeight() .padding(start = 11.dp) .alpha(animatedAlpha) .size(animatedIconSize), isActive = isSelected, activeIcon = screen.activeIcon, inactiveIcon = screen.inactiveIcon, contentDescription = screen.route ) AnimatedVisibility(visible = isSelected) { Text( text = screen.route, modifier = Modifier.padding(start = 8.dp, end = 15.dp), maxLines = 1, ) } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/navigation/FlipIcon.kt
2713357149
package com.example.controlpivot.ui.navigation import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.spring import androidx.compose.foundation.layout.Box import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource @Composable fun FlipIcon( modifier: Modifier = Modifier, isActive: Boolean, activeIcon: Int, inactiveIcon: Int, contentDescription: String, ) { val animationRotation by animateFloatAsState( targetValue = if (isActive) 180f else 0f, animationSpec = spring( stiffness = Spring.StiffnessLow, dampingRatio = Spring.DampingRatioMediumBouncy ), label = "" ) Box( modifier = modifier //.graphicsLayer { rotationY = animationRotation }, ,contentAlignment = Alignment.Center, ) { Icon( painter = painterResource(id = if (animationRotation > 90f) activeIcon else inactiveIcon), contentDescription = contentDescription, ) } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/BottomSheetIrrigation.kt
2919499708
package com.example.controlpivot.ui.component import android.annotation.SuppressLint 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.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredWidthIn import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Scaffold import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.convertCharacter import com.example.controlpivot.ui.theme.GreenHigh @SuppressLint("UnusedMaterialScaffoldPaddingParameter", "UnusedMaterial3ScaffoldPaddingParameter") @Composable fun BottomSheetIrrigation( checkIrrigate: Boolean, sector: Int, dosage: Int, onEvent: (AddTagEvent) -> Unit, ) { var bottomCheckIrrigate by remember { mutableStateOf(checkIrrigate) } var bottomDosage by remember { mutableIntStateOf(dosage) } Scaffold( modifier = Modifier .wrapContentHeight() .background(Color.White) ) { Column( modifier = Modifier .wrapContentHeight() .background(Color.White), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Box( modifier = Modifier, contentAlignment = Alignment.TopCenter ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( modifier = Modifier.padding(bottom = 10.dp), text = "SECTOR $sector", style = MaterialTheme.typography.headlineSmall ) Row( modifier = Modifier .fillMaxWidth(0.9f) .height(60.dp) .background( color = Color.LightGray.copy(alpha = 0.3f), shape = RoundedCornerShape(6.dp) ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( modifier = Modifier.padding(start = 15.dp), text = "Regar", style = MaterialTheme.typography.headlineSmall ) Box( modifier = Modifier.padding(end = 75.dp) ) { CircularCheckBox( checked = bottomCheckIrrigate, onCheckedChange = { bottomCheckIrrigate = !bottomCheckIrrigate }, borderColor = Color.DarkGray ) } } Spacer(modifier = Modifier.height(15.dp)) Row( modifier = Modifier .fillMaxWidth(0.9f) .height(60.dp) .background( color = Color.LightGray.copy(alpha = 0.3f), shape = RoundedCornerShape(6.dp) ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Text( modifier = Modifier.padding(start = 15.dp), text = "Dosificación", style = MaterialTheme.typography.headlineSmall ) Row( modifier = Modifier.padding(end = 15.dp), verticalAlignment = Alignment.CenterVertically, ) { Box( modifier = Modifier .size(35.dp) .clip(RoundedCornerShape(10.dp)) .background(Color.LightGray.copy(alpha = 0.6f)) .padding(4.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { if (bottomDosage > 0) bottomDosage = bottomDosage.dec() } ) { Icon( painter = painterResource(id = R.drawable.minus), contentDescription = null, modifier = Modifier .size(25.dp) .padding(2.dp) .align(Alignment.Center), tint = Color.Black.copy(alpha = 0.5f) ) } BasicTextField( value = bottomDosage.toString(), onValueChange = { it.convertCharacter() bottomDosage = if (it.isEmpty()) 0 else it.toInt() }, modifier = Modifier .requiredWidthIn(min = 20.dp, max = 100.dp) .width(35.dp) .height(30.dp) .background(Color.Transparent) .border(0.dp, Color.Transparent) .align(Alignment.CenterVertically) .padding(start = 4.dp, end = 4.dp), textStyle = MaterialTheme.typography.titleLarge.copy( textAlign = TextAlign.Center ), keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), ) Box( modifier = Modifier .size(35.dp) .clip(RoundedCornerShape(10.dp)) .background(Color.LightGray.copy(alpha = 0.6f)) .padding(4.dp) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { bottomDosage = bottomDosage.inc() } ) { Icon( painter = painterResource(id = R.drawable.plus), contentDescription = null, modifier = Modifier .size(25.dp) .padding(2.dp) .align(Alignment.Center), tint = Color.Black.copy(alpha = 0.5f) ) } } } Spacer(modifier = Modifier.height(15.dp)) Row( modifier = Modifier .fillMaxWidth(0.9f) .height(110.dp) .background( color = Color.LightGray.copy(alpha = 0.3f), shape = RoundedCornerShape(6.dp) ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { SpeedSelector(onSpeedChanged = {}) } } } Spacer(modifier = Modifier.height(15.dp)) TextButton( enabled = true, modifier = Modifier .fillMaxWidth() .padding(15.dp), onClick = { onEvent( AddTagEvent.Save( bottomCheckIrrigate, bottomDosage ) ) }, colors = ButtonDefaults.elevatedButtonColors( containerColor = GreenHigh, contentColor = Color.White ) ) { Text( modifier = Modifier .align(Alignment.CenterVertically) .padding(5.dp), fontSize = 20.sp, fontWeight = FontWeight.Bold, text = "Aceptar" ) } } } } sealed class AddTagEvent() { class Save(val checkIrrigate: Boolean, val dosage: Int) : AddTagEvent() object Close : AddTagEvent() } @Preview(showSystemUi = true, showBackground = true) @Composable fun SheetPreview() { BottomSheetIrrigation(checkIrrigate = true, sector = 1, dosage = 0, onEvent = {}) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/SearchBar.kt
3213918555
package com.example.controlpivot.ui.component import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Icon import androidx.compose.material.LocalTextStyle import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Search import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.dp import com.example.controlpivot.ui.theme.GreenHigh @Composable fun SearchBar( hint: String = "", textStyle: TextStyle = LocalTextStyle.current, onValueChange: (String) -> Unit, ) { var text by rememberSaveable { mutableStateOf(hint) } CustomTextField( value = text, onValueChange = { text = it.changeValueBehavior(hint, text) onValueChange(if (text != hint) text else "") }, modifier = Modifier .fillMaxWidth() .wrapContentHeight(align = Alignment.Top) .clip(RoundedCornerShape(20.dp)) .background(color = Color.LightGray.copy(alpha = 0.25f)) .padding(3.dp), textStyle = if (text == hint) textStyle.copy(color = GreenHigh.copy(alpha = 0.4f)) else textStyle, leadingIcon = { Icon( imageVector = Icons.Default.Search, contentDescription = null, modifier = Modifier .size(40.dp) .padding(10.dp), tint = GreenHigh.copy(alpha = 0.4f) ) }, trailingIcon = { Icon( imageVector = Icons.Default.Close, contentDescription = null, modifier = Modifier .size(38.dp) .padding(10.dp) .clickable( indication = null, interactionSource = remember { MutableInteractionSource() }) { onValueChange("") text = hint }, tint = GreenHigh.copy(alpha = 0.4f) ) }, singleLine = true ) } private fun String.changeValueBehavior( hint: String, text: String, maxLength: Long = Long.MAX_VALUE ): String { if (this.length > maxLength) return text if (this.isEmpty()) return hint if (text == hint) { var tempText = this hint.forEach { c -> tempText = tempText.replaceFirst(c.toString(), "") } return tempText } return this }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/PasswordTextField.kt
4199048733
package com.example.controlpivot.ui.component import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Text import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.convertCharacter import com.example.controlpivot.ui.theme.GreenHigh import com.example.controlpivot.ui.theme.GreenLow import com.example.controlpivot.ui.theme.PurpleGrey40 @Composable fun PasswordTextField( label: String, value: Any, keyboardType: KeyboardType, leadingIcon: Int, trailingIcon: @Composable()(() -> Unit)? = null, singleLine: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = TextStyle.Default, suffix: String = "", visualTransformation: VisualTransformation = VisualTransformation.None, imeAction: ImeAction = ImeAction.Next, onValueChange: (String) -> Unit, ) { var text by remember { mutableStateOf(if (value == 0.0) "" else value.toString()) } var isError by remember { mutableStateOf(false) } var isFocused by remember { mutableStateOf(false) } var passwordHidden by rememberSaveable { mutableStateOf(true) } var isTextFieldFilled by remember { mutableStateOf(false) } val keyboardController = LocalSoftwareKeyboardController.current val focusManager = LocalFocusManager.current val errorMessage = "Campo vacío" OutlinedTextField( value = text, onValueChange = { text = it onValueChange( if(value is Double && text.isEmpty()) "0.0" else text ) isError = it.isEmpty() isTextFieldFilled = it.isNotEmpty() }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) .padding(top = 8.dp) .onFocusChanged { isFocused = it.isFocused if (isTextFieldFilled) { //focusManager.clearFocus() } }, label = { Text( text = if (isError) "${label}*" else label, fontSize = if (isFocused || text.isNotEmpty() || value is Long) 12.sp else 15.sp, color = when { isFocused && !isError -> GreenHigh !isFocused && text.isNotEmpty() -> GreenHigh isError -> Color.Red else -> Color.Black } ) }, singleLine = singleLine, readOnly = readOnly, colors = OutlinedTextFieldDefaults.colors( unfocusedBorderColor = if (text.isEmpty()) Color.Black else GreenHigh, errorBorderColor = Color.Red, focusedLabelColor = GreenHigh, unfocusedContainerColor = if (text.isEmpty()) GreenLow else Color.Transparent ), leadingIcon = { Icon( modifier = Modifier .size(24.dp), painter = painterResource(id = leadingIcon), contentDescription = label, tint = PurpleGrey40 ) }, trailingIcon = { IconButton(onClick = { passwordHidden = !passwordHidden }) { val visibilityIcon = if (passwordHidden) R.drawable.show else R.drawable.hide Icon( painter = painterResource(id = visibilityIcon), contentDescription = null, modifier = Modifier .size(24.dp), tint = PurpleGrey40 ) } }, isError = isError, keyboardOptions = KeyboardOptions.Default.copy( imeAction = imeAction, keyboardType = keyboardType ), visualTransformation = if (passwordHidden) PasswordVisualTransformation() else VisualTransformation.None, keyboardActions = KeyboardActions( onDone = { keyboardController?.hide() } ), supportingText = { Text( text = if (isError) errorMessage else "", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.End, color = Color.Red, fontSize = 10.sp, ) }, suffix = { Text(text = suffix) }, shape = RoundedCornerShape(25.dp), textStyle = textStyle ) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/SpeedSelector.kt
3086106301
package com.example.controlpivot.ui.component import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Slider import androidx.compose.material3.SliderDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.controlpivot.ui.theme.GreenHigh import com.example.controlpivot.ui.theme.GreenMedium import kotlin.math.roundToInt @Composable fun SpeedSelector( onSpeedChanged: (Float) -> Unit, ) { var speed by remember { mutableFloatStateOf(0f) } Column( modifier = Modifier .fillMaxWidth() .padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Row( verticalAlignment = Alignment.CenterVertically, ) { Text( text = "Velocidad del Motor: ", style = MaterialTheme.typography.headlineSmall, modifier = Modifier.padding(bottom = 6.dp, end = 4.dp) ) Text( text = "${speed.roundToInt()} m/s", style = MaterialTheme.typography.headlineSmall.copy(fontWeight = FontWeight.Bold), modifier = Modifier.padding(bottom = 4.dp) ) } Spacer(modifier = Modifier.height(20.dp)) SpeedSlider( value = speed, onValueChange = { speed = it onSpeedChanged(it) } ) } } @Composable fun SpeedSlider( value: Float, onValueChange: (Float) -> Unit, ) { val thumbSize = 15.dp Slider( value = value, valueRange = 0f..100f, steps = 10, onValueChange = onValueChange, modifier = Modifier .fillMaxWidth() .graphicsLayer { translationY = -thumbSize.toPx() / 2 } .padding(7.dp), colors = SliderDefaults.colors( thumbColor = GreenHigh, activeTrackColor = GreenMedium, inactiveTrackColor = Color.Gray ) ) } @Preview @Composable fun SpeedSelectorPreview() { SpeedSelector(onSpeedChanged = {}) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/CustomCheckBox.kt
520797011
package com.example.controlpivot.ui.component import androidx.compose.foundation.background import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.selection.triStateToggleable import androidx.compose.material.CheckboxColors import androidx.compose.material.CheckboxDefaults import androidx.compose.material.Icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Check import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.state.ToggleableState import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun CustomCheckBox( checked: Boolean, onCheckedChange: ((Boolean) -> Unit)?, modifier: Modifier = Modifier, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, colors: CheckboxColors = CheckboxDefaults.colors(), ) { val selectableModifier = if (onCheckedChange != null) { Modifier.triStateToggleable( state = ToggleableState(checked), onClick = { onCheckedChange(!checked) }, enabled = enabled, interactionSource = interactionSource, indication = null ) } else { Modifier } Box( modifier = modifier .then(selectableModifier) .background( if (checked) colors.boxColor( enabled = enabled, state = ToggleableState.On ).value else colors.boxColor( enabled = enabled, state = ToggleableState.Off ).value ) ) { if (checked) Icon( imageVector = Icons.Rounded.Check, contentDescription = null, tint = colors.checkmarkColor( state = ToggleableState.On ).value, modifier = Modifier .padding(defaultCheckPadding) .fillMaxSize() ) } } private val defaultCheckPadding = 4.dp @Preview(showSystemUi = true, showBackground = true) @Composable fun CustomCheckBoxPreview() { CircularCheckBox(checked = true, onCheckedChange = {}) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/CustomTextField.kt
1857447184
package com.example.controlpivot.ui.component import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.LocalTextStyle import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Clear import androidx.compose.material.icons.rounded.Search import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment.Companion.CenterVertically import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun CustomTextField( value: String, onValueChange: (String) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, textStyle: TextStyle = LocalTextStyle.current, placeholder: @Composable (() -> Unit)? = null, leadingIcon: @Composable (() -> Unit)? = null, trailingIcon: @Composable (() -> Unit)? = null, singleLine: Boolean = false, maxLines: Int = Int.MAX_VALUE, visualTransformation: VisualTransformation = VisualTransformation.None, keyboardOptions: KeyboardOptions = KeyboardOptions.Default ) { BasicTextField( value = value, onValueChange = onValueChange, modifier = modifier, enabled = enabled, textStyle = textStyle, decorationBox = { innerTextField -> Row(verticalAlignment = CenterVertically) { if (leadingIcon != null) { Box { leadingIcon() } } if (placeholder != null) { placeholder() } else { Box( modifier = Modifier .weight(1f) .padding(start = 2.dp, top = 6.dp, bottom = 6.dp, end = 8.dp) ) { innerTextField() } } if (trailingIcon != null) { Box { trailingIcon() } } } }, singleLine = singleLine, visualTransformation = visualTransformation, keyboardOptions = keyboardOptions ) } @Preview(showSystemUi = true, showBackground = true) @Composable fun CustomTextFieldPreview() { CustomTextField( value = "text", onValueChange = { }, modifier = Modifier .fillMaxWidth() .wrapContentHeight(align = Alignment.Top) .clip(RoundedCornerShape(6.dp)) .background(color = Color.LightGray) .padding(5.dp), leadingIcon = { Icon( imageVector = Icons.Rounded.Search, //painter = painterResource(id = R.drawable.round_search), contentDescription = null, modifier = Modifier.padding(start = 10.dp) ) }, trailingIcon = { Icon( imageVector = Icons.Rounded.Clear, //painter = painterResource(id = R.drawable.round_clear), contentDescription = null, modifier = Modifier.padding(end = 4.dp) ) }, singleLine = true ) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/PivotSpinner.kt
3416855046
package com.example.controlpivot.ui.component import android.widget.Toast import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.toSize import com.example.controlpivot.ui.model.IdPivotModel @Composable fun PivotSpinner( optionList: List<IdPivotModel>, selectedOption: String, onSelected: (Int) -> Unit, loading: () -> Unit, ) { val context = LocalContext.current var expandedState by remember { mutableStateOf(false) } var option = selectedOption var textFieldSize by remember { mutableStateOf(Size.Zero) } val icon = if (expandedState) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown Column( modifier = Modifier .padding(10.dp) ) { TextField( value = option, onValueChange = { option = it }, trailingIcon = { Icon( imageVector = icon, contentDescription = "", Modifier.clickable { expandedState = !expandedState } ) }, modifier = Modifier .onGloballyPositioned { coordinates -> textFieldSize = coordinates.size.toSize() }, label = { Text( text = "Seleccionar Máquina de Pivote", fontSize = if (selectedOption.isNotEmpty()) 10.sp else 18.sp, fontWeight = if (selectedOption.isNotEmpty()) FontWeight.Thin else FontWeight.Bold, ) }, readOnly = true, textStyle = TextStyle( fontSize = 18.sp, fontWeight = FontWeight.Bold, ), colors = OutlinedTextFieldDefaults.colors( focusedContainerColor = Color.White, unfocusedContainerColor = Color.White ) ) DropdownMenu( expanded = expandedState, onDismissRequest = { expandedState = false }, modifier = Modifier .width(with(LocalDensity.current) { textFieldSize.width.toDp() }), ) { optionList.forEach { idPivotModel -> DropdownMenuItem( text = { Text( text = idPivotModel.pivotName, fontSize = 18.sp, fontWeight = FontWeight.Bold, ) }, onClick = { option = idPivotModel.pivotName Toast.makeText( context, "" + option, Toast.LENGTH_LONG ).show() onSelected(idPivotModel.idPivot) loading() }) } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/QuadrantIrrigation.kt
2568958305
package com.example.controlpivot.ui.component import androidx.compose.foundation.Canvas import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.center import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.ui.theme.Green import com.example.controlpivot.ui.theme.GreenHigh import kotlin.math.absoluteValue import kotlin.math.atan import kotlin.math.cos import kotlin.math.sin @Composable fun QuadrantIrrigation( onClick: (Int) -> Unit, isRunning: Boolean, pauseIrrigation: () -> Unit, progress: Float, sectorStateList: List<Boolean>, ) { Column( modifier = Modifier .fillMaxSize() .padding(16.dp) ) { Spacer(modifier = Modifier.height(16.dp)) QuadrantView( progress, getSector = { onClick(it) }, sectorStateList = sectorStateList) Spacer(modifier = Modifier.height(16.dp)) Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.Center ) { Button( onClick = { pauseIrrigation() }, modifier = Modifier .weight(1f) .padding(8.dp) .wrapContentWidth() ) { Icon( modifier = Modifier .size(30.dp), painter = if (isRunning) painterResource(id = R.drawable.pause) else painterResource(id = R.drawable.play), contentDescription = null ) Spacer(modifier = Modifier.width(10.dp)) Text( fontSize = 20.sp, text = if (isRunning) "Pausar" else "Iniciar" ) } } } } @Composable fun QuadrantView( progress: Float, getSector: (Int) -> Unit, sectorStateList: List<Boolean>, ) { var center by remember { mutableStateOf(Offset.Zero) } val strokeWidth: Dp = 1.dp Box( modifier = Modifier .fillMaxWidth() ) { Canvas( modifier = Modifier .aspectRatio(1f) .onGloballyPositioned { coordinates -> center = Offset( coordinates.size.width / 2f, coordinates.size.height / 2f ) } ) { val centerX = size.width / 2 val centerY = size.height / 2 val radius = size.width / 2 drawCircle( color = Green, radius = radius, ) drawCircle( color = Color.Black, center = size.center, radius = radius, style = Stroke(4f) ) drawArc( color = GreenHigh, startAngle = 0f, sweepAngle = progress, useCenter = true ) val angleIncrement = 360f / 4 var currentAngle = 0f for (i in 1..4) { var startAngle = currentAngle var endAngle = currentAngle - angleIncrement val endRadians = Math.toRadians(endAngle.absoluteValue.toDouble()) val endX = centerX + (radius * cos(endRadians)).toFloat() val endY = centerY + (radius * sin(endRadians)).toFloat() val fillProgress = progress.coerceIn(startAngle.absoluteValue, endAngle.absoluteValue) drawLine( color = Color.Black, start = Offset(centerX, centerY), end = Offset(endX, endY), strokeWidth = strokeWidth.toPx() ) drawLine( color = Color.Black, start = Offset(centerX, centerY), end = calculateEndPoint(centerX, centerY, radius, fillProgress), strokeWidth = strokeWidth.toPx() ) currentAngle = endAngle } } Row( modifier = Modifier.align(Alignment.Center) ) { Box( modifier = Modifier .aspectRatio(1f) .fillMaxSize() .padding(20.dp) ) { Box( modifier = Modifier .size(170.dp) .align(Alignment.BottomEnd) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(1) } ) { Row( modifier = Modifier .padding(18.dp) .wrapContentSize() .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(1) }, horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Sector 1", style = TextStyle( fontSize = 15.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center, ) ) Spacer(modifier = Modifier.width(4.dp)) CircularCheckBox( checked = sectorStateList[0], onCheckedChange = {}, borderColor = Color.DarkGray ) } } Box( modifier = Modifier .size(170.dp) .align(Alignment.BottomStart) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(2) } ) { Row( modifier = Modifier .padding(18.dp) .wrapContentSize() .align(Alignment.TopEnd) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(2) }, horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Sector 2", style = TextStyle( fontSize = 15.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center, ) ) Spacer(modifier = Modifier.width(4.dp)) CircularCheckBox( checked = sectorStateList[1], onCheckedChange = {}, borderColor = Color.DarkGray ) } } Box( modifier = Modifier .size(170.dp) .align(Alignment.TopStart) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(3) } ) { Row( modifier = Modifier .padding(18.dp) .wrapContentSize() .align(Alignment.BottomEnd) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(3) }, horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Sector 3", style = TextStyle( fontSize = 15.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center, ) ) Spacer(modifier = Modifier.width(4.dp)) CircularCheckBox( checked = sectorStateList[2], onCheckedChange = {}, borderColor = Color.DarkGray ) } } Box( modifier = Modifier .size(170.dp) .align(Alignment.TopEnd) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(4) } ) { Row( modifier = Modifier .padding(18.dp) .wrapContentSize() .align(Alignment.BottomStart) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = null ) { getSector(4) }, horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text( text = "Sector 4", style = TextStyle( fontSize = 15.sp, fontWeight = FontWeight.Bold, textAlign = TextAlign.Center, ) ) Spacer(modifier = Modifier.width(4.dp)) CircularCheckBox( checked = sectorStateList[3], onCheckedChange = {}, borderColor = Color.DarkGray ) } } } } } } private fun calculateEndPoint( centerX: Float, centerY: Float, radius: Float, angle: Float, ): Offset { val radians = Math.toRadians(angle.toDouble()) val endX = centerX + (radius * cos(radians)).toFloat() val endY = centerY + (radius * sin(radians)).toFloat() return Offset(endX, endY) } private fun calculateAngle( centerX: Float, centerY: Float, radius: Float, angle: Float, ): Float { var sectorAngle: Float val radians = Math.toRadians(angle.toDouble()) val endX = centerX + (radius * cos(radians)) val endY = centerY + (radius * sin(radians)) sectorAngle = if (endY.toInt() == 664) { Math.toDegrees( atan((endY - centerY) / (endX - centerX)) ).toFloat() } else { Math.toDegrees( atan((endX - centerX).absoluteValue / (endY - centerY).absoluteValue) ).toFloat() } return sectorAngle }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/OutlinedTextFieldWithValidation.kt
3993312052
package com.example.controlpivot.ui.component import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Text import androidx.compose.material3.Icon import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.convertCharacter import com.example.controlpivot.ui.theme.GreenHigh import com.example.controlpivot.ui.theme.GreenLow import com.example.controlpivot.ui.theme.PurpleGrey40 @Composable fun OutlinedTextFieldWithValidation( label: String, value: Any, keyboardType: KeyboardType, leadingIcon: Int, trailingIcon: @Composable()(() -> Unit)? = null, singleLine: Boolean = true, readOnly: Boolean = false, textStyle: TextStyle = TextStyle.Default, suffix: String = "", visualTransformation: VisualTransformation = VisualTransformation.None, imeAction: ImeAction = ImeAction.Next, onValueChange: (String) -> Unit, ) { var text by remember { mutableStateOf(if (value == 0.0) "" else value.toString()) } var isError by remember { mutableStateOf(false) } var isFocused by remember { mutableStateOf(false) } var isTextFieldFilled by remember { mutableStateOf(false) } val keyboardController = LocalSoftwareKeyboardController.current val focusManager = LocalFocusManager.current val errorMessage = "Campo vacío" OutlinedTextField( value = text, onValueChange = { if (keyboardType == KeyboardType.Text) text = it else text = it.convertCharacter() onValueChange( if(value is Double && text.isEmpty()) "0.0" else text ) isError = it.isEmpty() isTextFieldFilled = it.isNotEmpty() }, modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp) .padding(top = 8.dp) .onFocusChanged { isFocused = it.isFocused if (isTextFieldFilled) { //focusManager.clearFocus() } }, label = { Text( text = if (isError) "${label}*" else label, fontSize = if (isFocused || text.isNotEmpty() || value is Long) 12.sp else 15.sp, color = when { isFocused && !isError -> GreenHigh !isFocused && text.isNotEmpty() -> GreenHigh isError -> Color.Red else -> Color.Black } ) }, singleLine = singleLine, readOnly = readOnly, colors = OutlinedTextFieldDefaults.colors( unfocusedBorderColor = if (text.isEmpty()) Color.Black else GreenHigh, errorBorderColor = Color.Red, focusedLabelColor = GreenHigh, unfocusedContainerColor = if (text.isEmpty()) GreenLow else Color.Transparent ), leadingIcon = { Icon( modifier = Modifier .size(24.dp), painter = painterResource(id = leadingIcon), contentDescription = label, tint = PurpleGrey40 ) }, trailingIcon = { trailingIcon }, isError = isError, keyboardOptions = KeyboardOptions.Default.copy( imeAction = imeAction, keyboardType = keyboardType ), visualTransformation = visualTransformation, keyboardActions = KeyboardActions( onDone = { keyboardController?.hide() } ), supportingText = { Text( text = if (isError) errorMessage else "", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.End, color = Color.Red, fontSize = 10.sp, ) }, suffix = { Text(text = suffix) }, shape = RoundedCornerShape(25.dp), textStyle = textStyle ) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/component/CircularCheckBox.kt
3396838936
package com.example.controlpivot.ui.component import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.CheckboxColors import androidx.compose.material.CheckboxDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.example.controlpivot.ui.theme.GreenHigh @Composable fun CircularCheckBox( size: Dp = defaultSize, borderStroke: Dp = defaultBorderStroke, borderColor: Color = defaultBorderColor, checked: Boolean, onCheckedChange: ((Boolean) -> Unit)?, enabled: Boolean = true, colors: CheckboxColors = CheckboxDefaults.colors( checkedColor = defaultCheckedColor, checkmarkColor = defaultCheckMarkColor, ) ) { CustomCheckBox( checked = checked, onCheckedChange = onCheckedChange, modifier = Modifier .size(size) .clip(CircleShape) .border( border = BorderStroke( width = if (checked) 0.dp else borderStroke, color = borderColor ), CircleShape ), enabled = enabled, colors = colors ) } private val defaultSize = 25.dp private val defaultBorderStroke = 2.dp private val defaultBorderColor = Color.LightGray private val defaultCheckedColor = GreenHigh.copy(alpha = 0.7f) private val defaultCheckMarkColor = Color.White @Preview @Composable fun CircularCheckBoxPreview() { CircularCheckBox(checked = true, onCheckedChange = {}) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/theme/Color.kt
3201920971
package com.example.controlpivot.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) val GreenLow = Color(0xFFDCEDDC) val Green = Color(0xFFBDDEBD) val GreenMedium = Color(0xFF67DE6E) val GreenHigh = Color(0xFF04980F) val DarkGray = Color(0xFF43454A) val MediumGray = Color(0xFF727477)
pivot-control/app/src/main/java/com/example/controlpivot/ui/theme/Theme.kt
30715343
package com.example.controlpivot.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 = GreenHigh, secondary = Green, tertiary = GreenMedium ) private val LightColorScheme = lightColorScheme( primary = GreenHigh, secondary = Green, tertiary = GreenMedium /* 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 ControlPivotTheme( 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) dynamicLightColorScheme(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 ) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/theme/Type.kt
944949076
package com.example.controlpivot.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 ) */ )
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/PivotMachineEvent.kt
1621706090
package com.example.controlpivot.ui.screen.createpivot import com.example.controlpivot.data.local.model.PivotMachineEntity sealed class PivotMachineEvent { data class SearchMachine(val query: String) : PivotMachineEvent() data class DeleteMachine(val machineId: Int) : PivotMachineEvent() data class CreateMachine(val machine: PivotMachineEntity) : PivotMachineEvent() data class SelectMachine(val id: Int) : PivotMachineEvent() object ResetDataMachine : PivotMachineEvent() }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/ScreensNavEvent.kt
582678981
package com.example.controlpivot.ui.screen.createpivot import android.app.Activity import androidx.navigation.NavController import com.example.controlpivot.ui.screen.Screen sealed class ScreensNavEvent { object ToNewPivotMachine : ScreensNavEvent() object ToPivotMachineList : ScreensNavEvent() object ToClimate : ScreensNavEvent() object ToPivotControl : ScreensNavEvent() object ToSession : ScreensNavEvent() object Back : ScreensNavEvent() } fun Activity.pivotMachineNavEvent( navController: NavController, navEvent: ScreensNavEvent, ) { when (navEvent) { ScreensNavEvent.Back -> { navController.popBackStack() } ScreensNavEvent.ToNewPivotMachine -> { navController.navigate(Screen.PivotMachines.Machine.route) } ScreensNavEvent.ToPivotMachineList -> { navController.navigate(Screen.PivotMachines.List.route) } ScreensNavEvent.ToClimate -> { navController.navigate(Screen.Climate.route) } ScreensNavEvent.ToPivotControl -> { navController.navigate(Screen.Control.route) } ScreensNavEvent.ToSession -> { navController.navigate(Screen.Session.route) } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/AddEditPivotMachineScreen.kt
2817726513
package com.example.controlpivot.ui.screen.createpivot import android.annotation.SuppressLint import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.ArrowBack import androidx.compose.material.icons.filled.Done import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.example.controlpivot.R import com.example.controlpivot.ui.component.OutlinedTextFieldWithValidation import com.example.controlpivot.ui.theme.GreenMedium @OptIn(ExperimentalMaterial3Api::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun AddEditPivotMachineScreen( state: PivotMachineState, onEvent: (PivotMachineEvent) -> Unit, navEvent: (ScreensNavEvent) -> Unit, ) { val scrollState = rememberScrollState() var nameTextValue = state.currentMachine.name var locationTextValue = state.currentMachine.location var endowmentTextValue = state.currentMachine.endowment var flowTextValue = state.currentMachine.flow var pressureTextValue = state.currentMachine.pressure var lengthTextValue = state.currentMachine.length var areaTextValue = state.currentMachine.area var powerTextValue = state.currentMachine.power var speedTextValue = state.currentMachine.speed var efficiencyTextValue = state.currentMachine.efficiency Scaffold( modifier = Modifier.padding(bottom = 75.dp), floatingActionButton = { FloatingActionButton( onClick = { onEvent( PivotMachineEvent.CreateMachine( state.currentMachine.copy( name = nameTextValue, location = locationTextValue, endowment = endowmentTextValue, flow = flowTextValue, pressure = pressureTextValue, length = lengthTextValue, area = areaTextValue, power = powerTextValue, speed = speedTextValue, efficiency = efficiencyTextValue, isSave = false, ) ) ) }, shape = FloatingActionButtonDefaults.extendedFabShape, containerColor = GreenMedium, contentColor = Color.Black, modifier = Modifier ) { Icon(imageVector = Icons.Default.Done, contentDescription = "Save pivot machine") } } ) { Column( modifier = Modifier .fillMaxSize() .verticalScroll(state = scrollState) .padding(start = 15.dp, end = 15.dp) ) { Spacer(modifier = Modifier.height(20.dp)) Row( verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .wrapContentSize() .clip(RoundedCornerShape(15.dp)) .background(Color.LightGray.copy(alpha = 0.2f)) .clickable { navEvent(ScreensNavEvent.Back) }, ) { Icon( imageVector = Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = null, modifier = Modifier .size(40.dp) .padding(7.dp), tint = Color.Gray, ) } Spacer(modifier = Modifier.width(10.dp)) Column { Text( text = stringResource(id = R.string.new_pivot_machine), style = MaterialTheme.typography.h5.copy(fontFamily = FontFamily.SansSerif), modifier = Modifier .padding(start = 5.dp) ) } } Spacer(modifier = Modifier.height(10.dp)) HorizontalDivider( modifier = Modifier.height(5.dp), color = Color.Black ) Spacer(modifier = Modifier.height(20.dp)) OutlinedTextFieldWithValidation( label = "Nombre", value = nameTextValue, keyboardType = KeyboardType.Text, leadingIcon = R.drawable.ic_name, onValueChange = { nameTextValue = it.toString() } ) OutlinedTextFieldWithValidation( label = "Ubicación", value = locationTextValue, keyboardType = KeyboardType.Text, leadingIcon = R.drawable.ic_location, onValueChange = { locationTextValue = it.toString() }, singleLine = false, ) OutlinedTextFieldWithValidation( label = "Dotación", value = endowmentTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_flow, suffix = "L/seg ha", onValueChange = { endowmentTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Caudal Nominal", value = flowTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_endowment, suffix = "L/seg", onValueChange = { flowTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Presión", value = pressureTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_pressure, suffix = "kPa", onValueChange = { pressureTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Longitud Total", value = lengthTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_length, suffix = "m", onValueChange = { lengthTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Área", value = areaTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_area, suffix = "m^2", onValueChange = { areaTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Potencia", value = powerTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_power, suffix = "kW", onValueChange = { powerTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Velocidad del Motor", value = speedTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_speed2, suffix = "rpm", onValueChange = { speedTextValue = it.toDouble() } ) OutlinedTextFieldWithValidation( label = "Eficiencia", value = efficiencyTextValue, keyboardType = KeyboardType.Decimal, leadingIcon = R.drawable.ic_efficiency, suffix = "%", onValueChange = { efficiencyTextValue = it.toDouble() }, imeAction = ImeAction.Done ) Spacer(modifier = Modifier.height(10.dp)) } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/BottomNavScreen.kt
4214560250
package com.example.controlpivot.ui.screen.createpivot import androidx.annotation.DrawableRes import com.example.controlpivot.R import com.example.controlpivot.ui.screen.Screen sealed class BottomNavScreen( val route: String, @DrawableRes val activeIcon: Int, @DrawableRes val inactiveIcon: Int, ) { object PivotMachines : BottomNavScreen( Screen.PivotMachines.route, R.drawable.writing_filled, R.drawable.writing_outlined ) object Climate : BottomNavScreen( Screen.Climate.route, R.drawable.cloudy_day, R.drawable.cloudy_day_outlined ) object Control : BottomNavScreen( Screen.Control.route, R.drawable.control_filled, R.drawable.control_outlined ) object Settings : BottomNavScreen( Screen.Session.route, R.drawable.user_filled, R.drawable.user_outlined ) }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/PivotMachinesListScreen.kt
4199661792
package com.example.controlpivot.ui.screen.createpivot import android.annotation.SuppressLint import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.pullrefresh.PullRefreshIndicator import androidx.compose.material.pullrefresh.PullRefreshState import androidx.compose.material.pullrefresh.pullRefresh import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.material3.rememberTooltipState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.ui.component.SearchBar import com.example.controlpivot.ui.theme.GreenMedium @OptIn(ExperimentalMaterialApi::class, ExperimentalMaterial3Api::class) @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun PivotMachineListScreen( state: PivotMachineState, onEvent: (PivotMachineEvent) -> Unit, navEvent: (ScreensNavEvent) -> Unit, pullRefreshState: PullRefreshState, ) { val lazyListState = rememberLazyListState() Scaffold( modifier = Modifier, floatingActionButton = { AnimatedVisibility( lazyListState.canScrollForward || state.machines.isEmpty() || (!lazyListState.canScrollForward && !lazyListState.canScrollBackward), enter = scaleIn(), exit = scaleOut(), modifier = Modifier .padding(bottom = 75.dp) .wrapContentSize() ) { FloatingActionButton( onClick = { onEvent(PivotMachineEvent.ResetDataMachine) navEvent(ScreensNavEvent.ToNewPivotMachine) }, shape = FloatingActionButtonDefaults.extendedFabShape, containerColor = GreenMedium, contentColor = Color.Black, ) { Icon( imageVector = Icons.Default.Add, contentDescription = "Add pivot machine" ) } } } ) { Box( modifier = Modifier .fillMaxSize() .pullRefresh(pullRefreshState) .padding(bottom = 75.dp), ) { Column( modifier = Modifier .padding(horizontal = 15.dp), verticalArrangement = Arrangement.Center ) { Spacer(modifier = Modifier.height(20.dp)) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Box( modifier = Modifier .wrapContentSize() .clip(RoundedCornerShape(15.dp)) .background(Color.White.copy(alpha = 0.2f)) .clickable { }, ) { Icon( painter = painterResource(id = R.drawable.task_list), contentDescription = null, modifier = Modifier .size(30.dp) .padding(2.dp), ) } Spacer(modifier = Modifier.width(10.dp)) Text( text = stringResource(id = R.string.pivot_machines), style = MaterialTheme.typography.h5.copy(fontFamily = FontFamily.SansSerif), modifier = Modifier .padding(start = 5.dp), ) } Spacer(modifier = Modifier.height(10.dp)) SearchBar( hint = stringResource(id = R.string.search), textStyle = TextStyle( fontSize = 20.sp, fontWeight = FontWeight.Thin, fontStyle = FontStyle.Italic ) ) { onEvent(PivotMachineEvent.SearchMachine(it)) } Spacer(modifier = Modifier.height(10.dp)) LazyColumn( state = lazyListState, modifier = Modifier .fillMaxSize() .padding(bottom = 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { items(state.machines) { machine -> var stateHeight by remember { mutableStateOf(true) } val tooltipState = rememberTooltipState() val scope = rememberCoroutineScope() PivotMachineItem( machine = machine, onDeleteClick = { onEvent( PivotMachineEvent.DeleteMachine(machine.id) ) }, onClick = { onEvent( PivotMachineEvent.SelectMachine(machine.id) ) navEvent(ScreensNavEvent.ToNewPivotMachine) }, heightBox = !stateHeight, onExpanded = { stateHeight = !stateHeight }, tooltipState = tooltipState, scope = scope ) } } } PullRefreshIndicator( refreshing = state.isLoading, state = pullRefreshState, modifier = Modifier .align(Alignment.TopCenter) ) } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/PivotMachineState.kt
2885406243
package com.example.controlpivot.ui.screen.createpivot import com.example.controlpivot.data.local.model.PivotMachineEntity data class PivotMachineState( val machines: List<PivotMachineEntity> = listOf(), var currentMachine: PivotMachineEntity = PivotMachineEntity(), var isLoading: Boolean = false )
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/createpivot/PivotMachineItem.kt
744916916
package com.example.controlpivot.ui.screen.createpivot import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Done import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.material.icons.filled.Warning import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.PlainTooltip import androidx.compose.material3.Text import androidx.compose.material3.TooltipBox import androidx.compose.material3.TooltipDefaults import androidx.compose.material3.TooltipState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.clipPath import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight.Companion.Bold import androidx.compose.ui.text.font.FontWeight.Companion.Thin import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.controlpivot.R import com.example.controlpivot.data.local.model.PivotMachineEntity import com.example.controlpivot.ui.theme.Green import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun PivotMachineItem( machine: PivotMachineEntity, cornerRadius: Dp = 10.dp, onDeleteClick: () -> Unit, onClick: () -> Unit, heightBox: Boolean, onExpanded: () -> Unit, tooltipState: TooltipState, scope: CoroutineScope, ) { Box( modifier = Modifier .fillMaxWidth() .clickable { onClick() } ) { Canvas(modifier = Modifier.matchParentSize()) { val item = Path().apply { lineTo(size.width, 0f) lineTo(size.width, size.height) lineTo(0f, size.height) close() } clipPath(item) { drawRoundRect( color = Green, size = size, cornerRadius = CornerRadius(cornerRadius.toPx()) ) } } Row { Image( painter = painterResource( id = R.drawable.irrigation_machine ), contentDescription = null, modifier = Modifier .size(60.dp) .padding(12.dp) ) Column( modifier = Modifier .fillMaxSize() .padding(start = 5.dp, bottom = 32.dp, end = 16.dp) ) { Text( text = machine.name, style = MaterialTheme.typography.headlineLarge, fontWeight = Bold, fontSize = 22.sp, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Ubicación: ${machine.location}", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Dotación: ${machine.endowment} L/seg ha", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) if (heightBox) { Text( text = "Caudal: ${machine.flow} L/seg", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Presión: ${machine.pressure} kPa", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Longitud Total: ${machine.length} m", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Área: ${machine.area} m^2", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Tiempo de vuelta: ${machine.speed} horas", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Potencia: ${machine.power} kW", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis ) Text( text = "Eficiencia: ${machine.efficiency} %", style = MaterialTheme.typography.bodyMedium, fontWeight = Thin, color = colorScheme.onSurface, overflow = TextOverflow.Ellipsis, ) } } } IconButton( onClick = onDeleteClick, modifier = Modifier.align(Alignment.TopEnd) ) { Icon( imageVector = Icons.Default.Delete, contentDescription = "Delete alarm", modifier = Modifier.size(25.dp) ) } IconButton( onClick = {}, modifier = Modifier .align(Alignment.BottomStart), ) { TooltipBox( positionProvider = TooltipDefaults.rememberPlainTooltipPositionProvider(), tooltip = { PlainTooltip { Text( text = if (machine.isSave) stringResource(id = R.string.success_registred) else stringResource(id = R.string.pending_register) ) } }, state = tooltipState ) { } Icon( imageVector = if (machine.isSave) Icons.Default.Done else Icons.Default.Warning, contentDescription = "Pending Registration", modifier = Modifier .size(18.dp) .padding(top = 5.dp) .clickable { scope.launch { tooltipState.show() } } ) } IconButton( onClick = {}, modifier = Modifier .align(Alignment.BottomEnd) ) { Icon( imageVector = if (!heightBox) Icons.Default.KeyboardArrowDown else Icons.Default.KeyboardArrowUp, contentDescription = "isExpanded", modifier = Modifier .size(22.dp) .clickable { onExpanded() } ) } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/Screen.kt
3912117506
package com.example.controlpivot.ui.screen sealed class Screen( val route: String, ) { object PivotMachines : Screen("Información") { object List : Screen("${route}/list") object Machine : Screen("${route}/new") } object Climate : Screen("Clima") object Control : Screen("Control") object Session : Screen("Sesión") }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/SplashScreen.kt
2719246944
package com.example.controlpivot.ui.screen import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.requiredHeight import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.animateLottieCompositionAsState import com.airbnb.lottie.compose.rememberLottieComposition import com.example.controlpivot.R @Composable fun SplashScreen() { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { val composition by rememberLottieComposition(spec = LottieCompositionSpec.RawRes(R.raw.anim_irrigation)) val secondComposition by rememberLottieComposition(spec = LottieCompositionSpec.RawRes(R.raw.splash_animation)) val progress by animateLottieCompositionAsState( composition = composition, ) //if (progress == 1.0f) animationEnd(true) Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { LottieAnimation( composition = composition, progress = progress, modifier = Modifier .requiredHeight(350.dp) .fillMaxWidth(0.7f), ) LottieAnimation( composition = secondComposition, modifier = Modifier .requiredHeight(350.dp) .fillMaxWidth(0.7f), restartOnPlay = true, iterations = Int.MAX_VALUE ) } } } }
pivot-control/app/src/main/java/com/example/controlpivot/ui/screen/climate/ClimateState.kt
500640052
package com.example.controlpivot.ui.screen.climate import com.example.controlpivot.data.common.model.Climate import com.example.controlpivot.ui.model.IdPivotModel data class ClimateState ( val climates: List<Climate> = listOf(), var currentClimate: Climate? = null, var selectedIdPivot: Int = 0, var idPivotList: List<IdPivotModel> = listOf(), var isLoading: Boolean = false, )