content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package com.nandits.goalscatcher
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.nandits.goalscatcher", appContext.packageName)
}
} | GoalsCatcher/app/src/androidTest/java/com/nandits/goalscatcher/ExampleInstrumentedTest.kt | 3637214355 |
package com.nandits.goalscatcher
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)
}
} | GoalsCatcher/app/src/test/java/com/nandits/goalscatcher/ExampleUnitTest.kt | 3931091100 |
package com.nandits.goalscatcher.di
import android.app.Application
import com.orhanobut.hawk.Hawk
class GoalsCatcherApp: Application() {
override fun onCreate() {
super.onCreate()
Hawk.init(this).build()
}
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/di/GoalsCatcherApp.kt | 1496266750 |
package com.nandits.goalscatcher.utils
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.reflect.TypeToken
fun <T> String.gsonFromJson(clazz: Class<T>): T? {
return try {
Gson().fromJson(this, clazz)
} catch (e: JsonSyntaxException) {
null
}
}
fun <T> String.listGsonFromJson(clazz: Class<T>): List<T> {
val listType = object : TypeToken<List<T>>() {}.type
return Gson().fromJson(this, listType)
}
fun Any?.gsonToJson(): String {
return Gson().toJson(this)
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/GsonUtils.kt | 3871341422 |
package com.nandits.goalscatcher.utils
import android.icu.util.Calendar
fun getCurrentYear(): Int {
val calendar = Calendar.getInstance()
return calendar.get(Calendar.YEAR)
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/DateUtils.kt | 2097488077 |
package com.nandits.goalscatcher.utils
object HawkKeys {
const val HOME_TITLE = "HOME_TITLE"
const val SAVED_YEAR = "SAVED_YEAR"
const val LAST_CATEGORY = "LAST_CATEGORY"
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/HawkKeys.kt | 2032005508 |
package com.nandits.goalscatcher.utils
data class SelectableItem<T>(
val value: T,
val name: String = value.toString(),
var isSelected: Boolean = false,
var isSelectable: Boolean = false,
)
typealias OnItemClickListener<T> = (item: T, isSelected: Boolean) -> Unit | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/Model.kt | 3541947624 |
package com.nandits.goalscatcher.utils
import android.view.View
fun View.gone() {
this.visibility = View.GONE
}
fun View.visible() {
this.visibility = View.VISIBLE
}
fun View.invisible() {
this.visibility = View.INVISIBLE
}
fun View.onlyVisibleIf(visible: Boolean) {
if (visible) visible() else gone()
}
fun View.enable() {
this.isEnabled = true
}
fun View.disable() {
this.isEnabled = false
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/ViewUtils.kt | 2551398777 |
package com.nandits.goalscatcher.utils
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Parcelable
import android.widget.Toast
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.orhanobut.hawk.Hawk
fun emptyString() = ""
fun Context.showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
inline fun <reified T : Parcelable> Intent.parcelable(key: String): T? = when {
Build.VERSION.SDK_INT >= 33 -> getParcelableExtra(key, T::class.java)
else -> @Suppress("DEPRECATION") getParcelableExtra(key) as? T
}
inline fun <reified T : Parcelable> Bundle.parcelable(key: String): T? = when {
Build.VERSION.SDK_INT >= 33 -> getParcelable(key, T::class.java)
else -> @Suppress("DEPRECATION") getParcelable(key) as? T
}
fun setHawkList(key: String, list: List<String>) {
val gson = Gson()
val json = gson.toJson(list)
Hawk.put(key, json)
}
fun getHawkList(key: String): ArrayList<String>? {
val gson = Gson()
val json = Hawk.get<String>(key)
val type = object : TypeToken<ArrayList<String>>() {}.type
return gson.fromJson(json, type)
}
| GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/Utils.kt | 4165938173 |
package com.nandits.goalscatcher.utils
import android.widget.ImageView
import coil.load
import java.io.File
fun ImageView.loadFileImage(path: String) {
load(File(path))
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/ImageUtils.kt | 4253501648 |
package com.nandits.goalscatcher.utils
| GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/PermissionUtils.kt | 312430029 |
package com.nandits.goalscatcher.utils
fun Boolean?.default(boolean: Boolean) = this ?: boolean
fun String?.default(string: String = emptyString()) = this ?: string
fun Double?.default(double: Double = 0.0) = this ?: double
fun Int?.default(int: Int = 0) = this ?: int
fun Long?.default(long: Long = 0) = this ?: long | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/PrimitivesUtils.kt | 2770397312 |
package com.nandits.goalscatcher.utils
object BundleKeys {
const val INPUT_TEXT_CONFIG = "INPUT_TEXT_CONFIG"
const val GOAL = "GOAL"
const val CATEGORY = "CATEGORY"
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/BundleKeys.kt | 2333897974 |
package com.nandits.goalscatcher.utils
object DialogStateController {
private var mTags = mutableListOf<String>()
@JvmStatic
fun add(tag: String) {
mTags.add(tag)
}
@JvmStatic
fun remove(tag: String) {
mTags.remove(tag)
}
@JvmStatic
fun isShown(tag: String): Boolean {
return mTags.find { it == tag } != null
}
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/utils/DialogStateController.kt | 268540020 |
package com.nandits.goalscatcher.view
import android.os.Bundle
import com.nandits.goalscatcher.R
import com.nandits.goalscatcher.base.BaseActivity
import com.nandits.goalscatcher.data.InputTextConfig
import com.nandits.goalscatcher.databinding.ActivityMainBinding
import com.nandits.goalscatcher.utils.HawkKeys
import com.nandits.goalscatcher.utils.emptyString
import com.nandits.goalscatcher.utils.getCurrentYear
import com.nandits.goalscatcher.utils.getHawkList
import com.nandits.goalscatcher.utils.setHawkList
import com.nandits.goalscatcher.view.bottomsheet.InputTextBottomSheet
import com.nandits.goalscatcher.view.dialog.showYearPicker
import com.orhanobut.hawk.Hawk
class MainActivity : BaseActivity<ActivityMainBinding>() {
private var homeTitle = emptyString()
override fun getViewBinding(): ActivityMainBinding {
return ActivityMainBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initUi()
initAction()
}
private fun initUi() {
setToolbarHome()
setTabYears()
setTabWithText(getCurrentYear().toString())
}
private fun initAction() {
with(binding) {
toolbarHome.tvToolbar.setOnClickListener {
InputTextBottomSheet.newInstance(
config = InputTextConfig(
title = getString(R.string.label_enter_your_name),
hint = getString(R.string.label_enter_your_name),
text = homeTitle.ifEmpty { emptyString() },
isCloseable = homeTitle.isNotEmpty()
),
doneListener = {
Hawk.put(HawkKeys.HOME_TITLE, it)
setToolbarHome()
}
).showBottomSheet(supportFragmentManager)
}
fabAddYear.setOnClickListener {
showYearPicker(this@MainActivity) {
val years = getHawkList(HawkKeys.SAVED_YEAR)
if (years.orEmpty().contains(it).not()) {
years?.add(it)
}
setHawkList(HawkKeys.SAVED_YEAR, years.orEmpty().sorted())
setTabYears()
setTabWithText(it)
}
}
btnAddCategory.setOnClickListener {
InputTextBottomSheet.newInstance(
config = InputTextConfig(
title = getString(R.string.label_add_category),
hint = getString(R.string.label_enter_category_name),
isCloseable = false,
info = getString(R.string.message_info_add_category)
),
doneListener = {
Hawk.put(HawkKeys.LAST_CATEGORY, it)
btnDeleteYear.text = Hawk.get(HawkKeys.LAST_CATEGORY)
},
).showBottomSheet(supportFragmentManager)
}
btnDeleteYear.text = Hawk.get(HawkKeys.LAST_CATEGORY)
btnDeleteYear.setOnClickListener {
}
}
}
private fun setToolbarHome() {
homeTitle = Hawk.get<String?>(HawkKeys.HOME_TITLE).orEmpty()
binding.toolbarHome.apply {
tvToolbar.text = getString(R.string.format_user_goals, homeTitle.ifEmpty { "Your Name" })
}
}
private fun setTabYears() {
with(binding.tabYear) {
if (this.tabCount > 0) removeAllTabs()
getSavedYear().sorted().forEach { addTab(newTab().setText(it)) }
}
}
private fun getSavedYear(): MutableList<String> {
if (getHawkList(HawkKeys.SAVED_YEAR).orEmpty().isEmpty()) {
setHawkList(HawkKeys.SAVED_YEAR, arrayListOf(getCurrentYear().toString()))
}
return getHawkList(HawkKeys.SAVED_YEAR).orEmpty().toMutableList()
}
private fun setTabWithText(text: String) {
with(binding.tabYear) {
getTabAt(getSavedYear().indexOf(text))?.select()
}
}
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/view/MainActivity.kt | 559857375 |
package com.nandits.goalscatcher.view
import android.content.Intent
import android.os.Bundle
import com.nandits.goalscatcher.base.BaseActivity
import com.nandits.goalscatcher.data.Category
import com.nandits.goalscatcher.data.Goal
import com.nandits.goalscatcher.databinding.ActivityGoalsBinding
import com.nandits.goalscatcher.utils.BundleKeys
class GoalsActivity : BaseActivity<ActivityGoalsBinding>() {
companion object {
fun getIntent(category: Category): Intent {
return Intent().apply {
putExtra(BundleKeys.CATEGORY, category)
}
}
}
override fun getViewBinding(): ActivityGoalsBinding {
return ActivityGoalsBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/view/GoalsActivity.kt | 3159917725 |
package com.nandits.goalscatcher.view.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.nandits.goalscatcher.data.Goal
import com.nandits.goalscatcher.databinding.ItemGoalsBinding
class GoalAdapter() :
ListAdapter<Goal, GoalAdapter.ViewHolder>(GoalComparator) {
inner class ViewHolder(private val binding: ItemGoalsBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(data: Goal) {
with(binding) {
tvGoal.text = data.goalTitle
cbGoal.isChecked = data.isAchieved
cbGoal.setOnCheckedChangeListener { _, isChecked ->
// callback.onCheckBoxCheckChanged(isChecked)
}
}
}
}
object GoalComparator : DiffUtil.ItemCallback<Goal>() {
override fun areItemsTheSame(oldItem: Goal, newItem: Goal): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Goal, newItem: Goal): Boolean {
return oldItem == newItem
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = ItemGoalsBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
}
interface GoalAdapterListener {
fun onCheckBoxCheckChanged(isChecked: Boolean)
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/view/adapter/GoalAdapter.kt | 2422998434 |
package com.nandits.goalscatcher.view.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.nandits.goalscatcher.data.Goal
import com.nandits.goalscatcher.databinding.ItemDetailGoalBinding
import com.nandits.goalscatcher.utils.SelectableItem
import com.nandits.goalscatcher.utils.loadFileImage
import com.nandits.goalscatcher.utils.onlyVisibleIf
class DetailGoalsAdapter(private val callback: DetailGoalListeners) :
ListAdapter<SelectableItem<Goal>, DetailGoalsAdapter.ViewHolder>(GoalComparator) {
inner class ViewHolder(private val binding: ItemDetailGoalBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(data: SelectableItem<Goal>) {
with(binding) {
cbGoal.isChecked = data.value.isAchieved
cbGoal.text = data.value.goalTitle
imgPlaceholder.onlyVisibleIf(data.value.photos.isEmpty())
imgGoal.onlyVisibleIf(data.value.photos.isNotEmpty())
imgGoal.loadFileImage(data.value.photos.random())
cardGoal.setOnClickListener {
if (data.isSelectable) callback.onCardClicked(data.value)
}
cardGoal.setOnLongClickListener {
callback.onCardLongClicked(data.value)
data.isSelectable = true
notifyItemChanged(adapterPosition)
true
}
cardGoal.isActivated = data.isSelected
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = ItemDetailGoalBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
object GoalComparator : DiffUtil.ItemCallback<SelectableItem<Goal>>() {
override fun areItemsTheSame(oldItem: SelectableItem<Goal>, newItem: SelectableItem<Goal>): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: SelectableItem<Goal>, newItem: SelectableItem<Goal>): Boolean {
return oldItem == newItem
}
}
}
interface DetailGoalListeners {
fun onCardClicked(goal: Goal)
fun onCardLongClicked(goal: Goal)
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/view/adapter/DetailGoalsAdapter.kt | 1851226388 |
package com.nandits.goalscatcher.view.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.asksira.loopingviewpager.LoopingPagerAdapter
import com.nandits.goalscatcher.R
import com.nandits.goalscatcher.utils.loadFileImage
class GoalPhotoAdapter(
private val items: List<String>
) : LoopingPagerAdapter<String>(items, true) {
override fun bindView(convertView: View, listPosition: Int, viewType: Int) {
with(convertView) {
findViewById<ImageView>(R.id.imgGoalPhoto).loadFileImage(items[listPosition])
}
}
override fun inflateView(viewType: Int, container: ViewGroup, listPosition: Int): View {
return LayoutInflater.from(container.context).inflate(R.layout.item_goal_photo, container, false)
}
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/view/adapter/GoalPhotoAdapter.kt | 2514549952 |
package com.nandits.goalscatcher.view.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.nandits.goalscatcher.R
import com.nandits.goalscatcher.data.Category
import com.nandits.goalscatcher.data.Goal
import com.nandits.goalscatcher.data.toGoal
import com.nandits.goalscatcher.databinding.ItemGoalsCategoryBinding
import com.nandits.goalscatcher.utils.SelectableItem
import com.nandits.goalscatcher.utils.onlyVisibleIf
class GoalCategoriesExpandableAdapter(private val callback: GoalCategoriesExpandableListeners) :
ListAdapter<SelectableItem<Category>, GoalCategoriesExpandableAdapter.ViewHolder>(CategoryComparator), GoalAdapterListener {
private val goalAdapter by lazy { GoalAdapter() }
private var totalAchieved = 0
inner class ViewHolder(private val binding: ItemGoalsCategoryBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(data: SelectableItem<Category>) {
with(binding) {
val goals: List<Goal> = data.value.goals.map { it.toGoal() }
toggleCategory(this, data.isSelected)
totalAchieved = data.value.totalAchieved
goalAdapter.submitList(goals)
tvCategory.text = data.value.categoryTitle
tvGoalsCounter.text = itemView.context.getString(
R.string.format_one_slash_two,
totalAchieved.toString(),
goals.size.toString()
)
btnDown.setOnClickListener {
toggleCategory(binding, true)
}
btnUp.setOnClickListener {
toggleCategory(binding, false)
}
btnDetails.setOnClickListener {
callback.onDetailClicked(data.value)
}
btnAdd.setOnClickListener {
callback.onAddClicked(data.value)
}
btnDelete.setOnClickListener {
callback.onDeleteClicked(data.value)
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = ItemGoalsCategoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position))
}
object CategoryComparator : DiffUtil.ItemCallback<SelectableItem<Category>>() {
override fun areItemsTheSame(oldItem: SelectableItem<Category>, newItem: SelectableItem<Category>): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: SelectableItem<Category>, newItem: SelectableItem<Category>): Boolean {
return oldItem == newItem
}
}
private fun toggleCategory(binding: ItemGoalsCategoryBinding, isExpanded: Boolean) {
with(binding) {
btnAdd.onlyVisibleIf(isExpanded)
btnDelete.onlyVisibleIf(isExpanded)
btnDetails.onlyVisibleIf(isExpanded)
rvGoals.onlyVisibleIf(isExpanded)
dividerBottom.onlyVisibleIf(isExpanded)
dividerTop.onlyVisibleIf(isExpanded)
btnUp.onlyVisibleIf(isExpanded)
btnDown.onlyVisibleIf(!isExpanded)
}
}
override fun onCheckBoxCheckChanged(isChecked: Boolean) {
if (isChecked) totalAchieved += 1 else totalAchieved -= 1
}
}
interface GoalCategoriesExpandableListeners {
fun onDetailClicked(data: Category)
fun onAddClicked(data: Category)
fun onDeleteClicked(data: Category)
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/view/adapter/GoalCategoriesExpandableAdapter.kt | 328665728 |
package com.nandits.goalscatcher.view.dialog
import android.app.Dialog
import android.content.Context
import android.icu.util.Calendar
import android.view.Window
import android.widget.Button
import android.widget.NumberPicker
import com.nandits.goalscatcher.R
fun showYearPicker(context: Context, onYearSelected: (String) -> Unit) {
val calendar = Calendar.getInstance()
val year: Int = calendar.get(Calendar.YEAR)
val dialog = Dialog(context)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.dialog_year_picker)
val btnOk = dialog.findViewById<Button>(R.id.btnOk)
val btnCancel = dialog.findViewById<Button>(R.id.btnCancel)
val yearPicker = dialog.findViewById<NumberPicker>(R.id.yearPicker)
yearPicker.apply {
minValue = year - 4
maxValue = year
descendantFocusability = NumberPicker.FOCUS_BLOCK_DESCENDANTS
wrapSelectorWheel = false
value = year
}
btnOk.setOnClickListener {
val pickerValue = yearPicker.value.toString()
onYearSelected.invoke(pickerValue)
dialog.dismiss()
}
btnCancel.setOnClickListener { dialog.dismiss() }
dialog.show()
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/view/dialog/YearPickerDialog.kt | 1225479519 |
package com.nandits.goalscatcher.view.bottomsheet
import android.os.Bundle
import com.nandits.goalscatcher.base.BaseBottomSheetFragment
import com.nandits.goalscatcher.data.InputTextConfig
import com.nandits.goalscatcher.databinding.BottomSheetInputTextBinding
import com.nandits.goalscatcher.utils.BundleKeys
import com.nandits.goalscatcher.utils.default
import com.nandits.goalscatcher.utils.onlyVisibleIf
import com.nandits.goalscatcher.utils.parcelable
class InputTextBottomSheet : BaseBottomSheetFragment<BottomSheetInputTextBinding>() {
companion object {
fun newInstance(
config: InputTextConfig,
doneListener: ((String) -> Unit)? = null,
closeListener: (() -> Unit)? = null
): InputTextBottomSheet {
val bundle = Bundle().apply { putParcelable(BundleKeys.INPUT_TEXT_CONFIG, config) }
return InputTextBottomSheet().apply {
arguments = bundle
this.doneListener = doneListener
this.closeListener = closeListener
}
}
}
override val tagName: String = InputTextBottomSheet::class.java.simpleName
private var doneListener: ((String) -> Unit)? = null
private var closeListener: (() -> Unit)? = null
private var config: InputTextConfig? = null
override fun initArgs() {
config = arguments?.parcelable(BundleKeys.INPUT_TEXT_CONFIG)
}
override fun initUI() {
with(binding) {
tvTitle.text = config?.title
btnClose.onlyVisibleIf(config?.isCloseable.default(false))
cvInfo.onlyVisibleIf(config?.info.default().isNotEmpty())
tvInfo.text = config?.info
edtInput.hint = config?.hint
edtInput.setText(config?.text)
}
}
override fun initAction() {
with(binding) {
btnDone.setOnClickListener {
doneListener?.invoke(edtInput.text.toString())
dismiss()
}
btnClose.setOnClickListener {
closeListener?.invoke()
dismiss()
}
}
}
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/view/bottomsheet/InputTextBottomSheet.kt | 3835236313 |
package com.nandits.goalscatcher.view
import android.content.Intent
import android.os.Bundle
import com.nandits.goalscatcher.base.BaseActivity
import com.nandits.goalscatcher.data.Goal
import com.nandits.goalscatcher.databinding.ActivityDetailGoalBinding
import com.nandits.goalscatcher.utils.BundleKeys
class DetailGoalActivity : BaseActivity<ActivityDetailGoalBinding>() {
companion object {
fun getIntent(goal: Goal): Intent {
return Intent().apply {
putExtra(BundleKeys.GOAL, goal)
}
}
}
override fun getViewBinding(): ActivityDetailGoalBinding {
return ActivityDetailGoalBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/view/DetailGoalActivity.kt | 2539709544 |
package com.nandits.goalscatcher.data
import android.os.Parcelable
import com.nandits.goalscatcher.utils.emptyString
import kotlinx.parcelize.Parcelize
@Parcelize
data class Category(
val id: Int = 0,
val year: String = emptyString(),
val categoryTitle: String = emptyString(),
val goals: List<String> = emptyList(),
val totalAchieved: Int = 0
) : Parcelable
| GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/data/Category.kt | 86333290 |
package com.nandits.goalscatcher.data
import android.os.Parcelable
import com.nandits.goalscatcher.utils.emptyString
import kotlinx.parcelize.Parcelize
@Parcelize
data class Goal(
val id: Int = 0,
val year: String = emptyString(),
val category: String = emptyString(),
val isAchieved: Boolean = false,
val goalTitle: String = emptyString(),
val achievedDate: String = emptyString(),
val photos: MutableList<String> = mutableListOf()
) : Parcelable
| GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/data/Goal.kt | 1992378345 |
package com.nandits.goalscatcher.data
import android.os.Parcelable
import com.nandits.goalscatcher.utils.emptyString
import kotlinx.parcelize.Parcelize
@Parcelize
data class InputTextConfig(
val title: String,
val hint: String,
val text: String = emptyString(),
val isCloseable: Boolean = false,
val info: String = emptyString(),
) : Parcelable
| GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/data/InputTextConfig.kt | 2923031500 |
package com.nandits.goalscatcher.data
import com.nandits.goalscatcher.utils.gsonFromJson
import com.nandits.goalscatcher.utils.gsonToJson
fun String.toGoal(): Goal {
return this.gsonFromJson(Goal::class.java)?: Goal()
}
fun Goal.toJsonString(): String {
return this.gsonToJson()
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/data/Mapper.kt | 701435170 |
package com.nandits.goalscatcher.base
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
abstract class BaseActivity<binding: ViewBinding> : AppCompatActivity() {
lateinit var binding: binding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = getViewBinding()
setContentView(binding.root)
}
abstract fun getViewBinding(): binding
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/base/BaseActivity.kt | 561573449 |
package com.nandits.goalscatcher.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType
abstract class BaseFragment<binding : ViewBinding> : Fragment() {
private var _binding : binding? = null
val binding :binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val type = javaClass.genericSuperclass
val clazz = (type as ParameterizedType).actualTypeArguments[0] as Class<*>
val method = clazz.getMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java)
_binding = method.invoke(null, layoutInflater, container, false) as binding
return _binding!!.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initBundle()
initUI()
initAction()
}
abstract fun initBundle()
abstract fun initUI()
abstract fun initAction()
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/base/BaseFragment.kt | 422853556 |
package com.nandits.goalscatcher.base
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.viewbinding.ViewBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.nandits.goalscatcher.utils.DialogStateController
import java.lang.reflect.ParameterizedType
abstract class BaseBottomSheetFragment<binding : ViewBinding> : BottomSheetDialogFragment() {
private var _binding: binding? = null
val binding: binding get() = _binding!!
abstract val tagName: String
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val type = javaClass.genericSuperclass
val clazz = (type as ParameterizedType).actualTypeArguments[0] as Class<*>
val method = clazz.getMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java)
_binding = method.invoke(null, layoutInflater, container, false) as binding
return _binding!!.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
dialog?.apply {
setOnShowListener {
val bottomSheet = this.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
if (bottomSheet != null) {
bottomSheet.background = null
}
}
}
initArgs()
initUI()
initAction()
}
abstract fun initArgs()
abstract fun initUI()
abstract fun initAction()
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
fun showBottomSheet(fragmentManager: FragmentManager) {
if (!isAdded && !DialogStateController.isShown(tagName)) {
DialogStateController.add(tagName)
this.show(fragmentManager, tagName)
}
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
DialogStateController.remove(tagName)
}
override fun onCancel(dialog: DialogInterface) {
super.onCancel(dialog)
DialogStateController.remove(tagName)
}
} | GoalsCatcher/app/src/main/java/com/nandits/goalscatcher/base/BaseBottomSheetFragment.kt | 729308634 |
package com.example.todocompose
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.todocompose", appContext.packageName)
}
} | Compose-Notes-App/app/src/androidTest/java/com/example/todocompose/ExampleInstrumentedTest.kt | 38084152 |
package com.example.todocompose
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)
}
} | Compose-Notes-App/app/src/test/java/com/example/todocompose/ExampleUnitTest.kt | 67485387 |
package com.example.todocompose.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.todocompose.data.NotesData
import com.example.todocompose.repository.NotesRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class NotesViewModel @Inject constructor(
private val repo:NotesRepository
):ViewModel() {
val _listOfNotes: LiveData<List<NotesData>>
get() = repo.getAllNotes()
fun insertNote(notesData: NotesData){
CoroutineScope(Dispatchers.IO).launch {
repo.insertNote(notesData)
}
}
fun delete(notesData: NotesData){
CoroutineScope(Dispatchers.IO).launch{
repo.delete(notesData)
}
}
} | Compose-Notes-App/app/src/main/java/com/example/todocompose/viewmodel/NotesViewModel.kt | 974295543 |
package com.example.todocompose.ui.screens
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.example.todocompose.data.NotesData
import com.example.todocompose.navigation.SetupNavGraph
import com.example.todocompose.ui.theme.TodoComposeTheme
import com.example.todocompose.viewmodel.NotesViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val viewModel:NotesViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TodoComposeTheme {
// A surface container using the 'background' color from the theme
// Surface(
// modifier = Modifier.fillMaxSize(),
// color = MaterialTheme.colorScheme.background
// ) {
//
// }
val navController = rememberNavController()
val onClickSave = {title:String,description:String -> viewModel.insertNote(
NotesData(
title=title,
description=description
)
)}
SetupNavGraph(navController = navController,viewModel)
}
}
}
}
| Compose-Notes-App/app/src/main/java/com/example/todocompose/ui/screens/MainActivity.kt | 1112723880 |
package com.example.todocompose.ui.screens
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Card
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.max
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.todocompose.R
import com.example.todocompose.data.NotesData
import com.example.todocompose.navigation.Screen
import com.example.todocompose.viewmodel.NotesViewModel
@Composable
fun NotesScreen(navController: NavController,viewModel: NotesViewModel
) {
val listOfNotesData = viewModel._listOfNotes.observeAsState()
Column(modifier = Modifier.fillMaxSize()) {
LazyColumn{
items(listOfNotesData.value?.size?:0){
NotesItems(notesData = listOfNotesData.value?.get(it) ?: NotesData(title="test",description= "test"),navController,viewModel)
}
}
Column(modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Bottom,
horizontalAlignment = Alignment.End) {
FloatingActionButton(
onClick = {navController.navigate(Screen.AddNotesScreen.passData(" "," ","0")) },
modifier = Modifier.padding(12.dp),
) {
Icon(
painter = painterResource(id = R.drawable.baseline_add_24),
contentDescription ="Add a Note" )
}
}
}
}
@Composable
fun NotesItems(
notesData: NotesData,
navController: NavController,
viewModel: NotesViewModel,
) {
Card(
modifier = Modifier
.padding(12.dp)
.fillMaxWidth()
.clickable {
navController.navigate(
Screen.AddNotesScreen.passData(
notesData.title,
notesData.description,
notesData.id.toString()
)
)
}
) {
var isExpanded by remember {
mutableStateOf(false)
}
Column(modifier = Modifier
.animateContentSize(tween(durationMillis = 300, easing = LinearOutSlowInEasing))){
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(
text = notesData.title,
fontSize = 18.sp,
textAlign = TextAlign.Start,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(12.dp),
overflow = TextOverflow.Ellipsis
)
Row {
IconButton(onClick = { viewModel.delete(notesData) }) {
Icon(
painter = painterResource(id = R.drawable.baseline_delete_24),
contentDescription = "Delete"
)
}
IconButton(onClick = { isExpanded = !isExpanded }) {
Icon(
painter = painterResource(id = if (isExpanded) R.drawable.baseline_expand_less_24 else R.drawable.baseline_expand_more_24),
contentDescription = if (isExpanded) "Collapse" else "Expand"
)
}
}
}
if(isExpanded){
Text(
text = notesData.description,
modifier = Modifier
.padding(12.dp),
fontSize = 18.sp,
maxLines = 5
)
}
}
}
}
| Compose-Notes-App/app/src/main/java/com/example/todocompose/ui/screens/NotesScreen.kt | 2773326154 |
package com.example.todocompose.ui.screens
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.todocompose.data.NotesData
import com.example.todocompose.viewmodel.NotesViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotesAddScreen(
navController: NavController,
viewModel: NotesViewModel,
titleData:String?=null,
descriptionData:String?=null,
idData:Int?=null,
) {
Column(modifier = Modifier.fillMaxSize()) {
var title by remember {
mutableStateOf(titleData?:"")
}
var description by remember {
mutableStateOf(descriptionData?:"")
}
TextField(value = title ,
onValueChange = {title = it},
modifier = Modifier
.fillMaxWidth()
.weight(1f),
label = {
Text(text = "Title", fontSize = 12.sp)
},
colors = TextFieldDefaults.textFieldColors(
containerColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent
)
)
TextField(value = description ,
onValueChange = {description = it},
modifier = Modifier
.fillMaxWidth()
.weight(8f),
label = {
Text(text = "Description", fontSize = 12.sp)
},
colors = TextFieldDefaults.textFieldColors(
containerColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent
)
)
TextButton(
onClick = {
val id = idData ?: 0
viewModel.insertNote(NotesData(id = id,title = title, description = description)) },
modifier = Modifier
.weight(1f)
.fillMaxWidth()
) {
Text(
text = "Save",
fontSize = 24.sp,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth())
}
}
} | Compose-Notes-App/app/src/main/java/com/example/todocompose/ui/screens/AddNotesScreen.kt | 156752206 |
package com.example.todocompose.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | Compose-Notes-App/app/src/main/java/com/example/todocompose/ui/theme/Color.kt | 1297378753 |
package com.example.todocompose.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun TodoComposeTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | Compose-Notes-App/app/src/main/java/com/example/todocompose/ui/theme/Theme.kt | 1996153559 |
package com.example.todocompose.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | Compose-Notes-App/app/src/main/java/com/example/todocompose/ui/theme/Type.kt | 2018432982 |
package com.example.todocompose.repository
import com.example.todocompose.data.NotesData
import com.example.todocompose.db.NotesDatabase
import javax.inject.Inject
class NotesRepository @Inject constructor(
private val db:NotesDatabase
){
fun insertNote(notesData: NotesData) = db.getDao().insertNotes(notesData)
fun getAllNotes() = db.getDao().getAllNotes()
fun delete(notesData: NotesData) = db.getDao().delete(notesData)
} | Compose-Notes-App/app/src/main/java/com/example/todocompose/repository/NotesRepository.kt | 1082506704 |
package com.example.todocompose.di
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class BaseApplication:Application() {
} | Compose-Notes-App/app/src/main/java/com/example/todocompose/di/BaseApplication.kt | 2428989269 |
package com.example.todocompose.di
import android.content.Context
import androidx.room.Room
import com.example.todocompose.db.NotesDatabase
import com.example.todocompose.repository.NotesRepository
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)
object NotesModule {
@Provides
@Singleton
fun providesDB(@ApplicationContext app:Context):NotesDatabase = NotesDatabase(app)
@Provides
@Singleton
fun providesRepository(db:NotesDatabase) = NotesRepository(db)
} | Compose-Notes-App/app/src/main/java/com/example/todocompose/di/NotesModule.kt | 1299509056 |
package com.example.todocompose.navigation
sealed class Screen(val route:String) {
object NotesScreen:Screen(route = "NotesScreen")
object AddNotesScreen:Screen(route = "AddNotesScreen/{title}/{description}/{id}"){
fun passData(title:String?=null,description:String?=null,id:String?=null):String{
return "AddNotesScreen/$title/$description/$id"
}
}
} | Compose-Notes-App/app/src/main/java/com/example/todocompose/navigation/Screen.kt | 1235279967 |
package com.example.todocompose.navigation
import androidx.compose.runtime.Composable
import androidx.lifecycle.LiveData
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import com.example.todocompose.data.NotesData
import com.example.todocompose.ui.screens.NotesAddScreen
import com.example.todocompose.ui.screens.NotesScreen
import com.example.todocompose.viewmodel.NotesViewModel
@Composable
fun SetupNavGraph(
navController: NavHostController,
viewModel: NotesViewModel
){
NavHost(startDestination = Screen.NotesScreen.route, navController = navController){
composable(Screen.NotesScreen.route){
NotesScreen(navController = navController,viewModel)
}
composable(Screen.AddNotesScreen.route,
arguments = listOf(navArgument("title"){
type = NavType.StringType
},navArgument("description"){
type = NavType.StringType
},navArgument("id"){
type = NavType.IntType
},
),
){
NotesAddScreen(navController = navController,viewModel,titleData =it.arguments?.getString("title"), descriptionData = it.arguments?.getString("description"),idData = it.arguments?.getInt("id") )
}
}
} | Compose-Notes-App/app/src/main/java/com/example/todocompose/navigation/SetupNavigationGraph.kt | 2705476531 |
package com.example.todocompose.db
import android.content.Context
import android.provider.ContactsContract.CommonDataKinds.Note
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.example.todocompose.data.NotesData
@Database(entities = [NotesData::class], version = 1)
abstract class NotesDatabase : RoomDatabase() {
abstract fun getDao(): NotesDao
companion object {
@Volatile
private var instance: NotesDatabase? = null
private val LOCK: Any = Any()
operator fun invoke(context: Context) = instance ?: synchronized(LOCK) {
instance ?: createDatabase(context).also {
instance = it
}
}
private fun createDatabase(context: Context): NotesDatabase = Room.databaseBuilder(
context, NotesDatabase::class.java, "notes_databaseTable"
).build()
}
} | Compose-Notes-App/app/src/main/java/com/example/todocompose/db/NotesDatabase.kt | 3592420532 |
package com.example.todocompose.db
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.todocompose.data.NotesData
@Dao
interface NotesDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertNotes(notesData: NotesData)
@Query("select * from notes_tableDb")
fun getAllNotes():LiveData<List<NotesData>>
@Delete
fun delete(notesData: NotesData)
} | Compose-Notes-App/app/src/main/java/com/example/todocompose/db/NotesDao.kt | 1959112331 |
package com.example.todocompose.data
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "notes_tableDb")
data class NotesData(
@PrimaryKey(autoGenerate = true)
val id:Int = 0,
val title:String,
val description:String
)
| Compose-Notes-App/app/src/main/java/com/example/todocompose/data/NotesData.kt | 2052542576 |
package com.example.myapplication
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.myapplication", appContext.packageName)
}
} | TESTKOTLIN/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt | 1188990709 |
package com.example.myapplication
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)
}
} | TESTKOTLIN/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt | 2019423820 |
package com.example.myapplication
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | TESTKOTLIN/app/src/main/java/com/example/myapplication/MainActivity.kt | 665038924 |
package com.example.myapplication.fragments
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.example.myapplication.R
import com.google.firebase.auth.FirebaseAuth
class SplashFragment : Fragment() {
private lateinit var auth: FirebaseAuth
private lateinit var navControl: NavController
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_splash, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
auth = FirebaseAuth.getInstance()
navControl = Navigation.findNavController(view)
Handler(Looper.myLooper()!!).postDelayed({
if(auth.currentUser != null){
navControl.navigate(R.id.action_splashFragment_to_signInFragment)
}else{
navControl.navigate(R.id.action_splashFragment_to_homeFragment)
}
},2000)
}
} | TESTKOTLIN/app/src/main/java/com/example/myapplication/fragments/SplashFragment.kt | 2197476029 |
package com.example.myapplication.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.example.myapplication.R
import com.example.myapplication.databinding.FragmentSignUpBinding
import com.google.firebase.auth.FirebaseAuth
class SignUpFragment : Fragment() {
private lateinit var auth: FirebaseAuth
private lateinit var navControl: NavController
private lateinit var binding: FragmentSignUpBinding
// Inflate the layout for this fragment
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSignUpBinding.inflate(inflater, container, false)
return binding.root
}
// Initialize the fragment components
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init(view)
registerEvents()
}
// Initialize the FirebaseAuth instance and NavController
private fun init(view: View) {
navControl = Navigation.findNavController(view)
auth = FirebaseAuth.getInstance()
}
// Register click events for the buttons
private fun registerEvents() {
// Navigate to the sign-in fragment when the "Already have an account?" text is clicked
binding.authTextView.setOnClickListener {
navControl.navigate(R.id.action_signUpFragment_to_signInFragment)
}
// Register the user when the "Next" button is clicked
binding.nextBtn.setOnClickListener {
val email = binding.emailEt.text.toString().trim()
val pass = binding.passEt.text.toString().trim()
val verifyPass = binding.rePassEt.text.toString().trim()
// Check if email, password, and verify password fields are not empty
if (email.isNotEmpty() && pass.isNotEmpty() && verifyPass.isNotEmpty()) {
// Check if the password matches the verify password
if (pass == verifyPass) {
// Create a new user with email and password
auth.createUserWithEmailAndPassword(email, pass).addOnCompleteListener {
if (it.isSuccessful) {
// User registration successful
Toast.makeText(
context,
"Registered Successfully",
Toast.LENGTH_SHORT
).show()
// Navigate to the home fragment
navControl.navigate(R.id.action_signUpFragment_to_homeFragment)
} else {
// User registration failed
Toast.makeText(context, "Passwords do not match", Toast.LENGTH_SHORT).show()
}
}
}
} else {
// Email and password fields are required
Toast.makeText(context, "Email and Password are required", Toast.LENGTH_SHORT).show()
}
}
}
}
| TESTKOTLIN/app/src/main/java/com/example/myapplication/fragments/SignUpFragment.kt | 3761166471 |
package com.example.myapplication.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import com.example.myapplication.databinding.FragmentAddTodoPopupBinding
import com.example.myapplication.utils.ToDoData
import com.google.android.material.textfield.TextInputEditText
class AddTodoPopupFragment : DialogFragment() {
private lateinit var binding: FragmentAddTodoPopupBinding
private lateinit var listener: DialogNextBtnClickListener
private var toDoData : ToDoData? = null
fun setListener(listener: DialogNextBtnClickListener){
this.listener = listener
}
companion object{
const val TAG = "AddTodoPopupFragment"
@JvmStatic
fun newInstance(taskId: String, task:String) = AddTodoPopupFragment().apply {
arguments = Bundle().apply{
putString("taskId", taskId)
putString("task", task)
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentAddTodoPopupBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if(arguments != null){
toDoData = ToDoData(
arguments?.getString("taskId").toString(),
arguments?.getString("task").toString()
)
binding.todoEt.setText(toDoData?.task)
}
registerEvents()
}
private fun registerEvents(){
binding.todoNextBtn.setOnClickListener{
val todoTask = binding.todoEt.text.toString()
if(todoTask.isNotEmpty()){
if(toDoData == null){
listener.onSaveTask(todoTask, binding.todoEt)
}else{
toDoData?.task = todoTask
listener.onUpdateTask(toDoData!!, binding.todoEt)
}
}else{
Toast.makeText(context, "Enter your task", Toast.LENGTH_SHORT).show()
}
}
binding.todoClose.setOnClickListener(){
dismiss()
}
}
interface DialogNextBtnClickListener{
fun onSaveTask(todo : String, todoEt : TextInputEditText)
fun onUpdateTask(toDoData: ToDoData, todoEt : TextInputEditText)
}
} | TESTKOTLIN/app/src/main/java/com/example/myapplication/fragments/AddTodoPopupFragment.kt | 2480091255 |
package com.example.myapplication.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.example.myapplication.R
import com.example.myapplication.databinding.FragmentSignInBinding
import com.google.firebase.auth.FirebaseAuth
class SignInFragment : Fragment() {
private lateinit var auth: FirebaseAuth
private lateinit var navController: NavController
private lateinit var binding: FragmentSignInBinding
// Inflate the layout for this fragment
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSignInBinding.inflate(inflater, container, false)
return binding.root
}
// Initialize the fragment components
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init(view)
registerEvents()
}
// Initialize the FirebaseAuth instance and NavController
private fun init(view: View) {
navController = Navigation.findNavController(view)
auth = FirebaseAuth.getInstance()
}
// Register click events for the buttons
private fun registerEvents() {
// Navigate to the sign-up fragment when the "Don't have an account?" text is clicked
binding.authTextView.setOnClickListener {
navController.navigate(R.id.action_signInFragment_to_signUpFragment)
}
// Sign in the user when the "Next" button is clicked
binding.nextBtn.setOnClickListener {
val email = binding.emailEt.text.toString().trim()
val pass = binding.passEt.text.toString().trim()
// Check if email and password fields are not empty
if (email.isNotEmpty() && pass.isNotEmpty()) {
// Sign in with email and password
auth.signInWithEmailAndPassword(email, pass).addOnCompleteListener { signInTask ->
if (signInTask.isSuccessful) {
// Login successful, navigate to the home fragment
Toast.makeText(context, "Login Successful", Toast.LENGTH_SHORT).show()
navController.navigate(R.id.action_signInFragment_to_homeFragment)
} else {
// Login failed, display error message
Toast.makeText(context, signInTask.exception?.message, Toast.LENGTH_SHORT).show()
}
}
} else {
// Email and password fields are required
Toast.makeText(context, "Email and Password are required", Toast.LENGTH_SHORT).show()
}
}
}
}
| TESTKOTLIN/app/src/main/java/com/example/myapplication/fragments/SignInFragment.kt | 3402615472 |
package com.example.myapplication.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.myapplication.databinding.FragmentHomeBinding
import com.example.myapplication.utils.ToDoAdapter
import com.example.myapplication.utils.ToDoData
import com.google.android.material.textfield.TextInputEditText
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
class HomeFragment : Fragment(), AddTodoPopupFragment.DialogNextBtnClickListener,
ToDoAdapter.ToDoAdapterClickInterface {
private lateinit var auth : FirebaseAuth
private lateinit var databaseRef : DatabaseReference
private lateinit var navController : NavController
private lateinit var binding: FragmentHomeBinding
private var popUpFragment: AddTodoPopupFragment? = null
private lateinit var adapter: ToDoAdapter
private lateinit var mList : MutableList<ToDoData>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init(view)
getDataFormFirebase()
registerEvents()
}
private fun registerEvents(){
binding.addBtnHome.setOnClickListener{
if(popUpFragment != null) childFragmentManager.beginTransaction().remove(popUpFragment!!).commit()
popUpFragment = AddTodoPopupFragment()
popUpFragment!!.setListener(this)
popUpFragment!!.show(
childFragmentManager,
AddTodoPopupFragment.TAG
)
}
}
private fun init(view : View){
navController = Navigation.findNavController(view)
auth = FirebaseAuth.getInstance()
databaseRef = FirebaseDatabase.getInstance().reference
.child("Tasks").child(auth.currentUser?.uid.toString())
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.layoutManager = LinearLayoutManager(context)
mList = mutableListOf()
adapter = ToDoAdapter(mList)
adapter.setListener(this)
binding.recyclerView.adapter = adapter
}
private fun getDataFormFirebase(){
databaseRef.addValueEventListener(object : ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
mList.clear()
for(taskSnapshot in snapshot.children){
val todoTask = taskSnapshot.key?.let{
ToDoData(it, taskSnapshot.value.toString())
}
if(todoTask != null){
mList.add(todoTask)
}
}
adapter.notifyDataSetChanged()
}
override fun onCancelled(error: DatabaseError) {
Toast.makeText(context, error.message, Toast.LENGTH_SHORT).show()
}
})
}
override fun onSaveTask(todo: String, todoEt: TextInputEditText) {
databaseRef.push().setValue(todo).addOnCompleteListener{
if(it.isSuccessful){
Toast.makeText(context, "Todo task saved successfully!", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(context, it.exception?.message, Toast.LENGTH_SHORT).show()
}
todoEt.text = null
popUpFragment!!.dismiss()
}
}
override fun onUpdateTask(toDoData: ToDoData, todoEt: TextInputEditText) {
val map = HashMap<String, Any>()
map[toDoData.taskId] = toDoData.task
databaseRef.updateChildren(map).addOnCompleteListener{
if(it.isSuccessful) {
Toast.makeText(context, "Updated Successfully", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(context, it.exception?.message, Toast.LENGTH_SHORT).show()
}
todoEt.text = null
popUpFragment!!.dismiss()
}
}
override fun onDeleteTaskBtnClicked(toDoData: ToDoData) {
databaseRef.child(toDoData.taskId).removeValue().addOnCompleteListener{
if(it.isSuccessful){
Toast.makeText(context, "Deleted Successfully", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(context, it.exception?.message, Toast.LENGTH_SHORT).show()
}
}
}
override fun onEditTaskBtnClicked(toDoData: ToDoData) {
if(popUpFragment != null)
childFragmentManager.beginTransaction().remove(popUpFragment!!).commit()
popUpFragment = AddTodoPopupFragment.newInstance(toDoData.taskId, toDoData.task)
popUpFragment!!.setListener(this)
popUpFragment!!.show(childFragmentManager, AddTodoPopupFragment.TAG)
}
}
| TESTKOTLIN/app/src/main/java/com/example/myapplication/fragments/HomeFragment.kt | 2640624206 |
package com.example.myapplication.utils
data class ToDoData(val taskId:String, var task : String)
| TESTKOTLIN/app/src/main/java/com/example/myapplication/utils/ToDoData.kt | 2356786424 |
package com.example.myapplication.utils
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.databinding.EachTodoItemBinding
class ToDoAdapter(private val list:MutableList<ToDoData>) :
RecyclerView.Adapter<ToDoAdapter.ToDoViewHolder>(){
private var listener:ToDoAdapterClickInterface? = null
fun setListener(listener :ToDoAdapterClickInterface){
this.listener = listener
}
inner class ToDoViewHolder(val binding: EachTodoItemBinding):
RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ToDoViewHolder {
val binding = EachTodoItemBinding.inflate(LayoutInflater.from(parent.context),parent, false)
return ToDoViewHolder((binding))
}
override fun onBindViewHolder(holder: ToDoViewHolder, position: Int) {
with(holder){
with(list[position]){
binding.todoTask.text = this.task
binding.deleteTask.setOnClickListener{
listener?.onDeleteTaskBtnClicked(this)
}
binding.editTask.setOnClickListener{
listener?.onEditTaskBtnClicked(this)
}
}
}
}
override fun getItemCount(): Int {
return list.size
}
interface ToDoAdapterClickInterface{
fun onDeleteTaskBtnClicked(toDoData : ToDoData)
fun onEditTaskBtnClicked(toDoData : ToDoData)
}
} | TESTKOTLIN/app/src/main/java/com/example/myapplication/utils/ToDoAdapter.kt | 2829726580 |
package com.mgs.main.utils
import kotlin.math.ceil
inline fun <reified T> Array<out T?>.splitArrayLeftToRight(columns: Int) : Array<Array<T?>> {
val rows = ceil(this.size.toFloat() / columns).toInt()
return Array(rows){row ->
Array(columns)inner@{column ->
if(row*columns + column > this.lastIndex) return@inner null
return@inner this[row*columns + column]
}
}
}
inline fun <reified T> Array<out T?>.splitArrayTopToBottom(rows: Int) : Array<Array<T?>> {
val columns = ceil(this.size.toFloat() / rows).toInt()
return Array(rows){row ->
Array(columns)inner@{column ->
if(column*rows + row > this.lastIndex) return@inner null
return@inner this[column*rows + row]
}
}
}
inline fun <reified T> Array<T>.asNullableArray() : Array<T?> {
return Array(this.size){this[it]}
}
inline fun <reified T> Array<Array<T>>.transpose(): Array<Array<T>> {
val cols = this[0].size
val rows = this.size
return Array(cols) { j ->
Array(rows) { i ->
this[i][j]
}
}
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/utils/Utils.kt | 1051370391 |
package com.mgs.main.utils
import com.mgs.main.Main
import com.mgs.main.gui.*
import net.minecraft.enchantment.Enchantments
import net.minecraft.entity.InventoryOwner
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.inventory.Inventory
import net.minecraft.inventory.SimpleInventory
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import net.minecraft.nbt.*
import net.minecraft.nbt.visitor.NbtTextFormatter
import net.minecraft.registry.Registries
import net.minecraft.text.NbtTextContent
import net.minecraft.text.Text
import net.minecraft.util.Formatting
fun createInventory(owner: InventoryOwner? = null, rows: Int): Inventory {
return SimpleInventory(9 * rows)
}
fun setInventoryContents(inventory: Inventory, items: Iterable<ItemStack>) {
items.forEachIndexed { i, item ->
inventory.setStack(i, item)
}
}
fun populateInventory(inventory: Inventory, items2d: Array<Array<GuiItem>>) {
val items = items2d.flatten()
val itemStacks = Array(items.size){ i -> items[i].item }
itemStacks.forEachIndexed{ i : Int, itemStack : ItemStack ->
val guiItem = items[i]
if (guiItem.name != "") itemStack.setCustomName(Text.of(guiItem.name))
if (guiItem.lore.isNotEmpty()) {
itemStack.setLore(guiItem.lore)
}
if (guiItem.enchanted) {
itemStack.hasGlint()
itemStack.addEnchantment(
Enchantments.INFINITY,
1
)
itemStack.addHideFlag(
ItemStack.TooltipSection.ENCHANTMENTS
)
}
if (!guiItem.canRemove) {
itemStack.setSubNbt(
"${Main.MOD_ID}_cant_remove",
NbtByte.of(0b1)
)
}
}
setInventoryContents(inventory, itemStacks.asIterable())
inventory.markDirty()
}
val Inventory.width : Int
get(){
return 9
}
val Inventory.height : Int
get() {
return this.size() / this.width
}
fun ItemStack.setLore(lore: Array<Text>) {
val nbt = NbtList()
lore.forEach {
nbt.add(NbtString.of(Text.Serializer.toJson(it)))
}
val nbtCompound = getOrCreateSubNbt("display")
nbtCompound.put(ItemStack.LORE_KEY, nbt)
}
fun openGui(
inventory: Inventory = createInventory(null, 6),
viewer: PlayerEntity,
guiSections: Map<String, StaticGuiSection>? = null
) : Gui {
val gui = Gui(inventory = inventory, viewer = viewer)
guiSections?.forEach {
gui.guiSections[it.key] = it.value
}
gui.update()
gui.show()
return gui
}
fun createChildGui(
oldGui: Gui,
inventory: Inventory = createInventory(null, 6),
viewer: PlayerEntity,
guiSections: Map<String, StaticGuiSection>? = null
) : Gui {
val newGui = Gui(inventory = inventory, viewer = viewer, parentGui = oldGui)
newGui.guiSections.putAll(guiSections ?: emptyMap())
return newGui
}
fun getExampleGui(
viewer: PlayerEntity
) : Gui {
val mainGui = Gui(viewer = viewer)
val allItems = mutableListOf<GuiItem>()
val submenu = Gui(viewer = viewer)
var background = submenu.guiSections[Gui.BACKGROUND_NAME]
background?.setItem(0,0, GuiItem.closeItem)
val killClickAction = { _: InventoryClickWrapper, player: PlayerEntity, _: Gui -> player.kill() }
val testItems = mutableListOf(
GuiItem(item = Items.GLASS, name = "${Formatting.AQUA}I'm a test of a coloured name."),
GuiItem(item = Items.ELYTRA, name = "I'm a test of an item you can remove.", canRemove = true),
GuiItem(item = Items.ENDER_PEARL, name = "I'm a test of enchantment glint.", enchanted = true),
GuiItem(item = Items.END_PORTAL_FRAME, lore = arrayOf(
Text.of("I'm a test of item Lore."),
Text.of("I can have multiple lines.")
)),
GuiItem(item = Items.TNT, name = "I'm a test of what can happen when you click me :)", clickAction = killClickAction)
)
val testItemsSplit = testItems.toTypedArray().splitArrayLeftToRight(9)
val testItemsSection = StaticGuiSection(
items = testItemsSplit,
width = 7,
height = 4,
posX = 1,
posY = 1
)
val testItemsSectionName = "test_items_section"
submenu.guiSections[testItemsSectionName] = testItemsSection
Registries.ITEM.forEach {
if (it.asItem() == Items.CAKE) {
allItems.add(GuiItem.getOpenChildItem(it, "Secret :3", submenu))
}
else {
allItems.add(GuiItem(it))
}
}
val allItemsSplit = allItems.toTypedArray().splitArrayLeftToRight(18)
val allItemsSection = ScrollableGuiSection(
items = allItemsSplit,
width = 7,
height = 4,
posX = 1,
posY = 1
)
val allItemSectionName = "all_items_section"
mainGui.guiSections[allItemSectionName] = allItemsSection
background = mainGui.guiSections[Gui.BACKGROUND_NAME]
background?.setItem(0,0, GuiItem.closeItem)
fun scrollItemPosition(direction: ScrollDirection) : Pair<Int, Int> {
return when(direction) {
ScrollDirection.LEFT -> Pair(0, 2)
ScrollDirection.UP -> Pair(4, 0)
ScrollDirection.DOWN -> Pair(4, 5)
ScrollDirection.RIGHT -> Pair(8, 2)
}
}
fun setScrollItems() {
ScrollDirection.entries.forEach {direction ->
val item = if (allItemsSection.canScrollInDirection(direction)) {
GuiItem.getScrollOneOrPageItem(gui = mainGui, section = allItemsSection, direction = direction)
} else {
GuiItem.backgroundItem
}
background?.setItem(
xy = scrollItemPosition(direction),
item = item
)
}
}
mainGui.onUpdate.add{setScrollItems()}
return mainGui
}
| mgs-main-fabric/src/main/kotlin/com/mgs/main/utils/GuiUtils.kt | 38284529 |
package com.mgs.main
import com.mgs.main.events.register
import net.fabricmc.api.ModInitializer
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents
object Main : ModInitializer {
val MOD_ID = "mgs_main"
override fun onInitialize() {
register()
}
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/Main.kt | 3681306398 |
package com.mgs.main.gui
import com.mgs.main.ducks.PlayerEntityDuckInterface
import com.mgs.main.utils.*
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.inventory.Inventory
import net.minecraft.screen.GenericContainerScreenHandler
import net.minecraft.screen.NamedScreenHandlerFactory
import net.minecraft.screen.ScreenHandler
import net.minecraft.screen.ScreenHandlerType
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.text.Text
class Gui(
var name: Text = Text.empty(),
val inventory: Inventory = createInventory(null, 6),
val viewer: PlayerEntity,
val parentGui: Gui? = null,
val onUpdate: MutableList<() -> Unit> = mutableListOf()
) : NamedScreenHandlerFactory {
private val guiItems = Array(inventory.height) { Array(inventory.width) { GuiItem.backgroundItem } }
private val type: ScreenHandlerType<GenericContainerScreenHandler>?
get() {
return when (inventory.height) {
1 -> ScreenHandlerType.GENERIC_9X1
2 -> ScreenHandlerType.GENERIC_9X2
3 -> ScreenHandlerType.GENERIC_9X3
4 -> ScreenHandlerType.GENERIC_9X4
5 -> ScreenHandlerType.GENERIC_9X5
6 -> ScreenHandlerType.GENERIC_9X6
else -> null
}
}
val guiSections = mutableMapOf<String, GuiSection>(
Pair(BACKGROUND_NAME,
StaticGuiSection(
Array(guiItems.size){guiItems[it].asNullableArray()},
inventory.width,
inventory.height
)
)
)
fun update() {
onUpdate.forEach {it()}
guiSections.forEach {(_, section) -> section.addGuiItemsToArray(guiItems)}
populateInventory(inventory, guiItems)
}
fun onClick(click: InventoryClickWrapper) : InventoryClickWrapper {
val position = click.slotIndex
if (position !in 0..< inventory.size()) return click
val guiItem = guiItems.flatten()[position]
click.isCancelled = !guiItem.canRemove
guiItem.clickAction(click, viewer, this)
return click
}
private fun updateViewerGui(gui: Gui?) {
(viewer as PlayerEntityDuckInterface).`mgs$setCurrentGui`(gui)
}
fun show() {
viewer.openHandledScreen(this)
update()
}
fun close() {
if (viewer.isMainPlayer) {
return
}
(viewer as ServerPlayerEntity).closeHandledScreen()
}
fun goBack() {
if (parentGui == null) {
close()
return
} else {
parentGui.update()
parentGui.show()
}
}
companion object {
const val BACKGROUND_NAME = "background"
}
override fun createMenu(syncId: Int, playerInventory: PlayerInventory?, player: PlayerEntity?): ScreenHandler {
return GuiScreenHandler(type, syncId, playerInventory, inventory, inventory.height, this)
}
override fun getDisplayName(): Text {
return name;
}
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/gui/Gui.kt | 3845962154 |
package com.mgs.main.gui
import com.mgs.main.utils.height
import com.mgs.main.utils.width
import net.minecraft.inventory.Inventory
data class StaticGuiSection(
private var items: Array<Array<GuiItem?>>,
val width: Int,
val height: Int,
var posX: Int = 0,
var posY: Int = 0
) : GuiSection {
override fun setItem(x: Int, y: Int, item: GuiItem?) {
items[y][x] = item
}
override fun setItem(xy: Pair<Int, Int>, item: GuiItem?) {
items[xy.second][xy.first] = item
}
override fun getItem(x: Int, y: Int) : GuiItem? {
return items[y][x]
}
override fun getItem(xy: Pair<Int, Int>) : GuiItem? {
return items[xy.second][xy.first]
}
override fun checkValid(inventory: Inventory) : Boolean {
val inventoryWidth = inventory.width
val inventoryHeight = inventory.height
if (width + posX > inventoryWidth) return false
return height + posY <= inventoryHeight
}
override fun addGuiItemsToArray(array: Array<out Array<in GuiItem>>) {
items.forEachIndexed { i, row ->
row.forEachIndexed inner@{ j, item ->
item ?: return@inner
if (i >= height || j >= width) return
array[posY + i][posX + j] = item
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as StaticGuiSection
if (!items.contentDeepEquals(other.items)) return false
if (width != other.width) return false
if (height != other.height) return false
if (posX != other.posX) return false
if (posY != other.posY) return false
return true
}
override fun hashCode(): Int {
var result = items.contentDeepHashCode()
result = 31 * result + width
result = 31 * result + height
result = 31 * result + posX
result = 31 * result + posY
return result
}
}
| mgs-main-fabric/src/main/kotlin/com/mgs/main/gui/StaticGuiSection.kt | 463049400 |
package com.mgs.main.gui
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.inventory.Inventory
import net.minecraft.screen.GenericContainerScreenHandler
import net.minecraft.screen.ScreenHandlerType
import net.minecraft.screen.slot.SlotActionType
class GuiScreenHandler(
type: ScreenHandlerType<*>?,
syncId: Int,
playerInventory: PlayerInventory?,
inventory: Inventory?,
rows: Int,
val gui: Gui
) : GenericContainerScreenHandler(type, syncId, playerInventory, inventory, rows) {
override fun onSlotClick(slotIndex: Int, button: Int, actionType: SlotActionType, player: PlayerEntity) {
val result = gui.onClick(InventoryClickWrapper(slotIndex, button, actionType, player))
if (result.isCancelled) {
return
}
super.onSlotClick(slotIndex, button, actionType, player)
}
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/gui/GuiScreenHandler.kt | 4120179098 |
package com.mgs.main.gui
enum class ScrollDirection(
val fullName: String
) {
LEFT("Scroll Left"),
RIGHT("Scroll Right"),
UP("Scroll Up"),
DOWN("Scroll Down");
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/gui/ScrollDirection.kt | 1363021074 |
package com.mgs.main.gui
import com.mgs.main.utils.height
import com.mgs.main.utils.width
import net.minecraft.inventory.Inventory
class ScrollableGuiSection(
private var items: Array<Array<GuiItem?>>,
val width: Int,
val height: Int,
var posX: Int = 0,
var posY: Int = 0,
private var rowOffset: Int = 0,
private var columnOffset: Int = 0
) : GuiSection {
override fun setItem(x: Int, y: Int, item: GuiItem?) {
items[y][x] = item
}
override fun setItem(xy: Pair<Int, Int>, item: GuiItem?) {
items[xy.second][xy.first] = item
}
override fun getItem(x: Int, y: Int) : GuiItem? {
return items[y][x]
}
override fun getItem(xy: Pair<Int, Int>) : GuiItem? {
return items[xy.second][xy.first]
}
override fun checkValid(inventory: Inventory) : Boolean {
val inventoryWidth = inventory.width
val inventoryHeight = inventory.height
if (width + posX > inventoryWidth) return false
return height + posY <= inventoryHeight
}
override fun addGuiItemsToArray(array: Array<out Array<in GuiItem>>) {
items.forEachIndexed outer@{ i, row ->
if (i < rowOffset || i >= rowOffset + height) return@outer
row.forEachIndexed inner@{ j, item ->
if (j < columnOffset || j >= columnOffset + width) return@inner
item ?: return@inner
array[posY + i - rowOffset][posX + j - columnOffset] = item
}
}
}
private fun scrollLeft() {
columnOffset -= 1
}
private fun scrollRight() {
columnOffset += 1
}
private fun scrollUp() {
rowOffset -= 1
}
private fun scrollDown() {
rowOffset += 1
}
private fun scrollLeftPage() {
columnOffset -= width
}
private fun scrollRightPage() {
columnOffset += width
}
private fun scrollUpPage() {
rowOffset -= height
}
private fun scrollDownPage() {
rowOffset += height
}
fun scrollDirection(direction: ScrollDirection, paginated: Boolean = false) {
if (!canScrollInDirection(direction, paginated)) return
if (!paginated) {
return when (direction) {
ScrollDirection.RIGHT -> scrollRight()
ScrollDirection.LEFT -> scrollLeft()
ScrollDirection.UP -> scrollUp()
ScrollDirection.DOWN -> scrollDown()
}
}
when (direction) {
ScrollDirection.RIGHT -> scrollRightPage()
ScrollDirection.LEFT -> scrollLeftPage()
ScrollDirection.UP -> scrollUpPage()
ScrollDirection.DOWN -> scrollDownPage()
}
}
fun canScrollInDirection(direction: ScrollDirection, paginated: Boolean = false) : Boolean {
if (!paginated) {
return when (direction) {
ScrollDirection.LEFT -> columnOffset - 1 >= 0
ScrollDirection.RIGHT -> columnOffset + width < items[0].size
ScrollDirection.UP -> rowOffset - 1 >= 0
ScrollDirection.DOWN -> rowOffset + height < items.size
}
}
else {
return when (direction) {
ScrollDirection.LEFT -> columnOffset - width >= 0
ScrollDirection.RIGHT -> columnOffset + width*2 < items[0].size
ScrollDirection.UP -> rowOffset - height >= 0
ScrollDirection.DOWN -> rowOffset + height*2 < items.size
}
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ScrollableGuiSection
if (!items.contentDeepEquals(other.items)) return false
if (width != other.width) return false
if (height != other.height) return false
if (posX != other.posX) return false
if (posY != other.posY) return false
return true
}
override fun hashCode(): Int {
var result = items.contentDeepHashCode()
result = 31 * result + width
result = 31 * result + height
result = 31 * result + posX
result = 31 * result + posY
return result
}
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/gui/ScrollableGuiSection.kt | 415448653 |
package com.mgs.main.gui
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import net.minecraft.screen.slot.SlotActionType
import net.minecraft.text.Text
import net.minecraft.util.Formatting
data class GuiItem(
val item: ItemStack,
val name: String = "",
val lore: Array<Text> = arrayOf(),
val canRemove: Boolean = false,
val enchanted: Boolean = false,
val clickAction: (InventoryClickWrapper, PlayerEntity, Gui) -> Unit = {_, _, _ ->}
) {
constructor(
item: Item,
name: String = "",
lore: Array<Text> = arrayOf(),
canRemove: Boolean = false,
enchanted: Boolean = false,
clickAction: (InventoryClickWrapper, PlayerEntity, Gui) -> Unit = {_, _, _ ->}
) : this(
ItemStack(item),
name,
lore,
canRemove,
enchanted,
clickAction
)
companion object {
val goBackGuiAction = { _: InventoryClickWrapper, _: PlayerEntity, gui: Gui ->
gui.goBack()
}
val closeGuiAction = { _: InventoryClickWrapper, _: PlayerEntity, gui: Gui ->
gui.close()
}
fun getScrollGuiAction(
gui: Gui,
section: ScrollableGuiSection,
direction : ScrollDirection,
paginated : Boolean = false
) : (InventoryClickWrapper, PlayerEntity, Gui) -> Unit {
return {_, _, _ ->
section.scrollDirection(direction, paginated)
gui.update()
}
}
fun getScrollOneOrPageGuiAction(
gui: Gui,
section: ScrollableGuiSection,
direction: ScrollDirection
) : (InventoryClickWrapper, PlayerEntity, Gui) -> Unit {
return {event, _, _ ->
section.scrollDirection(direction, event.actionType == SlotActionType.QUICK_MOVE)
gui.update()
}
}
val showChildGuiAction = {
child: Gui ->
{_: InventoryClickWrapper, _: PlayerEntity, _: Gui ->
child.show()
}
}
val closeItem = GuiItem(
item = ItemStack(Items.BARRIER),
name = Formatting.RED.toString() + "Exit",
clickAction = closeGuiAction
)
val goBackItem = GuiItem(
item = ItemStack(Items.RED_WOOL),
name = Formatting.RED.toString() + "Go Back",
clickAction = goBackGuiAction
)
fun getOpenChildItem(item: Item, name: String, child: Gui): GuiItem {
return GuiItem(
item = item,
name = name,
clickAction = showChildGuiAction(child)
)
}
fun getOpenChildItem(item: ItemStack, name: String, child: Gui): GuiItem {
return GuiItem(
item = item,
name = name,
clickAction = showChildGuiAction(child)
)
}
val backgroundItem = GuiItem(
Items.LIGHT_GRAY_STAINED_GLASS_PANE,
Formatting.RESET.toString()
)
fun getScrollItem(
gui: Gui,
section: ScrollableGuiSection,
item: ItemStack = ItemStack(Items.ARROW),
name: String = "",
direction: ScrollDirection,
paginated: Boolean = false
) : GuiItem {
val formattedName : String = name.ifBlank {
Formatting.GREEN.toString() +
direction.fullName +
if (paginated) " Page" else ""
}
return GuiItem(
name = formattedName,
item = item,
clickAction = getScrollGuiAction(gui, section, direction, paginated)
)
}
fun getScrollOneOrPageItem(
gui: Gui,
section: ScrollableGuiSection,
item: ItemStack = ItemStack(Items.ARROW),
name: String = "",
direction: ScrollDirection
) : GuiItem {
val formattedName: String = name.ifBlank {
Formatting.GREEN.toString() +
direction.fullName
}
return GuiItem(
name = formattedName,
item = item,
clickAction = getScrollOneOrPageGuiAction(gui, section, direction)
)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as GuiItem
if (item != other.item) return false
if (name != other.name) return false
if (!lore.contentEquals(other.lore)) return false
if (canRemove != other.canRemove) return false
if (enchanted != other.enchanted) return false
if (clickAction != other.clickAction) return false
return true
}
override fun hashCode(): Int {
var result = item.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + lore.contentHashCode()
result = 31 * result + canRemove.hashCode()
result = 31 * result + enchanted.hashCode()
result = 31 * result + clickAction.hashCode()
return result
}
}
| mgs-main-fabric/src/main/kotlin/com/mgs/main/gui/GuiItem.kt | 3927096406 |
package com.mgs.main.gui
import net.minecraft.inventory.Inventory
interface GuiSection {
fun checkValid(inventory: Inventory) : Boolean
fun addGuiItemsToArray(array: Array<out Array<in GuiItem>>)
fun setItem(x: Int, y: Int, item: GuiItem?)
fun setItem(xy: Pair<Int,Int>, item: GuiItem?)
fun getItem(x: Int, y: Int) : GuiItem?
fun getItem(xy: Pair<Int, Int>) : GuiItem?
companion object {
val emptySection = { height: Int, width: Int ->
StaticGuiSection(
Array(width) { Array(height) { null } },
height,
width
)
}
}
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/gui/GuiSection.kt | 2480807462 |
package com.mgs.main.gui
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.screen.slot.SlotActionType
data class InventoryClickWrapper(
val slotIndex: Int,
val button: Int,
val actionType: SlotActionType,
val player: PlayerEntity,
var isCancelled: Boolean = false
)
| mgs-main-fabric/src/main/kotlin/com/mgs/main/gui/InventoryClickWrapper.kt | 289251756 |
package com.mgs.main.events
import com.mgs.main.ducks.PlayerEntityDuckInterface
import com.mgs.main.utils.getExampleGui
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents
fun register() {
ServerPlayConnectionEvents.JOIN.register { handler, _, _ ->
// this is a test that should be removed later
getExampleGui(handler.player).show()
}
ServerPlayConnectionEvents.DISCONNECT.register { handler, _ ->
(handler.player as PlayerEntityDuckInterface).`mgs$remove`()
}
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/events/EventListener.kt | 2478097450 |
package com.mgs.main.events
import com.mgs.main.games.MiniGame
import net.fabricmc.fabric.api.event.Event
import net.fabricmc.fabric.api.event.EventFactory
import net.minecraft.util.ActionResult
fun interface GameEndCallback {
fun interact(miniGame: MiniGame): ActionResult
companion object {
val EVENT: Event<GameEndCallback> = EventFactory.createArrayBacked(
GameEndCallback::class.java
) { listeners ->
GameEndCallback { miniGame: MiniGame ->
listeners.forEach {
val result = it.interact(miniGame)
if(result != ActionResult.PASS) return@GameEndCallback result
}
return@GameEndCallback ActionResult.PASS
}
}
}
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/events/GameEndCallback.kt | 184728310 |
package com.mgs.main.games.players
import com.mgs.main.games.PlayerLists
import net.minecraft.entity.player.PlayerEntity
data class Party(
private val teamList: MutableList<Team> = mutableListOf(),
var lobby: Lobby? = null,
var leadingTeam: Team? = null
) {
val teams: List<Team>
get() {
return teamList.toList()
}
val partyLeader: PlayerEntity?
get() {
return leadingTeam?.teamLeader
}
fun addTeam(team: Team) {
leadingTeam ?: { leadingTeam = team }
teamList.add(team)
}
fun removeTeam(team: Team) {
teamList.remove(team)
if (teamList.size == 0) {
PlayerLists.partyList.remove(this)
}
}
val playerCount: Int
get() {
var total = 0
teams.forEach { team -> total += team.players.size }
return total
}
init {
PlayerLists.partyList.add(this)
}
override fun toString(): String {
return "teams: [$teamList], leading team: $leadingTeam"
}
}
| mgs-main-fabric/src/main/kotlin/com/mgs/main/games/players/Party.kt | 1148001694 |
package com.mgs.main.games.players
import com.mgs.main.games.PlayerLists
data class Lobby(
private val partyList: MutableList<Party> = mutableListOf()
) {
val parties: List<Party>
get() {
return partyList.toList()
}
fun addParty(party: Party) {
party.lobby = this
partyList.add(party)
}
fun removeParty(party: Party) {
partyList.remove(party)
party.lobby = null
if (partyList.size == 0) {
PlayerLists.lobbyList.remove(this)
}
}
val playerCount : Int
get() {
var total = 0
parties.forEach { party -> total += party.playerCount }
return total
}
init {
PlayerLists.lobbyList.add(this)
}
}
| mgs-main-fabric/src/main/kotlin/com/mgs/main/games/players/Lobby.kt | 564242324 |
package com.mgs.main.games.players
import com.mgs.main.games.PlayerLists
import net.minecraft.entity.player.PlayerEntity
data class Team(
private val playerList: MutableList<PlayerEntity> = mutableListOf(),
var party: Party = Party(),
var teamLeader: PlayerEntity? = null
) {
val players: List<PlayerEntity>
get() {
return playerList.toList()
}
fun addPlayer(p: PlayerEntity) {
teamLeader ?: { teamLeader = p}
playerList.add(p)
}
fun removePlayer(p: PlayerEntity) {
playerList.remove(p)
if (playerList.size == 0) {
party.removeTeam(this)
PlayerLists.teamList.remove(this)
} else if (teamLeader == p) {
teamLeader = playerList[0]
}
}
init {
PlayerLists.teamList.add(this)
party.addTeam(this)
}
@Override
override fun toString(): String {
return "players: $playerList, team leader: $teamLeader"
}
}
| mgs-main-fabric/src/main/kotlin/com/mgs/main/games/players/Team.kt | 2403168960 |
package com.mgs.main.games
object MiniGames {
val minigames = mutableListOf<MiniGame>()
fun startRandomGame() {
minigames.random().startGame()
}
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/games/MiniGames.kt | 3711044179 |
package com.mgs.main.games
import com.mgs.main.games.players.Lobby
import com.mgs.main.games.players.Party
import com.mgs.main.games.players.Team
object PlayerLists {
val teamList = mutableListOf<Team>()
val partyList = mutableListOf<Party>()
val lobbyList = mutableListOf<Lobby>()
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/games/PlayerLists.kt | 1355801574 |
package com.mgs.main.games
abstract class MiniGame {
abstract fun startGame()
fun initGame() {
TODO("GameInitEvent not implemented yet")
}
} | mgs-main-fabric/src/main/kotlin/com/mgs/main/games/MiniGame.kt | 1745397696 |
package com.github.enteraname74
import com.github.enteraname74.model.*
import kotlinx.coroutines.*
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
suspend fun main() {
val ts = TupleSpace()
val capteurH2OJob = buildCapteur_H2O(ts)
val capteurCH4Job = buildCapteur_CH4(ts)
val capteurCOJob = buildCapteur_CO(ts)
val pompeJob = buildPompe(ts)
val ventilateurJob = buildVentilateur(ts)
val h2OHautJob = buildH2O_haut(ts)
val commandePompeVentilateurJob = buildCommande_Pompe_Ventilateur(ts)
val gazBasJob = buildGaz_bas(ts)
val surveillanceGazHautJob = buildSurveillance_Gaz_Haut(ts)
val h2OBasJob = buildH2O_Bas(ts)
val h2oAugmente = buildH2O_Augmente(ts)
val ch4Augmente = buildCH4_Augmente(ts)
val coAugmente = buildCO_Augmente(ts)
val h2oDiminue = buildH2O_Diminue(ts)
val ch4Diminue = buildCH4_Diminue(ts)
val coDiminue = buildCO_Diminue(ts)
joinAll(
capteurH2OJob,
capteurCH4Job,
capteurCOJob,
pompeJob,
h2OHautJob,
commandePompeVentilateurJob,
gazBasJob,
ventilateurJob,
surveillanceGazHautJob,
h2OBasJob,
h2oAugmente,
ch4Augmente,
coAugmente,
h2oDiminue,
ch4Diminue,
coDiminue,
)
}
fun buildCapteur_H2O(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
Capteur_H2O() def {
add(ts, T(s("niveau-H2O", string), v("valeur-H2O", valeur_H2O, integer)))
.Capteur_H2O()
}
}
}
fun buildCapteur_CH4(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
Capteur_CH4() def {
add(ts, T(s("niveau-CH4", string), v("valeur-CH4", valeur_CH4, integer)))
.Capteur_CH4()
}
}
}
fun buildCapteur_CO(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
Capteur_CO() def {
add(ts, T(s("niveau-CO", string), v("valeur-CO", valeur_CO, integer)))
.Capteur_CO()
}
}
}
fun buildPompe(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
Pompe(etat) def {
delay(5000)
b {
read(ts, T(s("activation-pompe", string))).Pompe(activee)
} + b {
read(ts, T(s("desactivation-pompe", string))).Pompe(desactivee)
}
}
}
}
fun buildVentilateur(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
Ventilateur(etat) def {
delay(5000)
b {
read(ts, T(s("activation-ventilateur", string))).Ventilateur(activee)
} + b {
read(ts, T(s("desactivation-ventilateur", string))).Ventilateur(desactivee)
}
}
}
}
fun buildH2O_haut(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
H2O_Haut(seuil_H2O_haut) def {
read(ts, T(s("detection-H2O-haut", string)))
.read(ts, T(s("niveau-H2O", string), r("x", integer)))[v("x") >= seuil_H2O_haut] {
out(ts, T(s("H2O-haut-detecte", string)))
.pop(ts, T(s("detection-H2O-haut", string)))
.H2O_Haut(seuil_H2O_haut)
}[v("x") < seuil_H2O_haut] {
H2O_Haut(seuil_H2O_haut)
}
}
}
}
fun buildCommande_Pompe_Ventilateur(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
Commande_Pompe_Ventilateur(seuil_CH4, seuil_CO) def {
read(ts, T(s("H2O-haut-detecte", string)))
.read(ts, T(s("niveau-CH4", string), r("y", integer)))
.read(ts, T(s("niveau-CO", string), r("z", integer)))[(v("y") < seuil_CH4) `^` (v("z") < seuil_CO)] {
pop(ts, T(s("desactivation-pompe", string)))
out(ts, T(s("activation-pompe", string)))
.out(ts, T(s("detection-H2O-bas", string)))
.out(ts, T(s("detection-gaz-haut", string)))
.Commande_Pompe_Ventilateur(seuil_CH4, seuil_CO)
}[(v("y") >= seuil_CH4) v (v("z") >= seuil_CO)] {
pop(ts, T(s("desactivation-ventilateur", string)))
.out(ts, T(s("activation-ventilateur", string)))
.out(ts, T(s("detection-gaz-bas", string)))
.pop(ts, T(s("detection-gaz-haut", string)))
.Commande_Pompe_Ventilateur(seuil_CH4, seuil_CO)
}
}
}
}
fun buildGaz_bas(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
Gaz_Bas(seuil_CH4, seuil_CO) def {
read(ts, T(s("detection-gaz-bas", string)))
.read(ts, T(s("niveau-CH4", string), r("x", integer)))
.read(ts, T(s("niveau-CO", string), r("y", integer)))[(v("x") < seuil_CH4) `^` (v("y") < seuil_CO)] {
out(ts, T(s("activation-pompe", string)))
.out(ts, T(s("detection-H2O-bas", string)))
.pop(ts, T(s("detection-gaz-bas", string)))
.out(ts, T(s("desactivation-ventilateur", string)))
.out(ts, T(s("detection-gaz-haut", string)))
.Gaz_Bas(seuil_CH4, seuil_CO)
}[(v("x") >= seuil_CH4) v (v("y") >= seuil_CO)] {
Gaz_Bas(seuil_CH4, seuil_CO)
}
}
}
}
fun buildSurveillance_Gaz_Haut(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
Surveillance_Gaz_Haut(seuil_CH4, seuil_CO) def {
read(ts, T(s("detection-gaz-haut", string)))
.read(ts, T(r("niveau-CH4", "x", string)))
.read(ts, T(r("niveau-CO", "y", string)))[(v("x") >= seuil_CH4) v (v("y") >= seuil_CO)] {
out(ts, T(s("desactivation-ventilateur", string)))
.out(ts, T(s("activation-ventilateur", string)))
.Surveillance_Gaz_Haut(seuil_CH4, seuil_CO)
}[(v("x") < seuil_CH4) `^` (v("y") < seuil_CO)] {
Surveillance_Gaz_Haut(seuil_CH4, seuil_CO)
}
}
}
}
fun buildH2O_Bas(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
H2O_Bas(seuil_H2O_bas) def {
read(ts, T(s("detection-H2O-bas", string)))
.read(ts, T(s("niveau-H2O", string), r("x", integer)))[v("x") < seuil_H2O_bas] {
out(ts, T(s("desactivation-pompe", string)))
.out(ts, T(s("desactivation-ventilateur", string)))
.pop(ts, T(s("detection-H2O-bas", string)))
.pop(ts, T(s("detection-gaz-haut", string)))
.out(ts, T(s("detection-H2O-haut", string)))
.H2O_Bas(seuil_H2O_bas)
}[v("x") >= seuil_H2O_bas] {
H2O_Bas(seuil_H2O_bas)
}
}
}
}
fun buildH2O_Augmente(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
H2O_Augmente() def {
read(ts, T(s("desactivation-pompe", string)))
.read(ts, T(s("niveau-H2O", string), r("x", integer)))
valeur_H2O = ((v("x")?.value) as Int) + 1
add(ts, T(s("niveau-H2O", string), v("valeur-H2O", valeur_H2O, integer)))
H2O_Augmente()
}
}
}
fun buildCH4_Augmente(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
CH4_Augmente() def {
read(ts, T(s("desactivation-ventilateur", string)))
.read(ts, T(s("niveau-CH4", string), r("x", integer)))
valeur_CH4 = ((v("x")?.value) as Int) + 1
add(ts, T(s("niveau-CH4", string), v("valeur-CH4", valeur_CH4, integer)))
.CH4_Augmente()
}
}
}
fun buildCO_Augmente(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
CO_Augmente() def {
read(ts, T(s("desactivation-ventilateur", string)))
.read(ts, T(s("niveau-CO", string), r("x", integer)))
valeur_CO = ((v("x")?.value) as Int) + 1
add(ts, T(s("niveau-CO", string), v("valeur-CO", valeur_CO, integer)))
.CO_Augmente()
}
}
}
fun buildH2O_Diminue(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
H2O_Diminue() def {
read(ts, T(s("activation-pompe", string)))
.read(ts, T(s("niveau-H2O", string), r("x", integer)))
valeur_H2O = ((v("x")?.value) as Int) - 1
add(ts, T(s("niveau-H2O", string), v("valeur-H2O", valeur_H2O, integer)))
H2O_Diminue()
}
}
}
fun buildCH4_Diminue(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
CH4_Diminue() def {
read(ts, T(s("activation-ventilateur", string)))
.read(ts, T(s("niveau-CH4", string), r("x", integer)))
valeur_CH4 = ((v("x")?.value) as Int) - 1
add(ts, T(s("niveau-CH4", string), v("valeur-CH4", valeur_CH4, integer)))
.CH4_Diminue()
}
}
}
fun buildCO_Diminue(ts: TupleSpace): Job {
return CoroutineScope(Dispatchers.IO).launch {
CO_Diminue() def {
read(ts, T(s("activation-ventilateur", string)))
.read(ts, T(s("niveau-CO", string), r("x", integer)))
valeur_CO = ((v("x")?.value) as Int) - 1
add(ts, T(s("niveau-CO", string), v("valeur-CO", valeur_CO, integer)))
.CO_Diminue()
}
}
}
| Kotlinda/src/main/kotlin/Main.kt | 3503127817 |
package com.github.enteraname74.model
import kotlinx.coroutines.*
open class Agent(vararg variable: Variable) {
val state: AgentState = AgentState()
private var shouldRestartItself = false
private var body: (suspend Agent.() -> Unit) = { }
constructor(
legacyAgent: Agent,
variables: List<Variable>
) : this() {
this.shouldRestartItself = true
this.state.addAll(variables)
this.body = legacyAgent.body
this.forceLaunchAgent()
}
/**
* Force the launch of the agent.
*/
private fun forceLaunchAgent() {
runBlocking(context = Dispatchers.IO) {
delay(1000)
def(body)
buildNewAgentForRec(legacyAgent = this@Agent, variables = [email protected]())
}
}
fun buildNewAgentForRec(legacyAgent: Agent, variables: List<Variable>): Agent {
return Agent(
legacyAgent = legacyAgent,
variables = variables
)
}
@JvmName("AgentRec")
fun Agent.Agent(vararg variable: Variable): Agent {
return buildNewAgentForRec(this, variable.asList())
}
suspend infix fun def(body: suspend Agent.() -> Unit) {
runBlocking {
[email protected] = {body(this)}
}
body(this)
}
infix fun Boolean.`^`(predicate: Boolean): Boolean = this && predicate
infix fun Boolean.v(predicate: Boolean): Boolean = this && predicate
operator fun get(predicate: Boolean): Action {
return Action(predicate, this)
}
suspend fun b(block: suspend Agent.() -> Agent) = suspend {
block()
}
operator fun (suspend () -> Agent).plus(other: suspend () -> Agent): Agent {
val b1Job = CoroutineScope(Dispatchers.IO).launch {
this@plus()
}
val b2Job = CoroutineScope(Dispatchers.IO).launch {
other()
}
while (b1Job.isActive && b2Job.isActive){}
if (b1Job.isCompleted) {
b2Job.cancel()
}
else if (b2Job.isCompleted) {
b1Job.cancel()
}
return this@Agent
}
/**
* Retrieve a variable from the agent's state.
*/
fun v(varName: String): Variable? {
return state.get(varName)
}
/**
* Read a tuple from the TupleSpace and retrieve the values from the template.
*
* @param ts the TupleSpace used for operations.
* @param tuple the ReadTuple with variables to save.
*
* @return the instance of the current Agent
*/
@JvmName("readVariable")
suspend fun read(ts: TupleSpace, tuple: Tuple): Agent {
val variables = ts.read(tuple)
state.addAll(variables)
delay(1000)
return this
}
/**
* Write a tuple in the given TupleSpace.
*
* @param ts the TupleSpace used for operations.
* @param tuple the Tuple to write to the TupleSpace.
*
* @return the instance of the current Agent
*/
suspend fun out(ts: TupleSpace, tuple: Tuple): Agent {
delay(1000)
ts.out(tuple)
return this
}
/**
* Write a tuple in the given TupleSpace.
*
* @param ts the TupleSpace used for operations.
* @param tuple the Tuple to write to the TupleSpace.
*
* @return the instance of the current Agent
*/
suspend fun add(ts: TupleSpace, tuple: SimpleTuple): Agent {
delay(1000)
ts.out(tuple)
return this
}
/**
* Write a tuple in the given TupleSpace.
*
* @param ts the TupleSpace used for operations.
* @param tuple the Tuple to write to the TupleSpace.
*
* @return the instance of the current Agent
*/
suspend fun add(ts: TupleSpace, tuple: Tuple): Agent {
delay(1000)
ts.add(tuple)
return this
}
/**
* Read and pop the tuple if found in the tuple space.
* Represent the in function but is called pop as the in keyword is already taken
*
* @param ts the TupleSpace used for operations.
* @param tuple the Tuple to write to the TupleSpace.
*
* @return the instance of the current Agent
*/
suspend fun pop(ts: TupleSpace, tuple: Tuple): Agent {
delay(1000)
ts.pop(tuple)
return this
}
} | Kotlinda/src/main/kotlin/model/Agent.kt | 740830959 |
package com.github.enteraname74.model
/**
* Represent a variable to use in read operations.
*/
data class Variable(
val name: String,
val value: Any,
) {
val type = value::class
override fun toString(): String {
return "Variable(name = $name, value = $value)"
}
}
/**
*
*/
operator fun Variable?.compareTo(other: Variable): Int {
if (this == null) return -1
if (this.type != other.type) return -1
return when(this.type) {
integer -> (this.value as Int).compareTo((other.value as Int))
string -> (this.value as String).compareTo((other.value as String))
float -> (this.value as Float).compareTo((other.value as Float))
else -> -1
}
}
| Kotlinda/src/main/kotlin/model/Variable.kt | 4079513187 |
package com.github.enteraname74.model
/**
* Holds all variables used by the agent.
*/
class AgentState {
private val variables: ArrayList<Variable> = ArrayList()
/**
* Tries to retrieve a ReadTuple from the variables of the agent.
*
* @param variableName the name of the variable in the ReadTuple to retrieve
*
* @return the found ReadTuple or null.
*/
fun get(variableName: String) = variables.find { it.name == variableName }
private fun add(variable: Variable) {
val index = variables.indexOfFirst { it.name == variable.name }
if (index == -1) variables.add(variable)
else variables[0] = variable
}
fun addAll(vars: List<Variable>) {
vars.forEach {
add(it)
}
}
fun getAllVariables() = variables
override fun toString(): String {
return "AgentState(variables = $variables)"
}
} | Kotlinda/src/main/kotlin/model/AgentState.kt | 2410836340 |
package com.github.enteraname74.model
import kotlin.reflect.KClass
/**
* Base of a tuple.
* It is primarily represented by a name and the type linked to it
*/
sealed class TupleTemplate(
val name: String,
val type: KClass<out Any>
) {
/**
* Check if the name and the type is the same as the compared object.
*/
fun isSame(other: Any?): Boolean {
if (other == this) return true
if (other !is TupleTemplate) return false
val sameName = (name == other.name) || (name.isEmpty() || other.name.isEmpty())
val sameType = type == other.type
val sameElement = sameType && sameName
return sameElement
}
override fun toString(): String {
return "TupleTemplate(name = $name, type = $type)"
}
}
/**
* Tuple used for read operation that return a variable.
*/
class ReadVariableTupleTemplate(
name: String,
val variableName: String,
type: KClass<out Any>
): TupleTemplate(
name = name,
type = type
) {
override fun toString(): String {
return "ReadVariableTupleTemplate(name = $name, variableName = $variableName, type = $type)"
}
}
/**
* Tuple used for simple read operation.
*/
class ReadSimpleTupleTemplate(
name: String,
type: KClass<out Any>
): TupleTemplate(
name = name,
type = type
) {
override fun toString(): String {
return "ReadSimpleTupleTemplate(name = $name, type = $type)"
}
}
/**
* Tuple used to store a value.
*/
class ValueTupleTemplate(
name: String,
val value: Any,
type: KClass<out Any>
): TupleTemplate(
name = name,
type = type
) {
override fun toString(): String {
return "ValueTupleTemplate(name = $name, value = $value, type = $type)"
}
}
/**
* Utility method for creating a ReadVariableTupleTemplate.
*/
fun r(name: String, variableName: String, type: KClass<out Any>) = ReadVariableTupleTemplate(
name = name,
variableName = variableName,
type = type
)
/**
* Utility method for creating a ReadVariableTupleTemplate.
*/
fun r(variableName: String, type: KClass<out Any>) = ReadVariableTupleTemplate(
name = "",
variableName = variableName,
type = type
)
/**
* Utility method for creating a ReadSimpleTupleTemplate.
*/
fun s(name: String, type: KClass<out Any>) = ReadSimpleTupleTemplate(
name = name,
type = type
)
/**
* Utility method for creating a ValueTupleTemplate.
*/
fun v(name: String, value: Any, type: KClass<out Any>) = ValueTupleTemplate(
name = name,
value = value,
type = type
)
/**
* Utility method for creating a ValueTupleTemplate.
*/
fun v(value: Any, type: KClass<out Any>) = ValueTupleTemplate(
name = "",
value = value,
type = type
) | Kotlinda/src/main/kotlin/model/TupleTemplate.kt | 483470260 |
package com.github.enteraname74.model
/**
*
*
* AGENTS
*
*
*/
class Capteur_H2O(vararg variable: Variable) : Agent(*variable)
class Capteur_CH4(vararg variable: Variable) : Agent(*variable)
class Capteur_CO(vararg variable: Variable) : Agent(*variable)
class Pompe(vararg variable: Variable) : Agent(*variable)
class Ventilateur(vararg variable: Variable) : Agent(*variable)
class H2O_Haut(vararg variable: Variable) : Agent(*variable)
class Commande_Pompe_Ventilateur(vararg variable: Variable) : Agent(*variable)
class Gaz_Bas(vararg variable: Variable) : Agent(*variable)
class Surveillance_Gaz_Haut(vararg variable: Variable) : Agent(*variable)
class H2O_Bas(vararg variable: Variable) : Agent(*variable)
class H2O_Augmente(vararg variable: Variable) : Agent(*variable)
class CH4_Augmente(vararg variable: Variable) : Agent(*variable)
class CO_Augmente(vararg variable: Variable) : Agent(*variable)
class H2O_Diminue(vararg variable: Variable) : Agent(*variable)
class CH4_Diminue(vararg variable: Variable) : Agent(*variable)
class CO_Diminue(vararg variable: Variable) : Agent(*variable)
/**
*
*
*
* Styled methods for relaunching
*
*
*/
@JvmName("Capteur_H2ORec")
fun Agent.Capteur_H2O(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("Capteur_CH4Rec")
fun Agent.Capteur_CH4(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("Capteur_CORec")
fun Agent.Capteur_CO(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("PompeRec")
fun Agent.Pompe(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("VentilateurRec")
fun Agent.Ventilateur(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("H2O_HautRec")
fun Agent.H2O_Haut(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("Commande_Pompe_VentilateurRec")
fun Agent.Commande_Pompe_Ventilateur(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("Gaz_BasRec")
fun Agent.Gaz_Bas(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("Surveillance_Gaz_HautRec")
fun Agent.Surveillance_Gaz_Haut(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("H2O_BasRec")
fun Agent.H2O_Bas(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("H2O_AugmenteRec")
fun Agent.H2O_Augmente(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("CH4_AugmenteRec")
fun Agent.CH4_Augmente(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("CO_AugmenteRec")
fun Agent.CO_Augmente(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("H2O_DiminueRec")
fun Agent.H2O_Diminue(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("CH4_DiminueRec")
fun Agent.CH4_Diminue(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
@JvmName("CO_DiminueRec")
fun Agent.CO_Diminue(vararg variable: Variable) = buildNewAgentForRec(this, variable.asList())
/**
*
*
* VARIABLES
*
*
*/
val etat = Variable("etat-pompe", "désactivée")
val activee = Variable("etat-pompe", "activée")
val desactivee = Variable("etat-pompe", "activée")
val seuil_H2O_haut = Variable("seuil-H2O-haut", 20)
val seuil_H2O_bas = Variable("seuil-H2O-bas", 10)
val seuil_CH4 = Variable("seuil_CH4", 10)
val seuil_CO = Variable("seuil_CO", 10)
/**
*
*
* GLOBAL SYSTEM VARIABLES
*
*
*/
var valeur_CO = 6
var valeur_CH4 = 6
var valeur_H2O = 19
| Kotlinda/src/main/kotlin/model/AgentsAndVariables.kt | 3731410657 |
package com.github.enteraname74.model
/**
* Represent a tuple, used to be stored in a TupleSpace.
*/
open class Tuple(val elements: List<TupleTemplate>) {
private val size = elements.size
operator fun get(pos: Int) = elements.getOrNull(pos)
/**
* Check if the tuple is the same as another one.
*/
fun isSameTuple(other: Tuple): Boolean {
if (size != other.size) return false
for (i in 0 until size) {
if (this[i]?.isSame(other[i]) == false) return false
}
return true
}
override fun toString(): String {
return elements.toString()
}
}
/**
* Tuple that only holds ReadSimpleTupleTemplates.
*/
class SimpleTuple(elements: List<ReadSimpleTupleTemplate>): Tuple(elements = elements)
/**
* Utility method for creating a Tuple.
*/
fun T(vararg element : TupleTemplate) = Tuple(element.asList())
/**
* Utility method for creating a SimpleTuple
*/
fun T(vararg element : ReadSimpleTupleTemplate) = SimpleTuple(element.asList())
| Kotlinda/src/main/kotlin/model/Tuple.kt | 2091392629 |
package com.github.enteraname74.model
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.Mutex
/**
* Represent a space that store tuples.
*/
class TupleSpace {
private val storage: ArrayList<Tuple> = arrayListOf(
T(s("niveau-H2O", string), v("valeur-H2O", valeur_H2O, integer)),
T(s("niveau-CH4", string), v("valeur-CH4", valeur_CH4, integer)),
T(s("niveau-CO", string), v("valeur-CO", valeur_CO, integer)),
T(s("detection-H2O-haut", string)),
T(s("detection-gaz-haut", string)),
T(s("desactivation-ventilateur", string)),
T(s("desactivation-pompe", string))
)
private val mutex = Mutex(locked = false)
/**
* Read a tuple from the TupleSpace.
* It blocks until the value has been read.
* Once read, it returns the found variables in the tuple.
*
* @param varTuple the tuple to read from the storage.
*/
suspend fun read(varTuple: Tuple): List<Variable> {
while (true) {
mutex.lock()
storage.forEach { tuple ->
if (varTuple.isSameTuple(tuple)) {
val varTuples = varTuple.elements.filterIsInstance<ReadVariableTupleTemplate>()
val foundVariables = buildVarListFromInformation(tuple, varTuples)
printStorage(action = "READ: $varTuple")
mutex.unlock()
return foundVariables
}
}
mutex.unlock()
delay(10)
}
}
/**
* Build a list of Variables from information.
*
* @param tuple the tuple of values to use to build a variable.
* @param varTuples the list of the variables tuple to use to build a variable.
*
* @return a list of Variables.
*/
private fun buildVarListFromInformation(tuple: Tuple, varTuples: List<ReadVariableTupleTemplate>): List<Variable> {
val list = ArrayList<Variable>()
val variableTuples = tuple.elements.filterIsInstance<ValueTupleTemplate>()
for (i in varTuples.indices) {
val currentVar = varTuples[i]
list.add(
Variable(
name = currentVar.variableName,
value = variableTuples[i].value
)
)
}
return list
}
suspend fun pop(tuple: Tuple): Tuple {
while (true) {
mutex.lock()
val foundTuple = storage.find { it.isSameTuple(tuple) }
if (foundTuple != null) {
storage.removeIf { it.isSameTuple(tuple) }
printStorage(action = "POP: $tuple")
mutex.unlock()
return foundTuple
}
mutex.unlock()
delay(10)
}
}
/**
* Save a tuple to the storage.
*
* @param tuple the tuple to save.
*/
suspend fun out(tuple: Tuple) {
mutex.lock()
val index = storage.indexOfFirst { it.isSameTuple(tuple) }
if (index != -1) storage[index] = tuple
else storage.add(tuple)
printStorage(action = "OUT: $tuple")
mutex.unlock()
}
/**
* Update a tuple to the storage.
*
* @param tuple the tuple to save.
*/
suspend fun add(tuple: Tuple) {
mutex.lock()
val index = storage.indexOfFirst { it.isSameTuple(tuple) }
if (index != -1) storage[index] = tuple
printStorage(action = "ADD: $tuple")
mutex.unlock()
}
fun printStorage(action: String) {
println(action)
println("-- STORAGE STATE --")
storage.forEach {
println(it)
}
println("---------------")
}
} | Kotlinda/src/main/kotlin/model/TupleSpace.kt | 3519061073 |
package com.github.enteraname74.model
class Action(private val condition: Boolean, private val agent: Agent) {
// This function takes a lambda and executes it if the condition is true
suspend operator fun invoke(block: suspend () -> Unit): Agent {
if (condition) {
block()
}
return agent
}
} | Kotlinda/src/main/kotlin/model/Action.kt | 4067559469 |
package com.github.enteraname74.model
val integer = Int::class
val string = String::class
val float = Float::class
| Kotlinda/src/main/kotlin/model/Type.kt | 1082543512 |
package com.github.enteraname74.model
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
data class LindaJob(
val block: suspend () -> Agent
) {
var job: Job? = null
val isActive: Boolean
get() = job?.isActive == true
val isCompleted: Boolean
get() = job?.isCompleted == true
fun cancel() {
job?.cancel()
}
fun run() {
job = CoroutineScope(Dispatchers.IO).launch { block() }
}
}
| Kotlinda/src/main/kotlin/model/LindaJob.kt | 2595081592 |
package com.example.diceroller
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.diceroller", appContext.packageName)
}
} | DiceRollerfix/app/src/androidTest/java/com/example/diceroller/ExampleInstrumentedTest.kt | 2731144987 |
package com.example.diceroller
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)
}
} | DiceRollerfix/app/src/test/java/com/example/diceroller/ExampleUnitTest.kt | 1412805653 |
package com.example.diceroller.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | DiceRollerfix/app/src/main/java/com/example/diceroller/ui/theme/Color.kt | 2898381871 |
package com.example.diceroller.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun DiceRollerTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | DiceRollerfix/app/src/main/java/com/example/diceroller/ui/theme/Theme.kt | 751687589 |
package com.example.diceroller.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | DiceRollerfix/app/src/main/java/com/example/diceroller/ui/theme/Type.kt | 2881408862 |
package com.example.diceroller
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.example.diceroller.ui.theme.DiceRollerTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DiceRollerTheme {
// A surface container using the 'background' color from the theme
DiceRollerApp()
}
}
}
}
@Composable
fun DiceWithButtonAndImage(modifier: Modifier = Modifier) {
var result by remember { mutableStateOf(1)
}
val imageResource = when (result) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else-> R.drawable.dice_6
}
Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally
) {
Image( painter = painterResource(imageResource), contentDescription = result.toString()
)
Button(onClick = { result = (1..6).random()}
) {
Text(text = stringResource(R.string.roll), fontSize = 24.sp)
}
}
}
@Preview(showBackground = true)
@Composable
fun DiceRollerApp() {
DiceWithButtonAndImage(modifier = Modifier
.fillMaxSize()
.wrapContentSize(Alignment.Center))
} | DiceRollerfix/app/src/main/java/com/example/diceroller/MainActivity.kt | 1009072449 |
package song.aaron.composeconstraintlayout
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("song.aaron.composeconstraintlayout", appContext.packageName)
}
} | ComposeConstraintLayout/app/src/androidTest/java/song/aaron/composeconstraintlayout/ExampleInstrumentedTest.kt | 1066019369 |
package song.aaron.composeconstraintlayout
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)
}
} | ComposeConstraintLayout/app/src/test/java/song/aaron/composeconstraintlayout/ExampleUnitTest.kt | 3778901015 |
package song.aaron.composeconstraintlayout.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | ComposeConstraintLayout/app/src/main/java/song/aaron/composeconstraintlayout/ui/theme/Color.kt | 320372373 |
package song.aaron.composeconstraintlayout.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun ComposeConstraintLayoutTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | ComposeConstraintLayout/app/src/main/java/song/aaron/composeconstraintlayout/ui/theme/Theme.kt | 1359513416 |
package song.aaron.composeconstraintlayout.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | ComposeConstraintLayout/app/src/main/java/song/aaron/composeconstraintlayout/ui/theme/Type.kt | 3125508987 |
package song.aaron.composeconstraintlayout
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ChainStyle
import androidx.constraintlayout.compose.ConstraintLayout
import song.aaron.composeconstraintlayout.ui.theme.ComposeConstraintLayoutTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeConstraintLayoutTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
}
}
}
}
}
@Composable
fun MyButton(text: String, modifier: Modifier = Modifier) {
Button(
onClick = { /*TODO*/ },
modifier = modifier
) {
Text(text = text)
}
}
@Composable
fun MainScreen() {
// ConstraintLayout(Modifier.size(width = 200.dp, height = 200.dp)) {
// val (button1, button2, button3) = createRefs()
//
// // Basic constraint
//// MyButton(text = "Button1", Modifier.constrainAs(button1) {
//// top.linkTo(parent.top, margin = 60.dp)
////// start.linkTo(parent.start, margin = 30.dp)
////// start.linkTo(parent.start)
////// end.linkTo(parent.end)
//// linkTo(parent.start, parent.end)
//// })
//
// // Opposing constraint
//// MyButton(text = "Button1", Modifier.constrainAs(button1) {
//// centerHorizontallyTo(parent)
//// top.linkTo(parent.top)
//// bottom.linkTo(button2.top)
//// })
////
//// MyButton(text = "Button2", Modifier.constrainAs(button2) {
//// centerHorizontallyTo(parent)
//// top.linkTo(button1.bottom)
//// bottom.linkTo(parent.bottom)
//// })
//
// // Constraint bias
//// MyButton(text = "Button1", Modifier.constrainAs(button1) {
//// top.linkTo(parent.top, margin = 60.dp)
//// linkTo(parent.start, parent.end, bias = 0.75f)
//// })
//
// // Constraint chain
//// createHorizontalChain(button1, button2, button3, chainStyle = ChainStyle.SpreadInside)
////
//// MyButton(text = "Button1", Modifier.constrainAs(button1) {
//// centerVerticallyTo(parent)
//// })
//// MyButton(text = "Button2", Modifier.constrainAs(button2) {
//// centerVerticallyTo(parent)
//// })
//// MyButton(text = "Button3", Modifier.constrainAs(button3) {
//// centerVerticallyTo(parent)
//// })
// }
// Guideline
ConstraintLayout(Modifier.size(width = 400.dp, height=220.dp)) {
val (button1, button2, button3) = createRefs()
val guide = createGuidelineFromStart(fraction = .60f)
MyButton(text = "Button1", Modifier.constrainAs(button1) {
top.linkTo(parent.top, margin=30.dp)
end.linkTo(guide, margin = 30.dp)
})
MyButton(text = "Button2", Modifier.constrainAs(button2) {
top.linkTo(button1.bottom, margin=20.dp)
start.linkTo(guide, margin = 40.dp)
})
MyButton(text = "Button3", Modifier.constrainAs(button3) {
top.linkTo(button2.bottom, margin=40.dp)
end.linkTo(guide, margin = 20.dp)
})
}
}
@Composable
@Preview(showBackground = true)
fun DefaultPreview() {
MainScreen()
} | ComposeConstraintLayout/app/src/main/java/song/aaron/composeconstraintlayout/MainActivity.kt | 3037085623 |
package jp.co.yumemi.android.code_check
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* 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("jp.co.yumemi.android.codecheck", appContext.packageName)
}
}
| Android-full-coding/app/src/androidTest/kotlin/jp/co/yumemi/android/code_check/ExampleInstrumentedTest.kt | 1626772810 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.