content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.davidm.payees.ui import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat.startActivity import androidx.recyclerview.widget.RecyclerView import com.davidm.payees.R import com.davidm.payees.utils.PayeesLocalMapper import kotlinx.android.synthetic.main.payee_item.view.* class PayeeListAdapter : RecyclerView.Adapter<PayeeListAdapter.PayeeListViewHolder>() { var data = listOf<PayeesLocalMapper.LocalPayee>() set(value) { field = value notifyDataSetChanged() } inner class PayeeListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val payeeName: TextView = itemView.payeeName val firstLastName: TextView = itemView.firstAndLastName val accountsNumber: TextView = itemView.accountNumberText val initials : TextView = itemView.initials val parent: ConstraintLayout = itemView.payeeItemParentView } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PayeeListViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.payee_item, parent, false) return PayeeListViewHolder(view) } override fun getItemCount(): Int { return data.size } override fun onBindViewHolder(holder: PayeeListViewHolder, position: Int) { val item = data[position] holder.payeeName.text = item.payeeName holder.firstLastName.text = item.firstAndLastName holder.accountsNumber.text = item.numberOfAccounts holder.initials.text = item.initials holder.parent.setOnClickListener { val intent = Intent(holder.itemView.context, PayeeProfileActivity::class.java) intent.putExtra("profileData", item) startActivity(holder.itemView.context, intent, null) } } }
BankApp/payees/src/main/java/com/davidm/payees/ui/PayeeListAdapter.kt
1433401997
package com.davidm.payees.repository import com.davidm.payees.entities.ErrorMessage import com.davidm.payees.entities.Payee import com.davidm.payees.entities.PayeeCreationResponse import com.davidm.payees.entities.defaultError import com.davidm.payees.network.PayeesApi import com.squareup.moshi.Moshi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.ResponseBody class PayeesRepository constructor( private val payeesApi: PayeesApi ) { /** * This method will retrieve the list of Payees for the account */ suspend fun retrievePayees( ): List<Payee> { return withContext(Dispatchers.IO) { return@withContext payeesApi.getPayees().payees } } /** * This method will create a new Payee for the account */ suspend fun createPayee( payee: Payee ): PayeeCreationResponse { return withContext(Dispatchers.IO) { val response = payeesApi.createPayee(body = payee) if (response.isSuccessful && response.body() !== null) { response.body()!! } else { PayeeCreationResponse( null, listOf(convertErrorBody(response.errorBody())), null, false ) } } } // hmm, I should use the moshi instance that Dagger provides! private fun convertErrorBody(throwable: ResponseBody?): ErrorMessage { if (throwable == null) { return defaultError } return try { throwable.source().let { val moshiAdapter = Moshi.Builder().build().adapter(ErrorMessage::class.java) moshiAdapter.fromJson(it) }!! } catch (exception: Exception) { defaultError } } }
BankApp/payees/src/main/java/com/davidm/payees/repository/PayeesRepository.kt
454341435
package com.davidm.payees.repository import com.davidm.network.BASE_URL import com.davidm.payees.network.PayeesApi import retrofit2.Retrofit class PayeesRepositoryModule { fun providesPayeesApi(retrofit: Retrofit.Builder): PayeesApi { return retrofit .baseUrl(BASE_URL) .build() .create(PayeesApi::class.java) } }
BankApp/payees/src/main/java/com/davidm/payees/repository/PayeesRepositoryModule.kt
1258448872
package com.davidm.payees.network import com.davidm.account.entities.Account import com.davidm.network.API_KEY import com.davidm.network.API_VERSION import com.davidm.payees.entities.Payee import com.davidm.payees.entities.PayeeCreationResponse import com.davidm.payees.entities.Payees import retrofit2.Response import retrofit2.http.* import java.time.Instant interface PayeesApi { @GET("api/$API_VERSION/payees") suspend fun getPayees( @Header("Authorization") token: String = "Bearer $API_KEY", @Header("Accept") value: String = "application/json" ): Payees @PUT("api/${API_VERSION}/payees") suspend fun createPayee( @Body body: Payee, @Header("Authorization") token: String = "Bearer $API_KEY", @Header("Accept") value: String = "application/json" ): Response<PayeeCreationResponse> }
BankApp/payees/src/main/java/com/davidm/payees/network/PayeesApi.kt
1131940270
package com.davidm.payees.utils import androidx.test.espresso.IdlingResource object EspressoIdlingResource { private const val resource = "GLOBAL" private val countingIdlingResource = SimpleCountingIdlingResource( resource ) fun increment() = countingIdlingResource.increment() fun decrement() = countingIdlingResource.decrement() fun getIdlingResource(): IdlingResource = countingIdlingResource }
BankApp/payees/src/main/java/com/davidm/payees/utils/EspressoIdlingResource.kt
314077672
package com.davidm.payees.utils import androidx.test.espresso.IdlingRegistry import androidx.test.espresso.idling.CountingIdlingResource import kotlinx.coroutines.CoroutineDispatcher import kotlin.coroutines.CoroutineContext class EspressoTrackedDispatcher(private val wrappedCoroutineDispatcher: CoroutineDispatcher) : CoroutineDispatcher() { private val counter: CountingIdlingResource = CountingIdlingResource("EspressoTrackedDispatcher for $wrappedCoroutineDispatcher") init { IdlingRegistry.getInstance().register(counter) } override fun dispatch(context: CoroutineContext, block: Runnable) { counter.increment() val blockWithDecrement = Runnable { try { block.run() } finally { counter.decrement() } } wrappedCoroutineDispatcher.dispatch(context, blockWithDecrement) } fun cleanUp() { IdlingRegistry.getInstance().unregister(counter) } }
BankApp/payees/src/main/java/com/davidm/payees/utils/EspressoTrackedDispatcher.kt
1093105248
package com.davidm.payees.utils import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers class CustomDispatcherClass : CustomDispatcher { var IO: CoroutineDispatcher = Dispatchers.IO var Default: CoroutineDispatcher = Dispatchers.Default override fun getStandardDispatcher() { Default = Dispatchers.Default } override fun getIODispatcher() { IO = Dispatchers.IO } }
BankApp/payees/src/main/java/com/davidm/payees/utils/CustomDispatcherClass.kt
2817423980
package com.davidm.payees.utils import com.davidm.resources.R class PayeeProfileInfoConverter { data class PayeeProfileInfo( val text: String, val icon: Int ) fun generateList(localPayee: PayeesLocalMapper.LocalPayee): List<PayeeProfileInfo> { val list: MutableList<PayeeProfileInfo> = listOf<PayeeProfileInfo>().toMutableList() list.add( PayeeProfileInfo( localPayee.firstAndLastName, R.drawable.ic_person_black_24dp ) ) if (!localPayee.phoneNumber.isNullOrBlank()) { list.add( PayeeProfileInfo( localPayee.phoneNumber, R.drawable.ic_phone_black_24dp ) ) } if (!localPayee.dateOfBirth.isNullOrBlank()) { list.add( PayeeProfileInfo( localPayee.dateOfBirth, R.drawable.ic_perm_contact_calendar_black_24dp ) ) } if (!localPayee.businessName.isNullOrBlank()) { list.add( PayeeProfileInfo( localPayee.businessName, R.drawable.ic_work_black_24dp ) ) } return list } }
BankApp/payees/src/main/java/com/davidm/payees/utils/PayeeProfileInfoConverter.kt
2771710019
package com.davidm.payees.utils import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout fun isFormValid(map: Map<TextInputLayout, TextInputEditText>): Boolean { var valid = true map.forEach { if (it.key.error.isNullOrEmpty()) { it.key.isErrorEnabled = false } else { valid = false } } return valid } fun searchAndSetErrorsOnForm(map: Map<TextInputLayout, TextInputEditText>) { map.map { (layout, edittext) -> if (edittext.text.toString().isBlank()) { // foreach required element in the form that is blank, we show an error message layout.error = "The field is required" } else { // if the required element is filled, we set the error to null layout.error = null } } }
BankApp/payees/src/main/java/com/davidm/payees/utils/FormValidatorHelper.kt
3051847174
package com.davidm.payees.utils import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext fun CoroutineScope.launchIdling( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ): Job { EspressoIdlingResource.increment() val job = this.launch(context, start, block) job.invokeOnCompletion { EspressoIdlingResource.decrement() } return job }
BankApp/payees/src/main/java/com/davidm/payees/utils/coroutines.kt
313552151
package com.davidm.payees.utils interface CustomDispatcher { fun getStandardDispatcher() fun getIODispatcher() }
BankApp/payees/src/main/java/com/davidm/payees/utils/CustomDispatcher.kt
1747909103
package com.davidm.payees.utils import android.os.Parcelable import com.davidm.payees.R import com.davidm.payees.entities.Payee import com.davidm.payees.entities.PayeeAccount import com.davidm.payees.entities.PayeeType import kotlinx.android.parcel.Parcelize import java.text.DateFormatSymbols import java.text.SimpleDateFormat import java.util.* class PayeesLocalMapper { @Parcelize data class LocalPayee( val payeeName: String, val firstAndLastName: String, val numberOfAccounts: String, val accounts: List<PayeeAccount>, val accountTypeIcon: Int, val initials: String, val businessName: String?, val phoneNumber: String?, val dateOfBirth: String? ) : Parcelable fun convertPayee(payee: Payee): LocalPayee { var firstAndLastName = "Name not specified" var initials = "" if (payee.firstName !== null && payee.lastName !== null) { firstAndLastName = "${payee.firstName} ${payee.lastName}" initials = "${payee.firstName[0]}${payee.lastName[0]}" } else if (payee.payeeName.isNotEmpty()) { initials = "${payee.payeeName[0]}${payee.payeeName[1]}" } else { initials = "" } val numberOfAccounts = if (payee.accounts.size > 1) { "${payee.accounts.size} accounts" } else { "1 account" } var calendarString: String? = null if (payee.dateOfBirth !== null) { val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) val formattedDate: Date? = dateFormat.parse(payee.dateOfBirth) if (formattedDate !== null) { val calendar = Calendar.getInstance() calendar.time = formattedDate calendarString = "${calendar.get(Calendar.DAY_OF_MONTH)} " + "${DateFormatSymbols().months[calendar.get(Calendar.MONTH)]} " + "${calendar.get(Calendar.YEAR)}" } } val payeeType = when (payee.payeeType) { PayeeType.INDIVIDUAL -> R.drawable.ic_person_black_24dp PayeeType.BUSINESS -> R.drawable.ic_work_black_24dp null -> R.drawable.ic_person_black_24dp } return LocalPayee( payeeName = payee.payeeName, firstAndLastName = firstAndLastName, numberOfAccounts = numberOfAccounts, accountTypeIcon = payeeType, initials = initials, businessName = payee.businessName, phoneNumber = payee.phoneNumber, accounts = payee.accounts, dateOfBirth = calendarString ) } }
BankApp/payees/src/main/java/com/davidm/payees/utils/PayeesLocalMapper.kt
552036662
package com.davidm.payees.utils import com.google.android.material.appbar.AppBarLayout import kotlin.math.abs abstract class CollapsingBarListener : AppBarLayout.OnOffsetChangedListener { enum class State { EXPANDED, COLLAPSED, IDLE } private var mCurrentState = State.IDLE override fun onOffsetChanged( appBarLayout: AppBarLayout, i: Int ) { mCurrentState = when { i == 0 -> { if (mCurrentState != State.EXPANDED) { onStateChanged(appBarLayout, State.EXPANDED) } State.EXPANDED } abs(i) >= appBarLayout.totalScrollRange -> { if (mCurrentState != State.COLLAPSED) { onStateChanged(appBarLayout, State.COLLAPSED) } State.COLLAPSED } else -> { if (mCurrentState != State.IDLE) { onStateChanged(appBarLayout, State.IDLE) } State.IDLE } } } abstract fun onStateChanged( appBarLayout: AppBarLayout?, state: State? ) }
BankApp/payees/src/main/java/com/davidm/payees/utils/CollapsingBarListener.kt
4156786246
package com.davidm.payees.utils import androidx.test.espresso.IdlingResource import java.util.concurrent.atomic.AtomicInteger class SimpleCountingIdlingResource(private val resourceName: String) : IdlingResource { private val counter = AtomicInteger(0) private var resourceCallback: IdlingResource.ResourceCallback? = null override fun getName(): String = resourceName override fun isIdleNow(): Boolean = counter.get() == 0 override fun registerIdleTransitionCallback(callback: IdlingResource.ResourceCallback?) { resourceCallback = callback } fun increment() = counter.getAndIncrement() @Throws(IllegalArgumentException::class) fun decrement() { val counterVal = counter.decrementAndGet() if (counterVal == 0) { resourceCallback?.onTransitionToIdle() } if (counterVal < 0) { throw IllegalArgumentException("Counter has been corrupted!") } } }
BankApp/payees/src/main/java/com/davidm/payees/utils/SimpleCountingIdlingResource.kt
1906518747
package com.davidm.payees.entities import com.squareup.moshi.Json data class Payee( val accounts: List<PayeeAccount>, val businessName: String?, val dateOfBirth: String?, val firstName: String?, val lastName: String?, val middleName: String?, val payeeName: String, val payeeType: PayeeType?, val payeeUid: String, val phoneNumber: String? ) data class Payees( val payees: List<Payee> ) enum class PayeeType { @Json(name = "BUSINESS") BUSINESS, @Json(name = "INDIVIDUAL") INDIVIDUAL, }
BankApp/payees/src/main/java/com/davidm/payees/entities/Payee.kt
2064298352
package com.davidm.payees.entities data class PayeeCreationResponse( val consentInformation: ConsentInformation?, val errors: List<ErrorMessage>?, val payeeUid: String?, val success: Boolean ) data class ConsentInformation( val approvalType: String ) data class ErrorMessage( val size: Int, val error: String, val error_description: String ) val defaultError = ErrorMessage(10,"Generic error", "Generic error")
BankApp/payees/src/main/java/com/davidm/payees/entities/PayeeCreationResponse.kt
1054619616
package com.davidm.payees.entities import android.os.Parcelable import kotlinx.android.parcel.Parcelize import java.util.* @Parcelize data class PayeeAccount( val accountIdentifier: String, val bankIdentifier: String, val bankIdentifierType: String?, val countryCode: String?, val defaultAccount: Boolean?, val description: String?, val payeeAccountUid: String? ): Parcelable val defaultAccount: PayeeAccount = PayeeAccount( accountIdentifier = "00000825", bankIdentifier = "204514", bankIdentifierType = "SORT_CODE", countryCode = "GB", defaultAccount = true, description = "Another account bites the dust", payeeAccountUid = UUID.randomUUID().toString() )
BankApp/payees/src/main/java/com/davidm/payees/entities/PayeeAccount.kt
198353347
package components import android.content.Context import android.util.AttributeSet import androidx.appcompat.widget.AppCompatButton class SweetButton : AppCompatButton { constructor(context: Context) : super(context) {} constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {} override fun setOnClickListener(l: OnClickListener?) { super.setOnClickListener(l) } }
BankApp/resources/src/main/java/components/SweetButton.kt
1400839177
package com.davidm.network 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.davidm.network.test", appContext.packageName) } }
BankApp/network/src/androidTest/java/com/davidm/network/ExampleInstrumentedTest.kt
1961396496
package com.davidm.network 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) } }
BankApp/network/src/test/java/com/davidm/network/ExampleUnitTest.kt
2673278552
package com.davidm.network.di import com.davidm.network.BASE_URL import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory val baseNetworkModule = module { factory<okhttp3.Interceptor> { HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT).setLevel( HttpLoggingInterceptor.Level.BODY ) } factory { OkHttpClient.Builder().addInterceptor(interceptor = get()).build() } factory<Moshi> { Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() } factory<Retrofit.Builder> { Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(MoshiConverterFactory.create(get())) .client(get()) } }
BankApp/network/src/main/java/com/davidm/network/di/BaseNetworkModuleX.kt
60165542
package com.davidm.balance 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.davidm.balance.test", appContext.packageName) } }
BankApp/balance/src/androidTest/java/com/davidm/balance/ExampleInstrumentedTest.kt
980561600
package com.davidm.balance 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) } }
BankApp/balance/src/test/java/com/davidm/balance/ExampleUnitTest.kt
3558109345
package com.davidm.ui 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.davidm.dashboard.test", appContext.packageName) } }
BankApp/dashboard/src/androidTest/java/com/davidm/ui/ExampleInstrumentedTest.kt
215410874
package com.davidm.ui 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) } }
BankApp/dashboard/src/test/java/com/davidm/ui/ExampleUnitTest.kt
406683188
package com.davidm.ui import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.ImageView import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.davidm.utils.DashboardLocalMapper import kotlinx.android.synthetic.main.purchase_list_item.view.* class DashboardNestedListAdapter : RecyclerView.Adapter<DashboardNestedListAdapter.DashboardNestedListViewHolder>() { var data = listOf<DashboardLocalMapper.LocalPurchase>() set(value) { field = value notifyDataSetChanged() } inner class DashboardNestedListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val mCounterParty: TextView = itemView.transactionTitle val mDate: TextView = itemView.shimmerDate val mAmount: TextView = itemView.shimmerAmount val mSpendingCategory: ImageView = itemView.spendingCategoryBox val purchaseListItem: ConstraintLayout = itemView.purchaseCardContainer } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): DashboardNestedListViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.purchase_list_item, parent, false) return DashboardNestedListViewHolder(view) } override fun getItemCount(): Int { return data.size } override fun onBindViewHolder(holder: DashboardNestedListViewHolder, position: Int) { val item = data[position] holder.purchaseListItem.animation = AnimationUtils.loadAnimation(holder.itemView.context, R.anim.translate_recyclerview) holder.mCounterParty.text = item.counterPartyName holder.mSpendingCategory.background.setTint( ContextCompat.getColor( holder.itemView.context, item.spendingCategoryColor ) ) holder.mSpendingCategory.setImageResource(item.spendingCategoryDrawable) holder.mSpendingCategory.setColorFilter( ContextCompat.getColor( holder.itemView.context, item.spendingCategoryColor ) ) holder.mDate.text = item.date holder.mAmount.text = item.amount holder.mAmount.setTextColor( ContextCompat.getColor( holder.itemView.context, item.amountColor ) ) } }
BankApp/dashboard/src/main/java/com/davidm/ui/DashboardNestedListAdapter.kt
1493675032
package com.davidm.ui import android.graphics.Bitmap import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.fragment.app.Fragment import androidx.recyclerview.widget.ItemTouchHelper import androidx.viewpager2.widget.ViewPager2 import com.davidm.ui.databinding.FragmentDashboardBinding import com.davidm.utils.DateIntervalHelper import com.davidm.utils.ImageUtils.Companion.getRealPathFromURI import com.davidm.utils.Permission import com.davidm.utils.PermissionManager import org.koin.android.ext.android.inject import java.io.File import java.text.DateFormatSymbols import java.util.* class DashboardFragment : Fragment() { val viewModel by inject<DashboardViewModel>() private var _binding: FragmentDashboardBinding? = null private val binding get() = _binding!! private lateinit var takePicture: ActivityResultLauncher<Void> lateinit var parentListAdapter: DashboardParentListAdapter lateinit var nestedListAdapter: DashboardNestedListAdapter lateinit var calendar: Calendar private val permissionManager = PermissionManager.from(this) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentDashboardBinding.inflate(inflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) calendar = Calendar.getInstance() nestedListAdapter = DashboardNestedListAdapter() viewModel.accountBalanceLiveData.observe(viewLifecycleOwner, { binding.balanceAmountMain.text = it.amount binding.balanceAmountCents.text = it.amountCents }) takePicture = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) { bitmap: Bitmap -> // Handle the image as a Bitmap val finalFile = File(getRealPathFromURI(requireContext(), bitmap)) viewModel.uploadProfilePicture(bitmap, finalFile) viewModel.profilePictureLiveData.observe(viewLifecycleOwner, { if (it != null) { binding.profilePicture.imageTintMode = null binding.profilePicture.setImageBitmap( it ) } }) } val data: List<DashboardParentListAdapter.ParentListItem> = DateIntervalHelper().generateDateIntervalList().map { DashboardParentListAdapter.ParentListItem(it.month, nestedListAdapter) } parentListAdapter = DashboardParentListAdapter(data, requireContext(), true) // starting point with the viewpager: we set the month to the current one and fetch the list binding.parentListViewPager.apply { adapter = parentListAdapter isUserInputEnabled = false currentItem = calendar.get(Calendar.MONTH) + 1 } binding.transactionsMonthTitle.text = DateFormatSymbols().months[binding.parentListViewPager.currentItem] viewModel.getPurchases(DateIntervalHelper().generateDateIntervalList()[binding.parentListViewPager.currentItem]) viewModel.userLiveData.observe(viewLifecycleOwner, { binding.helloUserTitle.text = getString( R.string.hello_user_text, it.firstName ) }) viewModel.getUserInfo() binding.profilePicture.setOnClickListener { permissionManager .request(Permission.Camera, Permission.Storage) .rationale("We need permission to use the camera") .checkDetailedPermission { result: Map<Permission, Boolean> -> if (result.all { it.value }) { // We have all the permissions takePicture.launch(null) } } } viewModel.fetchErrorLiveData.observe(viewLifecycleOwner, { parentListAdapter.error = it parentListAdapter.loading = false parentListAdapter.notifyDataSetChanged() }) binding.swipeRefresh.setOnRefreshListener { viewModel.getPurchases(DateIntervalHelper().generateDateIntervalList()[binding.parentListViewPager.currentItem]) binding.swipeRefresh.isRefreshing = false } binding.previousMonthButton.setOnClickListener { binding.parentListViewPager.setCurrentItem( binding.parentListViewPager.currentItem - 1, true ) } binding.nextMonthButton.setOnClickListener { binding.parentListViewPager.setCurrentItem( binding.parentListViewPager.currentItem + 1, true ) } binding.parentListViewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { binding.transactionsMonthTitle.text = DateFormatSymbols().months[position] viewModel.getPurchases(DateIntervalHelper().generateDateIntervalList()[position]) parentListAdapter.loading = true parentListAdapter.notifyDataSetChanged() } }) viewModel.purchasesLiveData.observe(viewLifecycleOwner, { nestedListAdapter.data = it parentListAdapter.data[binding.parentListViewPager.currentItem].listAdapter = nestedListAdapter parentListAdapter.loading = false parentListAdapter.notifyDataSetChanged() }) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
BankApp/dashboard/src/main/java/com/davidm/ui/DashboardFragment.kt
3832647120
package com.davidm.ui import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.facebook.shimmer.ShimmerFrameLayout import kotlinx.android.synthetic.main.empty_list_item.view.* import kotlinx.android.synthetic.main.parent_list_item.view.* import kotlinx.android.synthetic.main.shimmer_layout.view.* import java.text.DateFormatSymbols class DashboardParentListAdapter( val data: List<ParentListItem>, val context: Context, var loading: Boolean, var error: String? = null ) : RecyclerView.Adapter<RecyclerView.ViewHolder>( ) { inner class DashboardLoadingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val shimmer: ShimmerFrameLayout = itemView.shimmerContainer } inner class DashboardParentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val list: RecyclerView = itemView.transactionList } inner class DashboardEmptyListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val emptyListTextView: TextView = itemView.noResultText } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when (viewType) { 0 -> DashboardLoadingViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.shimmer_layout, parent, false) ) 1 -> DashboardEmptyListViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.empty_list_item, parent, false) ) else -> DashboardParentViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.parent_list_item, parent, false) ) } } override fun getItemCount(): Int { return data.size } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val item = data[position] when (holder) { is DashboardParentViewHolder -> holder.list.adapter = item.listAdapter is DashboardEmptyListViewHolder -> holder.emptyListTextView.text = if (error == null) { context.resources.getString( R.string.no_result_string, DateFormatSymbols().months[item.month] ) } else { error } is DashboardLoadingViewHolder -> holder.shimmer.run { stopShimmer() } } } override fun getItemViewType(position: Int): Int { return when { loading -> 0 data[position].listAdapter.data.isEmpty() -> 1 (error != null) -> 1 else -> 3 } } data class ParentListItem( val month: Int, var listAdapter: DashboardNestedListAdapter ) }
BankApp/dashboard/src/main/java/com/davidm/ui/DashboardParentListAdapter.kt
4247022459
package com.davidm.ui import android.os.Bundle import android.view.Menu import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import com.davidm.ui.databinding.ActivityHomepageBinding class HomepageActivity : AppCompatActivity() { private var _binding: ActivityHomepageBinding? = null private val binding get() = _binding!! private val dashboardFragment: DashboardFragment by lazy { DashboardFragment() } // private val payeesFragment: PayeesFragment by lazy { PayeesFragment() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) _binding = ActivityHomepageBinding.inflate(layoutInflater) window.setFlags( WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS ) setContentView(binding.root) // *** TEMPORARY DEACTIVATION OF SOME FEATURES BECAUSE OF NEW UI *** // setSupportActionBar(binding.bottomAppBar) // val bottomDialogFragment = // PayeeCreationFragment() // // fab.setOnClickListener { // bottomDialogFragment.show( // supportFragmentManager, // "new_payee_dialog_fragment" // ) // } // bottomAppBar.fabAlignmentMode = BottomAppBar.FAB_ALIGNMENT_MODE_CENTER // bottomAppBar.replaceMenu(R.menu.bottom_nav_menu) // initial position supportFragmentManager.beginTransaction() .replace(R.id.fragment_container_view_tag, dashboardFragment).commit() } // fun switchBottomAppBarVisibility(isAnimationCompleted: Boolean) { // if (isAnimationCompleted) // bottomAppBar.performHide() // else // bottomAppBar.performShow() // // } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.bottom_nav_menu, menu) return true } // override fun onOptionsItemSelected(item: MenuItem): Boolean { // when (item.itemId) { // R.id.navigation_payees -> { // // supportFragmentManager.beginTransaction() // .replace(R.id.fragment_container_view_tag, payeesFragment) // .addToBackStack("home").commit() // // bottomAppBar.fabAlignmentMode = BottomAppBar.FAB_ALIGNMENT_MODE_END // bottomAppBar.replaceMenu(R.menu.bottom_second_menu) // // } // R.id.navigation_home -> { // supportFragmentManager.popBackStack() // supportFragmentManager.beginTransaction() // .replace(R.id.fragment_container_view_tag, dashboardFragment).commit() // bottomAppBar.fabAlignmentMode = BottomAppBar.FAB_ALIGNMENT_MODE_CENTER // bottomAppBar.replaceMenu(R.menu.bottom_nav_menu) // } // // } // // return true // } // override fun onBackPressed() { // if (supportFragmentManager.backStackEntryCount > 0) { // bottomAppBar.fabAlignmentMode = BottomAppBar.FAB_ALIGNMENT_MODE_CENTER // bottomAppBar.replaceMenu(R.menu.bottom_nav_menu) // } // super.onBackPressed() // } }
BankApp/dashboard/src/main/java/com/davidm/ui/HomepageActivity.kt
3102875136
package com.davidm.ui import android.graphics.Bitmap import android.graphics.BitmapFactory import android.util.Base64 import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.davidm.account.entities.AccountHolder import com.davidm.account.entities.User import com.davidm.account.repository.AccountRepository import com.davidm.account.repository.UserRepository import com.davidm.entities.DateInterval import com.davidm.entities.StarlingTransaction import com.davidm.repository.TransactionsRepository import com.davidm.utils.AmountConverter import com.davidm.utils.DashboardLocalMapper import com.davidm.utils.ImageUtils import kotlinx.coroutines.* import java.io.File class DashboardViewModel( private val transactionsRepository: TransactionsRepository, private val accountRepository: AccountRepository, private val userRepository: UserRepository, ) : ViewModel() { private val coroutineScope = CoroutineScope(Job() + Dispatchers.Main) private val dashboardLocalMapper = DashboardLocalMapper() private val converter = AmountConverter() val purchasesLiveData = MutableLiveData<List<DashboardLocalMapper.LocalPurchase>>() val fetchErrorLiveData = MutableLiveData<String>() val accountBalanceLiveData = MutableLiveData<DashboardLocalMapper.LocalAccountBalance>() val userLiveData = MutableLiveData<User>() val profilePictureLiveData = MutableLiveData<Bitmap>() init { getAccountBalance() } fun getPurchases(dateInterval: DateInterval) { coroutineScope.launch { withContext(Dispatchers.IO) { try { val accounts = accountRepository.retrieveAccounts() val result = transactionsRepository.retrievePurchases( accounts.first(), dateInterval.startDate, dateInterval.endDate ) fetchErrorLiveData.postValue(null) updateView(starlingTransactionList = result) } catch (e: Exception) { Log.e("network_error", e.message!!) fetchErrorLiveData.postValue(e.message) } } } } fun getUserInfo() { coroutineScope.launch { val result = withContext(Dispatchers.IO) { try { userRepository.retrieveUser() } catch (e: Exception) { Log.e("user_retrieve_error", e.message!!) null } } if (result != null) { userLiveData.postValue( result ) } } } private fun getAccountBalance() { coroutineScope.launch { val result = withContext(Dispatchers.IO) { try { val accounts = accountRepository.retrieveAccounts() if (accounts.isNullOrEmpty()) { null } else { accountRepository.retrieveAccountBalance(accounts.firstOrNull()!!.accountUid) } } catch (e: Exception) { Log.e("account_retrieve_error", e.message!!) null } } if (result != null) { accountBalanceLiveData.postValue( dashboardLocalMapper.convertBalanceAmount( converter, result ) ) } } } private fun getAccountHolderID(): AccountHolder? { coroutineScope.launch { return@launch withContext(Dispatchers.IO) { try { accountRepository.retrieveAccountHolder() } catch (e: Exception) { Log.e("user_retrieve_error", e.message!!) } } } return null } private fun getProfilePicture() { coroutineScope.launch { val result = withContext(Dispatchers.IO) { try { val accountHolder = getAccountHolderID() if (accountHolder != null) { accountRepository.retrieveProfilePicture(accountHolder.accountHolderUid) } else { null } } catch (e: Exception) { Log.e("user_retrieve_error", e.message!!) null } } if (result != null) { val decodedString: ByteArray = Base64.decode(result, Base64.DEFAULT) val bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size) profilePictureLiveData.postValue( bitmap ) } } } fun uploadProfilePicture(bitmap: Bitmap, file: File) { coroutineScope.launch { val result = withContext(Dispatchers.IO) { try { val accountHolder = accountRepository.retrieveAccountHolder() accountRepository.uploadProfilePicture( accountHolder.accountHolderUid, file ) } catch (e: Exception) { Log.e("user_retrieve_error", e.message!!) null } } // it means it's ok if (result == null) { val fixedPicture = ImageUtils.checkAndFixPhotoOrientation( bitmap, file ) profilePictureLiveData.postValue( fixedPicture ) } } } private fun updateView(starlingTransactionList: List<StarlingTransaction>) { purchasesLiveData.postValue(starlingTransactionList.map { dashboardLocalMapper.convertPurchases(converter, it) }) } }
BankApp/dashboard/src/main/java/com/davidm/ui/DashboardViewModel.kt
3748653966
package com.davidm.repository import com.davidm.account.entities.Account import com.davidm.entities.StarlingTransaction import com.davidm.network.TransactionsApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class TransactionsRepository ( private val transactionsApi: TransactionsApi ) { /** * This method will retrieve the list of transactions for a specific account */ suspend fun retrievePurchases( account: Account, startDate: String, endDate: String ): List<StarlingTransaction> { return withContext(Dispatchers.IO) { return@withContext transactionsApi.getPurchasesInAWeek( account.accountUid, account.defaultCategory, startDate, endDate ).feedItems } } }
BankApp/dashboard/src/main/java/com/davidm/repository/TransactionsRepository.kt
1523429429
package com.davidm.repository import com.davidm.network.TransactionsApi import org.koin.dsl.module import retrofit2.Retrofit val transactionsRepositoryModule = module { single { TransactionsRepository(get()) } single<TransactionsApi> { (get() as Retrofit.Builder).build() .create(TransactionsApi::class.java) } }
BankApp/dashboard/src/main/java/com/davidm/repository/TransactionRepositoryModuleX.kt
494565750
package com.davidm import com.davidm.ui.DashboardFragment import com.davidm.ui.HomepageActivity import org.koin.dsl.module val dashboardModule = module { factory { HomepageActivity() } factory { DashboardFragment() } }
BankApp/dashboard/src/main/java/com/davidm/DashboardModuleX.kt
290903922
package com.davidm.network import com.davidm.entities.Purchases import retrofit2.http.* import java.time.Instant interface TransactionsApi { @GET("api/$API_VERSION/feed/account/{account}/category/{category}/transactions-between") suspend fun getPurchasesInAWeek( @Path("account") account: String, @Path("category") category: String, @Query("minTransactionTimestamp") minTime: String, @Query("maxTransactionTimestamp") maxTime: String, @Header("Authorization") token: String = "Bearer $API_KEY", @Header("Accept") value: String = "application/json" ): Purchases }
BankApp/dashboard/src/main/java/com/davidm/network/TransactionsApi.kt
3989363256
package com.davidm.utils import android.Manifest.permission.* sealed class Permission(vararg val permissions: String) { // Individual permissions object Camera : Permission(CAMERA) object Storage : Permission(WRITE_EXTERNAL_STORAGE) companion object { fun from(permission: String) = when (permission) { CAMERA -> Camera WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE -> Storage else -> throw IllegalArgumentException("Unknown permission: $permission") } } }
BankApp/dashboard/src/main/java/com/davidm/utils/Permissions.kt
2597114422
package com.davidm.utils import android.content.Context import android.database.Cursor import android.graphics.Bitmap import android.graphics.Matrix import android.net.Uri import android.provider.MediaStore import androidx.exifinterface.media.ExifInterface import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream class ImageUtils { companion object { private fun rotateImage(source: Bitmap, angle: Float): Bitmap { val matrix = Matrix() matrix.postRotate(angle) return Bitmap.createBitmap( source, 0, 0, source.width, source.height, matrix, true ) } fun checkAndFixPhotoOrientation(bitmap: Bitmap, file: File): Bitmap { val ei = ExifInterface(file) val orientation: Int = ei.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED ) val bitmap = when (orientation) { ExifInterface.ORIENTATION_ROTATE_90 -> rotateImage(bitmap, 90f) ExifInterface.ORIENTATION_ROTATE_180 -> rotateImage(bitmap, 180f) ExifInterface.ORIENTATION_ROTATE_270 -> rotateImage(bitmap, 270f) ExifInterface.ORIENTATION_NORMAL -> bitmap else -> rotateImage(bitmap, 270f) } val out = FileOutputStream(file) bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out) out.flush() out.close() return bitmap } private fun getImageUri(inContext: Context, inImage: Bitmap): Uri { val bytes = ByteArrayOutputStream() inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes) val outImage = Bitmap.createScaledBitmap(inImage, 1000, 1000, true) val path = MediaStore.Images.Media.insertImage( inContext.contentResolver, outImage, "Title", null ) return Uri.parse(path) } fun getRealPathFromURI(inContext: Context, inImage: Bitmap): String { var path = "" val uri = getImageUri(inContext, inImage) if (inContext.contentResolver != null) { val cursor: Cursor? = inContext.contentResolver.query(uri, null, null, null, null) if (cursor != null) { cursor.moveToFirst() val idx: Int = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA) path = cursor.getString(idx) cursor.close() } } return path } } }
BankApp/dashboard/src/main/java/com/davidm/utils/ImageUtils.kt
3289140878
package com.davidm.utils class AmountConverter { fun convertAmountToDouble(amount: Int): Double { return amount.toDouble() / 100.0 } fun convertAmountToInt(amount: Double): Int { return (amount * 100).toInt() } }
BankApp/dashboard/src/main/java/com/davidm/utils/AmountConverter.kt
3529309214
package com.davidm.utils import com.davidm.account.entities.AccountBalance import com.davidm.entities.StarlingTransaction import com.davidm.entities.SpendingCategory import com.davidm.ui.R import java.text.NumberFormat import java.text.SimpleDateFormat import java.util.* class DashboardLocalMapper { data class LocalPurchase( val counterPartyName: String, val amount: String, val amountColor: Int, val spendingCategoryColor: Int, val spendingCategoryDrawable: Int, val date: String, ) data class LocalAccountBalance( val amount: String, val amountCents: String, val currency: String ) fun convertPurchases( converter: AmountConverter, starlingTransaction: StarlingTransaction ): LocalPurchase { val formatter: NumberFormat = NumberFormat.getCurrencyInstance() val dateFormatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault()) val resultFormat = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()) formatter.currency = Currency.getInstance(starlingTransaction.amount.currency) val finalDate = dateFormatter.parse(starlingTransaction.transactionTime) val finalDateString = if (finalDate != null) { resultFormat.format(finalDate) } else { "Error" } val spendingCategoryColor: Int = when (starlingTransaction.spendingCategory) { SpendingCategory.EATING_OUT -> R.color.colorAccent SpendingCategory.INCOME -> R.color.spendingCategoryBlue SpendingCategory.PAYMENTS -> R.color.spendingCategoryPink SpendingCategory.GENERAL -> R.color.colorPrimary } val spendingCategoryDrawable: Int = when (starlingTransaction.spendingCategory) { SpendingCategory.EATING_OUT -> R.drawable.ic_hamburger SpendingCategory.INCOME -> R.drawable.ic_download SpendingCategory.PAYMENTS -> R.drawable.ic_money_bag SpendingCategory.GENERAL -> R.drawable.ic_credit_card } val absoluteAmount = formatter.format(converter.convertAmountToDouble(starlingTransaction.amount.minorUnits)) val amount = when (starlingTransaction.spendingCategory) { SpendingCategory.INCOME -> "+ $absoluteAmount" else -> "- $absoluteAmount" } val amountColor = when (starlingTransaction.spendingCategory) { SpendingCategory.INCOME -> R.color.positiveAmountGreen else -> R.color.negativeAmountRed } return LocalPurchase( counterPartyName = starlingTransaction.counterPartyName, amount = amount, amountColor = amountColor, spendingCategoryColor = spendingCategoryColor, spendingCategoryDrawable = spendingCategoryDrawable, date = finalDateString, ) } fun convertBalanceAmount( converter: AmountConverter, balance: AccountBalance ): LocalAccountBalance { val formatter = NumberFormat.getCurrencyInstance() formatter.currency = Currency.getInstance(balance.amount.currency) val amount: String = formatter.format(converter.convertAmountToDouble(balance.amount.minorUnits)) val amountMain = amount.split('.') return LocalAccountBalance( amount = amountMain[0], amountCents = ".${amountMain[1]}", currency = balance.amount.currency ) } }
BankApp/dashboard/src/main/java/com/davidm/utils/DashboardLocalMapper.kt
3773511837
package com.davidm.utils import android.app.AlertDialog import android.content.pm.PackageManager import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import com.davidm.ui.R import java.lang.ref.WeakReference class PermissionManager private constructor(private val fragment: WeakReference<Fragment>) { private val requiredPermissions = mutableListOf<Permission>() private var rationale: String? = null private var callback: (Boolean) -> Unit = {} private var detailedCallback: (Map<Permission,Boolean>) -> Unit = {} private val permissionCheck = fragment.get()?.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { grantResults -> sendResultAndCleanUp(grantResults) } companion object { fun from(fragment: Fragment) = PermissionManager(WeakReference(fragment)) } fun rationale(description: String): PermissionManager { rationale = description return this } fun request(vararg permission: Permission): PermissionManager { requiredPermissions.addAll(permission) return this } fun checkPermission(callback: (Boolean) -> Unit) { this.callback = callback handlePermissionRequest() } fun checkDetailedPermission(callback: (Map<Permission,Boolean>) -> Unit) { this.detailedCallback = callback handlePermissionRequest() } private fun handlePermissionRequest() { fragment.get()?.let { fragment -> when { areAllPermissionsGranted(fragment) -> sendPositiveResult() shouldShowPermissionRationale(fragment) -> displayRationale(fragment) else -> requestPermissions() } } } private fun displayRationale(fragment: Fragment) { AlertDialog.Builder(fragment.requireContext()) .setTitle("Give me your permission") .setMessage(rationale ?: "Because I want it") .setCancelable(false) .setPositiveButton("Ok sir") { _, _ -> requestPermissions() } .show() } private fun sendPositiveResult() { sendResultAndCleanUp(getPermissionList().associate { it to true } ) } private fun sendResultAndCleanUp(grantResults: Map<String, Boolean>) { callback(grantResults.all { it.value }) detailedCallback(grantResults.mapKeys { Permission.from(it.key) }) cleanUp() } private fun cleanUp() { requiredPermissions.clear() rationale = null callback = {} detailedCallback = {} } private fun requestPermissions() { permissionCheck?.launch(getPermissionList()) } private fun areAllPermissionsGranted(fragment: Fragment) = requiredPermissions.all { it.isGranted(fragment) } private fun shouldShowPermissionRationale(fragment: Fragment) = requiredPermissions.any { it.requiresRationale(fragment) } private fun getPermissionList() = requiredPermissions.flatMap { it.permissions.toList() }.toTypedArray() private fun Permission.isGranted(fragment: Fragment) = permissions.all { hasPermission(fragment, it) } private fun Permission.requiresRationale(fragment: Fragment) = permissions.any { fragment.shouldShowRequestPermissionRationale(it) } private fun hasPermission(fragment: Fragment, permission: String) = ContextCompat.checkSelfPermission( fragment.requireContext(), permission ) == PackageManager.PERMISSION_GRANTED }
BankApp/dashboard/src/main/java/com/davidm/utils/PermissionManager.kt
1199371365
package com.davidm.utils import com.davidm.entities.DateInterval import java.text.SimpleDateFormat import java.util.* class DateIntervalHelper { fun generateDateIntervalList(): List<DateInterval> { val calendar = Calendar.getInstance() // the string format that APIs want val dateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault()) val list = listOf<DateInterval>().toMutableList() for (i in Calendar.JANUARY..Calendar.DECEMBER) { // here the i variable is the month index so we can set the last day and first day date calendar.run { set(Calendar.MONTH, i) set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)) } // take the last day of the current month val endDate: Date = calendar.time calendar.set(Calendar.DAY_OF_MONTH, 1) // take the first day of the current month val startDate: Date = calendar.time list.add( DateInterval( dateFormat.format(startDate), dateFormat.format(endDate), calendar.get(Calendar.MONTH) ) ) } return list } }
BankApp/dashboard/src/main/java/com/davidm/utils/DateIntervalHelper.kt
3197559876
package com.davidm.entities data class DateInterval(val startDate: String, val endDate: String, val month: Int)
BankApp/dashboard/src/main/java/com/davidm/entities/DateInterval.kt
2938121137
package com.davidm.entities import com.davidm.account.entities.Amount import com.squareup.moshi.Json data class Purchases( val feedItems: List<StarlingTransaction> ) data class StarlingTransaction( val feedItemUid: String, val categoryUid: String, val amount: Amount, // val sourceAmount: SourceAmount, // val direction: String, // val updatedAt: String, val transactionTime: String, //val settlementTime: String?, // val source: String, //val sourceSubType: String?, //val status: String, // val counterPartyType: String, // val counterPartyUid: String, val counterPartyName: String, //val counterPartySubEntityUid: String, //val reference: String, //val country: String, val spendingCategory: SpendingCategory ) enum class SpendingCategory { @Json(name = "PAYMENTS") PAYMENTS, @Json(name = "EATING_OUT") EATING_OUT, @Json(name = "INCOME") INCOME, @Json(name = "GENERAL") GENERAL }
BankApp/dashboard/src/main/java/com/davidm/entities/StarlingTransaction.kt
1614645515
package com.davidm.account 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.davidm.account.test", appContext.packageName) } }
BankApp/account/src/androidTest/java/com/davidm/account/ExampleInstrumentedTest.kt
3107724013
package com.davidm.account 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) } }
BankApp/account/src/test/java/com/davidm/account/ExampleUnitTest.kt
2004659998
package com.davidm.account.repository import com.davidm.account.entities.Account import com.davidm.account.entities.AccountBalance import com.davidm.account.entities.AccountHolder import com.davidm.account.network.AccountApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody.Companion.asRequestBody import java.io.File class AccountRepository( private val accountApi: AccountApi ) { private var accountCachedData: List<Account>? = null private suspend fun getAccountCachedData(): List<Account> { return if (accountCachedData != null) accountCachedData!! else accountApi.getAccounts().accounts } suspend fun retrieveAccounts(): List<Account> { return if (getAccountCachedData().isNullOrEmpty()) { emptyList() } else { getAccountCachedData() } } suspend fun retrieveAccountBalance(accountId: String): AccountBalance { return withContext(Dispatchers.IO) { accountApi.getAccountBalance(accountId) } } suspend fun retrieveAccountHolder(): AccountHolder { return withContext(Dispatchers.IO) { accountApi.getAccountHolder() } } suspend fun retrieveProfilePicture(accountHolderId: String): String { return withContext(Dispatchers.IO) { accountApi.getAccountPicture(accountHolder = accountHolderId) } } suspend fun uploadProfilePicture( accountHolderId: String, file: File ): Array<String>? { return withContext(Dispatchers.IO) { accountApi.uploadAccountPicture( accountHolder = accountHolderId, requestBody = file.asRequestBody("image/*".toMediaTypeOrNull()) ) } } }
BankApp/account/src/main/java/com/davidm/account/repository/AccountRepository.kt
2958956986
package com.davidm.account.repository import com.davidm.account.entities.User import com.davidm.account.network.UserApi import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class UserRepository ( private val userApi: UserApi ) { suspend fun retrieveUser(): User { return withContext(Dispatchers.IO) { userApi.getUser() } } }
BankApp/account/src/main/java/com/davidm/account/repository/UserRepository.kt
928440738
package com.davidm.account.repository import com.davidm.account.network.AccountApi import org.koin.dsl.module import retrofit2.Retrofit val accountRepositoryModule = module { single { AccountRepository(get()) } single { (get() as Retrofit.Builder).build() .create(AccountApi::class.java) } }
BankApp/account/src/main/java/com/davidm/account/repository/AccountRepositoryModuleX.kt
2583243081
package com.davidm.account.repository import com.davidm.account.network.UserApi import org.koin.dsl.module import retrofit2.Retrofit val userRepositoryModule = module { single { UserRepository(get()) } single<UserApi> { (get() as Retrofit.Builder).build() .create(UserApi::class.java) } }
BankApp/account/src/main/java/com/davidm/account/repository/UserRepositoryModuleX.kt
1766897173
package com.davidm.account.network import com.davidm.account.entities.AccountBalance import com.davidm.account.entities.Accounts import com.davidm.account.entities.User import com.davidm.network.API_KEY import com.davidm.network.API_VERSION import retrofit2.http.GET import retrofit2.http.Header import retrofit2.http.Path interface UserApi { @GET("api/$API_VERSION/identity/individual") suspend fun getUser( @Header("Authorization") token: String = "Bearer $API_KEY", @Header("Accept") value: String = "application/json" ): User }
BankApp/account/src/main/java/com/davidm/account/network/UserApi.kt
1410169845
package com.davidm.account.network import com.davidm.account.entities.AccountBalance import com.davidm.account.entities.AccountHolder import com.davidm.account.entities.Accounts import com.davidm.network.API_KEY import com.davidm.network.API_VERSION import okhttp3.RequestBody import retrofit2.http.* interface AccountApi { @GET("api/$API_VERSION/accounts") suspend fun getAccounts( @Header("Authorization") token: String = "Bearer $API_KEY", @Header("Accept") value: String = "application/json" ): Accounts @GET("api/$API_VERSION/accounts/{accountId}/balance") suspend fun getAccountBalance( @Path("accountId") accountId: String, @Header("Authorization") token: String = "Bearer $API_KEY", @Header("Accept") value: String = "application/json" ): AccountBalance @GET("api/$API_VERSION/account-holder") suspend fun getAccountHolder( @Header("Authorization") token: String = "Bearer $API_KEY", @Header("Accept") value: String = "application/json" ): AccountHolder @GET("api/$API_VERSION/account-holder/{accountHolder}/profile-image") suspend fun getAccountPicture( @Header("Authorization") token: String = "Bearer $API_KEY", @Header("Accept") value: String = "application/json", @Path("accountHolder") accountHolder: String, ): String @PUT("api/$API_VERSION/account-holder/{accountHolder}/profile-image") suspend fun uploadAccountPicture( @Header("Authorization") token: String = "Bearer $API_KEY", @Header("Content-type") value: String = "image/jpeg", @Path("accountHolder") accountHolder: String, @Body requestBody: RequestBody ): Array<String>? }
BankApp/account/src/main/java/com/davidm/account/network/AccountApi.kt
1886841091
package com.davidm.account.entities data class AcceptedOverdraft( val currency: String, val minorUnits: Int )
BankApp/account/src/main/java/com/davidm/account/entities/AcceptedOverdraft.kt
1175723634
package com.davidm.account.entities data class Account( val accountUid: String, val defaultCategory: String, val currency: String, val createdAt: String )
BankApp/account/src/main/java/com/davidm/account/entities/Account.kt
1754479817
package com.davidm.account.entities data class PendingTransactions( val currency: String, val minorUnits: Int )
BankApp/account/src/main/java/com/davidm/account/entities/PendingTransactions.kt
3022887333
package com.davidm.account.entities data class Amount( val currency: String, val minorUnits: Int )
BankApp/account/src/main/java/com/davidm/account/entities/Amount.kt
2419081580
package com.davidm.account.entities data class Accounts( val accounts: List<Account> )
BankApp/account/src/main/java/com/davidm/account/entities/Accounts.kt
2429853834
package com.davidm.account.entities data class ClearedBalance( val currency: String, val minorUnits: Int )
BankApp/account/src/main/java/com/davidm/account/entities/ClearedBalance.kt
3711106160
package com.davidm.account.entities data class EffectiveBalance( val currency: String, val minorUnits: Int )
BankApp/account/src/main/java/com/davidm/account/entities/EffectiveBalance.kt
1136257457
package com.davidm.account.entities data class User( val dateOfBirth: String, val email: String, val firstName: String, val lastName: String, val phone: String, val title: String )
BankApp/account/src/main/java/com/davidm/account/entities/User.kt
266513236
package com.davidm.account.entities data class AccountHolder( val accountHolderType: String, val accountHolderUid: String )
BankApp/account/src/main/java/com/davidm/account/entities/AccountHolder.kt
1031638210
package com.davidm.account.entities data class AccountBalance( val acceptedOverdraft: AcceptedOverdraft, val amount: Amount, val clearedBalance: ClearedBalance, val effectiveBalance: EffectiveBalance, val pendingTransactions: PendingTransactions )
BankApp/account/src/main/java/com/davidm/account/entities/AccountBalance.kt
4183000570
package ir.mahozad.multiplatform.comshot import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.runSkikoComposeUiTest @OptIn(ExperimentalTestApi::class) actual fun captureToImage(composable: @Composable () -> Unit): ImageBitmap { // waitForIdle() var image: ImageBitmap? = null runSkikoComposeUiTest { setContent(composable) image = captureToImage() } return image!! }
comshot/library/src/iosMain/kotlin/ir/mahozad/multiplatform/comshot/Comshot.ios.kt
122375232
// Based on https://github.com/JetBrains/compose-multiplatform-core/blob/245896948b2c3716022312242691a0843ca131df/compose/ui/ui-test/src/skikoMain/kotlin/androidx/compose/ui/test/ComposeUiTest.skikoMain.kt // Relevant Code: // https://gist.github.com/handstandsam/6ecff2f39da72c0b38c07aa80bbb5a2f // https://github.com/JetBrains/compose-multiplatform-core/blob/jb-main/compose/ui/ui/src/skikoMain/kotlin/androidx/compose/ui/scene/ComposeScene.skiko.kt // https://github.com/JetBrains/compose-multiplatform-core/blob/jb-main/compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ComposeUiTest.kt // https://docs.google.com/document/d/1e7IlnBkJ5w6vJV5LqnXFPCGvomTdDxdXZRbfyBXQYsM/edit // https://github.com/JetBrains/compose-multiplatform/issues/4167 // https://github.com/JetBrains/compose-multiplatform-core/pull/589 // https://developer.android.com/jetpack/compose/migrate/interoperability-apis/compose-in-views // https://github.com/JetBrains/compose-multiplatform/issues/3972#event-11759307640 // The compose-multiplatform-core implementation for Android: // https://github.com/JetBrains/compose-multiplatform-core/blob/jb-main/compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/AndroidImageHelpers.android.kt // https://github.com/JetBrains/compose-multiplatform-core/blob/jb-main/compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/android/WindowCapture.android.kt // StackOverflow Posts: // https://stackoverflow.com/questions/63861095/jetpack-compose-take-screenshot-of-composable-function // https://stackoverflow.com/questions/74450838/convert-a-composable-view-into-image-in-jetpack-compose // https://stackoverflow.com/questions/76606244/how-to-take-a-full-screenshot-capture-in-android-compose // https://stackoverflow.com/questions/76283419/using-jetpack-compose-desktop-how-can-i-render-to-an-image-without-a-window // https://stackoverflow.com/questions/53529300/rendering-to-an-offscreen-view-and-saving-a-screenshot // https://stackoverflow.com/questions/68355969/take-screenshot-of-a-composable-fun-programmatically-in-jetpack-compose // https://stackoverflow.com/questions/69388898/taking-screenshot-of-webview-androidview-in-jetpack-compose // https://stackoverflow.com/questions/72802387/compose-view-instead-of-native-view-for-markers-info-window // https://stackoverflow.com/questions/73294041/crash-when-trying-to-measure-a-composeview-to-generate-a-bitmap-of-it // https://stackoverflow.com/questions/74256929/how-to-convert-a-composeview-to-bitmap // https://stackoverflow.com/questions/77595154/how-to-convert-all-content-of-a-composable-to-bitmap-in-android-jetpack-compose // https://stackoverflow.com/questions/70944722/composable-to-bitmap-without-displaying-it // https://stackoverflow.com/questions/75461048/how-to-renderor-convert-a-composable-to-image-in-compose-desktop // https://stackoverflow.com/questions/5604125/android-taking-screenshot-of-offscreen-page // https://stackoverflow.com/questions/7854664/render-view-to-bitmap-off-screen-in-android // https://stackoverflow.com/questions/4346710/bitmap-from-view-not-displayed-on-android // https://stackoverflow.com/questions/1240967/draw-inflated-layout-xml-on-an-bitmap // https://stackoverflow.com/questions/9062015/create-bitmap-of-layout-that-is-off-screen // https://stackoverflow.com/questions/2661536/how-to-programmatically-take-a-screenshot-on-android // https://stackoverflow.com/questions/29797590/android-webview-offscreen-rendering // https://stackoverflow.com/questions/14631682/creating-and-using-a-fragments-view-whilst-not-visible-to-the-user // https://stackoverflow.com/questions/11198872/execute-code-on-main-thread-in-android-without-access-to-an-activity // https://stackoverflow.com/questions/74433762/how-to-show-a-view-when-an-android-app-is-not-active-focused // https://stackoverflow.com/questions/74252634/how-can-i-call-a-composable-function-outside-of-an-activity // https://stackoverflow.com/questions/72497580/how-to-create-an-image-from-xml-or-composable-without-rendering // https://stackoverflow.com/questions/17189809/is-it-possible-to-take-a-screenshot-of-a-view-without-showing-the-view/26197623#26197623 // https://stackoverflow.com/questions/67586198/convert-jetpack-compose-component-to-imagebitmap /** * The compose-multiplatform-core/compose/ui/ui-test-junit4 depends on compose-multiplatform-core/compose/ui/ui-test * The Desktop, iOS, and Web depend on a SkikoMain source set for their same implementation. * The Android has a different implementation. */ package ir.mahozad.multiplatform.comshot import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.ImageBitmap expect fun captureToImage(composable: @Composable () -> Unit): ImageBitmap
comshot/library/src/commonMain/kotlin/ir/mahozad/multiplatform/comshot/Comshot.kt
4281352134
package ir.mahozad.multiplatform.comshot import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.runSkikoComposeUiTest // private val surface = Surface.makeRasterN32Premul(800, 600) // @OptIn(InternalComposeUiApi::class) // private lateinit var scene: ComposeScene // // @OptIn(InternalComposeUiApi::class) // private fun render(timeMillis: Long) { // scene.render( // surface.canvas.asComposeCanvas(), // timeMillis * NanoSecondsPerMilliSecond // ) // } // // @OptIn(InternalComposeUiApi::class) // private fun createUi() = MultiLayerComposeScene( // layoutDirection = LayoutDirection.Ltr, // invalidate = { render(0) }, // // density = Density(1f), // // coroutineContext = Dispatchers.Unconfined, // // composeSceneContext = TestComposeSceneContext(), // ).also { // it.boundsInWindow = IntSize(600, 400).toIntRect() // } // // @OptIn(InternalComposeUiApi::class) // actual fun initializeeeeeee() { // scene = createUi() // } // // @OptIn(InternalComposeUiApi::class) // actual fun setContenttt(content: @Composable () -> Unit) { // scene.setContent(content) // } @OptIn(ExperimentalTestApi::class) actual fun captureToImage(composable: @Composable () -> Unit): ImageBitmap { // waitForIdle() var image: ImageBitmap? = null runSkikoComposeUiTest { setContent(composable) image = captureToImage() } return image!! ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// // return renderComposeScene(300, 300) { // content() // }.toComposeImageBitmap() ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// // val scene = ImageComposeScene( // width = 300, // Or whatever you need // height = 300, // Or whatever you need // // density = Density(1f), // Or whatever you need // // coroutineContext = Dispatchers.Unconfined, // ) { // content() // } // val img = scene.render() // return Bitmap.makeFromImage(img).asComposeImageBitmap() ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// // MultiLayerComposeScene( // layoutDirection = LayoutDirection.Ltr, // invalidate = { render(0) }, // // density = Density(1f), // // coroutineContext = Dispatchers.Unconfined, // // composeSceneContext = TestComposeSceneContext() // ).apply { // boundsInWindow = IntSize(surface.width, surface.height).toIntRect() // } } ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // import java.util.concurrent.ExecutionException // import java.util.concurrent.FutureTask // import javax.swing.SwingUtilities // // /** // * Runs the given action on the UI thread. // * // * This method is blocking until the action is complete. // */ // internal actual fun <T> runOnUiThread(action: () -> T): T { // return if (isOnUiThread()) { // action() // } else { // val task: FutureTask<T> = FutureTask(action) // SwingUtilities.invokeAndWait(task) // try { // return task.get() // } catch (e: ExecutionException) { // Expose the original exception // throw e.cause!! // } // } // } // // /** // * Returns if the call is made on the main thread. // */ // internal actual fun isOnUiThread(): Boolean { // return SwingUtilities.isEventDispatchThread() // } // // /** // * Blocks the calling thread for [timeMillis] milliseconds. // */ // internal actual fun sleep(timeMillis: Long) { // Thread.sleep(timeMillis) // }
comshot/library/src/desktopMain/kotlin/ir/mahozad/multiplatform/comshot/Comshot.desktop.kt
2914752182
package ir.mahozad.multiplatform.comshot import android.view.ViewGroup import android.widget.Button import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.util.concurrent.Semaphore @RunWith(AndroidJUnit4::class) class ComshotTest { @get:Rule // This rule automatically creates an ActivityScenario and closes it on test finish // Could manually create and close the scenario like below: // val activityScenario = ActivityScenario.launch(ComshotTestActivity::class.java) var activityScenarioRule = ActivityScenarioRule(ComshotTestActivity::class.java) @Test fun exampleVisualTest() { // A Condition variable to prevent the activity to finish immediately and automatically var passed = false val semaphore = Semaphore(0) // activityScenarioRule.scenario.moveToState(Lifecycle.State.RESUMED) activityScenarioRule.scenario.onActivity { val fail = Button(it).apply { text = "Fail" } val pass = Button(it).apply { text = "Pass" } it.addContentView(fail, ViewGroup.LayoutParams(200, 100)) it.addContentView(pass, ViewGroup.LayoutParams(200, 100)) fail.setOnClickListener { passed = false semaphore.release() } pass.setOnClickListener { passed = true semaphore.release() } } semaphore.acquire() assert(passed) } }
comshot/library/src/androidInstrumentedTest/kotlin/ir/mahozad/multiplatform/comshot/ComshotTest.kt
393506672
package ir.mahozad.multiplatform.comshot import android.app.Activity import android.os.Bundle class ComshotTestActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // setContentView(ir.mahozad.android.test.R.layout.comshot_test_layout) // val container = findViewById(ir.mahozad.android.test.R.id.comshotTestContainer) } }
comshot/library/src/androidInstrumentedTest/kotlin/ir/mahozad/multiplatform/comshot/ComshotTestActivity.kt
3526012055
package ir.mahozad.multiplatform.comshot import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.runSkikoComposeUiTest @OptIn(ExperimentalTestApi::class) actual fun captureToImage(composable: @Composable () -> Unit): ImageBitmap { // waitForIdle() var image: ImageBitmap? = null runSkikoComposeUiTest { setContent(composable) image = captureToImage() } return image!! }
comshot/library/src/wasmJsMain/kotlin/ir/mahozad/multiplatform/comshot/Comshot.wasm.kt
122375232
package ir.mahozad.multiplatform.comshot import android.app.Activity import android.graphics.Bitmap import android.graphics.Canvas import android.os.Looper import android.view.View import android.view.ViewGroup import androidx.annotation.MainThread import androidx.compose.runtime.* import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import kotlinx.coroutines.Dispatchers actual fun captureToImage(composable: @Composable () -> Unit): ImageBitmap { error("Use the captureToImage(Activity, @Composable () -> Unit) instead") } /** * Should be called from the main thread. * You can use [Activity.runOnUiThread] if you are on another thread. * For Kotlin coroutines, use the below code if your coroutine is on another thread: * ```kotlin * val image = withContext(Dispatchers.Main) { * captureToImage(myActivity/*OR this*/, composable) * } * ``` */ @MainThread fun captureToImage( activity: Activity, composable: @Composable () -> Unit ): ImageBitmap { if (Looper.myLooper() != Looper.getMainLooper()) { error("This function should be called from the main (UI) thread. See the function documentation.") } ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// // val context = LocalContext.current // val composeView = ComposeView(this) // composeView.setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) // composeView.setParentCompositionContext(comcon) // composeView.setContent { content() } // val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager // windowManager.addView(composeView, LayoutParams()) // // composeView.createComposition() // val myBitmap: Bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888) // val myCanvas = Canvas(myBitmap) // composeView.draw(myCanvas) // return myBitmap.asImageBitmap() ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// // val composeView = ComposeView(context = this) // AndroidView( // factory = { composeView.apply { setContent(content) } }, // modifier = Modifier.wrapContentSize(unbounded = true) // Make sure to set unbounded true to draw beyond screen area // ) // return composeView.drawToBitmap().asImageBitmap() ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// // LocalView.current // val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater // val composeView = inflater.inflate(R.layout.temppp, findViewById(android.R.id.content), false) as ComposeView val composeView = ComposeView(activity) // Can also acquire CompositionContext by calling val compositionContext = rememberCompositionContext() // and passing it to our function as an argument and use that instead of this recomposer val recomposer = Recomposer(Dispatchers.Unconfined) composeView.setParentCompositionContext(recomposer) composeView.setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnLifecycleDestroyed(object : Lifecycle() { override val currentState: State get() = State.RESUMED override fun addObserver(observer: LifecycleObserver) {} override fun removeObserver(observer: LifecycleObserver) {} })) composeView.createComposition() composeView.setContent(composable) // Triggers rendering of the composable; only needed for ComposeView; not needed for other view types like TextView // The max allowed size for widthBits + heightBits is 31 bits (30_000 requires 15 bit) activity.addContentView(composeView, ViewGroup.LayoutParams(30_000, 30_000)) // OR setContentView(composeView) // @OptIn(InternalComposeUiApi::class) // composeView.showLayoutBounds = true // println("width: ${composeView.measuredWidth} height: ${composeView.measuredHeight}") // println("hasComposition: ${composeView.hasComposition}") return captureToImage(composeView) } fun captureToImage(view: View): ImageBitmap { view.measure( // OR to not constrain the image size: View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) View.MeasureSpec.makeMeasureSpec(15_000, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(15_000, View.MeasureSpec.AT_MOST), ) view.layout(0, 0, view.measuredWidth, view.measuredHeight) val bitmap = Bitmap.createBitmap( view.measuredWidth, view.measuredHeight, Bitmap.Config.ARGB_8888 ) val canvas = Canvas(bitmap) view.draw(canvas) return bitmap.asImageBitmap() } // /** // * Captures the underlying semantics node's surface into bitmap. This can be used to capture // * nodes in a normal composable, a dialog if API >=28 and in a Popup. Note that the mechanism // * used to capture the bitmap from a Popup is not the same as from a normal composable, since // * a PopUp is in a different window. // * // * @throws IllegalArgumentException if we attempt to capture a bitmap of a dialog before API 28. // */ // @OptIn(ExperimentalTestApi::class) // @RequiresApi(Build.VERSION_CODES.O) // fun SemanticsNodeInteraction.captureToImage(): ImageBitmap { // val node = fetchSemanticsNode("Failed to capture a node to bitmap.") // // Validate we are in popup // val popupParentMaybe = @Suppress("INVISIBLE_MEMBER") node.findClosestParentNode(includeSelf = true) { // it.config.contains(SemanticsProperties.IsPopup) // } // if (popupParentMaybe != null) { // return processMultiWindowScreenshot(node, @Suppress("INVISIBLE_MEMBER") testContext) // } // // val view = (node.root as ViewRootForTest).view // // // If we are in dialog use its window to capture the bitmap // val dialogParentNodeMaybe = @Suppress("INVISIBLE_MEMBER") node.findClosestParentNode(includeSelf = true) { // it.config.contains(SemanticsProperties.IsDialog) // } // var dialogWindow: Window? = null // if (dialogParentNodeMaybe != null) { // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { // // TODO(b/163023027) // throw IllegalArgumentException("Cannot currently capture dialogs on API lower than 28!") // } // // dialogWindow = findDialogWindowProviderInParent(view)?.window // ?: throw IllegalArgumentException( // "Could not find a dialog window provider to capture its bitmap" // ) // } // // val windowToUse = dialogWindow ?: view.context.getActivityWindow() // // val nodeBounds = node.boundsInRoot // val nodeBoundsRect = Rect( // nodeBounds.left.roundToInt(), // nodeBounds.top.roundToInt(), // nodeBounds.right.roundToInt(), // nodeBounds.bottom.roundToInt() // ) // // val locationInWindow = intArrayOf(0, 0) // view.getLocationInWindow(locationInWindow) // val x = locationInWindow[0] // val y = locationInWindow[1] // // // Now these are bounds in window // nodeBoundsRect.offset(x, y) // // return windowToUse.captureRegionToImage(@Suppress("INVISIBLE_MEMBER") testContext, nodeBoundsRect) // } // // @RequiresApi(Build.VERSION_CODES.O) // internal fun Window.captureRegionToImage( // testContext: TestContext, // boundsInWindow: Rect, // ): ImageBitmap { // // Turn on hardware rendering, if necessary // return withDrawingEnabled { // // First force drawing to happen // decorView.forceRedraw(testContext) // // Then we generate the bitmap // generateBitmap(boundsInWindow).asImageBitmap() // } // } // // @RequiresApi(Build.VERSION_CODES.O) // private fun Window.generateBitmap(boundsInWindow: Rect): Bitmap { // val destBitmap = // Bitmap.createBitmap( // boundsInWindow.width(), // boundsInWindow.height(), // Bitmap.Config.ARGB_8888 // ) // generateBitmapFromPixelCopy(boundsInWindow, destBitmap) // return destBitmap // } // // internal fun View.forceRedraw(testContext: TestContext) { // var drawDone = false // handler.post { // if (Build.VERSION.SDK_INT >= 29 && isHardwareAccelerated) { // FrameCommitCallbackHelper.registerFrameCommitCallback(viewTreeObserver) { // drawDone = true // } // } else { // viewTreeObserver.addOnDrawListener(object : ViewTreeObserver.OnDrawListener { // var handled = false // override fun onDraw() { // if (!handled) { // handled = true // handler.postAtFrontOfQueue { // drawDone = true // viewTreeObserver.removeOnDrawListener(this) // } // } // } // }) // } // invalidate() // } // // @OptIn(InternalTestApi::class) // @Suppress("INVISIBLE_MEMBER") // testContext.testOwner.mainClock.waitUntil(timeoutMillis = 2_000) { drawDone } // } // // // Unfortunately this is a copy paste from AndroidComposeTestRule. At this moment it is a bit // // tricky to share this method. We can expose it on TestOwner in theory. // private fun MainTestClock.waitUntil(timeoutMillis: Long, condition: () -> Boolean) { // val startTime = System.nanoTime() // while (!condition()) { // if (autoAdvance) { // advanceTimeByFrame() // } // // Let Android run measure, draw and in general any other async operations. // Thread.sleep(10) // if (System.nanoTime() - startTime > timeoutMillis * 1_000_000) { // throw ComposeTimeoutException( // "Condition still not satisfied after $timeoutMillis ms" // ) // } // } // } // // @RequiresApi(Build.VERSION_CODES.Q) // private object FrameCommitCallbackHelper { // @DoNotInline // fun registerFrameCommitCallback(viewTreeObserver: ViewTreeObserver, runnable: Runnable) { // viewTreeObserver.registerFrameCommitCallback(runnable) // } // } // // @RequiresApi(Build.VERSION_CODES.O) // private fun Window.generateBitmapFromPixelCopy(boundsInWindow: Rect, destBitmap: Bitmap) { // val latch = CountDownLatch(1) // var copyResult = 0 // val onCopyFinished = PixelCopy.OnPixelCopyFinishedListener { result -> // copyResult = result // latch.countDown() // } // PixelCopyHelper.request( // this, // boundsInWindow, // destBitmap, // onCopyFinished, // Handler(Looper.getMainLooper()) // ) // // if (!latch.await(1, TimeUnit.SECONDS)) { // throw AssertionError("Failed waiting for PixelCopy!") // } // if (copyResult != PixelCopy.SUCCESS) { // throw AssertionError("PixelCopy failed with result $copyResult!") // } // } // // @RequiresApi(Build.VERSION_CODES.O) // private object PixelCopyHelper { // @DoNotInline // fun request( // source: Window, // srcRect: Rect?, // dest: Bitmap, // listener: PixelCopy.OnPixelCopyFinishedListener, // listenerThread: Handler // ) { // PixelCopy.request(source, srcRect, dest, listener, listenerThread) // } // } // // private fun <R> withDrawingEnabled(block: () -> R): R { // val wasDrawingEnabled = HardwareRendererCompat.isDrawingEnabled() // try { // if (!wasDrawingEnabled) { // HardwareRendererCompat.setDrawingEnabled(true) // } // return block.invoke() // } finally { // if (!wasDrawingEnabled) { // HardwareRendererCompat.setDrawingEnabled(false) // } // } // } // // @ExperimentalTestApi // @RequiresApi(Build.VERSION_CODES.O) // private fun processMultiWindowScreenshot( // node: SemanticsNode, // testContext: TestContext // ): ImageBitmap { // // (node.root as ViewRootForTest).view.forceRedraw(testContext) // // val nodePositionInScreen = findNodePosition(node) // val nodeBoundsInRoot = node.boundsInRoot // // val combinedBitmap = InstrumentationRegistry.getInstrumentation().uiAutomation.takeScreenshot() // // val finalBitmap = Bitmap.createBitmap( // combinedBitmap, // (nodePositionInScreen.x + nodeBoundsInRoot.left).roundToInt(), // (nodePositionInScreen.y + nodeBoundsInRoot.top).roundToInt(), // nodeBoundsInRoot.width.roundToInt(), // nodeBoundsInRoot.height.roundToInt() // ) // return finalBitmap.asImageBitmap() // } // // private fun findNodePosition( // node: SemanticsNode // ): Offset { // val view = (node.root as ViewRootForTest).view // val locationOnScreen = intArrayOf(0, 0) // view.getLocationOnScreen(locationOnScreen) // val x = locationOnScreen[0] // val y = locationOnScreen[1] // // return Offset(x.toFloat(), y.toFloat()) // } // // internal fun findDialogWindowProviderInParent(view: View): DialogWindowProvider? { // if (view is DialogWindowProvider) { // return view // } // val parent = view.parent ?: return null // if (parent is View) { // return findDialogWindowProviderInParent(parent) // } // return null // } // // private fun Context.getActivityWindow(): Window { // fun Context.getActivity(): Activity { // return when (this) { // is Activity -> this // is ContextWrapper -> this.baseContext.getActivity() // else -> throw IllegalStateException( // "Context is not an Activity context, but a ${javaClass.simpleName} context. " + // "An Activity context is required to get a Window instance" // ) // } // } // return getActivity().window // }
comshot/library/src/androidMain/kotlin/ir/mahozad/multiplatform/comshot/Comshot.android.kt
3052906656
package ir.mahozad.multiplatform.comshot import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.runSkikoComposeUiTest @OptIn(ExperimentalTestApi::class) actual fun captureToImage(composable: @Composable () -> Unit): ImageBitmap { // waitForIdle() var image: ImageBitmap? = null runSkikoComposeUiTest { setContent(composable) image = captureToImage() } return image!! } ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // /** // * Runs the given action on the UI thread. // * // * This method is blocking until the action is complete. // */ // internal actual fun <T> runOnUiThread(action: () -> T): T { // return action() // } // // /** // * Returns if the call is made on the main thread. // */ // internal actual fun isOnUiThread(): Boolean = true // // /** // * Throws an [UnsupportedOperationException]. // */ // internal actual fun sleep(timeMillis: Long) { // throw UnsupportedOperationException("sleep is not supported in JS target") // }
comshot/library/src/jsMain/kotlin/ir/mahozad/multiplatform/comshot/Comshot.js.kt
3637186802
package comshot.showcase import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.window.CanvasBasedWindow import org.jetbrains.skiko.wasm.onWasmReady @OptIn(ExperimentalComposeUiApi::class) fun main() { console.log("Hello, Kotlin/JS!") onWasmReady { CanvasBasedWindow(title = "Comshot showcase") { MainView() } } }
comshot/showcase/jsApp/src/jsMain/kotlin/comshot/showcase/main.js.kt
2193615487
package comshot.showcase import androidx.compose.ui.window.ComposeUIViewController fun MainViewController() = ComposeUIViewController { App() }
comshot/showcase/shared/src/iosMain/kotlin/comshot/showcase/main.ios.kt
1648794561
package comshot.showcase import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.size import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.unit.dp import comshot.showcase.shared.generated.resources.Res import ir.mahozad.multiplatform.comshot.captureToImage import kotlinx.coroutines.delay import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.measureTimedValue @OptIn(ExperimentalResourceApi::class) @Composable fun App() { // To check UI responsiveness var counter by remember { mutableIntStateOf(0) } LaunchedEffect(Unit) { while (true) { counter++ delay(100.milliseconds) } } var time by remember { mutableStateOf<Duration?>(null) } var image by remember { mutableStateOf<ImageBitmap?>(null) } var padding by remember { mutableIntStateOf(1) } val composable: @Composable () -> Unit = remember { @Composable { Row(verticalAlignment = Alignment.CenterVertically) { Text(text = "!".repeat(padding)) Column(horizontalAlignment = Alignment.CenterHorizontally) { Image( painter = painterResource(Res.drawable.photo_by_lucas_chizzali_on_unsplash), modifier = Modifier.size(200.dp), contentDescription = null ) Text("Photo by Lucas Chizzali on Unsplash") Button({}) { Text("Example button $padding") } } } } } Column { Text(text = "Counter to check responsiveness: $counter") Button( onClick = { val timedValue = measureTimedValue { captureToImage(composable) } time = timedValue.duration image = timedValue.value padding++ // ImageIO.write(image.toAwtImage(), "PNG", Path("output.png").outputStream()) } ) { Text(text = "Capture ${if (time != null) "(Last one took $time)" else ""}") } image?.let { Image(it, contentDescription = null) } } }
comshot/showcase/shared/src/commonMain/kotlin/comshot/showcase/App.kt
1049671700
package comshot.showcase import androidx.compose.runtime.Composable @Composable fun MainView() = App()
comshot/showcase/shared/src/desktopMain/kotlin/comshot/showcase/main.desktop.kt
1709814691
package comshot.showcase import androidx.compose.runtime.Composable @Composable fun MainView() = App()
comshot/showcase/shared/src/wasmJsMain/kotlin/comshot/showcase/main.wasm.kt
1709814691
package comshot.showcase import android.app.Activity import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.size import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.unit.dp import comshot.showcase.shared.generated.resources.Res import ir.mahozad.multiplatform.comshot.captureToImage import kotlinx.coroutines.delay import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.measureTimedValue @OptIn(ExperimentalResourceApi::class) @Composable fun Activity.MainView() { // To check UI responsiveness var counter by remember { mutableIntStateOf(0) } LaunchedEffect(Unit) { while (true) { counter++ delay(100.milliseconds) } } var time by remember { mutableStateOf<Duration?>(null) } var image by remember { mutableStateOf<ImageBitmap?>(null) } var padding by remember { mutableIntStateOf(0) } val composable: @Composable () -> Unit = remember { @Composable { Row(verticalAlignment = Alignment.CenterVertically) { Text(text = "!".repeat(padding)) Column(horizontalAlignment = Alignment.CenterHorizontally) { Image( painter = painterResource(Res.drawable.photo_by_lucas_chizzali_on_unsplash), modifier = Modifier.size(200.dp), contentDescription = null ) Text("Photo by Lucas Chizzali on Unsplash") Button({}) { Text("Example button $padding") } } } } } Column { Text(text = "Counter to check responsiveness: $counter") Button( onClick = { val timedValue = measureTimedValue { captureToImage(this@MainView, composable) } time = timedValue.duration image = timedValue.value padding++ } ) { Text(text = "Capture ${if (time != null) "(Last one took $time)" else ""}") } image?.let { Image(it, contentDescription = null) } } }
comshot/showcase/shared/src/androidMain/kotlin/comshot/showcase/main.android.kt
2208033276
package comshot.showcase import androidx.compose.runtime.Composable @Composable fun MainView() = App()
comshot/showcase/shared/src/jsMain/kotlin/comshot/showcase/main.js.kt
1709814691
package comshot.showcase import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.window.CanvasBasedWindow @OptIn(ExperimentalComposeUiApi::class) fun main() { CanvasBasedWindow(title = "Comshot showcase") { MainView() } }
comshot/showcase/wasmJsApp/src/wasmJsMain/kotlin/comshot/showcase/main.wasm.kt
2644485262
package comshot.showcase import androidx.compose.ui.window.Window import androidx.compose.ui.window.application fun main() = application { Window( title = "Comshot showcase", onCloseRequest = ::exitApplication ) { MainView() } }
comshot/showcase/desktopApp/src/jvmMain/kotlin/comshot/showcase/main.kt
2530477514
package comshot.showcase import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MainView() } } }
comshot/showcase/androidApp/src/androidMain/kotlin/comshot/showcase/MainActivity.kt
3263682656
package edu.festu.ivankuznetsov.networkcomposeapp 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("edu.festu.ivankuznetsov.networkcomposeapp", appContext.packageName) } }
NetworkComposeApp/app/src/androidTest/java/edu/festu/ivankuznetsov/networkcomposeapp/ExampleInstrumentedTest.kt
2384524702
package edu.festu.ivankuznetsov.networkcomposeapp 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) } }
NetworkComposeApp/app/src/test/java/edu/festu/ivankuznetsov/networkcomposeapp/ExampleUnitTest.kt
1205858340
package edu.festu.ivankuznetsov.networkcomposeapp.viewmodel import androidx.lifecycle.ViewModel import edu.festu.ivankuznetsov.networkcomposeapp.repository.PostRepository /* * Будем использовать VM для того, чтобы обращаться к сети * */ class PostViewModel(private val postRepository: PostRepository):ViewModel() { fun getAllPosts() = postRepository.getAllPosts() }
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/viewmodel/PostViewModel.kt
2243994566
package edu.festu.ivankuznetsov.networkcomposeapp.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)
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/ui/theme/Color.kt
3255817776
package edu.festu.ivankuznetsov.networkcomposeapp.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 NetworkComposeAppTheme( 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 ) }
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/ui/theme/Theme.kt
1520748931
package edu.festu.ivankuznetsov.networkcomposeapp.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 ) */ )
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/ui/theme/Type.kt
3622468328
package edu.festu.ivankuznetsov.networkcomposeapp.repository import edu.festu.ivankuznetsov.networkcomposeapp.model.Post import kotlinx.coroutines.flow.Flow /* * Интерфейс, описывающий, что будем делать с сетью * */ interface PostRepository{ fun getAllPosts(): Flow<List<Post>> }
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/repository/PostRepository.kt
1446790899
package edu.festu.ivankuznetsov.networkcomposeapp.repository import edu.festu.ivankuznetsov.networkcomposeapp.model.Post import edu.festu.ivankuznetsov.networkcomposeapp.network.PostAPI import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import retrofit2.Retrofit /* * Будем брать посты с сетевого ресурса и паковать во flow * */ class PostRepositoryImpl(private val retrofit: Retrofit) : PostRepository { override fun getAllPosts(): Flow<List<Post>> = flow { emit(retrofit.create(PostAPI::class.java).getAllPosts()) } }
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/repository/PostRepositoryImpl.kt
1714026312
package edu.festu.ivankuznetsov.networkcomposeapp import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Create import androidx.compose.material3.Icon 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.runtime.mutableStateListOf 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.tooling.preview.Preview import androidx.lifecycle.viewModelScope import edu.festu.ivankuznetsov.networkcomposeapp.model.Post import edu.festu.ivankuznetsov.networkcomposeapp.network.NetworkObject import edu.festu.ivankuznetsov.networkcomposeapp.network.PostAPI import edu.festu.ivankuznetsov.networkcomposeapp.ui.theme.NetworkComposeAppTheme import edu.festu.ivankuznetsov.networkcomposeapp.viewmodel.PostViewModel import kotlinx.coroutines.launch import org.koin.androidx.compose.koinViewModel import retrofit2.Call import retrofit2.Callback import retrofit2.Response class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NetworkComposeAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Screen() } } } } } @Composable fun Screen(modifier: Modifier = Modifier, postViewModel: PostViewModel = koinViewModel()){ val posts by postViewModel.getAllPosts().collectAsState(initial = emptyList()) ListPost(listPost = posts) } @Composable fun ListPost(modifier: Modifier = Modifier, listPost: List<Post>) { LazyColumn { items(listPost) { PostCard(modifier = Modifier, title = it.title, completed = it.completed) } } } @Composable fun PostCard( modifier: Modifier, title: String, completed: Boolean ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start ) { Text(title) Icon( imageVector = if (completed) Icons.Filled.Check else Icons.Filled.Create, contentDescription = "" ) } } @Preview(showBackground = true) @Composable fun PreviewPostCard(modifier: Modifier = Modifier) { PostCard(modifier = modifier, title = "example example example", completed = false) }
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/MainActivity.kt
2603281045
package edu.festu.ivankuznetsov.networkcomposeapp.di import edu.festu.ivankuznetsov.networkcomposeapp.network.NetworkObject import edu.festu.ivankuznetsov.networkcomposeapp.network.PostAPI import edu.festu.ivankuznetsov.networkcomposeapp.repository.PostRepository import edu.festu.ivankuznetsov.networkcomposeapp.repository.PostRepositoryImpl import edu.festu.ivankuznetsov.networkcomposeapp.viewmodel.PostViewModel import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module /* * Koin для того, чтобы обеспечить работу VM с использованием PostRepository * */ val postModule = module { single<PostRepository> { PostRepositoryImpl(NetworkObject.retrofit) } viewModel { PostViewModel(get()) } }
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/di/PostModule.kt
706336970
package edu.festu.ivankuznetsov.networkcomposeapp import android.app.Application import edu.festu.ivankuznetsov.networkcomposeapp.di.postModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.GlobalContext.startKoin class PostApplication: Application(){ // lateinit var container: AppContainer override fun onCreate() { super.onCreate() // container = AppDataContainer(this) startKoin{ androidLogger() androidContext(this@PostApplication) modules(postModule) } } }
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/PostApplication.kt
1315995651
package edu.festu.ivankuznetsov.networkcomposeapp.network import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /* * Одиночка для сетевого взаимодействия * */ object NetworkObject { @Volatile var retrofit = Retrofit.Builder() .baseUrl("https://jsonplaceholder.typicode.com") .addConverterFactory(GsonConverterFactory.create()) .build() }
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/network/NetworkObject.kt
64017342
package edu.festu.ivankuznetsov.networkcomposeapp.network import edu.festu.ivankuznetsov.networkcomposeapp.model.Post import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path /* * API для взаимодействия. Поставляется одиночке для работы. * ОБРАТИТЕ ВНИМАНИЕ, функция getAllPosts - suspend! * */ interface PostAPI { @GET("todos/") suspend fun getAllPosts() :List<Post> }
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/network/PostAPI.kt
4062779003
package edu.festu.ivankuznetsov.networkcomposeapp.model /* * * Модель объекта, который будет получаться по сети * */ data class Post(val userId:Int = 0, val id:Int = 0, val title: String = "", val completed: Boolean = false)
NetworkComposeApp/app/src/main/java/edu/festu/ivankuznetsov/networkcomposeapp/model/Post.kt
793721494
package com.softyorch.firelogin 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.softyorch.firelogin", appContext.packageName) } }
FireLogin/app/src/androidTest/java/com/softyorch/firelogin/ExampleInstrumentedTest.kt
418605230
package com.softyorch.firelogin 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) } }
FireLogin/app/src/test/java/com/softyorch/firelogin/ExampleUnitTest.kt
71330712
package com.softyorch.firelogin.ui.splash import androidx.lifecycle.ViewModel import com.softyorch.firelogin.data.AuthService import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class SplashViewModel @Inject constructor(private val authService: AuthService) : ViewModel() { fun checkDestination(): SplashDestination = when (authService.isUserLogged()) { true -> SplashDestination.Home else -> SplashDestination.Login } }
FireLogin/app/src/main/java/com/softyorch/firelogin/ui/splash/SplashViewModel.kt
119810086
package com.softyorch.firelogin.ui.splash sealed class SplashDestination { object Login: SplashDestination() object Home: SplashDestination() }
FireLogin/app/src/main/java/com/softyorch/firelogin/ui/splash/SplashDestination.kt
1974225794
package com.softyorch.firelogin.ui.splash import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.softyorch.firelogin.databinding.ActivitySplashBinding import com.softyorch.firelogin.ui.detail.DetailActivity import com.softyorch.firelogin.ui.login.LoginActivity import dagger.hilt.android.AndroidEntryPoint @SuppressLint("CustomSplashScreen") @AndroidEntryPoint class SplashActivity : AppCompatActivity() { private val viewModel: SplashViewModel by viewModels() private lateinit var binding: ActivitySplashBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySplashBinding.inflate(layoutInflater) setContentView(binding.root) when (viewModel.checkDestination()) { SplashDestination.Home -> navigateToDetail() SplashDestination.Login -> navigateToLogin() } } private fun navigateToDetail() { startActivity(Intent(this, DetailActivity::class.java)) } private fun navigateToLogin() { startActivity(Intent(this, LoginActivity::class.java)) } }
FireLogin/app/src/main/java/com/softyorch/firelogin/ui/splash/SplashActivity.kt
2170736904
package com.softyorch.firelogin.ui.signup import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.softyorch.firelogin.data.AuthService import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class SignUpViewModel @Inject constructor(private val authService: AuthService) : ViewModel() { private var _isLoading = MutableStateFlow(false) val isLoading: StateFlow<Boolean> = _isLoading fun register(email: String, pass: String, navigateToDetail: () -> Unit) { if (email.isNotEmpty() && pass.isNotEmpty()) { viewModelScope.launch { _isLoading.update { true } try { val result = withContext(Dispatchers.IO) { authService.signUp(email, pass) } if (result != null) { navigateToDetail() } else { Log.w("FireLoginTag", "Firebase fail signUp") } } catch (e: Exception) { Log.e("FireLoginTag", "Firebase error: ${e.message.orEmpty()}") } _isLoading.update { false } } } } }
FireLogin/app/src/main/java/com/softyorch/firelogin/ui/signup/SignUpViewModel.kt
3372904544
package com.softyorch.firelogin.ui.signup import android.content.Intent import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isVisible import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.softyorch.firelogin.databinding.ActivitySignUpBinding import com.softyorch.firelogin.ui.detail.DetailActivity import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch @AndroidEntryPoint class SignUpActivity : AppCompatActivity() { private val viewModel: SignUpViewModel by viewModels() private lateinit var binding: ActivitySignUpBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySignUpBinding.inflate(layoutInflater) setContentView(binding.root) initUI() } private fun initUI() { initListeners() initUiState() } private fun initUiState() { lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.isLoading.collect { show -> binding.pbLoading.isVisible = show } } } } private fun initListeners() { binding.btnSingUp.setOnClickListener { viewModel.register( email = binding.tieEmail.text.toString(), pass = binding.tiePass.text.toString() ) { navigateToDetail() } } } private fun navigateToDetail() { startActivity(Intent(this, DetailActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK }) } }
FireLogin/app/src/main/java/com/softyorch/firelogin/ui/signup/SignUpActivity.kt
1658146621
package com.softyorch.firelogin.ui.detail import android.content.Intent import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.softyorch.firelogin.databinding.ActivityDetailBinding import com.softyorch.firelogin.ui.login.LoginActivity import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class DetailActivity : AppCompatActivity() { private val viewModel: DetailsViewModel by viewModels() private lateinit var binding: ActivityDetailBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailBinding.inflate(layoutInflater) setContentView(binding.root) initUI() } private fun initUI() { initListeners() } private fun initListeners() { binding.btnLogout.setOnClickListener { viewModel.logout { navigateToLogin() } } } private fun navigateToLogin() { startActivity(Intent(this, LoginActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK }) } }
FireLogin/app/src/main/java/com/softyorch/firelogin/ui/detail/DetailActivity.kt
3473678455