content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.myproducts.models
data class ErrorViewState(
val title : String,
val subTitle : String,
val cta : Cta
)
enum class Cta() {
Okay,
Retry,
} | products/app/src/main/java/com/example/myproducts/models/ErrorViewState.kt | 1810299057 |
package com.example.myproducts
import android.app.Application
import com.example.myproducts.di.KoinModules
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
class MyProductApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MyProductApplication)
modules(KoinModules.repositoryModules)
modules(KoinModules.viewModelModules)
}
}
} | products/app/src/main/java/com/example/myproducts/MyProductApplication.kt | 847665102 |
package com.example.neotaskmanager
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.neotaskmanager", appContext.packageName)
}
} | NeoTaskManager/app/src/androidTest/java/com/example/neotaskmanager/ExampleInstrumentedTest.kt | 289463680 |
package com.example.neotaskmanager
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)
}
} | NeoTaskManager/app/src/test/java/com/example/neotaskmanager/ExampleUnitTest.kt | 4214065609 |
package com.example.neotaskmanager.di
import com.example.neotaskmanager.data.repository.TaskRepository
import com.example.neotaskmanager.data.repository.TaskRepositoryImpl
import com.example.neotaskmanager.data.source.TaskDatabase
import com.example.neotaskmanager.presentation.ui.basket.GetDeletedTaskViewModel
import com.example.neotaskmanager.presentation.ui.main.DeleteTaskViewModel
import com.example.neotaskmanager.presentation.ui.main.GetCategoriesViewModel
import com.example.neotaskmanager.presentation.ui.main.GetTasksViewModel
import com.example.neotaskmanager.presentation.ui.main.InsertTaskViewModel
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.GlobalContext.loadKoinModules
import org.koin.dsl.module
fun injectFeature() = loadFeature
private val loadFeature by lazy {
loadKoinModules(
listOf(
databaseModule,
repositoryModule,
viewModelModule)
)
}
val databaseModule = module {
single { TaskDatabase.getInstance(androidContext()) }
single { get<TaskDatabase>().taskDao() }
}
val repositoryModule = module {
single<TaskRepository> { TaskRepositoryImpl(get()) }
}
val viewModelModule = module {
viewModel { GetCategoriesViewModel(get()) }
viewModel { GetTasksViewModel(get()) }
viewModel { InsertTaskViewModel(get()) }
viewModel { DeleteTaskViewModel(get()) }
viewModel { GetDeletedTaskViewModel(get()) }
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/di/DatabaseModule.kt | 3027565827 |
package com.example.neotaskmanager
import android.app.Application
import com.andexert.calendarlistview.library.BuildConfig
import com.example.neotaskmanager.di.injectFeature
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.GlobalContext.startKoin
import org.koin.core.context.stopKoin
import org.koin.core.logger.Level
class TaskTrackerApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin{
androidLogger(if (BuildConfig.DEBUG) Level.ERROR else Level.NONE)
androidContext(this@TaskTrackerApplication)
injectFeature()
}
}
override fun onTerminate() {
super.onTerminate()
stopKoin()
}
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/TaskTrackerApplication.kt | 2278657940 |
package com.example.neotaskmanager.data.repository
import com.example.neotaskmanager.data.model.CategoryWithColor
import com.example.neotaskmanager.data.model.Task
import com.example.neotaskmanager.data.source.TaskDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class TaskRepositoryImpl(private val taskDao: TaskDao) : TaskRepository {
override suspend fun insert(task: Task) {
return withContext(Dispatchers.IO) {
taskDao.insert(task)
}
}
override suspend fun update(task: Task) {
withContext(Dispatchers.IO) {
taskDao.update(task)
}
}
override suspend fun delete(taskId: Long) {
withContext(Dispatchers.IO) {
val task = taskDao.getTaskById(taskId)
task?.let {
it.isDeleted = true
taskDao.update(it)
}
}
}
override suspend fun restoreTask(taskId: Long) {
withContext(Dispatchers.IO) {
val task = taskDao.getTaskById(taskId)
task?.let {
it.isDeleted = false
taskDao.update(it)
}
}
}
override suspend fun deletedTasks(): MutableList<Task?>? {
return taskDao.deletedTasks()
}
override suspend fun getCategories(): List<CategoryWithColor> {
return taskDao.getCategories()
}
override suspend fun allTasks(currentDate: String): MutableList<Task?>? {
return taskDao.allTasks(currentDate)
}
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/data/repository/TaskRepositoryImpl.kt | 529126138 |
package com.example.neotaskmanager.data.repository
import com.example.neotaskmanager.data.model.CategoryWithColor
import com.example.neotaskmanager.data.model.Task
interface TaskRepository {
suspend fun insert(task: Task)
suspend fun update(task: Task)
suspend fun delete(taskId: Long)
suspend fun restoreTask(taskId: Long)
suspend fun deletedTasks(): MutableList<Task?>?
suspend fun getCategories(): List<CategoryWithColor>
suspend fun allTasks(currentDate: String): MutableList<Task?>?
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/data/repository/TaskRepository.kt | 3967072583 |
package com.example.neotaskmanager.data.source
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.example.neotaskmanager.data.model.Converters
import com.example.neotaskmanager.data.model.Task
import com.example.neotaskmanager.data.model.TaskData
@Database(entities = [Task::class, TaskData::class], version = 11, exportSchema = false)
@TypeConverters(Converters::class)
abstract class TaskDatabase : RoomDatabase() {
abstract fun taskDao(): TaskDao?
companion object {
@Volatile
private var INSTANCE: TaskDatabase? = null
fun getInstance(context: Context): TaskDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
TaskDatabase::class.java, "task_database"
)
.fallbackToDestructiveMigration()
.build()
INSTANCE = instance
instance
}
}
}
}
| NeoTaskManager/app/src/main/java/com/example/neotaskmanager/data/source/TaskDatabase.kt | 4145984828 |
package com.example.neotaskmanager.data.source
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.neotaskmanager.data.model.CategoryWithColor
import com.example.neotaskmanager.data.model.Task
@Dao
interface TaskDao {
@Insert
fun insert(task: Task?)
@Update
fun update(task: Task?)
@Query("SELECT * FROM tasks WHERE id = :taskId")
suspend fun getTaskById(taskId: Long?): Task?
@Query("SELECT * FROM tasks WHERE isDeleted = 1")
suspend fun deletedTasks(): MutableList<Task?>?
@Query("DELETE FROM tasks WHERE id = :taskId")
fun delete(taskId: Long)
@Query("SELECT * FROM tasks WHERE isDeleted = 0 and date == :currentDate")
suspend fun allTasks(currentDate: String): MutableList<Task?>?
@Query("SELECT DISTINCT category, categoryColor FROM tasks")
suspend fun getCategories(): List<CategoryWithColor>
}
| NeoTaskManager/app/src/main/java/com/example/neotaskmanager/data/source/TaskDao.kt | 1551063223 |
package com.example.neotaskmanager.data.model
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.DatabaseView
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverter
import kotlinx.parcelize.Parcelize
import kotlinx.parcelize.RawValue
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.util.UUID
@Parcelize
@Entity(tableName = "tasks")
data class Task(
@PrimaryKey(autoGenerate = true)
val id: Long? = null,
var category: String? = null,
var categoryColor: Int? = null,
var subTasks: @RawValue MutableList<TaskData?>? = null,
var date: String? = null,
var isDeleted: Boolean = false
) : Parcelable
@Parcelize
@Entity(tableName = "task_data")
data class TaskData(
@PrimaryKey(autoGenerate = true)
val id: Long? = null,
val title: String?,
var completed: Boolean?,
) : Parcelable
data class CategoryWithColor(
val category: String,
val categoryColor: Int
)
class Converters {
@TypeConverter
fun fromJson(value: String): MutableList<TaskData?> {
val listType = object : TypeToken<MutableList<TaskData?>>() {}.type
return Gson().fromJson(value, listType)
}
@TypeConverter
fun toJson(list: MutableList<TaskData?>): String {
return Gson().toJson(list)
}
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/data/model/Task.kt | 1084244292 |
package com.example.neotaskmanager.presentation.ui.basket
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.neotaskmanager.data.model.Task
import com.example.neotaskmanager.databinding.ItemDeletedCardBinding
import com.example.neotaskmanager.presentation.ui.main.DeleteTaskViewModel
import com.example.neotaskmanager.presentation.ui.main.TaskAdapter
class DeletedTasksAdapter(var items: MutableList<Task?>, val restoreViewModel: DeleteTaskViewModel, private val lifecycleScope: LifecycleCoroutineScope) : RecyclerView.Adapter<DeletedTasksAdapter.TaskViewHolder>(){
private var itemClickListener: OnItemClickListener? = null
fun setOnItemClickListener(listener: OnItemClickListener) {
itemClickListener = listener
}
interface OnItemClickListener {
fun onRecoverClick(task: Task)
}
fun updateData(newList: MutableList<Task?>) {
val diffResult = DiffUtil.calculateDiff(
DisplayableItemDiffCallback(
items,
newList
)
)
items = newList
diffResult.dispatchUpdatesTo(this)
}
inner class TaskViewHolder(private val binding: ItemDeletedCardBinding) : RecyclerView.ViewHolder(binding.root) {
var color: Int? = null
private val taskAdapter = TaskAdapter(mutableListOf())
init {
setupRecyclerView()
}
private fun setupRecyclerView() {
binding.rvTasks.layoutManager = LinearLayoutManager(binding.root.context)
binding.rvTasks.adapter = taskAdapter
taskAdapter.attachItemTouchHelper(binding.rvTasks)
}
fun bind(item: Task?) {
binding.cardTasksInProcess.visibility = View.GONE
if (item?.subTasks != null) {
binding.cardTasksInProcess.visibility = View.VISIBLE
}
binding.rvTasks.layoutManager = LinearLayoutManager(binding.root.context)
binding.rvTasks.adapter = taskAdapter
taskAdapter.attachItemTouchHelper(binding.rvTasks)
item?.subTasks?.let { taskAdapter.updateData(it) }
binding.categoryName.text = item?.category.toEditable()
item?.categoryColor?.let { binding.imageView.setImageResource(it) }
binding.btnRestore.setOnClickListener {
if (item != null) {
itemClickListener?.onRecoverClick(item)
}
}
}
}
fun String?.toEditable(): Editable? {
return this?.let { Editable.Factory.getInstance().newEditable(this) }
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemDeletedCardBinding.inflate(inflater, parent, false)
return TaskViewHolder(binding)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int = items.size
class DisplayableItemDiffCallback(
private val oldList: List<Task?>,
private val newList: List<Task?>
) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
}
}
| NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/basket/DeletedTasksAdapter.kt | 1038821089 |
package com.example.neotaskmanager.presentation.ui.basket
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.neotaskmanager.data.model.Task
import com.example.neotaskmanager.data.repository.TaskRepository
import kotlinx.coroutines.launch
class GetDeletedTaskViewModel(private val repository: TaskRepository) : ViewModel() {
private val _result = MutableLiveData<Result<MutableList<Task?>?>>()
val result: LiveData<Result<MutableList<Task?>?>>
get() = _result
fun fetchTasks() {
viewModelScope.launch {
try {
val tasks = repository.deletedTasks()
_result.value = Result.success(tasks)
} catch (e: Exception) {
_result.value = Result.failure(e)
}
}
}
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/basket/GetDeletedTaskViewModel.kt | 217994600 |
package com.example.neotaskmanager.presentation.ui.basket
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.neotaskmanager.R
import com.example.neotaskmanager.data.model.Task
import com.example.neotaskmanager.databinding.FragmentTrashBinding
import com.example.neotaskmanager.presentation.MainActivity
import com.example.neotaskmanager.presentation.ui.main.CategoryAdapter
import com.example.neotaskmanager.presentation.ui.main.DeleteTaskViewModel
import com.example.neotaskmanager.presentation.ui.main.InsertTaskViewModel
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
class TrashFragment : Fragment() {
private var _binding: FragmentTrashBinding? = null
private val binding: FragmentTrashBinding get() = _binding!!
private val viewModel: GetDeletedTaskViewModel by viewModel()
private val deleteTaskViewModel: DeleteTaskViewModel by viewModel()
private lateinit var adapter: DeletedTasksAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentTrashBinding.inflate(inflater, container, false)
(requireActivity() as MainActivity).hideBtmNav()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
setupNavigation()
observeTasks()
setupClickListener()
}
private fun setupNavigation() {
binding.btnBack.setOnClickListener {
findNavController().navigate(R.id.mainPageFragment)
}
}
private fun setupClickListener() {
adapter.setOnItemClickListener(object: DeletedTasksAdapter.OnItemClickListener{
override fun onRecoverClick(task: Task) {
task.id?.let { deleteTaskViewModel.restoreTask(it) }
adapter.items.remove(task)
val position = adapter.items.indexOf(task)
adapter.notifyItemRemoved(position)
Snackbar.make(binding.root, "Заметка восстановлена", Snackbar.LENGTH_SHORT)
.setActionTextColor(ContextCompat.getColor(requireContext(), R.color.yellow))
.setAction("Отменить") {
lifecycleScope.launch {
task.id?.let { it1 -> deleteTaskViewModel.deleteTask(it1) }
adapter.items.add(task)
adapter.notifyItemInserted(adapter.items.size - 1)
}
}
.show()
}
})
}
private fun setupRecyclerView() {
adapter = DeletedTasksAdapter(mutableListOf(), deleteTaskViewModel, viewLifecycleOwner.lifecycleScope)
binding.rvDeletedTasks.layoutManager = LinearLayoutManager(requireContext())
binding.rvDeletedTasks.adapter = adapter
}
private fun observeTasks() {
viewModel.fetchTasks()
viewModel.result.observe(viewLifecycleOwner, Observer { result ->
result.onSuccess { tasks ->
if (tasks != null) {
adapter.updateData(tasks)
}
}
})
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/basket/TrashFragment.kt | 4134706984 |
package com.example.neotaskmanager.presentation.ui.calendar
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CalendarView
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.example.neotaskmanager.R
import com.example.neotaskmanager.databinding.FragmentCalendarBinding
import com.example.neotaskmanager.presentation.MainActivity
import java.text.SimpleDateFormat
class CalendarFragment : Fragment() {
private var _binding: FragmentCalendarBinding? = null
private val binding: FragmentCalendarBinding
get() = _binding!!
private lateinit var calendar: CalendarView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentCalendarBinding.inflate(inflater, container, false)
(requireActivity() as MainActivity).hideBtmNav()
calendar = binding.calendar
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupCalendar()
}
private fun setupCalendar() {
calendar.setOnDateChangeListener { view, year, month, dayOfMonth ->
val selectedDate = "$year-0${month + 1}-$dayOfMonth"
binding.btnBack.setOnClickListener {
val bundle = Bundle()
bundle.putString("selectedDate", selectedDate)
findNavController().navigate(R.id.mainPageFragment, bundle)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/calendar/CalendarFragment.kt | 1432510113 |
package com.example.neotaskmanager.presentation.ui.main
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.neotaskmanager.data.model.CategoryWithColor
import com.example.neotaskmanager.data.repository.TaskRepository
import kotlinx.coroutines.launch
class GetCategoriesViewModel(private val repository: TaskRepository) : ViewModel() {
private val _result = MutableLiveData<Result<List<CategoryWithColor>>>()
val result: LiveData<Result<List<CategoryWithColor>>>
get() = _result
fun fetchCategories() {
viewModelScope.launch {
try {
val categories = repository.getCategories()
_result.value = Result.success(categories)
} catch (e: Exception) {
_result.value = Result.failure(e)
}
}
}
}
| NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/GetCategoriesViewModel.kt | 2612757549 |
package com.example.neotaskmanager.presentation.ui.main
class CustomItem(val spinnerName: String, val spinnerImage: Int)
| NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/CustomItem.kt | 864981676 |
package com.example.neotaskmanager.presentation.ui.main
import android.graphics.Paint
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.example.neotaskmanager.R
import com.example.neotaskmanager.data.model.Task
import com.example.neotaskmanager.data.model.TaskData
import com.example.neotaskmanager.databinding.ItemCardTaskBinding
import java.util.Collections
class TaskAdapter(var items: MutableList<TaskData?>) : RecyclerView.Adapter<TaskAdapter.TaskViewHolder>(){
private var itemTouchHelper: ItemTouchHelper? = null
private var itemClickListener: OnItemClickListener? = null
fun setOnItemClickListener(listener: OnItemClickListener) {
itemClickListener = listener
}
interface OnItemClickListener {
fun onDeleteClick(item: TaskData?)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemCardTaskBinding.inflate(inflater, parent, false)
return TaskViewHolder(binding)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
val item = items[position]
holder.bind(item)
}
override fun getItemCount(): Int {
return items.size
}
inner class TaskViewHolder(private val binding: ItemCardTaskBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
binding.root.setOnClickListener {
binding.btnTaskDelete.visibility = View.VISIBLE
binding.btnTaskDelete.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
val deletedItem = items[position]
items.removeAt(position)
notifyItemRemoved(position)
itemClickListener?.onDeleteClick(deletedItem)
}
}
}
binding.etTask.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
items[position] = TaskData(0, s.toString(), false)
}
}
override fun afterTextChanged(s: Editable?) {}
})
}
fun bind(task: TaskData?) {
binding.etTask.text = task?.title.toEditable()
if (task?.completed == true) {
binding.etTask.setTextColor(ContextCompat.getColor(binding.root.context, R.color.grey))
binding.etTask.paintFlags = binding.etTask.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
}
binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
items[adapterPosition]?.completed = true
binding.etTask.setTextColor(ContextCompat.getColor(binding.root.context, R.color.grey))
binding.etTask.paintFlags = binding.etTask.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
} else {
items[adapterPosition]?.completed = false
binding.etTask.setTextColor(ContextCompat.getColor(binding.root.context, R.color.black))
binding.etTask.paintFlags = binding.etTask.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
}
}
}
}
fun updateData(newList: MutableList<TaskData?>) {
val diffResult = DiffUtil.calculateDiff(
DisplayableItemDiffCallback(
items,
newList
)
)
items = newList
diffResult.dispatchUpdatesTo(this)
}
fun String?.toEditable(): Editable? {
return this?.let { Editable.Factory.getInstance().newEditable(this) }
}
fun attachItemTouchHelper(recyclerView: RecyclerView) {
itemTouchHelper = ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(
ItemTouchHelper.UP or ItemTouchHelper.DOWN,
ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT
) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
val fromPosition = viewHolder.adapterPosition
val toPosition = target.adapterPosition
if (fromPosition < toPosition) {
for (i in fromPosition until toPosition) {
Collections.swap(items, i, i + 1)
}
} else {
for (i in fromPosition downTo toPosition + 1) {
Collections.swap(items, i, i - 1)
}
}
notifyItemMoved(fromPosition, toPosition)
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
}
})
itemTouchHelper?.attachToRecyclerView(recyclerView)
}
class DisplayableItemDiffCallback(
private val oldList: List<TaskData?>,
private val newList: List<TaskData?>
) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
}
}
| NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/TaskAdapter.kt | 2385589366 |
package com.example.neotaskmanager.presentation.ui.main
class CustomColorItem(val spinnerImage: Int) | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/CustomColorItem.kt | 2513999344 |
package com.example.neotaskmanager.presentation.ui.main
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.neotaskmanager.data.repository.TaskRepository
import kotlinx.coroutines.launch
class DeleteTaskViewModel(private val repository: TaskRepository) : ViewModel() {
fun deleteTask(taskId: Long) {
viewModelScope.launch {
repository.delete(taskId)
}
}
fun restoreTask(taskId: Long) {
viewModelScope.launch {
repository.restoreTask(taskId)
}
}
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/DeleteTaskViewModel.kt | 3978355956 |
package com.example.neotaskmanager.presentation.ui.main
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.neotaskmanager.data.model.Task
import com.example.neotaskmanager.data.repository.TaskRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class GetTasksViewModel(private val repository: TaskRepository) : ViewModel() {
private val _result = MutableLiveData<Result<MutableList<Task?>?>>()
val result: LiveData<Result<MutableList<Task?>?>>
get() = _result
fun fetchTasks(currentDate: String) {
viewModelScope.launch(Dispatchers.Main) {
try {
val tasks = repository.allTasks(currentDate)
_result.value = Result.success(tasks)
} catch (e: Exception) {
_result.value = Result.failure(e)
}
}
}
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/GetTasksViewModel.kt | 1706272188 |
package com.example.neotaskmanager.presentation.ui.main
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.NonNull
import com.example.neotaskmanager.R
class CustomColorAdapter(context: Context, resource: Int, items: ArrayList<CustomColorItem>) :
ArrayAdapter<CustomColorItem>(context, resource, items) {
@NonNull
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertedView = convertView
if (convertedView == null) {
convertedView = LayoutInflater.from(context).inflate(R.layout.custom_color_spinner_layout, parent, false)
}
val item = getItem(position)
val spinnerIV = convertedView!!.findViewById<ImageView>(R.id.spinner_color)
if (item != null) {
spinnerIV.setImageResource(item.spinnerImage)
}
return convertedView
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertedView = convertView
if (convertedView == null) {
convertedView = LayoutInflater.from(context).inflate(R.layout.item_circle, parent, false)
}
val item = getItem(position)
val dropdownIV = convertedView!!.findViewById<ImageView>(R.id.dropdown_icon)
if (item != null) {
dropdownIV.setImageResource(item.spinnerImage)
}
return convertedView
}
}
| NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/CustomColorAdapter.kt | 3818236351 |
package com.example.neotaskmanager.presentation.ui.main
import android.annotation.SuppressLint
import android.content.ContentValues.TAG
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.neotaskmanager.R
import com.example.neotaskmanager.data.model.CategoryWithColor
import com.example.neotaskmanager.data.model.Task
import com.example.neotaskmanager.databinding.FragmentMainPageBinding
import com.example.neotaskmanager.presentation.MainActivity
import com.google.android.material.snackbar.Snackbar
import com.harrywhewell.scrolldatepicker.DayScrollDatePicker
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class MainPageFragment : Fragment() {
private var _binding: FragmentMainPageBinding? = null
private val binding: FragmentMainPageBinding get() = _binding!!
private val viewModel: GetCategoriesViewModel by viewModel()
private val taskViewModel: GetTasksViewModel by viewModel()
private val insertTaskViewModel: InsertTaskViewModel by viewModel()
private val deleteTaskViewModel: DeleteTaskViewModel by viewModel()
private lateinit var mPicker: DayScrollDatePicker
private lateinit var adapter: CategoryAdapter
private lateinit var recyclerView: RecyclerView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMainPageBinding.inflate(inflater, container, false)
initViews()
return binding.root
}
private fun initViews() {
(requireActivity() as MainActivity).showBtmNav()
mPicker = binding.dayScrollDatePicker
recyclerView = binding.rvTasks
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val date = arguments?.getString("selectedDate")
setupRecyclerView()
setCurrentMonth()
setupNavigation()
if (date != null) {
getTasks(date)
setupPopUpMenu(date)
}
getValue()
}
private fun setupRecyclerView() {
adapter = CategoryAdapter(mutableListOf(), insertTaskViewModel, deleteTaskViewModel, viewLifecycleOwner.lifecycleScope)
recyclerView.layoutManager = LinearLayoutManager(requireContext())
binding.rvTasks.adapter = adapter
}
private fun setupNavigation() {
binding.btnCalendar.setOnClickListener {
findNavController().navigate(R.id.calendarFragment)
}
val addButton = requireActivity().findViewById<View>(R.id.add_button)
addButton.setOnClickListener {
addEmptyCard()
}
}
private fun getTasks(date: String) {
observeTasks(date)
setupAdapterClicks(date)
}
private fun setCurrentMonth() {
val dateFormat = SimpleDateFormat("MMMM", Locale("ru"))
val currentDate = Date()
val currentMonth = dateFormat.format(currentDate)
binding.btnCalendar.text = currentMonth
}
private fun observeTasks(currentDate: String) {
adapter.deleteAllItems()
taskViewModel.fetchTasks(currentDate)
taskViewModel.result.observe(viewLifecycleOwner, Observer { result ->
result.onSuccess { tasks ->
println("tasks by date: $tasks")
if (tasks != null) {
if (tasks.isEmpty()) {
binding.textNoTasks.visibility = View.VISIBLE
} else {
binding.textNoTasks.visibility = View.GONE
adapter.updateData(tasks)
}
}
}
})
}
private fun setupPopUpMenu(currentDate: String) {
lifecycleScope.launch {
viewModel.fetchCategories()
viewModel.result.observe(viewLifecycleOwner) { result ->
result.onSuccess { categories ->
if (categories.isNotEmpty()) {
showCategoryMenu(categories, currentDate)
} else {
Snackbar.make(binding.root, "Категорий для фильтра нет", Snackbar.LENGTH_SHORT)
.setActionTextColor(ContextCompat.getColor(requireContext(), R.color.yellow))
.setAction("Создать") {
addEmptyCard()
}
.show()
}
}.onFailure { error ->
Log.e(TAG, "Error fetching categories: $error")
}
}
}
}
private fun showCategoryMenu(categoriesWithColors: List<CategoryWithColor>, currentDate: String) {
val spinner = binding.spinner
val categoriesWithAll = mutableListOf(CategoryWithColor("Все", R.drawable.spinner_item_1)).apply { addAll(categoriesWithColors) }
val customAdapter = CustomAdapter(requireContext(), R.layout.custom_spinner_layout, getCustomItems(categoriesWithAll))
spinner.adapter = customAdapter
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
@SuppressLint("NotifyDataSetChanged")
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val selectedCategory = categoriesWithAll[position].category
if (selectedCategory == "Все") {
observeTasks(currentDate)
} else {
adapter.filterByCategoryAndDate(selectedCategory, currentDate)
adapter.notifyDataSetChanged()
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
observeTasks(currentDate)
}
}
}
private fun getCustomItems(categoriesWithColors: List<CategoryWithColor>): ArrayList<CustomItem> {
val customItems = ArrayList<CustomItem>()
for (categoryWithColor in categoriesWithColors) {
customItems.add(CustomItem(categoryWithColor.category, categoryWithColor.categoryColor))
}
return customItems
}
@SuppressLint("SimpleDateFormat")
private fun getValue() {
mPicker.getSelectedDate { date ->
date?.let {
val selectedDate = SimpleDateFormat("yyyy-MM-dd").format(date)
observeTasks(selectedDate)
setupAdapterClicks(selectedDate)
setupPopUpMenu(selectedDate)
}
}
}
private fun addEmptyCard() {
val emptyTask = Task()
adapter.items.add(emptyTask)
adapter.notifyItemInserted(adapter.items.size - 1)
binding.textNoTasks.visibility = View.GONE
}
private fun setupAdapterClicks(selectedDate: String) {
adapter.setOnItemClickListener(object : CategoryAdapter.OnItemClickListener {
override fun onDeleteClick(item: Task?) {
lifecycleScope.launch {
item?.let {
it.id?.let { it1 -> deleteTaskViewModel.deleteTask(it1) }
}
}
Snackbar.make(binding.root, "Заметка отправлена в корзину", Snackbar.LENGTH_SHORT)
.setActionTextColor(ContextCompat.getColor(requireContext(), R.color.yellow))
.setAction("Отменить") {
lifecycleScope.launch {
if (item != null) {
item.id?.let { it1 -> deleteTaskViewModel.restoreTask(it1) }
}
adapter.items.add(item)
adapter.notifyItemInserted(adapter.items.size - 1)
}
}
.show()
}
override fun onSaveClick(item: Task?) {
lifecycleScope.launch {
if (item != null) {
println("item: $item")
item.date = selectedDate
insertTaskViewModel.insertTask(item)
}
}
}
override fun onUpdateClick(item: Task?) {
if (item != null) {
println("item: $item")
insertTaskViewModel.updateTask(item)
}
}
})
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/MainPageFragment.kt | 234151713 |
package com.example.neotaskmanager.presentation.ui.main
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.NonNull
import com.example.neotaskmanager.R
class CustomAdapter(context: Context, resource: Int, private val items: ArrayList<CustomItem>) :
ArrayAdapter<CustomItem>(context, resource, items) {
@NonNull
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertedView = convertView
if (convertedView == null) {
convertedView = LayoutInflater.from(context).inflate(R.layout.custom_spinner_layout, parent, false)
}
val item = getItem(position)
val spinnerIV = convertedView!!.findViewById<ImageView>(R.id.spinner_icon)
val spinnerTV = convertedView.findViewById<TextView>(R.id.spinner_text)
if (item != null) {
spinnerIV.setImageResource(item.spinnerImage)
spinnerTV.text = item.spinnerName
}
return convertedView
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
var convertedView = convertView
if (convertedView == null) {
convertedView = LayoutInflater.from(context).inflate(R.layout.custom_spinner_item, parent, false)
}
val item = getItem(position)
val dropdownIV = convertedView!!.findViewById<ImageView>(R.id.dropdown_icon)
val dropdownTV = convertedView.findViewById<TextView>(R.id.dropdown_text)
if (item != null) {
dropdownIV.setImageResource(item.spinnerImage)
dropdownTV.text = item.spinnerName
}
return convertedView
}
}
| NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/CustomAdapter.kt | 452692684 |
package com.example.neotaskmanager.presentation.ui.main
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.neotaskmanager.data.model.Task
import com.example.neotaskmanager.data.repository.TaskRepository
import kotlinx.coroutines.launch
class InsertTaskViewModel(private val repository: TaskRepository) : ViewModel() {
fun insertTask(task: Task) {
viewModelScope.launch {
repository.insert(task)
}
}
fun updateTask(task: Task) {
viewModelScope.launch {
repository.update(task)
}
}
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/InsertTaskViewModel.kt | 3273443471 |
package com.example.neotaskmanager.presentation.ui.main
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.neotaskmanager.R
import com.example.neotaskmanager.data.model.CategoryWithColor
import com.example.neotaskmanager.data.model.Task
import com.example.neotaskmanager.data.model.TaskData
import com.example.neotaskmanager.databinding.ItemCategoryCardBinding
import com.google.common.base.Strings
import kotlinx.coroutines.launch
import java.util.UUID
class CategoryAdapter(var items: MutableList<Task?>, val insertViewModel: InsertTaskViewModel, val deleteViewModel: DeleteTaskViewModel, private val lifecycleScope: LifecycleCoroutineScope) : RecyclerView.Adapter<CategoryAdapter.TaskViewHolder>(){
private var itemClickListener: OnItemClickListener? = null
fun setOnItemClickListener(listener: OnItemClickListener) {
itemClickListener = listener
}
interface OnItemClickListener {
fun onDeleteClick(item: Task?)
fun onSaveClick(item: Task?)
fun onUpdateClick(item: Task?)
}
fun updateData(newList: MutableList<Task?>) {
val diffResult = DiffUtil.calculateDiff(
DisplayableItemDiffCallback(
items,
newList
)
)
items = newList
diffResult.dispatchUpdatesTo(this)
}
fun filterByCategoryAndDate(category: String, date: String) {
val filteredList = items.filter { task ->
task?.category == category && task.date == date
}.toMutableList()
updateData(filteredList)
}
inner class TaskViewHolder(private val binding: ItemCategoryCardBinding) : RecyclerView.ViewHolder(binding.root) {
var isClicked = true
var color: Int? = null
private val taskAdapter = TaskAdapter(mutableListOf())
init {
binding.btnSave.visibility = View.VISIBLE
setupSpinner()
setupClickListener()
setupTextWatcher()
setupAddTaskButton()
setupDeleteButton()
setupSaveButton()
setupRecyclerView()
setupStarButton()
}
private fun setupStarButton() {
binding.star.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
if(isClicked) {
binding.star.setImageResource(R.drawable.star_clicked)
moveToTop(position)
} else {
binding.star.setImageResource(R.drawable.icon_star)
moveToOriginalPosition(position)
}
isClicked = !isClicked
}
}
}
private fun setupSpinner() {
val spinnerItems = arrayListOf(
CustomColorItem(R.drawable.spinner_item_1),
CustomColorItem(R.drawable.spinner_item_2),
CustomColorItem(R.drawable.spinner_item_3),
CustomColorItem(R.drawable.spinner_item_4),
CustomColorItem(R.drawable.spinner_item_5)
)
val customAdapter = CustomColorAdapter(binding.root.context, R.layout.custom_color_spinner_layout, spinnerItems)
binding.spinner.adapter = customAdapter
binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
color = spinnerItems[position].spinnerImage
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
}
private fun setupClickListener() {
binding.root.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
val clickedItem = items[position]
val drawable = ContextCompat.getDrawable(binding.root.context, R.drawable.rounded_red_card_background)
binding.card.background = drawable
binding.btnDelete.visibility = View.VISIBLE
}
}
}
private fun setupTextWatcher() {
binding.categoryName.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
val text = s.toString().trim()
binding.addTaskBtn.visibility = if (text.isNotEmpty()) View.VISIBLE else View.GONE
binding.star.visibility = if (text.isNotEmpty()) View.VISIBLE else View.GONE
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
}
private fun setupAddTaskButton() {
binding.addTaskBtn.setOnClickListener {
binding.cardTasksInProcess.visibility = View.VISIBLE
val emptyTask = TaskData(0, "", false)
taskAdapter.items.add(emptyTask)
taskAdapter.notifyItemInserted(taskAdapter.items.size - 1)
}
}
private fun setupDeleteButton() {
binding.btnDelete.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
val item = items[position]
itemClickListener?.onDeleteClick(item)
items.removeAt(position)
notifyItemRemoved(position)
}
}
}
private fun setupSaveButton() {
binding.btnSave.setOnClickListener {
val category = binding.categoryName.text.toString()
val categoryColor = color
val subTasks = taskAdapter.items
val task = Task(null, category, categoryColor, subTasks)
itemClickListener?.onSaveClick(task)
}
}
private fun setupRecyclerView() {
binding.recyclerViewInProgress.layoutManager = LinearLayoutManager(binding.root.context)
binding.recyclerViewInProgress.adapter = taskAdapter
taskAdapter.attachItemTouchHelper(binding.recyclerViewInProgress)
binding.recyclerViewCompleted.layoutManager = LinearLayoutManager(binding.root.context)
binding.recyclerViewCompleted.adapter = taskAdapter
taskAdapter.attachItemTouchHelper(binding.recyclerViewCompleted)
}
fun bind(item: Task?) {
binding.cardTasksInProcess.visibility = View.GONE
if (item?.category == null) {
binding.categoryName.visibility = View.VISIBLE
binding.spinner.visibility = View.VISIBLE
binding.nameCategory.visibility = View.GONE
binding.iconImg.visibility = View.GONE
} else {
binding.categoryName.visibility = View.GONE
binding.spinner.visibility = View.GONE
binding.nameCategory.visibility = View.VISIBLE
binding.iconImg.visibility = View.VISIBLE
binding.addTaskBtn.visibility = View.VISIBLE
}
binding.addTaskBtn.setOnClickListener {
binding.cardTasksInProcess.visibility = View.VISIBLE
val emptyTask = TaskData(0, "", false)
taskAdapter.items.add(emptyTask)
taskAdapter.notifyItemInserted(taskAdapter.items.size - 1)
}
binding.btnDelete.setOnClickListener {
itemClickListener?.onDeleteClick(item)
deleteItem(position)
}
if (item?.subTasks != null) {
binding.cardTasksInProcess.visibility = View.VISIBLE
}
binding.recyclerViewInProgress.layoutManager = LinearLayoutManager(binding.root.context)
binding.recyclerViewInProgress.adapter = taskAdapter
taskAdapter.attachItemTouchHelper(binding.recyclerViewInProgress)
val filteredNotCompletedSubTasks = item?.subTasks.filterNotCompleted()
taskAdapter.updateData(filteredNotCompletedSubTasks)
binding.recyclerViewCompleted.layoutManager = LinearLayoutManager(binding.root.context)
val completedTaskAdapter = TaskAdapter(mutableListOf())
binding.recyclerViewCompleted.adapter = completedTaskAdapter
completedTaskAdapter.attachItemTouchHelper(binding.recyclerViewCompleted)
val filteredCompletedSubTasks = item?.subTasks.filterCompleted()
if (filteredCompletedSubTasks.isEmpty()) {
binding.textViewCompleted.visibility = View.GONE
binding.recyclerViewCompleted.visibility = View.GONE
} else {
binding.textViewCompleted.visibility = View.VISIBLE
binding.recyclerViewCompleted.visibility = View.VISIBLE
completedTaskAdapter.updateData(filteredCompletedSubTasks)
}
binding.nameCategory.text = item?.category
item?.categoryColor?.let { binding.iconImg.setImageResource(it) }
if (item?.id != null) {
binding.btnSave.visibility = View.GONE
binding.btnUpdate.visibility = View.VISIBLE
} else {
binding.btnSave.visibility = View.VISIBLE
binding.btnUpdate.visibility = View.GONE
}
binding.btnUpdate.setOnClickListener {
val subTasks = taskAdapter.items
val updatedTask = item?.copy(subTasks = subTasks)
itemClickListener?.onUpdateClick(updatedTask)
}
}
}
fun List<TaskData?>?.filterCompleted(): MutableList<TaskData?> {
return this?.filter { it?.completed == true }?.toMutableList() ?: mutableListOf()
}
fun List<TaskData?>?.filterNotCompleted(): MutableList<TaskData?> {
return this?.filter { it?.completed == false }?.toMutableList() ?: mutableListOf()
}
fun moveToTop(position: Int) {
val item = items.removeAt(position)
items.add(0, item)
notifyItemMoved(position, 0)
}
fun moveToOriginalPosition(position: Int) {
val item = items.removeAt(position)
items.add(item)
notifyItemMoved(position, items.size - 1)
}
fun deleteItem(position: Int) {
items.removeAt(position)
notifyItemRemoved(position)
}
fun deleteAllItems() {
items.clear()
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = ItemCategoryCardBinding.inflate(inflater, parent, false)
return TaskViewHolder(binding)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int = items.size
class DisplayableItemDiffCallback(
private val oldList: List<Task?>,
private val newList: List<Task?>
) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
}
}
| NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/ui/main/CategoryAdapter.kt | 2435637259 |
package com.example.neotaskmanager.presentation
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.example.neotaskmanager.R
import com.example.neotaskmanager.databinding.ActivityMainBinding
import com.example.neotaskmanager.databinding.FragmentMainPageBinding
import com.google.android.material.bottomnavigation.BottomNavigationView
class MainActivity : AppCompatActivity() {
private lateinit var bottomNavigationView: BottomNavigationView
private var _binding: ActivityMainBinding? = null
private val binding: ActivityMainBinding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.fragmentContainer) as NavHostFragment
val navController = navHostFragment.navController
bottomNavigationView = findViewById(R.id.bottomNavigation)
bottomNavigationView.setupWithNavController(navController)
bottomNavigationView.setOnNavigationItemSelectedListener { menuItem ->
when(menuItem.itemId) {
R.id.btn_trash -> {
navController.navigate(R.id.trashFragment)
true
}
else -> {
false
}
}
}
}
fun hideBtmNav() {
val navBar = findViewById<View>(R.id.bottomAppBar)
val btn = findViewById<View>(R.id.add_button)
navBar.visibility = View.GONE
btn.visibility = View.GONE
}
fun showBtmNav() {
val navBar = findViewById<View>(R.id.bottomAppBar)
val btn = findViewById<View>(R.id.add_button)
navBar.visibility = View.VISIBLE
btn.visibility = View.VISIBLE
}
} | NeoTaskManager/app/src/main/java/com/example/neotaskmanager/presentation/MainActivity.kt | 4255278561 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.lint
import com.android.tools.lint.client.api.IssueRegistry
import com.android.tools.lint.client.api.Vendor
import com.android.tools.lint.detector.api.CURRENT_API
class GetoIssueRegistry : IssueRegistry() {
override val issues = listOf(
TestMethodNameDetector.FORMAT,
TestMethodNameDetector.PREFIX,
)
override val api: Int = CURRENT_API
override val minApi: Int = 12
override val vendor: Vendor = Vendor(
vendorName = "Geto",
feedbackUrl = "https://github.com/JackEblan/Geto/issues",
contact = "https://github.com/JackEblan/Geto",
)
}
| Geto/lint/src/main/kotlin/com/android/geto/lint/GetoIssueRegistry.kt | 904479574 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.lint
import com.android.tools.lint.detector.api.AnnotationInfo
import com.android.tools.lint.detector.api.AnnotationUsageInfo
import com.android.tools.lint.detector.api.Category.Companion.TESTING
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.LintFix
import com.android.tools.lint.detector.api.Scope.JAVA_FILE
import com.android.tools.lint.detector.api.Scope.TEST_SOURCES
import com.android.tools.lint.detector.api.Severity.WARNING
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.android.tools.lint.detector.api.TextFormat.RAW
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UElement
import java.util.EnumSet
import kotlin.io.path.Path
/**
* A detector that checks for common patterns in naming the test methods:
* - [detectPrefix] removes unnecessary "test" prefix in all unit test.
* - [detectFormat] Checks the `given_when_then` format of Android instrumented tests (backticks are not supported).
*/
class TestMethodNameDetector : Detector(), SourceCodeScanner {
override fun applicableAnnotations() = listOf("org.junit.Test")
override fun visitAnnotationUsage(
context: JavaContext,
element: UElement,
annotationInfo: AnnotationInfo,
usageInfo: AnnotationUsageInfo,
) {
val method = usageInfo.referenced as? PsiMethod ?: return
method.detectPrefix(context, usageInfo)
method.detectFormat(context, usageInfo)
}
private fun JavaContext.isAndroidTest() = Path("androidTest") in file.toPath()
private fun PsiMethod.detectPrefix(
context: JavaContext,
usageInfo: AnnotationUsageInfo,
) {
if (!name.startsWith("test")) return
context.report(
issue = PREFIX,
scope = usageInfo.usage,
location = context.getNameLocation(this),
message = PREFIX.getBriefDescription(RAW),
quickfixData = LintFix.create().name("Remove prefix").replace()
.pattern("""test[\s_]*""").with("").autoFix().build(),
)
}
private fun PsiMethod.detectFormat(
context: JavaContext,
usageInfo: AnnotationUsageInfo,
) {
if (!context.isAndroidTest()) return
if ("""[^\W_]+(_[^\W_]+){1,2}""".toRegex().matches(name)) return
context.report(
issue = FORMAT,
scope = usageInfo.usage,
location = context.getNameLocation(this),
message = FORMAT.getBriefDescription(RAW),
)
}
companion object {
private fun issue(
id: String,
briefDescription: String,
explanation: String,
): Issue = Issue.create(
id = id,
briefDescription = briefDescription,
explanation = explanation,
category = TESTING,
priority = 5,
severity = WARNING,
implementation = Implementation(
TestMethodNameDetector::class.java,
EnumSet.of(JAVA_FILE, TEST_SOURCES),
),
)
@JvmField
val PREFIX: Issue = issue(
id = "TestMethodPrefix",
briefDescription = "Test method starts with `test`",
explanation = "Test method should not start with `test`.",
)
@JvmField
val FORMAT: Issue = issue(
id = "TestMethodFormat",
briefDescription = "Test method does not follow the `given_when_then` or `when_then` format",
explanation = "Test method should follow the `given_when_then` or `when_then` format.",
)
}
}
| Geto/lint/src/main/kotlin/com/android/geto/lint/TestMethodNameDetector.kt | 2241110639 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.ui
import androidx.compose.ui.tooling.preview.Preview
/**
* Multipreview annotation that represents various device sizes. Add this annotation to a composable
* to render various devices.
*/
@Preview(name = "phone", device = "spec:shape=Normal,width=360,height=640,unit=dp,dpi=480")
@Preview(name = "landscape", device = "spec:shape=Normal,width=640,height=360,unit=dp,dpi=480")
@Preview(name = "foldable", device = "spec:shape=Normal,width=673,height=841,unit=dp,dpi=480")
@Preview(name = "tablet", device = "spec:shape=Normal,width=1280,height=800,unit=dp,dpi=480")
annotation class DevicePreviews
| Geto/core/ui/src/main/kotlin/com/android/geto/core/ui/DevicePreviews.kt | 994990271 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.ui
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import com.android.geto.core.model.TargetApplicationInfo
import com.android.geto.core.ui.TargetApplicationInfoPreviewParameterData.installedApplications
class TargetApplicationInfoPreviewParameterProvider :
PreviewParameterProvider<List<TargetApplicationInfo>> {
override val values: Sequence<List<TargetApplicationInfo>> = sequenceOf(installedApplications)
}
object TargetApplicationInfoPreviewParameterData {
val installedApplications = List(5) { index ->
TargetApplicationInfo(
flags = 0,
packageName = "packageName$index",
label = "Label $index",
)
}
}
| Geto/core/ui/src/main/kotlin/com/android/geto/core/ui/TargetApplicationInfoPreviewParameterProvider.kt | 4221674933 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.ui
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SettingType
import com.android.geto.core.ui.AppSettingsPreviewParameterData.appSettings
class AppSettingsPreviewParameterProvider : PreviewParameterProvider<List<AppSetting>> {
override val values: Sequence<List<AppSetting>> = sequenceOf(appSettings)
}
object AppSettingsPreviewParameterData {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = false,
settingType = SettingType.SECURE,
packageName = "com.android.geto",
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
}
| Geto/core/ui/src/main/kotlin/com/android/geto/core/ui/AppSettingsPreviewParameterProvider.kt | 884750241 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.dao
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import com.android.geto.core.database.AppDatabase
import com.android.geto.core.database.model.AppSettingEntity
import com.android.geto.core.model.SettingType
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Before
import org.junit.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class AppSettingsDaoTest {
private lateinit var appSettingsDao: AppSettingsDao
private lateinit var db: AppDatabase
@Before
fun setup() {
val context = ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder(
context,
AppDatabase::class.java,
).build()
appSettingsDao = db.appSettingsDao()
}
@After
fun tearDown() {
db.close()
}
@Test
fun getAppSettingEntitiesByPackageName() = runTest {
val appSettingEntities = List(10) { index ->
AppSettingEntity(
id = index,
enabled = false,
settingType = SettingType.GLOBAL,
packageName = "com.android.geto",
label = "Geto",
key = "Geto",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
appSettingsDao.upsertAppSettingEntities(appSettingEntities)
val appSettingEntitiesByPackageName =
appSettingsDao.getAppSettingEntitiesByPackageName("com.android.geto").first()
assertTrue {
appSettingEntitiesByPackageName.containsAll(appSettingEntities)
}
}
@Test
fun deleteAppSettingEntitiesByPackageName() = runTest {
val oldAppSettingsEntities = List(10) { index ->
AppSettingEntity(
id = index,
enabled = false,
settingType = SettingType.GLOBAL,
packageName = "com.android.geto.old",
label = "Geto",
key = "Geto",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
val newAppSettingsEntities = List(10) { index ->
AppSettingEntity(
id = index + 11,
enabled = false,
settingType = SettingType.GLOBAL,
packageName = "com.android.geto.new",
label = "Geto",
key = "Geto",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
appSettingsDao.upsertAppSettingEntities(oldAppSettingsEntities + newAppSettingsEntities)
appSettingsDao.deleteAppSettingEntitiesByPackageName(packageNames = listOf("com.android.geto.old"))
val appSettingsList = appSettingsDao.getAppSettingEntities().first()
assertFalse {
appSettingsList.containsAll(oldAppSettingsEntities)
}
assertTrue {
appSettingsList.containsAll(newAppSettingsEntities)
}
}
}
| Geto/core/database/src/androidTest/kotlin/com/android/geto/core/database/dao/AppSettingsDaoTest.kt | 1625029292 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.migration
import androidx.room.Room
import androidx.room.testing.MigrationTestHelper
import androidx.test.platform.app.InstrumentationRegistry
import com.android.geto.core.database.AppDatabase
import org.junit.Rule
import org.junit.Test
import java.io.IOException
class MigrationTest {
private val testDb = "migration-test"
private val allMigrations = arrayOf(
Migration1To2(),
Migration2To3(),
Migration3To4(),
Migration4To5(),
Migration5To6(),
Migration6To7(),
)
@get:Rule
val helper: MigrationTestHelper = MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(),
AppDatabase::class.java,
)
@Test
@Throws(IOException::class)
fun migrate1To2() {
helper.createDatabase(testDb, 1).apply {
execSQL("INSERT INTO UserAppSettingsItemEntity (enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert) VALUES (1, 'GLOBAL', 'com.android.geto', 'label', 'key', 'valueOnLaunch', 'valueOnRevert')")
close()
}
helper.runMigrationsAndValidate(testDb, 2, true, Migration1To2())
}
@Test
@Throws(IOException::class)
fun migrate2To3() {
helper.createDatabase(testDb, 2).apply {
execSQL("INSERT INTO AppSettingsItemEntity (enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert) VALUES (1, 'GLOBAL', 'com.android.geto', 'label', 'key', 'valueOnLaunch', 'valueOnRevert')")
close()
}
helper.runMigrationsAndValidate(testDb, 3, true, Migration2To3())
}
@Test
@Throws(IOException::class)
fun migrate3To4() {
helper.createDatabase(testDb, 3).apply {
execSQL("INSERT INTO AppSettingsItemEntity (id, enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert) VALUES (0, 1, 'GLOBAL', 'com.android.geto', 'label', 'key', 'valueOnLaunch', 'valueOnRevert')")
close()
}
helper.runMigrationsAndValidate(testDb, 4, true, Migration3To4())
}
@Test
@Throws(IOException::class)
fun migrate4To5() {
helper.createDatabase(testDb, 4).apply {
execSQL("INSERT INTO AppSettingsItemEntity (id, enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert, safeToWrite) VALUES (0, 1, 'GLOBAL', 'com.android.geto', 'label', 'key', 'valueOnLaunch', 'valueOnRevert', 1)")
close()
}
helper.runMigrationsAndValidate(testDb, 5, true, Migration4To5())
}
@Test
@Throws(IOException::class)
fun migrate5To6() {
helper.createDatabase(testDb, 5).apply {
execSQL("INSERT INTO AppSettingsEntity (id, enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert, safeToWrite) VALUES (0, 1, 'GLOBAL', 'com.android.geto', 'label', 'key', 'valueOnLaunch', 'valueOnRevert', 1)")
close()
}
helper.runMigrationsAndValidate(testDb, 6, true, Migration5To6())
}
@Test
@Throws(IOException::class)
fun migrate6To7() {
helper.createDatabase(testDb, 6).apply {
execSQL("INSERT INTO AppSettingsEntity (id, enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert) VALUES (0, 1, 'GLOBAL', 'com.android.geto', 'label', 'key', 'valueOnLaunch', 'valueOnRevert')")
close()
}
helper.runMigrationsAndValidate(testDb, 7, true, Migration6To7())
}
@Test
@Throws(IOException::class)
fun migrateAll() {
helper.createDatabase(testDb, 1).apply {
close()
}
Room.databaseBuilder(
InstrumentationRegistry.getInstrumentation().targetContext,
AppDatabase::class.java,
testDb,
).addMigrations(*allMigrations).build().apply {
openHelper.writableDatabase.close()
}
}
}
| Geto/core/database/src/androidTest/kotlin/com/android/geto/core/database/migration/MigrationTest.kt | 2940208385 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.di
import com.android.geto.core.database.AppDatabase
import com.android.geto.core.database.dao.AppSettingsDao
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal object DaoModule {
@Provides
@Singleton
fun appSettingsDao(appDatabase: AppDatabase): AppSettingsDao = appDatabase.appSettingsDao()
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/di/DaoModule.kt | 813798821 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.di
import android.content.Context
import androidx.room.Room
import com.android.geto.core.database.AppDatabase
import com.android.geto.core.database.migration.Migration1To2
import com.android.geto.core.database.migration.Migration2To3
import com.android.geto.core.database.migration.Migration3To4
import com.android.geto.core.database.migration.Migration4To5
import com.android.geto.core.database.migration.Migration5To6
import com.android.geto.core.database.migration.Migration6To7
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal object DatabaseModule {
@Singleton
@Provides
fun appDatabase(@ApplicationContext context: Context): AppDatabase = Room.databaseBuilder(
context,
AppDatabase::class.java,
AppDatabase.DATABASE_NAME,
).addMigrations(
Migration1To2(),
Migration2To3(),
Migration3To4(),
Migration4To5(),
Migration5To6(),
Migration6To7(),
).build()
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/di/DatabaseModule.kt | 784754154 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.dao
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Query
import androidx.room.Upsert
import com.android.geto.core.database.model.AppSettingEntity
import kotlinx.coroutines.flow.Flow
@Dao
interface AppSettingsDao {
@Upsert
suspend fun upsertAppSettingEntity(entity: AppSettingEntity)
@Delete
suspend fun deleteAppSettingEntity(entity: AppSettingEntity)
@Query("SELECT * FROM AppSettingEntity WHERE packageName = :packageName")
fun getAppSettingEntitiesByPackageName(packageName: String): Flow<List<AppSettingEntity>>
@Query("SELECT * FROM AppSettingEntity")
fun getAppSettingEntities(): Flow<List<AppSettingEntity>>
@Query("DELETE FROM AppSettingEntity WHERE packageName IN (:packageNames)")
suspend fun deleteAppSettingEntitiesByPackageName(packageNames: List<String>)
@Upsert
suspend fun upsertAppSettingEntities(entities: List<AppSettingEntity>)
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/dao/AppSettingsDao.kt | 2775469883 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.RoomDatabase
import com.android.geto.core.database.dao.AppSettingsDao
import com.android.geto.core.database.migration.DeleteSafeToWrite
import com.android.geto.core.database.migration.RenameAppSettingsEntityToAppSettingEntity
import com.android.geto.core.database.migration.RenameAppSettingsItemEntityToAppSettingsEntity
import com.android.geto.core.database.migration.RenameUserAppSettingsItemEntityToAppSettingsItemEntity
import com.android.geto.core.database.model.AppSettingEntity
@Database(
entities = [AppSettingEntity::class],
version = 7,
autoMigrations = [
AutoMigration(
from = 1,
to = 2,
spec = RenameUserAppSettingsItemEntityToAppSettingsItemEntity::class,
),
AutoMigration(
from = 4,
to = 5,
spec = RenameAppSettingsItemEntityToAppSettingsEntity::class,
),
AutoMigration(
from = 5,
to = 6,
spec = DeleteSafeToWrite::class,
),
AutoMigration(
from = 6,
to = 7,
spec = RenameAppSettingsEntityToAppSettingEntity::class,
),
],
exportSchema = true,
)
internal abstract class AppDatabase : RoomDatabase() {
abstract fun appSettingsDao(): AppSettingsDao
companion object {
const val DATABASE_NAME = "Geto.db"
}
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/AppDatabase.kt | 1003201855 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SettingType
@Entity
data class AppSettingEntity(
@PrimaryKey(autoGenerate = true) val id: Int? = null,
val enabled: Boolean,
val settingType: SettingType,
val packageName: String,
val label: String,
val key: String,
val valueOnLaunch: String,
val valueOnRevert: String,
)
fun AppSettingEntity.asExternalModel(): AppSetting {
return AppSetting(
id = id,
enabled = enabled,
settingType = settingType,
packageName = packageName,
label = label,
key = key,
valueOnLaunch = valueOnLaunch,
valueOnRevert = valueOnRevert,
)
}
fun AppSetting.asEntity(): AppSettingEntity {
return AppSettingEntity(
id = id,
enabled = enabled,
settingType = settingType,
packageName = packageName,
label = label,
key = key,
valueOnLaunch = valueOnLaunch,
valueOnRevert = valueOnRevert,
)
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/model/AppSettingEntity.kt | 4270809972 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
internal class Migration4To5 : Migration(4, 5) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE IF NOT EXISTS new_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
enabled INTEGER NOT NULL,
settingsType TEXT NOT NULL,
packageName TEXT NOT NULL,
label TEXT NOT NULL,
key TEXT NOT NULL,
valueOnLaunch TEXT NOT NULL,
valueOnRevert TEXT NOT NULL,
safeToWrite INTEGER NOT NULL DEFAULT 1
)
""".trimIndent(),
)
db.execSQL("INSERT INTO new_table (id, enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert, safeToWrite) SELECT * FROM AppSettingsItemEntity")
db.execSQL("DROP TABLE AppSettingsItemEntity")
db.execSQL("ALTER TABLE new_table RENAME TO AppSettingsEntity")
}
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/migration/Migration4To5.kt | 466006396 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
internal class Migration3To4 : Migration(3, 4) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE IF NOT EXISTS new_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
enabled INTEGER NOT NULL,
settingsType TEXT NOT NULL,
packageName TEXT NOT NULL,
label TEXT NOT NULL,
key TEXT NOT NULL,
valueOnLaunch TEXT NOT NULL,
valueOnRevert TEXT NOT NULL,
safeToWrite INTEGER NOT NULL DEFAULT 1
)
""".trimIndent(),
)
db.execSQL("INSERT INTO new_table (id, enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert) SELECT * FROM AppSettingsItemEntity")
db.execSQL("DROP TABLE AppSettingsItemEntity")
db.execSQL("ALTER TABLE new_table RENAME TO AppSettingsItemEntity")
}
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/migration/Migration3To4.kt | 2499900213 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
internal class Migration1To2 : Migration(1, 2) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE IF NOT EXISTS new_table (
enabled INTEGER NOT NULL,
settingsType TEXT NOT NULL,
packageName TEXT NOT NULL,
label TEXT NOT NULL,
key TEXT NOT NULL,
valueOnLaunch TEXT NOT NULL,
valueOnRevert TEXT NOT NULL,
PRIMARY KEY(key)
)
""".trimIndent(),
)
db.execSQL("INSERT INTO new_table (enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert) SELECT * FROM UserAppSettingsItemEntity")
db.execSQL("DROP TABLE UserAppSettingsItemEntity")
db.execSQL("ALTER TABLE new_table RENAME TO AppSettingsItemEntity")
}
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/migration/Migration1To2.kt | 3553329432 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.migration
import androidx.room.DeleteColumn
import androidx.room.RenameColumn
import androidx.room.RenameTable
import androidx.room.migration.AutoMigrationSpec
@RenameTable(fromTableName = "UserAppSettingsItemEntity", toTableName = "AppSettingsItemEntity")
internal class RenameUserAppSettingsItemEntityToAppSettingsItemEntity : AutoMigrationSpec
@RenameTable(fromTableName = "AppSettingsItemEntity", toTableName = "AppSettingsEntity")
internal class RenameAppSettingsItemEntityToAppSettingsEntity : AutoMigrationSpec
@DeleteColumn(tableName = "AppSettingsEntity", columnName = "safeToWrite")
internal class DeleteSafeToWrite : AutoMigrationSpec
@RenameTable(fromTableName = "AppSettingsEntity", toTableName = "AppSettingEntity")
@RenameColumn(
tableName = "AppSettingsEntity",
fromColumnName = "settingsType",
toColumnName = "settingType",
)
internal class RenameAppSettingsEntityToAppSettingEntity : AutoMigrationSpec
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/migration/AutoMigration.kt | 716700297 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
internal class Migration5To6 : Migration(5, 6) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE IF NOT EXISTS new_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
enabled INTEGER NOT NULL,
settingsType TEXT NOT NULL,
packageName TEXT NOT NULL,
label TEXT NOT NULL,
key TEXT NOT NULL,
valueOnLaunch TEXT NOT NULL,
valueOnRevert TEXT NOT NULL
)
""".trimIndent(),
)
db.execSQL("INSERT INTO new_table (id, enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert) SELECT id, enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert FROM AppSettingsEntity")
db.execSQL("DROP TABLE AppSettingsEntity")
db.execSQL("ALTER TABLE new_table RENAME TO AppSettingsEntity")
}
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/migration/Migration5To6.kt | 3710321044 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
internal class Migration6To7 : Migration(6, 7) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE IF NOT EXISTS new_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
enabled INTEGER NOT NULL,
settingType TEXT NOT NULL,
packageName TEXT NOT NULL,
label TEXT NOT NULL,
key TEXT NOT NULL,
valueOnLaunch TEXT NOT NULL,
valueOnRevert TEXT NOT NULL
)
""".trimIndent(),
)
db.execSQL("INSERT INTO new_table (id, enabled, settingType, packageName, label, key, valueOnLaunch, valueOnRevert) SELECT id, enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert FROM AppSettingsEntity")
db.execSQL("DROP TABLE AppSettingsEntity")
db.execSQL("ALTER TABLE new_table RENAME TO AppSettingEntity")
}
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/migration/Migration6To7.kt | 88768157 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.database.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
internal class Migration2To3 : Migration(2, 3) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL(
"""
CREATE TABLE IF NOT EXISTS new_table (
id INTEGER PRIMARY KEY AUTOINCREMENT,
enabled INTEGER NOT NULL,
settingsType TEXT NOT NULL,
packageName TEXT NOT NULL,
label TEXT NOT NULL,
key TEXT NOT NULL,
valueOnLaunch TEXT NOT NULL,
valueOnRevert TEXT NOT NULL
)
""".trimIndent(),
)
db.execSQL("INSERT INTO new_table (enabled, settingsType, packageName, label, key, valueOnLaunch, valueOnRevert) SELECT * FROM AppSettingsItemEntity")
db.execSQL("DROP TABLE AppSettingsItemEntity")
db.execSQL("ALTER TABLE new_table RENAME TO AppSettingsItemEntity")
}
}
| Geto/core/database/src/main/kotlin/com/android/geto/core/database/migration/Migration2To3.kt | 1221735591 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.unit.dp
import com.android.geto.core.designsystem.theme.BackgroundTheme
import com.android.geto.core.designsystem.theme.DarkAndroidBackgroundTheme
import com.android.geto.core.designsystem.theme.DarkAndroidColorScheme
import com.android.geto.core.designsystem.theme.DarkDefaultColorScheme
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.designsystem.theme.LightAndroidBackgroundTheme
import com.android.geto.core.designsystem.theme.LightAndroidColorScheme
import com.android.geto.core.designsystem.theme.LightDefaultColorScheme
import com.android.geto.core.designsystem.theme.LocalBackgroundTheme
import com.android.geto.core.designsystem.theme.LocalTintTheme
import com.android.geto.core.designsystem.theme.TintTheme
import org.junit.Rule
import org.junit.Test
import kotlin.test.assertEquals
/**
* Tests [GetoTheme] using different combinations of the theme mode parameters:
* darkTheme, disableDynamicTheming, and androidTheme.
*
* It verifies that the various composition locals — [MaterialTheme] and
* [LocalBackgroundTheme] — have the expected values for a given theme mode, as specified by the
* design system.
*/
class ThemeTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun darkThemeFalse_dynamicColorFalse_androidThemeFalse() {
composeTestRule.setContent {
GetoTheme(
darkTheme = false,
disableDynamicTheming = true,
androidTheme = false,
) {
val colorScheme = LightDefaultColorScheme
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val backgroundTheme = defaultBackgroundTheme(colorScheme)
assertEquals(backgroundTheme, LocalBackgroundTheme.current)
val tintTheme = defaultTintTheme()
assertEquals(tintTheme, LocalTintTheme.current)
}
}
}
@Test
fun darkThemeTrue_dynamicColorFalse_androidThemeFalse() {
composeTestRule.setContent {
GetoTheme(
darkTheme = true,
disableDynamicTheming = true,
androidTheme = false,
) {
val colorScheme = DarkDefaultColorScheme
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val backgroundTheme = defaultBackgroundTheme(colorScheme)
assertEquals(backgroundTheme, LocalBackgroundTheme.current)
val tintTheme = defaultTintTheme()
assertEquals(tintTheme, LocalTintTheme.current)
}
}
}
@Test
fun darkThemeFalse_dynamicColorTrue_androidThemeFalse() {
composeTestRule.setContent {
GetoTheme(
darkTheme = false,
disableDynamicTheming = false,
androidTheme = false,
) {
val colorScheme = dynamicLightColorSchemeWithFallback()
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val backgroundTheme = defaultBackgroundTheme(colorScheme)
assertEquals(backgroundTheme, LocalBackgroundTheme.current)
val tintTheme = dynamicTintThemeWithFallback(colorScheme)
assertEquals(tintTheme, LocalTintTheme.current)
}
}
}
@Test
fun darkThemeTrue_dynamicColorTrue_androidThemeFalse() {
composeTestRule.setContent {
GetoTheme(
darkTheme = true,
disableDynamicTheming = false,
androidTheme = false,
) {
val colorScheme = dynamicDarkColorSchemeWithFallback()
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val backgroundTheme = defaultBackgroundTheme(colorScheme)
assertEquals(backgroundTheme, LocalBackgroundTheme.current)
val tintTheme = dynamicTintThemeWithFallback(colorScheme)
assertEquals(tintTheme, LocalTintTheme.current)
}
}
}
@Test
fun darkThemeFalse_dynamicColorFalse_androidThemeTrue() {
composeTestRule.setContent {
GetoTheme(
darkTheme = false,
disableDynamicTheming = true,
androidTheme = true,
) {
val colorScheme = LightAndroidColorScheme
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val backgroundTheme = LightAndroidBackgroundTheme
assertEquals(backgroundTheme, LocalBackgroundTheme.current)
val tintTheme = defaultTintTheme()
assertEquals(tintTheme, LocalTintTheme.current)
}
}
}
@Test
fun darkThemeTrue_dynamicColorFalse_androidThemeTrue() {
composeTestRule.setContent {
GetoTheme(
darkTheme = true,
disableDynamicTheming = true,
androidTheme = true,
) {
val colorScheme = DarkAndroidColorScheme
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val backgroundTheme = DarkAndroidBackgroundTheme
assertEquals(backgroundTheme, LocalBackgroundTheme.current)
val tintTheme = defaultTintTheme()
assertEquals(tintTheme, LocalTintTheme.current)
}
}
}
@Test
fun darkThemeFalse_dynamicColorTrue_androidThemeTrue() {
composeTestRule.setContent {
GetoTheme(
darkTheme = false,
disableDynamicTheming = false,
androidTheme = true,
) {
val colorScheme = LightAndroidColorScheme
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val backgroundTheme = LightAndroidBackgroundTheme
assertEquals(backgroundTheme, LocalBackgroundTheme.current)
val tintTheme = defaultTintTheme()
assertEquals(tintTheme, LocalTintTheme.current)
}
}
}
@Test
fun darkThemeTrue_dynamicColorTrue_androidThemeTrue() {
composeTestRule.setContent {
GetoTheme(
darkTheme = true,
disableDynamicTheming = false,
androidTheme = true,
) {
val colorScheme = DarkAndroidColorScheme
assertColorSchemesEqual(colorScheme, MaterialTheme.colorScheme)
val backgroundTheme = DarkAndroidBackgroundTheme
assertEquals(backgroundTheme, LocalBackgroundTheme.current)
val tintTheme = defaultTintTheme()
assertEquals(tintTheme, LocalTintTheme.current)
}
}
}
@Composable
private fun dynamicLightColorSchemeWithFallback(): ColorScheme = when {
SDK_INT >= VERSION_CODES.S -> dynamicLightColorScheme(LocalContext.current)
else -> LightDefaultColorScheme
}
@Composable
private fun dynamicDarkColorSchemeWithFallback(): ColorScheme = when {
SDK_INT >= VERSION_CODES.S -> dynamicDarkColorScheme(LocalContext.current)
else -> DarkDefaultColorScheme
}
private fun defaultBackgroundTheme(colorScheme: ColorScheme): BackgroundTheme = BackgroundTheme(
color = colorScheme.surface,
tonalElevation = 2.dp,
)
private fun defaultTintTheme(): TintTheme = TintTheme()
private fun dynamicTintThemeWithFallback(colorScheme: ColorScheme): TintTheme = when {
SDK_INT >= VERSION_CODES.S -> TintTheme(colorScheme.primary)
else -> TintTheme()
}
/**
* Workaround for the fact that the Geto design system specify all color scheme values.
*/
private fun assertColorSchemesEqual(
expectedColorScheme: ColorScheme,
actualColorScheme: ColorScheme,
) {
assertEquals(expectedColorScheme.primary, actualColorScheme.primary)
assertEquals(expectedColorScheme.onPrimary, actualColorScheme.onPrimary)
assertEquals(expectedColorScheme.primaryContainer, actualColorScheme.primaryContainer)
assertEquals(expectedColorScheme.onPrimaryContainer, actualColorScheme.onPrimaryContainer)
assertEquals(expectedColorScheme.secondary, actualColorScheme.secondary)
assertEquals(expectedColorScheme.onSecondary, actualColorScheme.onSecondary)
assertEquals(expectedColorScheme.secondaryContainer, actualColorScheme.secondaryContainer)
assertEquals(
expectedColorScheme.onSecondaryContainer,
actualColorScheme.onSecondaryContainer,
)
assertEquals(expectedColorScheme.tertiary, actualColorScheme.tertiary)
assertEquals(expectedColorScheme.onTertiary, actualColorScheme.onTertiary)
assertEquals(expectedColorScheme.tertiaryContainer, actualColorScheme.tertiaryContainer)
assertEquals(expectedColorScheme.onTertiaryContainer, actualColorScheme.onTertiaryContainer)
assertEquals(expectedColorScheme.error, actualColorScheme.error)
assertEquals(expectedColorScheme.onError, actualColorScheme.onError)
assertEquals(expectedColorScheme.errorContainer, actualColorScheme.errorContainer)
assertEquals(expectedColorScheme.onErrorContainer, actualColorScheme.onErrorContainer)
assertEquals(expectedColorScheme.background, actualColorScheme.background)
assertEquals(expectedColorScheme.onBackground, actualColorScheme.onBackground)
assertEquals(expectedColorScheme.surface, actualColorScheme.surface)
assertEquals(expectedColorScheme.onSurface, actualColorScheme.onSurface)
assertEquals(expectedColorScheme.surfaceVariant, actualColorScheme.surfaceVariant)
assertEquals(expectedColorScheme.onSurfaceVariant, actualColorScheme.onSurfaceVariant)
assertEquals(expectedColorScheme.inverseSurface, actualColorScheme.inverseSurface)
assertEquals(expectedColorScheme.inverseOnSurface, actualColorScheme.inverseOnSurface)
assertEquals(expectedColorScheme.outline, actualColorScheme.outline)
}
}
| Geto/core/designsystem/src/androidTest/kotlin/com/android/geto/core/designsystem/ThemeTest.kt | 2269846538 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem
import androidx.activity.ComponentActivity
import androidx.compose.material3.Surface
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import com.android.geto.core.designsystem.component.GetoRadioButtonGroup
import com.android.geto.core.screenshot.testing.util.captureMultiTheme
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(application = HiltTestApplication::class, qualifiers = "480dpi")
@LooperMode(LooperMode.Mode.PAUSED)
class RadioButtonScreenshotTests {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun getoRadioButtonGroup_multipleThemes() {
composeTestRule.captureMultiTheme("RadioButton") {
Surface {
GetoRadioButtonGroup(
selected = 0,
onSelect = {},
items = arrayOf("Item 0", "Item 1"),
)
}
}
}
}
| Geto/core/designsystem/src/test/kotlin/com/android/geto/core/designsystem/RadioButtonScreenshotTests.kt | 871183884 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import com.android.geto.core.designsystem.component.GetoBackground
import com.android.geto.core.designsystem.component.SimpleDialog
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.screenshot.testing.util.DefaultTestDevices
import com.android.geto.core.screenshot.testing.util.captureDialogForDevice
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Rule
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.LooperMode
import kotlin.test.Test
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(application = HiltTestApplication::class, qualifiers = "480dpi")
@LooperMode(LooperMode.Mode.PAUSED)
class SimpleDialogScreenshotTests {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun simpleDialog() {
composeTestRule.captureDialogForDevice(
name = "SimpleDialog",
fileName = "SimpleDialog",
deviceName = "phone",
deviceSpec = DefaultTestDevices.PHONE.spec,
) {
GetoTheme {
SimpleDialog(
title = "Simple Dialog",
text = "Hello from Simple Dialog",
onDismissRequest = {},
negativeButtonText = "Cancel",
positiveButtonText = "Okay",
onNegativeButtonClick = {},
onPositiveButtonClick = {},
contentDescription = "Simple Dialog",
)
}
}
}
@Test
fun simpleDialog_dark() {
composeTestRule.captureDialogForDevice(
name = "SimpleDialog",
fileName = "SimpleDialog",
deviceName = "phone_dark",
deviceSpec = DefaultTestDevices.PHONE.spec,
darkMode = true,
) {
GetoTheme {
GetoBackground {
SimpleDialog(
title = "Simple Dialog",
text = "Hello from Simple Dialog",
onDismissRequest = {},
negativeButtonText = "Cancel",
positiveButtonText = "Okay",
onNegativeButtonClick = {},
onPositiveButtonClick = {},
contentDescription = "Simple Dialog",
)
}
}
}
}
}
| Geto/core/designsystem/src/test/kotlin/com/android/geto/core/designsystem/SimpleDialogScreenshotTests.kt | 3797507464 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.unit.dp
import com.android.geto.core.designsystem.component.GetoBackground
import com.android.geto.core.screenshot.testing.util.captureMultiTheme
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(application = HiltTestApplication::class, qualifiers = "480dpi")
@LooperMode(LooperMode.Mode.PAUSED)
class BackgroundScreenshotTests {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun getoBackground_multipleThemes() {
composeTestRule.captureMultiTheme("Background") { description ->
GetoBackground(Modifier.size(100.dp)) {
Text("$description background")
}
}
}
}
| Geto/core/designsystem/src/test/kotlin/com/android/geto/core/designsystem/BackgroundScreenshotTests.kt | 878850399 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem
import androidx.activity.ComponentActivity
import androidx.compose.material3.Surface
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onRoot
import com.android.geto.core.designsystem.component.GetoLoadingWheel
import com.android.geto.core.designsystem.component.GetoOverlayLoadingWheel
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.screenshot.testing.util.DefaultRoborazziOptions
import com.android.geto.core.screenshot.testing.util.captureMultiTheme
import com.github.takahirom.roborazzi.captureRoboImage
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(application = HiltTestApplication::class, qualifiers = "480dpi")
@LooperMode(LooperMode.Mode.PAUSED)
class LoadingWheelScreenshotTests {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun loadingWheel_multipleThemes() {
composeTestRule.captureMultiTheme("LoadingWheel") {
Surface {
GetoLoadingWheel(contentDescription = "test")
}
}
}
@Test
fun overlayLoadingWheel_multipleThemes() {
composeTestRule.captureMultiTheme("LoadingWheel", "OverlayLoadingWheel") {
Surface {
GetoOverlayLoadingWheel(contentDescription = "test")
}
}
}
@Test
fun loadingWheelAnimation() {
composeTestRule.mainClock.autoAdvance = false
composeTestRule.setContent {
GetoTheme {
GetoLoadingWheel(contentDescription = "")
}
}
// Try multiple frames of the animation; some arbitrary, some synchronized with duration.
listOf(20L, 115L, 724L, 1000L).forEach { deltaTime ->
composeTestRule.mainClock.advanceTimeBy(deltaTime)
composeTestRule.onRoot().captureRoboImage(
"src/test/screenshots/LoadingWheel/LoadingWheel_animation_$deltaTime.png",
roborazziOptions = DefaultRoborazziOptions,
)
}
}
}
| Geto/core/designsystem/src/test/kotlin/com/android/geto/core/designsystem/LoadingWheelScreenshotTests.kt | 3664445084 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem
import androidx.activity.ComponentActivity
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import com.android.geto.core.designsystem.component.GetoBackground
import com.android.geto.core.designsystem.component.SingleSelectionDialog
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.screenshot.testing.util.DefaultTestDevices
import com.android.geto.core.screenshot.testing.util.captureDialogForDevice
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Rule
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.LooperMode
import kotlin.test.Test
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(application = HiltTestApplication::class, qualifiers = "480dpi")
@LooperMode(LooperMode.Mode.PAUSED)
class SingleSelectionDialogScreenshotTests {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun singleSelectionDialog() {
composeTestRule.captureDialogForDevice(
name = "SingleSelectionDialog",
fileName = "SingleSelectionDialog",
deviceName = "phone",
deviceSpec = DefaultTestDevices.PHONE.spec,
) {
GetoTheme {
SingleSelectionDialog(
title = "Single Selection",
items = arrayOf(
"Item 0",
"Item 1",
),
onDismissRequest = {},
selected = 0,
onSelect = {},
negativeButtonText = "Cancel",
positiveButtonText = "Okay",
onNegativeButtonClick = {},
onPositiveButtonClick = {},
contentDescription = "Dark Dialog",
)
}
}
}
@Test
fun singleSelectionDialog_dark() {
composeTestRule.captureDialogForDevice(
name = "SingleSelectionDialog",
fileName = "SingleSelectionDialog",
deviceName = "phone_dark",
deviceSpec = DefaultTestDevices.PHONE.spec,
darkMode = true,
) {
GetoTheme {
GetoBackground {
SingleSelectionDialog(
title = "Single Selection",
items = arrayOf(
"Item 0",
"Item 1",
),
onDismissRequest = {},
selected = 0,
onSelect = {},
negativeButtonText = "Cancel",
positiveButtonText = "Okay",
onNegativeButtonClick = {},
onPositiveButtonClick = {},
contentDescription = "Dark Dialog",
)
}
}
}
}
}
| Geto/core/designsystem/src/test/kotlin/com/android/geto/core/designsystem/SingleSelectionDialogScreenshotTests.kt | 843384661 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.component
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.compose.AsyncImagePainter.State.Error
import coil.compose.AsyncImagePainter.State.Loading
import coil.compose.rememberAsyncImagePainter
import com.android.geto.core.designsystem.R
/**
* A wrapper around [AsyncImage] which determines the colorFilter based on the theme
*/
@Composable
fun DynamicAsyncImage(
model: Any?,
contentDescription: String?,
modifier: Modifier = Modifier,
placeholder: Painter = painterResource(R.drawable.core_designsystem_ic_placeholder_default),
) {
var isLoading by remember { mutableStateOf(true) }
var isError by remember { mutableStateOf(false) }
val imageLoader = rememberAsyncImagePainter(
model = model,
onState = { state ->
isLoading = state is Loading
isError = state is Error
},
)
val isLocalInspection = LocalInspectionMode.current
Box(
modifier = modifier,
contentAlignment = Alignment.Center,
) {
if (isLoading && !isLocalInspection) {
CircularProgressIndicator(
modifier = Modifier
.align(Alignment.Center)
.size(80.dp),
color = MaterialTheme.colorScheme.tertiary,
)
}
Image(
contentScale = ContentScale.Crop,
painter = if (isError.not() && !isLocalInspection) imageLoader else placeholder,
contentDescription = contentDescription,
)
}
}
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/component/DynamicAsyncImage.kt | 21694631 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.component
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.android.geto.core.designsystem.theme.GetoTheme
@Composable
fun SimpleDialog(
modifier: Modifier = Modifier,
title: String,
text: String,
onDismissRequest: () -> Unit,
negativeButtonText: String,
positiveButtonText: String,
onNegativeButtonClick: () -> Unit,
onPositiveButtonClick: () -> Unit,
contentDescription: String,
) {
DialogContainer(
modifier = modifier,
onDismissRequest = onDismissRequest,
contentDescription = contentDescription,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp),
) {
DialogTitle(title = title)
SimpleDialogContent(text = text)
DialogButtons(
modifier = modifier,
negativeButtonText = negativeButtonText,
positiveButtonText = positiveButtonText,
onNegativeButtonClick = onNegativeButtonClick,
onPositiveButtonClick = onPositiveButtonClick,
)
}
}
}
@Composable
fun DialogContainer(
modifier: Modifier = Modifier,
onDismissRequest: () -> Unit,
contentDescription: String,
content: @Composable (ColumnScope.() -> Unit),
) {
Dialog(onDismissRequest = onDismissRequest) {
Card(
modifier = modifier
.fillMaxWidth()
.wrapContentSize()
.padding(16.dp)
.semantics { this.contentDescription = contentDescription },
shape = RoundedCornerShape(16.dp),
) {
content()
}
}
}
@Composable
fun DialogTitle(modifier: Modifier = Modifier, title: String) {
Spacer(modifier = Modifier.height(10.dp))
Text(
modifier = modifier.padding(horizontal = 5.dp),
text = title,
style = MaterialTheme.typography.titleLarge,
)
}
@Composable
private fun SimpleDialogContent(modifier: Modifier = Modifier, text: String) {
Spacer(modifier = Modifier.height(10.dp))
Text(
modifier = modifier.padding(horizontal = 5.dp),
text = text,
style = MaterialTheme.typography.bodyLarge,
)
}
@Composable
fun DialogButtons(
modifier: Modifier = Modifier,
negativeButtonText: String,
positiveButtonText: String,
onNegativeButtonClick: () -> Unit,
onPositiveButtonClick: () -> Unit,
) {
Spacer(modifier = Modifier.height(10.dp))
Row(
modifier = modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
) {
TextButton(
onClick = onNegativeButtonClick,
modifier = Modifier.padding(5.dp),
) {
Text(text = negativeButtonText)
}
TextButton(
onClick = onPositiveButtonClick,
modifier = Modifier.padding(5.dp),
) {
Text(text = positiveButtonText)
}
}
}
@Preview
@Composable
private fun SimpleDialogPreview() {
GetoTheme {
SimpleDialog(
title = "Simple Dialog",
text = "Hello from Simple Dialog",
onDismissRequest = {},
negativeButtonText = "Cancel",
positiveButtonText = "Okay",
onNegativeButtonClick = {},
onPositiveButtonClick = {},
contentDescription = "Simple Dialog",
)
}
}
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/component/SimpleDialog.kt | 960059303 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.component
import androidx.compose.animation.animateColor
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.StartOffset
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.keyframes
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import com.android.geto.core.designsystem.theme.GetoTheme
import kotlinx.coroutines.launch
@Composable
fun GetoLoadingWheel(
contentDescription: String,
modifier: Modifier = Modifier,
) {
val infiniteTransition = rememberInfiniteTransition(label = "wheel transition")
// Specifies the float animation for slowly drawing out the lines on entering
val startValue = if (LocalInspectionMode.current) 0F else 1F
val floatAnimValues = (0 until NUM_OF_LINES).map { remember { Animatable(startValue) } }
LaunchedEffect(floatAnimValues) {
(0 until NUM_OF_LINES).map { index ->
launch {
floatAnimValues[index].animateTo(
targetValue = 0F,
animationSpec = tween(
durationMillis = 100,
easing = FastOutSlowInEasing,
delayMillis = 40 * index,
),
)
}
}
}
// Specifies the rotation animation of the entire Canvas composable
val rotationAnim by infiniteTransition.animateFloat(
initialValue = 0F,
targetValue = 360F,
animationSpec = infiniteRepeatable(
animation = tween(durationMillis = ROTATION_TIME, easing = LinearEasing),
),
label = "wheel rotation animation",
)
// Specifies the color animation for the base-to-progress line color change
val baseLineColor = MaterialTheme.colorScheme.onBackground
val progressLineColor = MaterialTheme.colorScheme.inversePrimary
val colorAnimValues = (0 until NUM_OF_LINES).map { index ->
infiniteTransition.animateColor(
initialValue = baseLineColor,
targetValue = baseLineColor,
animationSpec = infiniteRepeatable(
animation = keyframes {
durationMillis = ROTATION_TIME / 2
progressLineColor at ROTATION_TIME / NUM_OF_LINES / 2 using LinearEasing
baseLineColor at ROTATION_TIME / NUM_OF_LINES using LinearEasing
},
repeatMode = RepeatMode.Restart,
initialStartOffset = StartOffset(ROTATION_TIME / NUM_OF_LINES / 2 * index),
),
label = "wheel color animation",
)
}
// Draws out the LoadingWheel Canvas composable and sets the animations
Canvas(
modifier = modifier
.size(48.dp)
.padding(8.dp)
.graphicsLayer { rotationZ = rotationAnim }
.semantics { this.contentDescription = contentDescription }
.testTag("loadingWheel"),
) {
repeat(NUM_OF_LINES) { index ->
rotate(degrees = index * 30f) {
drawLine(
color = colorAnimValues[index].value,
// Animates the initially drawn 1 pixel alpha from 0 to 1
alpha = if (floatAnimValues[index].value < 1f) 1f else 0f,
strokeWidth = 4F,
cap = StrokeCap.Round,
start = Offset(size.width / 2, size.height / 4),
end = Offset(size.width / 2, floatAnimValues[index].value * size.height / 4),
)
}
}
}
}
@Composable
fun GetoOverlayLoadingWheel(
contentDescription: String,
modifier: Modifier = Modifier,
) {
Surface(
shape = RoundedCornerShape(60.dp),
shadowElevation = 8.dp,
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.83f),
modifier = modifier.size(60.dp),
) {
GetoLoadingWheel(
contentDescription = contentDescription,
)
}
}
@ThemePreviews
@Composable
fun GetoLoadingWheelPreview() {
GetoTheme {
Surface {
GetoLoadingWheel(contentDescription = "GetoOverlayLoadingWheel")
}
}
}
@ThemePreviews
@Composable
fun GetoOverlayLoadingWheelPreview() {
GetoTheme {
Surface {
GetoOverlayLoadingWheel(contentDescription = "GetoOverlayLoadingWheel")
}
}
}
private const val ROTATION_TIME = 12000
private const val NUM_OF_LINES = 12
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/component/GetoLoadingWheel.kt | 2030493790 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.component
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.android.geto.core.designsystem.theme.GetoTheme
@Composable
fun SingleSelectionDialog(
modifier: Modifier = Modifier,
title: String,
items: Array<String>,
onDismissRequest: () -> Unit,
selected: Int,
onSelect: (Int) -> Unit,
negativeButtonText: String,
positiveButtonText: String,
onNegativeButtonClick: () -> Unit,
onPositiveButtonClick: () -> Unit,
contentDescription: String,
) {
DialogContainer(
modifier = modifier,
onDismissRequest = onDismissRequest,
contentDescription = contentDescription,
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp),
) {
DialogTitle(title = title)
GetoRadioButtonGroup(
selected = selected,
onSelect = onSelect,
items = items,
)
DialogButtons(
negativeButtonText = negativeButtonText,
positiveButtonText = positiveButtonText,
onNegativeButtonClick = onNegativeButtonClick,
onPositiveButtonClick = onPositiveButtonClick,
)
}
}
}
@Preview
@Composable
private fun SingleSelectionDialogPreview() {
GetoTheme {
SingleSelectionDialog(
title = "Single selection dialog",
items = arrayOf("Item 0", "item 1"),
onDismissRequest = {},
selected = 0,
onSelect = {},
negativeButtonText = "Cancel",
positiveButtonText = "Okay",
onNegativeButtonClick = {},
onPositiveButtonClick = {},
contentDescription = "Single selection dialog",
)
}
}
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/component/SingleSelectionDialog.kt | 1061804850 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.component
import android.content.res.Configuration
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.LocalAbsoluteTonalElevation
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.android.geto.core.designsystem.theme.GetoTheme
import com.android.geto.core.designsystem.theme.LocalBackgroundTheme
/**
* The main background for the app.
* Uses [LocalBackgroundTheme] to set the color and tonal elevation of a [Surface].
*
* @param modifier Modifier to be applied to the background.
* @param content The background content.
*/
@Composable
fun GetoBackground(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
val color = LocalBackgroundTheme.current.color
val tonalElevation = LocalBackgroundTheme.current.tonalElevation
Surface(
color = if (color == Color.Unspecified) Color.Transparent else color,
tonalElevation = if (tonalElevation == Dp.Unspecified) 0.dp else tonalElevation,
modifier = modifier.fillMaxSize(),
) {
CompositionLocalProvider(LocalAbsoluteTonalElevation provides 0.dp) {
content()
}
}
}
/**
* Multipreview annotation that represents light and dark themes. Add this annotation to a
* composable to render the both themes.
*/
@Preview(uiMode = Configuration.UI_MODE_NIGHT_NO, name = "Light theme")
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES, name = "Dark theme")
annotation class ThemePreviews
@ThemePreviews
@Composable
fun BackgroundDefault() {
GetoTheme(disableDynamicTheming = true) {
GetoBackground(Modifier.size(100.dp), content = {})
}
}
@ThemePreviews
@Composable
fun BackgroundDynamic() {
GetoTheme(disableDynamicTheming = false) {
GetoBackground(Modifier.size(100.dp), content = {})
}
}
@ThemePreviews
@Composable
fun BackgroundAndroid() {
GetoTheme(androidTheme = true) {
GetoBackground(Modifier.size(100.dp), content = {})
}
}
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/component/Background.kt | 3461825808 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.component
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
@Composable
fun GetoRadioButtonGroup(
modifier: Modifier = Modifier,
selected: Int,
onSelect: (Int) -> Unit,
items: Array<String>,
) {
Spacer(modifier = Modifier.height(10.dp))
Column(
modifier = modifier
.fillMaxWidth()
.selectableGroup(),
) {
items.forEachIndexed { index, text ->
Row(
Modifier
.padding(vertical = 10.dp)
.selectable(
selected = index == selected,
role = Role.RadioButton,
enabled = true,
onClick = {
onSelect(index)
},
)
.padding(horizontal = 16.dp)
.semantics { contentDescription = text },
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(
selected = index == selected,
onClick = null,
)
Text(
text = text,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(start = 10.dp),
)
}
}
}
}
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/component/RadioButton.kt | 3643675154 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.theme
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.graphics.Color
@Immutable
data class TintTheme(
val iconTint: Color = Color.Unspecified,
)
val LocalTintTheme = staticCompositionLocalOf { TintTheme() }
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/theme/Tint.kt | 3276609626 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.theme
import androidx.compose.ui.graphics.Color
internal val Blue10 = Color(0xFF001F28)
internal val Blue20 = Color(0xFF003544)
internal val Blue30 = Color(0xFF004D61)
internal val Blue40 = Color(0xFF006780)
internal val Blue80 = Color(0xFF5DD5FC)
internal val Blue90 = Color(0xFFB8EAFF)
internal val DarkGreen10 = Color(0xFF0D1F12)
internal val DarkGreen20 = Color(0xFF223526)
internal val DarkGreen30 = Color(0xFF394B3C)
internal val DarkGreen40 = Color(0xFF4F6352)
internal val DarkGreen80 = Color(0xFFB7CCB8)
internal val DarkGreen90 = Color(0xFFD3E8D3)
internal val DarkGreenGray10 = Color(0xFF1A1C1A)
internal val DarkGreenGray20 = Color(0xFF2F312E)
internal val DarkGreenGray90 = Color(0xFFE2E3DE)
internal val DarkGreenGray95 = Color(0xFFF0F1EC)
internal val DarkGreenGray99 = Color(0xFFFBFDF7)
internal val DarkPurpleGray10 = Color(0xFF201A1B)
internal val DarkPurpleGray20 = Color(0xFF362F30)
internal val DarkPurpleGray90 = Color(0xFFECDFE0)
internal val DarkPurpleGray95 = Color(0xFFFAEEEF)
internal val DarkPurpleGray99 = Color(0xFFFCFCFC)
internal val Green10 = Color(0xFF00210B)
internal val Green20 = Color(0xFF003919)
internal val Green30 = Color(0xFF005227)
internal val Green40 = Color(0xFF006D36)
internal val Green80 = Color(0xFF0EE37C)
internal val Green90 = Color(0xFF5AFF9D)
internal val GreenGray30 = Color(0xFF414941)
internal val GreenGray50 = Color(0xFF727971)
internal val GreenGray60 = Color(0xFF8B938A)
internal val GreenGray80 = Color(0xFFC1C9BF)
internal val GreenGray90 = Color(0xFFDDE5DB)
internal val Orange10 = Color(0xFF380D00)
internal val Orange20 = Color(0xFF5B1A00)
internal val Orange30 = Color(0xFF812800)
internal val Orange40 = Color(0xFFA23F16)
internal val Orange80 = Color(0xFFFFB59B)
internal val Orange90 = Color(0xFFFFDBCF)
internal val Purple10 = Color(0xFF36003C)
internal val Purple20 = Color(0xFF560A5D)
internal val Purple30 = Color(0xFF702776)
internal val Purple40 = Color(0xFF8B418F)
internal val Purple80 = Color(0xFFFFA9FE)
internal val Purple90 = Color(0xFFFFD6FA)
internal val PurpleGray30 = Color(0xFF4D444C)
internal val PurpleGray50 = Color(0xFF7F747C)
internal val PurpleGray60 = Color(0xFF998D96)
internal val PurpleGray80 = Color(0xFFD0C3CC)
internal val PurpleGray90 = Color(0xFFEDDEE8)
internal val Red10 = Color(0xFF410002)
internal val Red20 = Color(0xFF690005)
internal val Red30 = Color(0xFF93000A)
internal val Red40 = Color(0xFFBA1A1A)
internal val Red80 = Color(0xFFFFB4AB)
internal val Red90 = Color(0xFFFFDAD6)
internal val Teal10 = Color(0xFF001F26)
internal val Teal20 = Color(0xFF02363F)
internal val Teal30 = Color(0xFF214D56)
internal val Teal40 = Color(0xFF3A656F)
internal val Teal80 = Color(0xFFA2CED9)
internal val Teal90 = Color(0xFFBEEAF6)
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/theme/Color.kt | 1463952251 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.theme
import android.os.Build
import androidx.annotation.ChecksSdkIntAtLeast
import androidx.annotation.VisibleForTesting
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.CompositionLocalProvider
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
@VisibleForTesting
val LightDefaultColorScheme = lightColorScheme(
primary = Purple40,
onPrimary = Color.White,
primaryContainer = Purple90,
onPrimaryContainer = Purple10,
secondary = Orange40,
onSecondary = Color.White,
secondaryContainer = Orange90,
onSecondaryContainer = Orange10,
tertiary = Blue40,
onTertiary = Color.White,
tertiaryContainer = Blue90,
onTertiaryContainer = Blue10,
error = Red40,
onError = Color.White,
errorContainer = Red90,
onErrorContainer = Red10,
background = DarkPurpleGray99,
onBackground = DarkPurpleGray10,
surface = DarkPurpleGray99,
onSurface = DarkPurpleGray10,
surfaceVariant = PurpleGray90,
onSurfaceVariant = PurpleGray30,
inverseSurface = DarkPurpleGray20,
inverseOnSurface = DarkPurpleGray95,
outline = PurpleGray50,
)
@VisibleForTesting
val DarkDefaultColorScheme = darkColorScheme(
primary = Purple80,
onPrimary = Purple20,
primaryContainer = Purple30,
onPrimaryContainer = Purple90,
secondary = Orange80,
onSecondary = Orange20,
secondaryContainer = Orange30,
onSecondaryContainer = Orange90,
tertiary = Blue80,
onTertiary = Blue20,
tertiaryContainer = Blue30,
onTertiaryContainer = Blue90,
error = Red80,
onError = Red20,
errorContainer = Red30,
onErrorContainer = Red90,
background = DarkPurpleGray10,
onBackground = DarkPurpleGray90,
surface = DarkPurpleGray10,
onSurface = DarkPurpleGray90,
surfaceVariant = PurpleGray30,
onSurfaceVariant = PurpleGray80,
inverseSurface = DarkPurpleGray90,
inverseOnSurface = DarkPurpleGray10,
outline = PurpleGray60,
)
@VisibleForTesting
val LightAndroidColorScheme = lightColorScheme(
primary = Green40,
onPrimary = Color.White,
primaryContainer = Green90,
onPrimaryContainer = Green10,
secondary = DarkGreen40,
onSecondary = Color.White,
secondaryContainer = DarkGreen90,
onSecondaryContainer = DarkGreen10,
tertiary = Teal40,
onTertiary = Color.White,
tertiaryContainer = Teal90,
onTertiaryContainer = Teal10,
error = Red40,
onError = Color.White,
errorContainer = Red90,
onErrorContainer = Red10,
background = DarkGreenGray99,
onBackground = DarkGreenGray10,
surface = DarkGreenGray99,
onSurface = DarkGreenGray10,
surfaceVariant = GreenGray90,
onSurfaceVariant = GreenGray30,
inverseSurface = DarkGreenGray20,
inverseOnSurface = DarkGreenGray95,
outline = GreenGray50,
)
@VisibleForTesting
val DarkAndroidColorScheme = darkColorScheme(
primary = Green80,
onPrimary = Green20,
primaryContainer = Green30,
onPrimaryContainer = Green90,
secondary = DarkGreen80,
onSecondary = DarkGreen20,
secondaryContainer = DarkGreen30,
onSecondaryContainer = DarkGreen90,
tertiary = Teal80,
onTertiary = Teal20,
tertiaryContainer = Teal30,
onTertiaryContainer = Teal90,
error = Red80,
onError = Red20,
errorContainer = Red30,
onErrorContainer = Red90,
background = DarkGreenGray10,
onBackground = DarkGreenGray90,
surface = DarkGreenGray10,
onSurface = DarkGreenGray90,
surfaceVariant = GreenGray30,
onSurfaceVariant = GreenGray80,
inverseSurface = DarkGreenGray90,
inverseOnSurface = DarkGreenGray10,
outline = GreenGray60,
)
val LightAndroidBackgroundTheme = BackgroundTheme(color = DarkGreenGray95)
val DarkAndroidBackgroundTheme = BackgroundTheme(color = Color.Black)
@Composable
fun GetoTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
androidTheme: Boolean = false,
disableDynamicTheming: Boolean = true,
content: @Composable () -> Unit,
) {
// Color scheme
val colorScheme = when {
androidTheme -> if (darkTheme) DarkAndroidColorScheme else LightAndroidColorScheme
!disableDynamicTheming && supportsDynamicTheming() -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
else -> if (darkTheme) DarkDefaultColorScheme else LightDefaultColorScheme
}
// Background theme
val defaultBackgroundTheme = BackgroundTheme(
color = colorScheme.surface,
tonalElevation = 2.dp,
)
val backgroundTheme = when {
androidTheme -> if (darkTheme) DarkAndroidBackgroundTheme else LightAndroidBackgroundTheme
else -> defaultBackgroundTheme
}
val tintTheme = when {
androidTheme -> TintTheme()
!disableDynamicTheming && supportsDynamicTheming() -> TintTheme(colorScheme.primary)
else -> TintTheme()
}
// Composition locals
CompositionLocalProvider(
LocalBackgroundTheme provides backgroundTheme,
LocalTintTheme provides tintTheme,
) {
MaterialTheme(
colorScheme = colorScheme,
typography = GetoTypography,
content = content,
)
}
}
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S)
fun supportsDynamicTheming() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/theme/Theme.kt | 1513117839 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.theme
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
@Immutable
data class BackgroundTheme(
val color: Color = Color.Unspecified,
val tonalElevation: Dp = Dp.Unspecified,
)
val LocalBackgroundTheme = staticCompositionLocalOf { BackgroundTheme() }
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/theme/Background.kt | 2290101642 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.LineHeightStyle
import androidx.compose.ui.text.style.LineHeightStyle.Alignment
import androidx.compose.ui.text.style.LineHeightStyle.Trim
import androidx.compose.ui.unit.sp
internal val GetoTypography = Typography(
displayLarge = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 57.sp,
lineHeight = 64.sp,
letterSpacing = (-0.25).sp,
),
displayMedium = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 45.sp,
lineHeight = 52.sp,
letterSpacing = 0.sp,
),
displaySmall = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 36.sp,
lineHeight = 44.sp,
letterSpacing = 0.sp,
),
headlineLarge = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 32.sp,
lineHeight = 40.sp,
letterSpacing = 0.sp,
),
headlineMedium = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 28.sp,
lineHeight = 36.sp,
letterSpacing = 0.sp,
),
headlineSmall = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 24.sp,
lineHeight = 32.sp,
letterSpacing = 0.sp,
lineHeightStyle = LineHeightStyle(
alignment = Alignment.Bottom,
trim = Trim.None,
),
),
titleLarge = TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp,
lineHeightStyle = LineHeightStyle(
alignment = Alignment.Bottom,
trim = Trim.LastLineBottom,
),
),
titleMedium = TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 18.sp,
lineHeight = 24.sp,
letterSpacing = 0.1.sp,
),
titleSmall = TextStyle(
fontWeight = FontWeight.Medium,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.1.sp,
),
// Default text style
bodyLarge = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp,
lineHeightStyle = LineHeightStyle(
alignment = Alignment.Center,
trim = Trim.None,
),
),
bodyMedium = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.25.sp,
),
bodySmall = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = 0.4.sp,
),
// Used for Button
labelLarge = TextStyle(
fontWeight = FontWeight.Medium,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.1.sp,
lineHeightStyle = LineHeightStyle(
alignment = Alignment.Center,
trim = Trim.LastLineBottom,
),
),
// Used for Navigation items
labelMedium = TextStyle(
fontWeight = FontWeight.Medium,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp,
lineHeightStyle = LineHeightStyle(
alignment = Alignment.Center,
trim = Trim.LastLineBottom,
),
),
// Used for Tag
labelSmall = TextStyle(
fontWeight = FontWeight.Medium,
fontSize = 10.sp,
lineHeight = 14.sp,
letterSpacing = 0.sp,
lineHeightStyle = LineHeightStyle(
alignment = Alignment.Center,
trim = Trim.LastLineBottom,
),
),
)
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/theme/Type.kt | 415386389 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.designsystem.icon
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.List
import androidx.compose.material.icons.filled.Android
import androidx.compose.material.icons.filled.AppShortcut
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Settings
object GetoIcons {
val Settings = Icons.Default.Settings
val Android = Icons.Default.Android
val Back = Icons.AutoMirrored.Filled.ArrowBack
val Empty = Icons.AutoMirrored.Filled.List
val Refresh = Icons.Default.Refresh
val Shortcut = Icons.Default.AppShortcut
}
| Geto/core/designsystem/src/main/kotlin/com/android/geto/core/designsystem/icon/GetoIcons.kt | 769770845 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.shortcutmanager
import android.content.Context
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import com.android.geto.core.model.TargetShortcutInfoCompat
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
internal class DefaultShortcutManagerCompatWrapper @Inject constructor(@ApplicationContext private val context: Context) :
ShortcutManagerCompatWrapper {
override fun isRequestPinShortcutSupported(): Boolean {
return ShortcutManagerCompat.isRequestPinShortcutSupported(context)
}
override fun requestPinShortcut(
packageName: String,
appName: String,
targetShortcutInfoCompat: TargetShortcutInfoCompat,
): Boolean {
return ShortcutManagerCompat.requestPinShortcut(
context,
targetShortcutInfoCompat.asShortcutInfoCompat(
context = context,
packageName = packageName,
appName = appName,
),
null,
)
}
override fun updateShortcuts(
packageName: String,
appName: String,
targetShortcutInfoCompat: TargetShortcutInfoCompat,
): Boolean {
return ShortcutManagerCompat.updateShortcuts(
context,
listOf(
targetShortcutInfoCompat.asShortcutInfoCompat(
context = context,
packageName = packageName,
appName = appName,
),
),
)
}
override fun getShortcuts(matchFlags: Int): List<TargetShortcutInfoCompat> {
return ShortcutManagerCompat.getShortcuts(
context,
matchFlags,
).map(ShortcutInfoCompat::asTargetShortcutInfoCompat)
}
}
| Geto/core/shortcutmanager/src/main/kotlin/com/android/geto/core/shortcutmanager/DefaultShortcutManagerCompatWrapper.kt | 2101325677 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.shortcutmanager
import com.android.geto.core.model.TargetShortcutInfoCompat
interface ShortcutManagerCompatWrapper {
fun isRequestPinShortcutSupported(): Boolean
fun requestPinShortcut(
packageName: String,
appName: String,
targetShortcutInfoCompat: TargetShortcutInfoCompat,
): Boolean
fun updateShortcuts(
packageName: String,
appName: String,
targetShortcutInfoCompat: TargetShortcutInfoCompat,
): Boolean
fun getShortcuts(matchFlags: Int): List<TargetShortcutInfoCompat>
}
| Geto/core/shortcutmanager/src/main/kotlin/com/android/geto/core/shortcutmanager/ShortcutManagerCompatWrapper.kt | 3181286975 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.shortcutmanager
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal interface ShortcutManagerModule {
@Binds
@Singleton
fun shortcutManagerCompatWrapper(impl: DefaultShortcutManagerCompatWrapper): ShortcutManagerCompatWrapper
}
| Geto/core/shortcutmanager/src/main/kotlin/com/android/geto/core/shortcutmanager/ShortcutManagerModule.kt | 3047536715 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.shortcutmanager
import android.content.Context
import android.content.Intent
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.core.net.toUri
import com.android.geto.core.model.TargetShortcutInfoCompat
internal fun ShortcutInfoCompat.asTargetShortcutInfoCompat(): TargetShortcutInfoCompat {
return TargetShortcutInfoCompat(
id = id,
shortLabel = shortLabel.toString(),
longLabel = longLabel.toString(),
)
}
internal fun TargetShortcutInfoCompat.asShortcutInfoCompat(
context: Context,
packageName: String,
appName: String,
): ShortcutInfoCompat {
val shortcutIntent = Intent().apply {
action = Intent.ACTION_VIEW
// TODO: Do not hard code the className for MainActivity
setClassName(context.packageName, "com.android.geto.MainActivity")
data = "https://www.android.geto.com/$packageName/$appName".toUri()
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
return ShortcutInfoCompat.Builder(context, id).apply {
if (icon != null) {
setIcon(IconCompat.createWithBitmap(icon!!))
}
setShortLabel(shortLabel)
setLongLabel(longLabel)
setIntent(shortcutIntent)
}.build()
}
| Geto/core/shortcutmanager/src/main/kotlin/com/android/geto/core/shortcutmanager/ShortcutInfoCompat.kt | 138579846 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.packagemanager
interface ClipboardManagerWrapper {
val atLeastApi32: Boolean
fun setPrimaryClip(label: String, text: String)
}
| Geto/core/clipboardmanager/src/main/kotlin/com/android/geto/core/packagemanager/ClipboardManagerWrapper.kt | 1054908826 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.packagemanager
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal interface ClipboardManagerModule {
@Binds
@Singleton
fun clipboardManagerWrapper(impl: DefaultClipboardManagerWrapper): ClipboardManagerWrapper
}
| Geto/core/clipboardmanager/src/main/kotlin/com/android/geto/core/packagemanager/ClipboardManagerModule.kt | 417297176 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.packagemanager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import androidx.annotation.ChecksSdkIntAtLeast
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
internal class DefaultClipboardManagerWrapper @Inject constructor(
@ApplicationContext private val context: Context,
) : ClipboardManagerWrapper {
private val clipboardManager =
context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
@ChecksSdkIntAtLeast(api = Build.VERSION_CODES.S_V2)
override val atLeastApi32 =
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S_V2
override fun setPrimaryClip(label: String, text: String) {
clipboardManager.setPrimaryClip(ClipData.newPlainText(label, text))
}
}
| Geto/core/clipboardmanager/src/main/kotlin/com/android/geto/core/packagemanager/DefaultClipboardManagerWrapper.kt | 1522384185 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.securesettings
import android.content.Context
import android.provider.Settings
import androidx.core.database.getLongOrNull
import androidx.core.database.getStringOrNull
import com.android.geto.core.common.Dispatcher
import com.android.geto.core.common.GetoDispatchers.IO
import com.android.geto.core.model.SecureSetting
import com.android.geto.core.model.SettingType
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import javax.inject.Inject
internal class DefaultSecureSettingsWrapper @Inject constructor(
@Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher,
@ApplicationContext private val context: Context,
) : SecureSettingsWrapper {
private val contentResolver = context.contentResolver
private val settingsProjection: Array<String> = arrayOf(
Settings.NameValueTable._ID,
Settings.NameValueTable.NAME,
Settings.NameValueTable.VALUE,
)
override suspend fun canWriteSecureSettings(
settingType: SettingType,
key: String,
value: String,
): Boolean {
return withContext(ioDispatcher) {
when (settingType) {
SettingType.SYSTEM -> Settings.System.putString(
contentResolver,
key,
value,
)
SettingType.SECURE -> Settings.Secure.putString(
contentResolver,
key,
value,
)
SettingType.GLOBAL -> Settings.Global.putString(
contentResolver,
key,
value,
)
}
}
}
override suspend fun getSecureSettings(settingType: SettingType): List<SecureSetting> {
return withContext(ioDispatcher) {
val cursor = when (settingType) {
SettingType.SYSTEM -> contentResolver.query(
Settings.System.CONTENT_URI,
settingsProjection,
null,
null,
null,
)
SettingType.SECURE -> contentResolver.query(
Settings.Secure.CONTENT_URI,
settingsProjection,
null,
null,
null,
)
SettingType.GLOBAL -> contentResolver.query(
Settings.Global.CONTENT_URI,
settingsProjection,
null,
null,
null,
)
}
cursor?.use {
generateSequence { if (cursor.moveToNext()) cursor else null }.map {
val idIndex = cursor.getColumnIndex(Settings.NameValueTable._ID).takeIf { it != -1 }
val nameIndex = cursor.getColumnIndex(Settings.NameValueTable.NAME).takeIf { it != -1 }
val valueIndex = cursor.getColumnIndex(Settings.NameValueTable.VALUE).takeIf { it != -1 }
val id = cursor.getLongOrNull(idIndex!!)
val name = cursor.getStringOrNull(nameIndex!!)
val value = cursor.getStringOrNull(valueIndex!!)
SecureSetting(
settingType = settingType,
id = id,
name = name,
value = value,
)
}.sortedBy { it.name }.toList()
} ?: emptyList()
}
}
}
| Geto/core/securesettings/src/main/kotlin/com/android/geto/core/securesettings/DefaultSecureSettingsWrapper.kt | 3722337148 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.securesettings
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal interface SecureSettingsModule {
@Binds
@Singleton
fun secureSettingsWrapper(impl: DefaultSecureSettingsWrapper): SecureSettingsWrapper
}
| Geto/core/securesettings/src/main/kotlin/com/android/geto/core/securesettings/SecureSettingsModule.kt | 2613345342 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.securesettings
import com.android.geto.core.model.SecureSetting
import com.android.geto.core.model.SettingType
interface SecureSettingsWrapper {
suspend fun canWriteSecureSettings(
settingType: SettingType,
key: String,
value: String,
): Boolean
suspend fun getSecureSettings(settingType: SettingType): List<SecureSetting>
}
| Geto/core/securesettings/src/main/kotlin/com/android/geto/core/securesettings/SecureSettingsWrapper.kt | 2057606723 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.data.test.repository
import com.android.geto.core.data.repository.ShortcutRepository
import com.android.geto.core.data.repository.ShortcutResult
import com.android.geto.core.model.TargetShortcutInfoCompat
import javax.inject.Inject
class FakeShortcutRepository @Inject constructor() : ShortcutRepository {
override fun requestPinShortcut(
packageName: String,
appName: String,
targetShortcutInfoCompat: TargetShortcutInfoCompat,
): ShortcutResult {
return ShortcutResult.SupportedLauncher
}
override fun updateRequestPinShortcut(
packageName: String,
appName: String,
targetShortcutInfoCompat: TargetShortcutInfoCompat,
): ShortcutResult {
return ShortcutResult.ShortcutUpdateSuccess
}
override fun getShortcut(id: String): ShortcutResult {
return ShortcutResult.NoShortcutFound
}
}
| Geto/core/data-test/src/main/kotlin/com/android/geto/core/data/test/repository/FakeShortcutRepository.kt | 1914090647 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.data.test.repository
import com.android.geto.core.data.repository.AppSettingsRepository
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SettingType
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flowOf
import javax.inject.Inject
class FakeAppSettingsRepository @Inject constructor() : AppSettingsRepository {
override val appSettings: Flow<List<AppSetting>> = emptyFlow()
override suspend fun upsertAppSetting(appSetting: AppSetting) {}
override suspend fun deleteAppSetting(appSetting: AppSetting) {}
override fun getAppSettingsByPackageName(packageName: String): Flow<List<AppSetting>> {
val appSettings = List(5) { index ->
AppSetting(
id = index,
enabled = false,
settingType = SettingType.SECURE,
packageName = "com.android.geto",
label = "Geto",
key = "Geto $index",
valueOnLaunch = "0",
valueOnRevert = "1",
)
}
return flowOf(appSettings)
}
override suspend fun deleteAppSettingsByPackageName(packageNames: List<String>) {}
}
| Geto/core/data-test/src/main/kotlin/com/android/geto/core/data/test/repository/FakeAppSettingsRepository.kt | 63532489 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.data.test.repository
import com.android.geto.core.data.repository.UserDataRepository
import com.android.geto.core.model.DarkThemeConfig
import com.android.geto.core.model.ThemeBrand
import com.android.geto.core.model.UserData
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import javax.inject.Inject
class FakeUserDataRepository @Inject constructor() : UserDataRepository {
override val userData: Flow<UserData> = flowOf(
UserData(
themeBrand = ThemeBrand.DEFAULT,
darkThemeConfig = DarkThemeConfig.DARK,
useDynamicColor = false,
useAutoLaunch = false,
),
)
override suspend fun setAutoLaunchPreference(useAutoLaunch: Boolean) {}
override suspend fun setThemeBrand(themeBrand: ThemeBrand) {}
override suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) {}
override suspend fun setDynamicColorPreference(useDynamicColor: Boolean) {}
}
| Geto/core/data-test/src/main/kotlin/com/android/geto/core/data/test/repository/FakeUserDataRepository.kt | 1806377896 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.data.test.repository
import com.android.geto.core.data.repository.SecureSettingsRepository
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SecureSetting
import com.android.geto.core.model.SettingType
import javax.inject.Inject
class FakeSecureSettingsRepository @Inject constructor() : SecureSettingsRepository {
override suspend fun applySecureSettings(appSettings: List<AppSetting>): Boolean {
return true
}
override suspend fun revertSecureSettings(appSettings: List<AppSetting>): Boolean {
return true
}
override suspend fun getSecureSettings(settingType: SettingType): List<SecureSetting> {
return emptyList()
}
override suspend fun getSecureSettingsByName(
settingType: SettingType,
text: String,
): List<SecureSetting> {
return emptyList()
}
}
| Geto/core/data-test/src/main/kotlin/com/android/geto/core/data/test/repository/FakeSecureSettingsRepository.kt | 658777177 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.data.test.repository
import android.content.Intent
import android.graphics.drawable.Drawable
import com.android.geto.core.data.repository.PackageRepository
import com.android.geto.core.model.TargetApplicationInfo
import javax.inject.Inject
class FakePackageRepository @Inject constructor() : PackageRepository {
override suspend fun getInstalledApplications(): List<TargetApplicationInfo> {
return List(20) { index ->
TargetApplicationInfo(
flags = 0,
packageName = "com.android.geto$index",
label = "Geto $index",
)
}
}
override suspend fun getApplicationIcon(packageName: String): Drawable? {
return null
}
override fun getLaunchIntentForPackage(packageName: String): Intent? {
return null
}
}
| Geto/core/data-test/src/main/kotlin/com/android/geto/core/data/test/repository/FakePackageRepository.kt | 1860620825 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.data.test.repository
import com.android.geto.core.data.repository.ClipboardRepository
import com.android.geto.core.data.repository.ClipboardResult
import javax.inject.Inject
class FakeClipboardRepository @Inject constructor() : ClipboardRepository {
override fun setPrimaryClip(label: String, text: String): ClipboardResult {
return ClipboardResult.NoResult
}
}
| Geto/core/data-test/src/main/kotlin/com/android/geto/core/data/test/repository/FakeClipboardRepository.kt | 396819423 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.data.test
import com.android.geto.core.data.di.DataModule
import com.android.geto.core.data.repository.AppSettingsRepository
import com.android.geto.core.data.repository.ClipboardRepository
import com.android.geto.core.data.repository.PackageRepository
import com.android.geto.core.data.repository.SecureSettingsRepository
import com.android.geto.core.data.repository.ShortcutRepository
import com.android.geto.core.data.repository.UserDataRepository
import com.android.geto.core.data.test.repository.FakeAppSettingsRepository
import com.android.geto.core.data.test.repository.FakeClipboardRepository
import com.android.geto.core.data.test.repository.FakePackageRepository
import com.android.geto.core.data.test.repository.FakeSecureSettingsRepository
import com.android.geto.core.data.test.repository.FakeShortcutRepository
import com.android.geto.core.data.test.repository.FakeUserDataRepository
import dagger.Binds
import dagger.Module
import dagger.hilt.components.SingletonComponent
import dagger.hilt.testing.TestInstallIn
import javax.inject.Singleton
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [DataModule::class],
)
internal interface TestDataModule {
@Binds
@Singleton
fun appSettingsRepository(impl: FakeAppSettingsRepository): AppSettingsRepository
@Binds
@Singleton
fun secureSettingsRepository(impl: FakeSecureSettingsRepository): SecureSettingsRepository
@Binds
@Singleton
fun packageRepository(impl: FakePackageRepository): PackageRepository
@Binds
@Singleton
fun clipboardRepository(impl: FakeClipboardRepository): ClipboardRepository
@Binds
@Singleton
fun shortcutRepository(impl: FakeShortcutRepository): ShortcutRepository
@Binds
@Singleton
fun userDataRepository(impl: FakeUserDataRepository): UserDataRepository
}
| Geto/core/data-test/src/main/kotlin/com/android/geto/core/data/test/TestDataModule.kt | 2528809021 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.screenshot.testing.util
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.hasTestTag
import androidx.compose.ui.test.junit4.AndroidComposeTestRule
import androidx.compose.ui.test.onRoot
import androidx.test.ext.junit.rules.ActivityScenarioRule
import com.android.geto.core.designsystem.theme.GetoTheme
import com.github.takahirom.roborazzi.ExperimentalRoborazziApi
import com.github.takahirom.roborazzi.RoborazziOptions
import com.github.takahirom.roborazzi.RoborazziOptions.CompareOptions
import com.github.takahirom.roborazzi.RoborazziOptions.RecordOptions
import com.github.takahirom.roborazzi.captureRoboImage
import com.github.takahirom.roborazzi.captureScreenRoboImage
import com.google.accompanist.testharness.TestHarness
import org.robolectric.RuntimeEnvironment
@OptIn(ExperimentalRoborazziApi::class)
val DefaultRoborazziOptions = RoborazziOptions(
// Pixel-perfect matching
compareOptions = CompareOptions(changeThreshold = 0f),
// Reduce the size of the PNGs
recordOptions = RecordOptions(resizeScale = 0.5),
)
enum class DefaultTestDevices(val description: String, val spec: String) {
PHONE("phone", "spec:shape=Normal,width=640,height=360,unit=dp,dpi=480"),
FOLDABLE(
"foldable",
"spec:shape=Normal,width=673,height=841,unit=dp,dpi=480",
),
TABLET("tablet", "spec:shape=Normal,width=1280,height=800,unit=dp,dpi=480"),
}
fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureMultiDevice(
fileName: String,
body: @Composable () -> Unit,
) {
DefaultTestDevices.entries.forEach {
this.captureForDevice(
deviceName = it.description,
deviceSpec = it.spec,
fileName = fileName,
body = body,
)
}
}
fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureMultiDeviceSnackbar(
snackbarHostState: SnackbarHostState,
message: String,
testTag: String,
fileName: String,
body: @Composable () -> Unit,
) {
DefaultTestDevices.entries.forEach {
this.captureSnackbarForDevice(
snackbarHostState = snackbarHostState,
message = message,
testTag = testTag,
deviceName = it.description,
deviceSpec = it.spec,
fileName = fileName,
body = body,
)
}
}
fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureForDevice(
deviceName: String,
deviceSpec: String,
fileName: String,
roborazziOptions: RoborazziOptions = DefaultRoborazziOptions,
darkMode: Boolean = false,
body: @Composable () -> Unit,
) {
val (width, height, dpi) = extractSpecs(deviceSpec)
// Set qualifiers from specs
RuntimeEnvironment.setQualifiers("w${width}dp-h${height}dp-${dpi}dpi")
this.activity.setContent {
CompositionLocalProvider(
LocalInspectionMode provides true,
) {
TestHarness(darkMode = darkMode) {
body()
}
}
}
this.onRoot().captureRoboImage(
filePath = "src/test/screenshots/${fileName}_$deviceName.png",
roborazziOptions = roborazziOptions,
)
}
@OptIn(ExperimentalTestApi::class)
fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureSnackbarForDevice(
snackbarHostState: SnackbarHostState,
message: String,
testTag: String,
deviceName: String,
deviceSpec: String,
fileName: String,
roborazziOptions: RoborazziOptions = DefaultRoborazziOptions,
darkMode: Boolean = false,
body: @Composable () -> Unit,
) {
val (width, height, dpi) = extractSpecs(deviceSpec)
// Set qualifiers from specs
RuntimeEnvironment.setQualifiers("w${width}dp-h${height}dp-${dpi}dpi")
this.activity.setContent {
CompositionLocalProvider(
LocalInspectionMode provides true,
) {
TestHarness(darkMode = darkMode) {
LaunchedEffect(key1 = true) {
snackbarHostState.showSnackbar(message = message)
}
body()
}
}
}
waitUntilAtLeastOneExists(matcher = hasTestTag(testTag = testTag))
this.onRoot().captureRoboImage(
filePath = "src/test/screenshots/${fileName}_$deviceName.png",
roborazziOptions = roborazziOptions,
)
}
/**
* Experimental feature to capture the entire screen, including dialogs combining light/dark and default/Android themes and whether dynamic color
* is enabled.
*/
@OptIn(ExperimentalRoborazziApi::class)
fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureDialogForDevice(
name: String,
fileName: String,
deviceName: String,
deviceSpec: String,
roborazziOptions: RoborazziOptions = DefaultRoborazziOptions,
darkMode: Boolean = false,
body: @Composable () -> Unit,
) {
val (width, height, dpi) = extractSpecs(deviceSpec)
// Set qualifiers from specs
RuntimeEnvironment.setQualifiers("w${width}dp-h${height}dp-${dpi}dpi")
this.activity.setContent {
CompositionLocalProvider(
LocalInspectionMode provides true,
) {
TestHarness(darkMode = darkMode) {
body()
}
}
}
captureScreenRoboImage(
filePath = "src/test/screenshots/$name/${fileName}_$deviceName.png",
roborazziOptions = roborazziOptions,
)
}
/**
* Takes six screenshots combining light/dark and default/Android themes and whether dynamic color
* is enabled.
*/
fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.captureMultiTheme(
name: String,
overrideFileName: String? = null,
shouldCompareDarkMode: Boolean = true,
shouldCompareDynamicColor: Boolean = true,
shouldCompareAndroidTheme: Boolean = true,
content: @Composable (desc: String) -> Unit,
) {
val darkModeValues = if (shouldCompareDarkMode) listOf(true, false) else listOf(false)
val dynamicThemingValues = if (shouldCompareDynamicColor) listOf(true, false) else listOf(false)
val androidThemeValues = if (shouldCompareAndroidTheme) listOf(true, false) else listOf(false)
var darkMode by mutableStateOf(true)
var dynamicTheming by mutableStateOf(false)
var androidTheme by mutableStateOf(false)
this.setContent {
CompositionLocalProvider(
LocalInspectionMode provides true,
) {
GetoTheme(
androidTheme = androidTheme,
darkTheme = darkMode,
disableDynamicTheming = !dynamicTheming,
) {
// Keying is necessary in some cases (e.g. animations)
key(androidTheme, darkMode, dynamicTheming) {
val description = generateDescription(
shouldCompareDarkMode = shouldCompareDarkMode,
darkMode = darkMode,
shouldCompareAndroidTheme = shouldCompareAndroidTheme,
androidTheme = androidTheme,
shouldCompareDynamicColor = shouldCompareDynamicColor,
dynamicTheming = dynamicTheming,
)
content(description)
}
}
}
}
// Create permutations
darkModeValues.forEach { isDarkMode ->
darkMode = isDarkMode
val darkModeDesc = if (isDarkMode) "dark" else "light"
androidThemeValues.forEach { isAndroidTheme ->
androidTheme = isAndroidTheme
val androidThemeDesc = if (isAndroidTheme) "androidTheme" else "defaultTheme"
dynamicThemingValues.forEach dynamicTheme@{ isDynamicTheming ->
// Skip tests with both Android Theme and Dynamic color as they're incompatible.
if (isAndroidTheme && isDynamicTheming) return@dynamicTheme
dynamicTheming = isDynamicTheming
val dynamicThemingDesc = if (isDynamicTheming) "dynamic" else "notDynamic"
val filename = overrideFileName ?: name
this.onRoot().captureRoboImage(
filePath = "src/test/screenshots/" + "$name/$filename" + "_$darkModeDesc" + "_$androidThemeDesc" + "_$dynamicThemingDesc" + ".png",
roborazziOptions = DefaultRoborazziOptions,
)
}
}
}
}
@Composable
private fun generateDescription(
shouldCompareDarkMode: Boolean,
darkMode: Boolean,
shouldCompareAndroidTheme: Boolean,
androidTheme: Boolean,
shouldCompareDynamicColor: Boolean,
dynamicTheming: Boolean,
): String {
val description = "" + if (shouldCompareDarkMode) {
if (darkMode) "Dark" else "Light"
} else {
""
} + if (shouldCompareAndroidTheme) {
if (androidTheme) " Android" else " Default"
} else {
""
} + if (shouldCompareDynamicColor) {
if (dynamicTheming) " Dynamic" else ""
} else {
""
}
return description.trim()
}
/**
* Extracts some properties from the spec string. Note that this function is not exhaustive.
*/
private fun extractSpecs(deviceSpec: String): TestDeviceSpecs {
val specs = deviceSpec.substringAfter("spec:").split(",").map { it.split("=") }
.associate { it[0] to it[1] }
val width = specs["width"]?.toInt() ?: 640
val height = specs["height"]?.toInt() ?: 480
val dpi = specs["dpi"]?.toInt() ?: 480
return TestDeviceSpecs(width, height, dpi)
}
data class TestDeviceSpecs(val width: Int, val height: Int, val dpi: Int)
| Geto/core/screenshot-testing/src/main/kotlin/com/android/geto/core/screenshot/testing/util/ScreenshotHelper.kt | 1255757716 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.packagemanager
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal interface PackageManagerModule {
@Binds
@Singleton
fun packageManagerWrapper(impl: DefaultPackageManagerWrapper): PackageManagerWrapper
}
| Geto/core/packagemanager/src/main/kotlin/com/android/geto/core/packagemanager/PackageManagerModule.kt | 2223589344 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.packagemanager
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import com.android.geto.core.model.TargetApplicationInfo
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
internal class DefaultPackageManagerWrapper @Inject constructor(@ApplicationContext private val context: Context) :
PackageManagerWrapper {
private val packageManager = context.packageManager
@SuppressLint("QueryPermissionsNeeded")
override fun getInstalledApplications(): List<TargetApplicationInfo> {
return packageManager.getInstalledApplications(0)
.map { applicationInfo ->
applicationInfo.asTargetApplicationInfo(packageManager)
}
}
override fun getApplicationIcon(packageName: String): Drawable {
return packageManager.getApplicationIcon(packageName)
}
override fun getLaunchIntentForPackage(packageName: String): Intent? {
return packageManager.getLaunchIntentForPackage(packageName)
}
}
| Geto/core/packagemanager/src/main/kotlin/com/android/geto/core/packagemanager/DefaultPackageManagerWrapper.kt | 3133275479 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.packagemanager
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import com.android.geto.core.model.TargetApplicationInfo
internal fun ApplicationInfo.asTargetApplicationInfo(packageManager: PackageManager): TargetApplicationInfo {
val label = try {
packageManager.getApplicationLabel(this)
} catch (e: PackageManager.NameNotFoundException) {
null
}
val icon = try {
packageManager.getApplicationIcon(this)
} catch (e: PackageManager.NameNotFoundException) {
null
}
return TargetApplicationInfo(
flags = flags,
icon = icon,
packageName = packageName,
label = label.toString(),
)
}
| Geto/core/packagemanager/src/main/kotlin/com/android/geto/core/packagemanager/ApplicationInfo.kt | 2992663856 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.packagemanager
import android.content.Intent
import android.graphics.drawable.Drawable
import com.android.geto.core.model.TargetApplicationInfo
interface PackageManagerWrapper {
fun getInstalledApplications(): List<TargetApplicationInfo>
fun getApplicationIcon(packageName: String): Drawable
fun getLaunchIntentForPackage(packageName: String): Intent?
}
| Geto/core/packagemanager/src/main/kotlin/com/android/geto/core/packagemanager/PackageManagerWrapper.kt | 3445766365 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.testing
import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
import dagger.hilt.android.testing.HiltTestApplication
/**
* A custom runner to set up the instrumented application class for tests.
*/
class GetoTestRunner : AndroidJUnitRunner() {
override fun newApplication(cl: ClassLoader, name: String, context: Context): Application =
super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
| Geto/core/testing/src/main/kotlin/com/android/geto/core/testing/GetoTestRunner.kt | 1650505025 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.testing.repository
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import com.android.geto.core.data.repository.PackageRepository
import com.android.geto.core.model.TargetApplicationInfo
class TestPackageRepository : PackageRepository {
private var _installedApplications = listOf<TargetApplicationInfo>()
override suspend fun getInstalledApplications(): List<TargetApplicationInfo> {
return _installedApplications
}
override suspend fun getApplicationIcon(packageName: String): Drawable? {
return if (packageName in _installedApplications.map { it.packageName }) ColorDrawable() else null
}
override fun getLaunchIntentForPackage(packageName: String): Intent? {
return if (packageName in _installedApplications.map { it.packageName }) Intent() else null
}
fun setInstalledApplications(value: List<TargetApplicationInfo>) {
_installedApplications = value
}
}
| Geto/core/testing/src/main/kotlin/com/android/geto/core/testing/repository/TestPackageRepository.kt | 2871664975 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.testing.repository
import com.android.geto.core.data.repository.AppSettingsRepository
import com.android.geto.core.model.AppSetting
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.map
class TestAppSettingsRepository : AppSettingsRepository {
private val _appSettingsFlow = MutableSharedFlow<List<AppSetting>>(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
private val currentAppSettings get() = _appSettingsFlow.replayCache.firstOrNull() ?: emptyList()
override val appSettings: Flow<List<AppSetting>> = _appSettingsFlow.asSharedFlow()
override suspend fun upsertAppSetting(appSetting: AppSetting) {
_appSettingsFlow.tryEmit((currentAppSettings + appSetting).distinct())
}
override suspend fun deleteAppSetting(appSetting: AppSetting) {
_appSettingsFlow.tryEmit(currentAppSettings - appSetting)
}
override fun getAppSettingsByPackageName(packageName: String): Flow<List<AppSetting>> {
return _appSettingsFlow.map { entities ->
entities.filter { it.packageName == packageName }
}
}
override suspend fun deleteAppSettingsByPackageName(packageNames: List<String>) {
_appSettingsFlow.tryEmit(currentAppSettings.filterNot { it.packageName in packageNames })
}
fun setAppSettings(value: List<AppSetting>) {
_appSettingsFlow.tryEmit(value)
}
}
| Geto/core/testing/src/main/kotlin/com/android/geto/core/testing/repository/TestAppSettingsRepository.kt | 994031522 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.testing.repository
import com.android.geto.core.data.repository.UserDataRepository
import com.android.geto.core.model.DarkThemeConfig
import com.android.geto.core.model.ThemeBrand
import com.android.geto.core.model.UserData
import kotlinx.coroutines.channels.BufferOverflow.DROP_OLDEST
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.filterNotNull
val emptyUserData = UserData(
themeBrand = ThemeBrand.DEFAULT,
darkThemeConfig = DarkThemeConfig.FOLLOW_SYSTEM,
useDynamicColor = false,
useAutoLaunch = false,
)
class TestUserDataRepository : UserDataRepository {
private val _userData = MutableSharedFlow<UserData>(replay = 1, onBufferOverflow = DROP_OLDEST)
private val currentUserData get() = _userData.replayCache.firstOrNull() ?: emptyUserData
override val userData: Flow<UserData> = _userData.filterNotNull()
override suspend fun setThemeBrand(themeBrand: ThemeBrand) {
currentUserData.let { current ->
_userData.tryEmit(current.copy(themeBrand = themeBrand))
}
}
override suspend fun setDarkThemeConfig(darkThemeConfig: DarkThemeConfig) {
currentUserData.let { current ->
_userData.tryEmit(current.copy(darkThemeConfig = darkThemeConfig))
}
}
override suspend fun setDynamicColorPreference(useDynamicColor: Boolean) {
currentUserData.let { current ->
_userData.tryEmit(current.copy(useDynamicColor = useDynamicColor))
}
}
override suspend fun setAutoLaunchPreference(useAutoLaunch: Boolean) {
currentUserData.let { current ->
_userData.tryEmit(current.copy(useAutoLaunch = useAutoLaunch))
}
}
/**
* A test-only API to allow setting of user data directly.
*/
fun setUserData(userData: UserData) {
_userData.tryEmit(userData)
}
}
| Geto/core/testing/src/main/kotlin/com/android/geto/core/testing/repository/TestUserDataRepository.kt | 1428294534 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.testing.repository
import com.android.geto.core.data.repository.SecureSettingsRepository
import com.android.geto.core.model.AppSetting
import com.android.geto.core.model.SecureSetting
import com.android.geto.core.model.SettingType
class TestSecureSettingsRepository : SecureSettingsRepository {
private var writeSecureSettings = false
private var invalidValues = false
private var secureSettingList = listOf<SecureSetting>()
override suspend fun applySecureSettings(appSettings: List<AppSetting>): Boolean {
return if (!writeSecureSettings) {
throw SecurityException()
} else if (invalidValues) {
throw IllegalArgumentException()
} else {
true
}
}
override suspend fun revertSecureSettings(appSettings: List<AppSetting>): Boolean {
return if (!writeSecureSettings) {
throw SecurityException()
} else if (invalidValues) {
throw IllegalArgumentException()
} else {
true
}
}
override suspend fun getSecureSettings(settingType: SettingType): List<SecureSetting> {
return secureSettingList
}
override suspend fun getSecureSettingsByName(
settingType: SettingType,
text: String,
): List<SecureSetting> {
return secureSettingList.filter { it.name!!.contains(text) }.take(20)
}
fun setWriteSecureSettings(value: Boolean) {
writeSecureSettings = value
}
fun setInvalidValues(value: Boolean) {
invalidValues = value
}
fun setSecureSettings(value: List<SecureSetting>) {
secureSettingList = value
}
}
| Geto/core/testing/src/main/kotlin/com/android/geto/core/testing/repository/TestSecureSettingsRepository.kt | 3544714603 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.testing.repository
import com.android.geto.core.data.repository.ClipboardRepository
import com.android.geto.core.data.repository.ClipboardResult
class TestClipboardRepository : ClipboardRepository {
private var _atleastApi32 = false
override fun setPrimaryClip(label: String, text: String): ClipboardResult {
return if (_atleastApi32) {
ClipboardResult.NoResult
} else {
ClipboardResult.Notify(text)
}
}
fun setAtLeastApi32(value: Boolean) {
_atleastApi32 = value
}
}
| Geto/core/testing/src/main/kotlin/com/android/geto/core/testing/repository/TestClipboardRepository.kt | 2231682911 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.testing.repository
import com.android.geto.core.data.repository.ShortcutRepository
import com.android.geto.core.data.repository.ShortcutResult
import com.android.geto.core.model.TargetShortcutInfoCompat
class TestShortcutRepository : ShortcutRepository {
private var requestPinShortcutSupported = false
private var targetShortcutInfoCompats = listOf<TargetShortcutInfoCompat>()
private var updateImmutableShortcuts = false
override fun requestPinShortcut(
packageName: String,
appName: String,
targetShortcutInfoCompat: TargetShortcutInfoCompat,
): ShortcutResult {
return if (requestPinShortcutSupported) {
ShortcutResult.SupportedLauncher
} else {
ShortcutResult.UnsupportedLauncher
}
}
override fun updateRequestPinShortcut(
packageName: String,
appName: String,
targetShortcutInfoCompat: TargetShortcutInfoCompat,
): ShortcutResult {
return if (updateImmutableShortcuts) {
ShortcutResult.ShortcutUpdateImmutableShortcuts
} else {
ShortcutResult.ShortcutUpdateSuccess
}
}
override fun getShortcut(id: String): ShortcutResult {
val targetShortcutInfoCompat = targetShortcutInfoCompats.find { it.id == id }
return if (targetShortcutInfoCompat != null) {
ShortcutResult.ShortcutFound(
targetShortcutInfoCompat = targetShortcutInfoCompat,
)
} else {
ShortcutResult.NoShortcutFound
}
}
fun setRequestPinShortcutSupported(value: Boolean) {
requestPinShortcutSupported = value
}
fun setShortcuts(value: List<TargetShortcutInfoCompat>) {
targetShortcutInfoCompats = value
}
fun setUpdateImmutableShortcuts(value: Boolean) {
updateImmutableShortcuts = value
}
}
| Geto/core/testing/src/main/kotlin/com/android/geto/core/testing/repository/TestShortcutRepository.kt | 2922519028 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.testing.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal object TestDispatcherModule {
@Provides
@Singleton
fun providesTestDispatcher(): TestDispatcher = UnconfinedTestDispatcher()
}
| Geto/core/testing/src/main/kotlin/com/android/geto/core/testing/di/TestDispatcherModule.kt | 2567519524 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.testing.di
import com.android.geto.core.common.Dispatcher
import com.android.geto.core.common.GetoDispatchers.Default
import com.android.geto.core.common.GetoDispatchers.IO
import com.android.geto.core.common.di.DispatchersModule
import dagger.Module
import dagger.Provides
import dagger.hilt.components.SingletonComponent
import dagger.hilt.testing.TestInstallIn
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.test.TestDispatcher
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [DispatchersModule::class],
)
internal object TestDispatchersModule {
@Provides
@Dispatcher(IO)
fun providesIODispatcher(testDispatcher: TestDispatcher): CoroutineDispatcher = testDispatcher
@Provides
@Dispatcher(Default)
fun providesDefaultDispatcher(
testDispatcher: TestDispatcher,
): CoroutineDispatcher = testDispatcher
}
| Geto/core/testing/src/main/kotlin/com/android/geto/core/testing/di/TestDispatchersModule.kt | 2162558278 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.testing.util
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description
@OptIn(ExperimentalCoroutinesApi::class)
class MainDispatcherRule(
private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(),
) : TestWatcher() {
override fun starting(description: Description) = Dispatchers.setMain(testDispatcher)
override fun finished(description: Description) = Dispatchers.resetMain()
}
| Geto/core/testing/src/main/kotlin/com/android/geto/core/testing/util/MainDispatcherRule.kt | 3345066799 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.core.datastore.test
import androidx.datastore.core.DataStore
import androidx.datastore.core.DataStoreFactory
import com.android.geto.core.common.di.ApplicationScope
import com.android.geto.core.datastore.UserPreferences
import com.android.geto.datastore.UserPreferencesSerializer
import com.android.geto.datastore.di.DataStoreModule
import dagger.Module
import dagger.Provides
import dagger.hilt.components.SingletonComponent
import dagger.hilt.testing.TestInstallIn
import kotlinx.coroutines.CoroutineScope
import org.junit.rules.TemporaryFolder
import javax.inject.Singleton
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [DataStoreModule::class],
)
internal object TestDataStoreModule {
@Provides
@Singleton
fun providesUserPreferencesDataStore(
@ApplicationScope scope: CoroutineScope,
userPreferencesSerializer: UserPreferencesSerializer,
tmpFolder: TemporaryFolder,
): DataStore<UserPreferences> = tmpFolder.testUserPreferencesDataStore(
coroutineScope = scope,
userPreferencesSerializer = userPreferencesSerializer,
)
}
fun TemporaryFolder.testUserPreferencesDataStore(
coroutineScope: CoroutineScope,
userPreferencesSerializer: UserPreferencesSerializer = UserPreferencesSerializer(),
) = DataStoreFactory.create(
serializer = userPreferencesSerializer,
scope = coroutineScope,
) {
newFile("user_preferences_test.pb")
}
| Geto/core/datastore-test/src/main/kotlin/com/android/geto/core/datastore/test/TestDataStoreModule.kt | 3514276019 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.datastore
import androidx.datastore.core.CorruptionException
import com.android.geto.core.datastore.userPreferences
import kotlinx.coroutines.test.runTest
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import kotlin.test.assertEquals
class UserPreferencesSerializerTest {
private val userPreferencesSerializer = UserPreferencesSerializer()
@Test
fun defaultUserPreferences_isEmpty() {
assertEquals(
userPreferences {
// Default value
},
userPreferencesSerializer.defaultValue,
)
}
@Test
fun writingAndReadingUserPreferences_outputsCorrectValue() = runTest {
val expectedUserPreferences = userPreferences {
useDynamicColor = true
}
val outputStream = ByteArrayOutputStream()
expectedUserPreferences.writeTo(outputStream)
val inputStream = ByteArrayInputStream(outputStream.toByteArray())
val actualUserPreferences = userPreferencesSerializer.readFrom(inputStream)
assertEquals(
expectedUserPreferences,
actualUserPreferences,
)
}
@Test(expected = CorruptionException::class)
fun readingInvalidUserPreferences_throwsCorruptionException() = runTest {
userPreferencesSerializer.readFrom(ByteArrayInputStream(byteArrayOf(0)))
}
}
| Geto/core/datastore/src/test/kotlin/com/android/geto/datastore/UserPreferencesSerializerTest.kt | 3846249877 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.datastore
import com.android.geto.core.datastore.test.testUserPreferencesDataStore
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.Before
import org.junit.Rule
import org.junit.rules.TemporaryFolder
class GetoPreferencesDataSourceTest {
private val testScope = TestScope(UnconfinedTestDispatcher())
private lateinit var subject: GetoPreferencesDataSource
@get:Rule
val tmpFolder: TemporaryFolder = TemporaryFolder.builder().assureDeletion().build()
@Before
fun setup() {
subject = GetoPreferencesDataSource(
tmpFolder.testUserPreferencesDataStore(testScope),
)
}
//
// @Test
// fun shouldUseDynamicColorFalseByDefault() = testScope.runTest {
// assertFalse(subject.userData.first().useDynamicColor)
// }
//
// @Test
// fun userShouldUseDynamicColorIsTrueWhenSet() = testScope.runTest {
// subject.setDynamicColorPreference(true)
// assertTrue(subject.userData.first().useDynamicColor)
// }
}
| Geto/core/datastore/src/test/kotlin/com/android/geto/datastore/GetoPreferencesDataSourceTest.kt | 3885638515 |
/*
*
* Copyright 2023 Einstein Blanco
*
* Licensed under the GNU General Public License v3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.geto.datastore
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.Serializer
import com.android.geto.core.datastore.UserPreferences
import com.google.protobuf.InvalidProtocolBufferException
import java.io.InputStream
import java.io.OutputStream
import javax.inject.Inject
/**
* An [androidx.datastore.core.Serializer] for the [UserPreferences] proto.
*/
class UserPreferencesSerializer @Inject constructor() : Serializer<UserPreferences> {
override val defaultValue: UserPreferences = UserPreferences.getDefaultInstance()
override suspend fun readFrom(input: InputStream): UserPreferences = try {
// readFrom is already called on the data store background thread
UserPreferences.parseFrom(input)
} catch (exception: InvalidProtocolBufferException) {
throw CorruptionException("Cannot read proto.", exception)
}
override suspend fun writeTo(t: UserPreferences, output: OutputStream) {
// writeTo is already called on the data store background thread
t.writeTo(output)
}
}
| Geto/core/datastore/src/main/kotlin/com/android/geto/datastore/UserPreferencesSerializer.kt | 1289498868 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.