content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package io.github.yuazer.zaxworld.commands
import io.github.yuazer.zaxworld.ZaxWorld
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import taboolib.common.platform.command.*
import taboolib.platform.util.asLangText
import taboolib.platform.util.sendLang
@CommandHeader("zaxworld", ["zw"], permission = "zaxworld.reload")
object MainCommand {
@CommandBody
val reload = subCommand {
execute<CommandSender> { sender, context, argument ->
ZaxWorld.config.reload()
sender.sendLang("reload-message")
}
}
@CommandBody
val add = subCommand {
dynamic("user") {
dynamic ("world"){
dynamic ("time"){
execute<CommandSender> { sender, context, argument ->
// 获取参数的值
val user = context["user"]
val worldName:String = context["world"]
val time:Int = context.int("time")
ZaxWorld.getPlayerCacheMap().add(user,worldName, time)
sender.sendMessage(sender.asLangText("manage-command-message-add")
.replace("{user}",user)
.replace("{world}",worldName)
.replace("{time}",time.toString()))
}
}
}
}
dynamic ("time"){
execute<CommandSender> { sender, context, argument ->
// 获取参数的值
if (sender is Player){
val user:Player = sender
val worldName:String = user.world.name
val time:Int = context.int("time")
ZaxWorld.getPlayerCacheMap().add(sender.name,worldName, time)
sender.sendMessage(sender.asLangText("manage-command-message-add")
.replace("{user}",user.name)
.replace("{world}",worldName)
.replace("{time}",time.toString()))
}
}
}
}
@CommandBody
val reduce = subCommand {
dynamic("user") {
dynamic ("world"){
dynamic ("time"){
execute<CommandSender> { sender, context, argument ->
val user = context["user"]
val worldName:String = context["world"]
val time:Int = context.int("time")
ZaxWorld.getPlayerCacheMap().reduce(user,worldName, time)
sender.sendMessage(sender.asLangText("manage-command-message-reduce")
.replace("{user}",user)
.replace("{world}",worldName)
.replace("{time}",time.toString()))
}
}
}
}
dynamic ("time"){
execute<CommandSender> { sender, context, argument ->
// 获取参数的值
if (sender is Player){
val user:Player = sender
val worldName:String = user.world.name
val time:Int = context.int("time")
ZaxWorld.getPlayerCacheMap().reduce(sender.name,worldName, time)
sender.sendMessage(sender.asLangText("manage-command-message-reduce")
.replace("{user}",user.name)
.replace("{world}",worldName)
.replace("{time}",time.toString()))
}
}
}
}
@CommandBody
val set = subCommand {
dynamic("user") {
dynamic ("world"){
dynamic ("time"){
execute<CommandSender> { sender, context, argument ->
// 获取参数的值
val user = context["user"]
val worldName:String = context["world"]
val time:Int = context.int("time")
ZaxWorld.getPlayerCacheMap().set(user,worldName, time)
sender.sendMessage(sender.asLangText("manage-command-message-set")
.replace("{user}",user)
.replace("{world}",worldName)
.replace("{time}",time.toString()))
}
}
}
}
dynamic ("time"){
execute<CommandSender> { sender, context, argument ->
if (sender is Player){
val user:Player = sender
val worldName:String = user.world.name
val time:Int = context.int("time")
ZaxWorld.getPlayerCacheMap().set(sender.name,worldName, time)
sender.sendMessage(sender.asLangText("manage-command-message-set")
.replace("{user}",user.name)
.replace("{world}",worldName)
.replace("{time}",time.toString()))
}
}
}
}
@CommandBody
val check = subCommand {
dynamic("user") {
dynamic ("world"){
execute<CommandSender> { sender, context, argument ->
// 获取参数的值
val user = context["user"]
val worldName:String = context["world"]
val time = ZaxWorld.getPlayerCacheMap().getPlayerWorldTime(user,worldName)
sender.sendMessage(sender.asLangText("manage-command-message-check")
.replace("{user}",user)
.replace("{world}",worldName)
.replace("{time}",time.toString()))
}
}
}
execute<CommandSender> { sender, context, argument ->
if (sender is Player){
val user:Player = sender
val worldName:String = user.world.name
val time = ZaxWorld.getPlayerCacheMap().getPlayerWorldTime(user.name,worldName)
sender.sendMessage(sender.asLangText("manage-command-message-check")
.replace("{user}",user.name)
.replace("{world}",worldName)
.replace("{time}",time.toString()))
}
}
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/commands/MainCommand.kt
|
2151242436
|
package io.github.yuazer.zaxworld.mymap
import io.github.yuazer.zaxworld.ZaxWorld
object PlayerWorldMap{
private var mutableMap:MutableMap<String,Int> = mutableMapOf()
fun getMap():MutableMap<String,Int>{
return this.mutableMap
}
fun getPlayerWorldTime(playerName:String,worldName:String): Int {
val defaultTime = ZaxWorld.config.getInt("World.${worldName}.time")
return mutableMap[getPWKey(playerName,worldName)] ?:defaultTime
}
fun getPWKey(playerName: String,worldName: String):String{
return playerName+"<>"+worldName
}
fun getPlayerAllWorld(playerName: String):MutableSet<String>{
val worldSet = mutableSetOf<String>()
mutableMap.keys.forEach {
val name = it.split("<>")[0]
if (playerName.equals(name,ignoreCase = true)){
worldSet.add(it.split("<>")[1])
}
}
return worldSet
}
fun add(playerName: String,worldName: String,time:Int){
val defaultTime = ZaxWorld.config.getInt("World.${worldName}.time")
set(playerName, worldName, mutableMap[getPWKey(playerName, worldName)] ?: (defaultTime + time))
}
fun reduce(playerName: String,worldName: String,time:Int){
val defaultTime = ZaxWorld.config.getInt("World.${worldName}.time")
set(playerName, worldName, mutableMap[getPWKey(playerName, worldName)] ?: (defaultTime - time))
}
fun set(playerName: String,worldName: String,time:Int){
mutableMap[getPWKey(playerName,worldName)] = time
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/mymap/PlayerWorldMap.kt
|
1652429188
|
package io.github.yuazer.zaxworld.hook
import io.github.yuazer.zaxworld.ZaxWorld
import org.bukkit.entity.Player
import taboolib.platform.compat.PlaceholderExpansion
object TimeHook:PlaceholderExpansion {
override val identifier: String = "zaxworld"
override fun onPlaceholderRequest(player: Player?, args: String): String {
val time = if (player==null) 0 else ZaxWorld.getPlayerCacheMap().getPlayerWorldTime(player.name,args)
return "$time"
}
}
|
ZaxWorld/src/main/kotlin/io/github/yuazer/zaxworld/hook/TimeHook.kt
|
2605347444
|
package com.auth.flowopreator
|
Flow-Opreators/app/src/main/java/com/auth/flowopreator/FlowOpreators.kt
|
3062849873
|
package com.ccap.playground
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.ccap.playground", appContext.packageName)
}
}
|
ccap-playground-android/app/src/androidTest/java/com/ccap/playground/ExampleInstrumentedTest.kt
|
3372233958
|
package com.ccap.playground
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)
}
}
|
ccap-playground-android/app/src/test/java/com/ccap/playground/ExampleUnitTest.kt
|
967261694
|
package com.ccap.playground.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)
|
ccap-playground-android/app/src/main/java/com/ccap/playground/ui/theme/Color.kt
|
1190320225
|
package com.ccap.playground.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 CCapPlaygroundAndroidTheme(
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
)
}
|
ccap-playground-android/app/src/main/java/com/ccap/playground/ui/theme/Theme.kt
|
1694748545
|
package com.ccap.playground.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
)
*/
)
|
ccap-playground-android/app/src/main/java/com/ccap/playground/ui/theme/Type.kt
|
2529074934
|
package com.ccap.playground
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.ccap.playground.ui.theme.CCapPlaygroundAndroidTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CCapPlaygroundAndroidTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
CCapPlaygroundAndroidTheme {
Greeting("Android")
}
}
|
ccap-playground-android/app/src/main/java/com/ccap/playground/MainActivity.kt
|
1774626143
|
package ui
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF006780)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFB8EAFF)
val md_theme_light_onPrimaryContainer = Color(0xFF001F28)
val md_theme_light_secondary = Color(0xFF4C626B)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFCFE6F1)
val md_theme_light_onSecondaryContainer = Color(0xFF071E26)
val md_theme_light_tertiary = Color(0xFF5A5B7E)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFE1E0FF)
val md_theme_light_onTertiaryContainer = Color(0xFF171837)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFBFCFE)
val md_theme_light_onBackground = Color(0xFF191C1D)
val md_theme_light_surface = Color(0xFFFBFCFE)
val md_theme_light_onSurface = Color(0xFF191C1D)
val md_theme_light_surfaceVariant = Color(0xFFDBE4E8)
val md_theme_light_onSurfaceVariant = Color(0xFF40484C)
val md_theme_light_outline = Color(0xFF70787C)
val md_theme_light_inverseOnSurface = Color(0xFFEFF1F2)
val md_theme_light_inverseSurface = Color(0xFF2E3132)
val md_theme_light_inversePrimary = Color(0xFF57D5FE)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF006780)
val md_theme_light_outlineVariant = Color(0xFFBFC8CC)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFF57D5FE)
val md_theme_dark_onPrimary = Color(0xFF003544)
val md_theme_dark_primaryContainer = Color(0xFF004D61)
val md_theme_dark_onPrimaryContainer = Color(0xFFB8EAFF)
val md_theme_dark_secondary = Color(0xFFB3CAD4)
val md_theme_dark_onSecondary = Color(0xFF1E333B)
val md_theme_dark_secondaryContainer = Color(0xFF344A52)
val md_theme_dark_onSecondaryContainer = Color(0xFFCFE6F1)
val md_theme_dark_tertiary = Color(0xFFC3C3EB)
val md_theme_dark_onTertiary = Color(0xFF2C2E4D)
val md_theme_dark_tertiaryContainer = Color(0xFF434465)
val md_theme_dark_onTertiaryContainer = Color(0xFFE1E0FF)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF191C1D)
val md_theme_dark_onBackground = Color(0xFFE1E3E4)
val md_theme_dark_surface = Color(0xFF191C1D)
val md_theme_dark_onSurface = Color(0xFFE1E3E4)
val md_theme_dark_surfaceVariant = Color(0xFF40484C)
val md_theme_dark_onSurfaceVariant = Color(0xFFBFC8CC)
val md_theme_dark_outline = Color(0xFF8A9296)
val md_theme_dark_inverseOnSurface = Color(0xFF191C1D)
val md_theme_dark_inverseSurface = Color(0xFFE1E3E4)
val md_theme_dark_inversePrimary = Color(0xFF006780)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFF57D5FE)
val md_theme_dark_outlineVariant = Color(0xFF40484C)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFF00A9D0)
|
ZWLab/composeApp/src/commonMain/kotlin/ui/Color.kt
|
609587789
|
package ui
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import getDynamicTheme
val LightColors = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
)
val DarkColors = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun getTheme(dark: Boolean): ColorScheme {
getDynamicTheme().let{
if(it!=null){
return if(dark){ it.second }else{ it.first }
}
}
return if(dark){ DarkColors }else{ LightColors }
}
|
ZWLab/composeApp/src/commonMain/kotlin/ui/Theme.kt
|
1830241257
|
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.stringResource
import ui.getTheme
import zwlab.composeapp.generated.resources.*
@Composable
fun App(dark: Boolean, changeTheme: (Boolean) -> Unit) {
var page by remember{mutableStateOf("Home")}
var showDialog by remember{mutableStateOf(false)}
MaterialTheme(
colorScheme = getTheme(dark)
){
Scaffold(
bottomBar = { NavBar(page){page=it} }
){paddingValues->
if(page=="Insert"){ InsertZW(paddingValues) }
if(page=="Remove"){ RemoveZW(paddingValues) }
if(page=="Home"){ ZWList(paddingValues, dark, changeTheme){showDialog = true} }
if(page=="Encode"){ EncodeZW(paddingValues) }
if(page=="Decode"){ DecodeZW(paddingValues) }
AboutDialog(showDialog){showDialog=false}
}
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun DecodeZW(paddingValues: PaddingValues){
var visible by remember{mutableStateOf("")}
var hidden by remember{mutableStateOf("")}
var input by remember{mutableStateOf("")}
var expandVisible by remember{mutableStateOf(true)}
var expandHidden by remember{mutableStateOf(true)}
var expandInput by remember{mutableStateOf(true)}
val focusManager = LocalFocusManager.current
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize().padding(horizontal = 8.dp).verticalScroll(rememberScrollState())
){
Spacer(Modifier.padding(vertical = 10.dp))
TextField(
value = input, onValueChange = {input = it},
label = {Text(text = stringResource(Res.string.input))},
trailingIcon = if(input.contains("\n")){ {ExpandIcon(expandInput) {expandInput = !expandInput}} }else{ null },
modifier = Modifier.fillMaxWidth(),
singleLine = !expandInput
)
Spacer(Modifier.padding(vertical = 2.dp))
Button(
onClick = {
focusManager.clearFocus()
decode(input).let{
visible = it.first
hidden = it.second
}
expandInput = false
}
){
Text(text = stringResource(Res.string.go))
}
Spacer(Modifier.padding(vertical = 3.dp))
AnimatedVisibility(visible!=""||hidden!=""){
Column{
TextField(
value = visible, onValueChange = {visible = it},
label = {Text(text = stringResource(Res.string.visible_text))},
modifier = Modifier.fillMaxWidth(),
trailingIcon = if(visible.contains("\n")){ {ExpandIcon(expandVisible) {expandVisible = !expandVisible}} }else{ null },
singleLine = !expandVisible
)
Spacer(Modifier.padding(vertical = 2.dp))
TextField(
value = hidden, onValueChange = {hidden = it},
label = {Text(text = stringResource(Res.string.hidden_text))},
modifier = Modifier.fillMaxWidth(),
trailingIcon = if(hidden.contains("\n")){ {ExpandIcon(expandHidden) {expandHidden = !expandHidden}} }else{ null },
singleLine = !expandHidden
)
Spacer(Modifier.padding(vertical = 3.dp))
Row(
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier.fillMaxWidth()
){
CopyButton(stringResource(Res.string.copy_visible), visible, 160.dp)
CopyButton(stringResource(Res.string.copy_hidden), hidden, 160.dp)
}
}
}
Spacer(Modifier.padding(top = paddingValues.calculateBottomPadding(), bottom = 60.dp).imePadding())
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun EncodeZW(paddingValues: PaddingValues){
var visible1 by remember{mutableStateOf("")}
var hidden by remember{mutableStateOf("")}
var visible2 by remember{mutableStateOf("")}
var output by remember{mutableStateOf("")}
var expandVisible1 by remember{mutableStateOf(true)}
var expandHidden by remember{mutableStateOf(true)}
var expandVisible2 by remember{mutableStateOf(true)}
var expandOutput by remember{mutableStateOf(true)}
val focusManager = LocalFocusManager.current
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize().padding(horizontal = 8.dp).verticalScroll(rememberScrollState())
){
Spacer(Modifier.padding(vertical = 10.dp))
TextField(
value = visible1, onValueChange = {visible1 = it},
label = {Text(text = stringResource(Res.string.visible_text))},
modifier = Modifier.fillMaxWidth(),
trailingIcon = if(visible1.contains("\n")){ {ExpandIcon(expandVisible1) {expandVisible1 = !expandVisible1}} }else{ null },
singleLine = !expandVisible1
)
Spacer(Modifier.padding(vertical = 2.dp))
TextField(
value = hidden, onValueChange = {hidden = it},
label = {Text(text = stringResource(Res.string.hidden_text))},
modifier = Modifier.fillMaxWidth(),
trailingIcon = if(hidden.contains("\n")){ {ExpandIcon(expandHidden) {expandHidden = !expandHidden}} }else{ null },
singleLine = !expandHidden
)
Spacer(Modifier.padding(vertical = 2.dp))
TextField(
value = visible2, onValueChange = {visible2 = it},
label = {Text(text = stringResource(Res.string.visible_text))},
modifier = Modifier.fillMaxWidth(),
trailingIcon = if(visible2.contains("\n")){ {ExpandIcon(expandVisible2) {expandVisible2 = !expandVisible2}} }else{ null },
singleLine = !expandVisible2
)
Spacer(Modifier.padding(vertical = 3.dp))
Button(
onClick = {
focusManager.clearFocus()
output = encode(visible1, hidden, visible2)
expandVisible1 = false
expandHidden = false
expandVisible2 = false
}
){
Text(text = stringResource(Res.string.go))
}
Spacer(Modifier.padding(vertical = 3.dp))
AnimatedVisibility(output!=""){
Column{
OutlinedTextField(
value = output, onValueChange = {output = it},
label = {Text(text = stringResource(Res.string.output))}, readOnly = true,
trailingIcon = if(output.contains("\n")){ {ExpandIcon(expandOutput) {expandOutput = !expandOutput}} }else{ null },
modifier = Modifier.fillMaxWidth(),
singleLine = !expandOutput
)
Spacer(Modifier.padding(vertical = 2.dp))
CopyButton(stringResource(Res.string.copy), output)
}
}
Spacer(Modifier.padding(top = paddingValues.calculateBottomPadding(), bottom = 60.dp).imePadding())
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun ZWList(paddingValues: PaddingValues, dark:Boolean, changeTheme:(Boolean)->Unit, showDialog:()->Unit){
val list = listOf(
Pair("\u200B" ,stringResource(Res.string.zw_space)),
Pair("\uFEFF" ,stringResource(Res.string.zw_no_break_space)),
Pair("\u200C" ,stringResource(Res.string.zw_non_joiner)),
Pair("\u200D" ,stringResource(Res.string.zw_joiner)),
Pair("\u200E" ,stringResource(Res.string.ltr_mark)),
Pair("\u200F" ,stringResource(Res.string.rtl_mark))
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState())
){
Row(
horizontalArrangement = Arrangement.SpaceAround,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
){
Text(
text = stringResource(Res.string.zero_width_lab), style = MaterialTheme.typography.headlineLarge,
modifier = Modifier.padding(top = 15.dp, bottom = 10.dp)
)
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 3.dp)){
Text(text = stringResource(Res.string.dark), modifier = Modifier.padding(end = 5.dp))
Switch(onCheckedChange = changeTheme, checked = dark)
}
}
if(getPlatform()=="android"){
for(i in list){
CopyZWCharacter(i.first, i.second)
}
}else{
Row(horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.fillMaxWidth()){
CopyZWCharacter(list[0].first, list[0].second)
CopyZWCharacter(list[1].first, list[1].second)
}
Row(horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.fillMaxWidth()){
CopyZWCharacter(list[2].first, list[2].second)
CopyZWCharacter(list[3].first, list[3].second)
}
Row(horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.fillMaxWidth()){
CopyZWCharacter(list[4].first, list[4].second)
CopyZWCharacter(list[5].first, list[5].second)
}
}
Spacer(modifier = Modifier.padding(top = 30.dp))
if(getPlatform()!="desktop"){TextButton(onClick = showDialog){Text(stringResource(Res.string.about))}}
Spacer(Modifier.padding(top = 30.dp, bottom = paddingValues.calculateBottomPadding()))
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun InsertZW(paddingValues: PaddingValues){
var input by remember{mutableStateOf("")}
var output by remember{mutableStateOf("")}
var selectedZW by remember{mutableStateOf("b")}
var expandInput by remember{mutableStateOf(true)}
var expandOutput by remember{mutableStateOf(true)}
var stats by remember{mutableIntStateOf(0)}
val focusManager = LocalFocusManager.current
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize().padding(horizontal = 8.dp).verticalScroll(rememberScrollState())
){
Spacer(Modifier.padding(vertical = 10.dp))
TextField(
value = input, onValueChange = {input = it},
label = {Text(text = stringResource(Res.string.input))},
modifier = Modifier.fillMaxWidth(),
trailingIcon = if(input.contains("\n")){ {ExpandIcon(expandInput) {expandInput = !expandInput}} }else{ null },
singleLine = !expandInput
)
Spacer(Modifier.padding(vertical = 3.dp))
Text(
text = stringResource(Res.string.zw_char_type_is),
modifier = Modifier.align(Alignment.Start).padding(start = 6.dp, top = 6.dp, bottom = 2.dp).animateContentSize()
)
RadioButtonItem(text = stringResource(Res.string.zw_space), selected = selectedZW=="b", onClick = {selectedZW = "b"})
RadioButtonItem(text = stringResource(Res.string.zw_no_break_space), selected = selectedZW=="feff", onClick = {selectedZW = "feff"})
RadioButtonItem(text = stringResource(Res.string.zw_non_joiner), selected = selectedZW=="c", onClick = {selectedZW = "c"})
RadioButtonItem(text = stringResource(Res.string.zw_joiner), selected = selectedZW=="d", onClick = {selectedZW = "d"})
RadioButtonItem(text = stringResource(Res.string.ltr_mark), selected = selectedZW=="e", onClick = {selectedZW = "e"})
RadioButtonItem(text = stringResource(Res.string.rtl_mark), selected = selectedZW=="f", onClick = {selectedZW = "f"})
Button(
onClick = {
focusManager.clearFocus()
addZW(input,selectedZW).let{
output = it.first
stats = it.second
}
expandInput = false
}
){
Text(text = stringResource(Res.string.go))
}
Spacer(Modifier.padding(vertical = 3.dp))
AnimatedVisibility(output!=""){
Column{
OutlinedTextField(
value = output, onValueChange = {output = it},
label = {Text(text = stringResource(Res.string.output))}, readOnly = true,
trailingIcon = if(output.contains("\n")){ {ExpandIcon(expandOutput) {expandOutput = !expandOutput}} }else{ null },
modifier = Modifier.fillMaxWidth(),
singleLine = !expandOutput
)
Spacer(Modifier.padding(vertical = 2.dp))
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()){
Text(
text = stringResource(Res.string.insert_stat,stats.toString()),
modifier = Modifier.padding(start = 5.dp)
)
CopyButton("Copy", output)
}
}
}
Spacer(Modifier.padding(top = paddingValues.calculateBottomPadding(), bottom = 60.dp).imePadding())
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun RemoveZW(paddingValues: PaddingValues){
var input by remember{mutableStateOf("")}
var output by remember{mutableStateOf("")}
var expandInput by remember{mutableStateOf(true)}
var expandOutput by remember{mutableStateOf(true)}
var stat by remember{mutableStateOf(0)}
val focusManager = LocalFocusManager.current
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize().padding(horizontal = 8.dp).verticalScroll(rememberScrollState())
){
Spacer(Modifier.padding(vertical = 10.dp))
TextField(
value = input, onValueChange = {input = it},
label = {Text(text = stringResource(Res.string.input))},
modifier = Modifier.fillMaxWidth(),
trailingIcon = if(input.contains("\n")){ {ExpandIcon(expandInput) {expandInput = !expandInput}} }else{ null },
singleLine = !expandInput
)
Spacer(Modifier.padding(vertical = 3.dp))
Button(
onClick = {
focusManager.clearFocus()
removeZW(input).let{
output = it.first
stat = it.second
}
expandInput = false
}
){
Text(text = stringResource(Res.string.go))
}
Spacer(Modifier.padding(vertical = 3.dp))
AnimatedVisibility(output!=""){
Column{
OutlinedTextField(
value = output, onValueChange = {output = it},
label = {Text(text = stringResource(Res.string.output))}, readOnly = true,
trailingIcon = if(output.contains("\n")){ {ExpandIcon(expandOutput) {expandOutput = !expandOutput}} }else{ null },
modifier = Modifier.fillMaxWidth(),
singleLine = !expandOutput
)
Spacer(Modifier.padding(vertical = 2.dp))
Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()){
Text(
text = stringResource(Res.string.remove_stat,stat.toString()),
modifier = Modifier.padding(start = 5.dp)
)
CopyButton(stringResource(Res.string.copy), output)
}
}
}
Spacer(Modifier.padding(top = paddingValues.calculateBottomPadding(), bottom = 60.dp).imePadding())
}
}
|
ZWLab/composeApp/src/commonMain/kotlin/App.kt
|
3679685740
|
import androidx.compose.animation.core.FiniteAnimationSpec
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
val animateAlpha: FiniteAnimationSpec<Float> = spring(stiffness = Spring.StiffnessLow)
|
ZWLab/composeApp/src/commonMain/kotlin/Animation.kt
|
1032624573
|
import androidx.compose.material3.ColorScheme
expect fun getPlatform():String
expect fun writeClipBoard(content:String)
expect fun getDynamicTheme():Pair<ColorScheme, ColorScheme>?
|
ZWLab/composeApp/src/commonMain/kotlin/Platform.kt
|
235977873
|
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.*
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.MaterialTheme.typography
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.*
import zwlab.composeapp.generated.resources.*
@Composable
fun RadioButtonItem(text:String, selected:Boolean, onClick:()->Unit){
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(25))
.clickable(onClick = onClick)
){
RadioButton(
selected = selected,
onClick = onClick,
)
Text(text = text)
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun ExpandIcon(expanded:Boolean, onClick:()->Unit){
val degrees: Float by animateFloatAsState(if (expanded) 180f else 0f)
Icon(
painter = painterResource(Res.drawable.expand_more_fill0),
contentDescription = stringResource(if(expanded){Res.string.shrink_textfield}else{Res.string.expand_textfield}),
modifier = Modifier
.clip(RoundedCornerShape(50))
.clickable(onClick = onClick)
.rotate(degrees)
.padding(3.dp)
)
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun CopyZWCharacter(char:String, desc:String){
var copying by remember{mutableStateOf(false)}
val alpha: Float by animateFloatAsState(targetValue = if (copying) 1f else 0f, animationSpec = animateAlpha)
val coroutine = rememberCoroutineScope()
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.padding(vertical = 5.dp)
.clip(RoundedCornerShape(25))
.background(colorScheme.primaryContainer)
.width(270.dp)
.padding(10.dp)
){
Text(
text = desc,
color = colorScheme.onPrimaryContainer,
style = typography.titleLarge,
modifier = Modifier.padding(start = 10.dp, end = 10.dp)
)
IconButton(
onClick = {
copying = true
coroutine.launch{ delay(1500); copying=false }
writeClipBoard(char)
},
colors = IconButtonDefaults.iconButtonColors(contentColor = colorScheme.primary)
){
Icon(
painter = painterResource(Res.drawable.content_copy_fill0),
contentDescription = stringResource(Res.string.copy),
modifier = Modifier.alpha(1F - alpha)
)
Icon(
painter = painterResource(Res.drawable.check_fill0),
contentDescription = stringResource(Res.string.copied),
modifier = Modifier.alpha(alpha)
)
}
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun CopyButton(text:String, content:String, minWidth:Dp=Dp.Unspecified){
var copying by remember{mutableStateOf(false)}
val coroutine = rememberCoroutineScope()
val alpha: Float by animateFloatAsState(targetValue = if (copying) 1f else 0f, animationSpec = animateAlpha)
Button(
onClick = {
copying = true
coroutine.launch{delay(1500); copying = false}
writeClipBoard(content)
},
modifier = Modifier.widthIn(min = minWidth)
){
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround,
modifier = Modifier.animateContentSize()
){
Box{
Icon(
painter = painterResource(Res.drawable.content_copy_fill0),
contentDescription = stringResource(Res.string.copy),
modifier = Modifier.alpha(1F - alpha)
)
Icon(
painter = painterResource(Res.drawable.check_fill0),
contentDescription = stringResource(Res.string.copied),
modifier = Modifier.alpha(alpha)
)
}
Text(
text = if(copying){stringResource(Res.string.copied)}else{text},
modifier = Modifier.animateContentSize().padding(start = 5.dp)
)
}
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun NavBar(page:String, setPage:(String)->Unit){
NavigationBar{
for(item in pageList){
NavigationBarItem(
selected = page==item.id, label = {Text(text = stringResource(item.name))},
onClick = {setPage(item.id)},
icon = {Icon(painterResource(item.icon),contentDescription = null)}
)
}
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun AboutDialog(showDialog:Boolean, onDismiss:()->Unit){
if(showDialog){
var copying by remember{mutableStateOf(false)}
val coroutine = rememberCoroutineScope()
val url = stringResource(Res.string.project_on_github_url)
AlertDialog(
onDismissRequest = onDismiss,
icon = {Icon(painterResource(Res.drawable.info_fill0), contentDescription = "App icon")},
title = {Text(text = stringResource(Res.string.zero_width_lab))},
text = {
Column{
Text(text = stringResource(Res.string.author_info))
Text(text = stringResource(Res.string.project_on_github))
SelectionContainer{
Text(text = url, color = colorScheme.onPrimaryContainer)
}
}
},
dismissButton = {
TextButton(
onClick = {
copying = true
coroutine.launch{ delay(1500); copying = false}
writeClipBoard(url)
},
modifier = Modifier.width(100.dp)
){
Text(
text = stringResource(if(copying){Res.string.copied}else{Res.string.copy_link}),
modifier = Modifier.animateContentSize()
)
}
},
confirmButton = {TextButton(onClick = onDismiss){Text(text = stringResource(Res.string.confirm))} }
)
}
}
data class PageListItem @OptIn(ExperimentalResourceApi::class) constructor(
val id: String,
val name: StringResource,
val icon: DrawableResource
)
@OptIn(ExperimentalResourceApi::class)
val pageList = listOf(
PageListItem("Insert",Res.string.insert,Res.drawable.add_fill0),
PageListItem("Remove",Res.string.remove,Res.drawable.remove_fill0),
PageListItem("Home",Res.string.home,Res.drawable.format_list_bulleted_fill0),
PageListItem("Encode",Res.string.encode,Res.drawable.lock_fill0),
PageListItem("Decode",Res.string.decode,Res.drawable.lock_open_right_fill0)
)
|
ZWLab/composeApp/src/commonMain/kotlin/Components.kt
|
4219432235
|
fun addZW(input:String, type:String):Pair<String,Int>{
val length = input.length
var count = 0
var index = 0
val builder = StringBuilder(input)
val zw = when(type){"b"->"\u200B"; "c"->"\u200C"; "d"->"\u200D"; "e"->"\u200E"; "f"->"\u200F"; else->" "}
while(count<length){
builder.insert(index,zw)
count+=1
index+=2
}
return Pair(builder.toString(),count)
}
fun removeZW(input: String):Pair<String,Int>{
var output = ""
var stat =0
input.forEach{
if(it in zwDict){ stat++ }
else{ output+=it }
}
return Pair(output,stat)
}
fun encode(visible1:String, hidden:String, visible2:String, method:String="bin"):String{
var output = ""
when(method){
"bin"->{
output+=visible1
var bin = ""
hidden.forEach{ bin += it.code.toString(2); bin+="\u200D" }
bin.forEach{ output += if(it=='0'){"\u200C"}else if(it=='1'){"\u200B"}else{"\u200D"} }
output+=visible2
}
}
return output
}
fun decode(content:String, method:String="bin"):Pair<String,String>{
var visible = ""
var hidden = ""
when(method){
"bin"->{
var bin = ""
content.forEach{
if(it in zwDict){
if(it.toString()=="\u200C"){bin += "0"}
if(it.toString()=="\u200B"){bin += "1"}
if(it.toString()=="\u200D"){ hidden+=bin.toInt(2).toChar(); bin="" }
}else{
visible += it
}
}
}
}
return Pair(visible,hidden)
}
val zwDict = setOf('\u200B', '\u200C', '\u200D', '\u200E', '\u200F', '\uFEFF')
|
ZWLab/composeApp/src/commonMain/kotlin/Util.kt
|
1776218691
|
import androidx.compose.material3.ColorScheme
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
actual fun getPlatform() = "desktop"
actual fun writeClipBoard(content: String) {
try{
val stringSelection = StringSelection(content)
val clipboard = Toolkit.getDefaultToolkit().systemClipboard
clipboard.setContents(stringSelection,null)
}catch(e:Exception){
println(e)
}
}
actual fun getDynamicTheme():Pair<ColorScheme, ColorScheme>? = null
|
ZWLab/composeApp/src/desktopMain/kotlin/Platform.jvm.kt
|
437116989
|
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.resources.stringResource
import ui.getTheme
import zwlab.composeapp.generated.resources.Res
import zwlab.composeapp.generated.resources.about
import zwlab.composeapp.generated.resources.info_fill0
import zwlab.composeapp.generated.resources.zw_lab
@OptIn(ExperimentalResourceApi::class)
fun main() = application {
var dark:Boolean by remember{mutableStateOf(false)}
dark = isSystemInDarkTheme()
Window(
onCloseRequest = ::exitApplication, title = stringResource(Res.string.zw_lab)
) {
DesktopApp(dark){dark=it}
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun DesktopApp(dark:Boolean, changeTheme:(Boolean)->Unit){
var page by remember{mutableStateOf("Home")}
var showAboutDialog by remember{mutableStateOf(false)}
val list = listOf(pageList[2] ,pageList[0], pageList[1], pageList[3], pageList[4])
MaterialTheme(colorScheme = getTheme(dark)){
Row(
modifier = Modifier.fillMaxSize()
){
NavigationRail(
containerColor = colorScheme.surfaceContainer
){
Spacer(Modifier.padding(vertical = 5.dp))
Column(verticalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxHeight()){
Column{
for(item in list){
NavigationRailItem(
icon = {Icon(painter = painterResource(item.icon), contentDescription = stringResource(item.name))},
label = {Text(text = stringResource(item.name))},
selected = page==item.id,
onClick = {page=item.id}
)
}
}
NavigationRailItem(
icon = {Icon(painter = painterResource(Res.drawable.info_fill0), contentDescription = stringResource(Res.string.about))},
label = {Text(text = stringResource(Res.string.about))},
selected = false,
onClick = {showAboutDialog = true}
)
}
}
Scaffold{
if(page=="Home"){ ZWList(PaddingValues(), dark, changeTheme){showAboutDialog = true} }
if(page=="Insert"){ InsertZW(PaddingValues()) }
if(page=="Remove"){ RemoveZW(PaddingValues()) }
if(page=="Encode"){ EncodeZW(PaddingValues()) }
if(page=="Decode"){ DecodeZW(PaddingValues()) }
}
}
AboutDialog(showAboutDialog){showAboutDialog = false}
}
}
|
ZWLab/composeApp/src/desktopMain/kotlin/main.kt
|
3061592366
|
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.window.CanvasBasedWindow
@OptIn(ExperimentalComposeUiApi::class)
fun main() {
CanvasBasedWindow(canvasElementId = "ComposeTarget"){
var dark by remember{mutableStateOf(false)}
var inited by remember{mutableStateOf(false)}
if(!inited){dark = isSystemInDarkTheme(); inited = true}
App(dark){dark=it}
}
}
|
ZWLab/composeApp/src/wasmJsMain/kotlin/main.kt
|
2691367013
|
import androidx.compose.material3.ColorScheme
actual fun getPlatform() = "web"
actual fun writeClipBoard(content: String) {
js("""
document.body.addEventListener(
'click',
async () => {
try {
await navigator.clipboard.writeText(content);
console.log('Page URL copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
)
""")
}
actual fun getDynamicTheme(): Pair<ColorScheme, ColorScheme>? = null
|
ZWLab/composeApp/src/wasmJsMain/kotlin/Platform.wasmJs.kt
|
3126668851
|
import androidx.compose.material3.ColorScheme
import com.bintianqi.zwlab.dynamicTheme
import com.bintianqi.zwlab.writeClipBoardContent
actual fun writeClipBoard(content: String) {
writeClipBoardContent = content
}
actual fun getPlatform() = "android"
actual fun getDynamicTheme(): Pair<ColorScheme, ColorScheme>? {
return dynamicTheme
}
|
ZWLab/composeApp/src/androidMain/kotlin/Platform.android.kt
|
669364900
|
package com.bintianqi.zwlab
import AboutDialog
import DecodeZW
import EncodeZW
import InsertZW
import NavBar
import RemoveZW
import ZWList
import android.app.Activity
import android.os.Build.VERSION
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.material3.*
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import kotlinx.coroutines.delay
import ui.getTheme
var writeClipBoardContent = ""
var dynamicTheme:Pair<ColorScheme, ColorScheme>? = null
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
super.onCreate(savedInstanceState)
setContent {
val context = LocalContext.current
var inited by remember{mutableStateOf(false)}
var dark by remember{mutableStateOf(false)}
if(!inited){ dark = isSystemInDarkTheme(); inited = true}
enableEdgeToEdge()
LaunchedEffect(Unit){
while(true){
if(writeClipBoardContent!=""){
Log.e("ZW","Android:WriteClipboard")
copyToClipBoard(context, writeClipBoardContent)
writeClipBoardContent = ""
}
delay(200)
}
}
if(VERSION.SDK_INT>=31){
dynamicTheme = Pair(dynamicLightColorScheme(context), dynamicDarkColorScheme(context))
}
val view = LocalView.current
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = Color.Transparent.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !dark
}
MaterialTheme(
colorScheme = getTheme(dark)
){
AppContent(dark){dark = it}
}
}
}
}
@Composable
private fun AppContent(dark:Boolean, changeTheme:(Boolean)->Unit){
val navController = rememberNavController()
val backStackEntry by navController.currentBackStackEntryAsState()
var showDialog by remember{mutableStateOf(false)}
Scaffold(
bottomBar = {
NavBar(backStackEntry?.destination?.route?:"Home"){
if(it!=backStackEntry?.destination?.route){
navController.navigate(it){
popUpTo("Home"){
inclusive = false
}
}
}
}
},
modifier = Modifier.background(colorScheme.background).statusBarsPadding()
){paddingValues->
NavHost(
navController = navController,
startDestination = "Home"
){
composable(route = "Insert"){ InsertZW(paddingValues) }
composable(route = "Remove"){ RemoveZW(paddingValues) }
composable(route = "Home"){ ZWList(paddingValues, dark, changeTheme){showDialog = true} }
composable(route = "Encode"){ EncodeZW(paddingValues) }
composable(route = "Decode"){ DecodeZW(paddingValues) }
}
AboutDialog(showDialog){showDialog=false}
}
}
|
ZWLab/composeApp/src/androidMain/kotlin/com/bintianqi/zwlab/MainActivity.kt
|
2804571809
|
package com.bintianqi.zwlab
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
fun copyToClipBoard(context: Context, string: String):Boolean{
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
try {
clipboardManager.setPrimaryClip(ClipData.newPlainText("", string))
}catch(e:Exception){
return false
}
return true
}
|
ZWLab/composeApp/src/androidMain/kotlin/com/bintianqi/zwlab/Utils.kt
|
3366874694
|
package com.example.kotlin_businesscard
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.kotlin_businesscard", appContext.packageName)
}
}
|
Kotlin-BusinessCard/app/src/androidTest/java/com/example/kotlin_businesscard/ExampleInstrumentedTest.kt
|
616417040
|
package com.example.kotlin_businesscard
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)
}
}
|
Kotlin-BusinessCard/app/src/test/java/com/example/kotlin_businesscard/ExampleUnitTest.kt
|
473890933
|
package com.example.kotlin_businesscard.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)
|
Kotlin-BusinessCard/app/src/main/java/com/example/kotlin_businesscard/ui/theme/Color.kt
|
2624854607
|
package com.example.kotlin_businesscard.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 KotlinBusinessCardTheme(
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
)
}
|
Kotlin-BusinessCard/app/src/main/java/com/example/kotlin_businesscard/ui/theme/Theme.kt
|
1118964487
|
package com.example.kotlin_businesscard.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
)
*/
)
|
Kotlin-BusinessCard/app/src/main/java/com/example/kotlin_businesscard/ui/theme/Type.kt
|
2788783046
|
package com.example.kotlin_businesscard
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.kotlin_businesscard.ui.theme.KotlinBusinessCardTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
KotlinBusinessCardTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
BusinessCardLayout()
}
}
}
}
}
@Composable
fun LogoSection() {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
val image = painterResource(id = R.drawable.ic_task_completed)
Image(
painter = image,
contentDescription = "Logo",
contentScale = ContentScale.Crop,
modifier = Modifier.size(130.dp)
)
Text(
text = "Full Name",
fontSize = 24.sp,
color = Color(0xFF3ddc84)
)
Text(
text = "Title",
fontSize = 16.sp,
color = Color(0xFF3ddc84)
)
}
}
@Composable
fun ContactInfoSection() {
Column {
val image = painterResource(id = R.drawable.ic_task_completed)
Row {
Image(
painter = image,
contentDescription = "Logo",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(25.dp)
.padding(5.dp)
)
Text(
text = "Contact Information",
fontSize = 20.sp,
color = Color(0xFF3ddc84)
)
}
Row {
Image(
painter = image,
contentDescription = "Logo",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(25.dp)
.padding(5.dp)
)
Text(
text = "Address: Your Address",
fontSize = 16.sp,
color = Color(0xFF3ddc84)
)
}
Row {
Image(
painter = image,
contentDescription = "Logo",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(25.dp)
.padding(5.dp)
)
Text(
text = "Phone: Your Phone",
fontSize = 16.sp,
color = Color(0xFF3ddc84)
)
}
Row {
Image(
painter = image,
contentDescription = "Logo",
contentScale = ContentScale.Crop,
modifier = Modifier
.size(25.dp)
.padding(5.dp)
)
Text(
text = "Email: Your Email",
fontSize = 16.sp,
color = Color(0xFF3ddc84)
)
}
}
}
@Composable
fun BusinessCardLayout() {
Box {
Column(
modifier = Modifier
.fillMaxSize()
.padding(top = 100.dp),
verticalArrangement = Arrangement.Top,
horizontalAlignment = Alignment.CenterHorizontally
) {
LogoSection()
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(bottom = 5.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
ContactInfoSection()
}
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
KotlinBusinessCardTheme {
BusinessCardLayout()
}
}
|
Kotlin-BusinessCard/app/src/main/java/com/example/kotlin_businesscard/MainActivity.kt
|
2337126984
|
package com.gotkicry.netplayer
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.gotkicry.netplayer", appContext.packageName)
}
}
|
NetPlayer/app/src/androidTest/java/com/gotkicry/netplayer/ExampleInstrumentedTest.kt
|
3445709362
|
package com.gotkicry.netplayer
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)
}
}
|
NetPlayer/app/src/test/java/com/gotkicry/netplayer/ExampleUnitTest.kt
|
3796490182
|
package com.gotkicry.netplayer.viewmodel
import android.app.Activity
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.gotkicry.netplayer.event.LoadResult
import com.gotkicry.netplayer.model.WebDAVConfig
import com.gotkicry.netplayer.model.WebDAVRepository
import com.gotkicry.netplayer.util.LoadingDialog
import com.gotkicry.netplayer.util.ToastUtil
import com.thegrizzlylabs.sardineandroid.DavResource
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import java.io.IOException
import java.io.InputStream
class WebDAVViewModel() : ViewModel() {
companion object{
private const val TAG = "WebDAVViewModel"
}
private val webDAVRepository by lazy { WebDAVRepository() }
private val _data = MutableLiveData<MutableList<DavResource>>()
val davList : LiveData<MutableList<DavResource>> = _data
init {
_data.value = mutableListOf()
}
private fun getDefConfig():WebDAVConfig{
return WebDAVConfig(
userName = "lzh",
password = "lzh1103.",
isEnableSSL = true,
baseURL = "gotkicry.com",
suffix = "dav"
)
}
fun getWebDAVFileList(activity: Activity,params:String? = null){
viewModelScope.launch {
LoadingDialog.show(activity)
try {
_data.value = webDAVRepository.getFileList(getDefConfig(),params)
}catch (e : IOException){
if(e.message == "Not a valid DAV response"){
ToastUtil.show("获取列表超时")
}
EventBus.getDefault().post(LoadResult(LoadResult.TIMEOUT,e.message))
}
Log.d(TAG,"_data.value : ${_data.value}")
}
}
fun getDownloadUrl(url:String):String{
return getDefConfig().getDownloadUrl(url)
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/viewmodel/WebDAVViewModel.kt
|
1130405876
|
package com.gotkicry.netplayer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.gotkicry.netplayer.base.BaseActivity
import com.gotkicry.netplayer.databinding.ActivityMainBinding
import com.gotkicry.netplayer.event.MsgEvent
import com.gotkicry.netplayer.view.WebDAVFileFragment
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.videolan.libvlc.util.VLCUtil
class MainActivity : BaseActivity() {
companion object{
private const val TAG = "MainActivity"
}
private val viewBinding : ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
openWebDAVFileList()
}
override fun onGetMsgEvent(event: MsgEvent, isSticky: Boolean) {
}
private fun openWebDAVFileList(){
val beginTransaction = supportFragmentManager.beginTransaction()
beginTransaction.replace(viewBinding.mainFragment.id,WebDAVFileFragment())
beginTransaction.commit()
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/MainActivity.kt
|
680344779
|
package com.gotkicry.netplayer.util
import android.content.Context
import android.net.Uri
import android.view.SurfaceView
import android.view.TextureView
import org.videolan.libvlc.LibVLC
import org.videolan.libvlc.Media
import org.videolan.libvlc.MediaPlayer
import java.io.InputStream
import java.net.URL
class VLCManager(context: Context, private val textureView: TextureView) {
private var libVLC: LibVLC? = null
private var mediaPlayer: MediaPlayer? = null
init {
initializeLibVLC(context)
initializeMediaPlayer()
}
private fun initializeLibVLC(context: Context) {
val args = ArrayList<String>()
args.add("--no-xlib")
libVLC = LibVLC(context, args)
}
private fun initializeMediaPlayer() {
mediaPlayer = MediaPlayer(libVLC)
mediaPlayer?.let {
it.volume = 0
val vlcVout = it.vlcVout
vlcVout.setVideoView(textureView)
vlcVout.attachViews()
}
}
fun setMediaPath(mediaPath: String) {
val media = Media(libVLC, mediaPath)
mediaPlayer?.media = media
}
fun setMediaPath(mediaPath: Uri) {
val media = Media(libVLC, mediaPath)
mediaPlayer?.media = media
}
fun prepareAndPlay() {
mediaPlayer?.let {
if (!it.isPlaying){
it.play()
}
it.setEventListener { event->
when(event.type){
MediaPlayer.Event.Opening->{
LogUtil.d("Opening")
}
MediaPlayer.Event.Buffering->{
LogUtil.d("Buffering")
}
MediaPlayer.Event.Stopped->{
LogUtil.d("Stopped")
}
MediaPlayer.Event.Paused->{
LogUtil.d("Paused")
}
MediaPlayer.Event.Playing->{
LogUtil.d("Playing")
}
}
}
}
}
fun pause(){
mediaPlayer?.pause()
}
fun release() {
mediaPlayer?.release()
libVLC?.release()
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/util/VLCManager.kt
|
1367605646
|
package com.gotkicry.netplayer.util
import android.app.Activity
import android.graphics.Color
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.FrameLayout
import android.widget.ImageView
import com.gotkicry.netplayer.R
object LoadingDialog {
@JvmStatic
fun show(context: Activity) {
show(context, null)
}
@JvmStatic
fun show(context: Activity, text: CharSequence?) {
val viewGroup = context.window.decorView.rootView as ViewGroup
viewGroup.addView(createLoadingView(context))
}
@JvmStatic
fun hide(context: Activity) {
val loadingView = context.window.decorView.rootView.findViewById<View>(R.id.loading_root)
val parent = context.window.decorView.rootView as ViewGroup
parent.removeView(loadingView)
}
private fun createLoadingView(context: Activity): View {
val frameLayout = FrameLayout(context)
frameLayout.id = R.id.loading_root
val layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
layoutParams.gravity = Gravity.CENTER
frameLayout.layoutParams = layoutParams
frameLayout.setBackgroundColor(Color.argb(200, 20, 20, 20))
val imageView = ImageView(context)
imageView.setImageResource(R.drawable.loading)
imageView.layoutParams = FrameLayout.LayoutParams(200, 200, Gravity.CENTER)
val rotateAnimation = RotateAnimation(
0f,
360f,
Animation.RELATIVE_TO_SELF,
0.5f,
Animation.RELATIVE_TO_SELF,
0.5f
)
rotateAnimation.duration = 600
rotateAnimation.interpolator = LinearInterpolator()
rotateAnimation.repeatMode = Animation.RESTART
rotateAnimation.repeatCount = Animation.INFINITE
rotateAnimation.fillAfter = true
imageView.animation = rotateAnimation
rotateAnimation.start()
frameLayout.addView(imageView)
frameLayout.setOnTouchListener { v, event -> true }
return frameLayout
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/util/LoadingDialog.kt
|
3842582406
|
package com.gotkicry.netplayer.util
import android.widget.Toast
import com.gotkicry.netplayer.PlayerApplication
object ToastUtil {
fun show(msg:String){
val toast = Toast(PlayerApplication.application)
toast.duration = Toast.LENGTH_SHORT
toast.setText(msg)
toast.show()
// Toast.makeText(PlayerApplication.application,msg,Toast.LENGTH_SHORT).show()
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/util/ToastUtil.kt
|
1018655749
|
package com.gotkicry.netplayer.util
import android.util.Log
object LogUtil {
private const val TAG = "GotKiCry"
fun d(msg:String){
Log.d(TAG,msg)
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/util/LogUtil.kt
|
328185065
|
package com.gotkicry.netplayer.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gotkicry.netplayer.databinding.ItemDavFileBinding
import com.gotkicry.netplayer.event.DavResEvent
import com.thegrizzlylabs.sardineandroid.DavResource
import org.greenrobot.eventbus.EventBus
class WebDavRecycleViewAdapter : RecyclerView.Adapter<WebDavRecycleViewAdapter.WebDavRecycleViewViewHolder>() {
private val davResources : MutableList<DavResource> by lazy { mutableListOf() }
class WebDavRecycleViewViewHolder(private val viewBinding: ItemDavFileBinding) : RecyclerView.ViewHolder(viewBinding.root){
fun setFileName(name:String){
viewBinding.tvFileName.text = name
}
fun setOnClick(onClick:()->Unit){
viewBinding.tvFileName.setOnClickListener {
onClick()
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WebDavRecycleViewViewHolder {
val itemDavListViewBinding = ItemDavFileBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return WebDavRecycleViewViewHolder(itemDavListViewBinding)
}
override fun getItemCount(): Int {
return davResources.count() - 1
}
override fun onBindViewHolder(holder: WebDavRecycleViewViewHolder, position: Int) {
val davResource = davResources[position + 1]
holder.setFileName(davResource.displayName)
holder.setOnClick {
EventBus.getDefault().post(DavResEvent(DavResEvent.ActionCode.CLICK,davResource))
}
}
fun setData(davResources: List<DavResource>){
this.davResources.clear()
this.davResources.addAll(davResources)
notifyDataSetChanged()
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/adapter/WebDavRecycleViewAdapter.kt
|
1342108606
|
package com.gotkicry.netplayer.model
import android.util.Log
import com.gotkicry.netplayer.util.LogUtil
import com.thegrizzlylabs.sardineandroid.DavResource
import com.thegrizzlylabs.sardineandroid.impl.OkHttpSardine
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import java.io.FileInputStream
import java.io.InputStream
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit
class WebDAVRepository {
companion object{
private const val TAG = "WebDAVRepository"
}
private val okHttpSardine = OkHttpSardine(
OkHttpClient.Builder()
.callTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.build()
)
suspend fun getFileList(webDAVConfig: WebDAVConfig,params:String?=null):MutableList<DavResource>{
return withContext(Dispatchers.IO){
okHttpSardine.setCredentials(webDAVConfig.userName,webDAVConfig.password)
Log.d(TAG,"get webdav Request")
okHttpSardine.list(webDAVConfig.getConnectURL(params))
}
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/model/WebDAVRepository.kt
|
2510100046
|
package com.gotkicry.netplayer.model
import android.net.Uri
import com.gotkicry.netplayer.util.LogUtil
data class WebDAVConfig(
var userName: String = "",
var password: String = "",
var isEnableSSL: Boolean = true,
var baseURL: String = "",
var suffix: String = "",
var port: Int = -1
){
fun getConnectURL(dirName:String?=null) : String{
var urlSuffix = suffix
if (dirName != null){
urlSuffix = dirName
if (urlSuffix.first() == '/'){
urlSuffix = urlSuffix.removeRange(0,1)
}
}
urlSuffix = Uri.encode(urlSuffix)
val url = "${getStartHttp()}://${baseURL}:${getPORT()}/${urlSuffix}"
LogUtil.d("getConnectURL : $url")
return url
}
fun getDownloadUrl(dirName: String):String{
var urlSuffix = dirName
if (urlSuffix.first() == '/'){
urlSuffix = urlSuffix.removeRange(0,1)
}
urlSuffix = Uri.encode(urlSuffix)
val url = "${getStartHttp()}://${userName}:${password}@${baseURL}:${getPORT()}/${urlSuffix}"
LogUtil.d("getDownloadUrl : $url")
return url
}
private fun getStartHttp():String{
return if (isEnableSSL){
"https"
}else{
"http"
}
}
private fun getPORT():String{
return if (port == -1){
if (isEnableSSL){
"443"
}else{
""
}
}else{
"$port"
}
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/model/WebDAVConfig.kt
|
25483893
|
package com.gotkicry.netplayer.view
import android.net.Uri
import android.os.Bundle
import android.util.Log
import com.gotkicry.netplayer.base.BaseActivity
import com.gotkicry.netplayer.databinding.ActivityVlcPlayerBinding
import com.gotkicry.netplayer.event.MsgEvent
import com.gotkicry.netplayer.util.LogUtil
import com.gotkicry.netplayer.util.VLCManager
class VLCPlayerActivity : BaseActivity(){
private val viewBinding : ActivityVlcPlayerBinding by lazy { ActivityVlcPlayerBinding.inflate(layoutInflater) }
private lateinit var vlcManager: VLCManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewBinding.root)
vlcManager = VLCManager(this,viewBinding.vlc)
if (intent.hasExtra("url")){
val url = intent.getStringExtra("url")
if (url != null) {
LogUtil.d("url : $url")
vlcManager.setMediaPath(Uri.parse(url))
}
}
}
override fun onGetMsgEvent(event: MsgEvent, isSticky: Boolean) {
}
override fun onStart() {
super.onStart()
vlcManager.prepareAndPlay()
Log.d("VLC","play !!!")
}
override fun onPause() {
super.onPause()
vlcManager.pause()
}
override fun onDestroy() {
super.onDestroy()
vlcManager.release()
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/view/VLCPlayerActivity.kt
|
2514625697
|
package com.gotkicry.netplayer.view
import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.addCallback
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.gotkicry.netplayer.adapter.WebDavRecycleViewAdapter
import com.gotkicry.netplayer.base.BaseFragment
import com.gotkicry.netplayer.databinding.FragmentWebdavFileListBinding
import com.gotkicry.netplayer.event.DavResEvent
import com.gotkicry.netplayer.event.LoadResult
import com.gotkicry.netplayer.event.MsgEvent
import com.gotkicry.netplayer.service.CacheTempVideoService
import com.gotkicry.netplayer.util.LoadingDialog
import com.gotkicry.netplayer.util.LogUtil
import com.gotkicry.netplayer.util.ToastUtil
import com.gotkicry.netplayer.viewmodel.WebDAVViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
class WebDAVFileFragment : BaseFragment() {
companion object{
private const val TAG = "WebDAVFileFragment"
}
private lateinit var webDAVViewModel: WebDAVViewModel
private lateinit var webdavFileListBinding: FragmentWebdavFileListBinding
private val webDavListAdapter : WebDavRecycleViewAdapter by lazy { WebDavRecycleViewAdapter() }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
super.onCreateView(inflater, container, savedInstanceState)
webdavFileListBinding = FragmentWebdavFileListBinding.inflate(layoutInflater,container,false)
webDAVViewModel = ViewModelProvider(this)[WebDAVViewModel::class.java]
webDAVViewModel.davList.observe(viewLifecycleOwner){
Log.d(TAG,"show data $it")
webDavListAdapter.setData(it)
LoadingDialog.hide(requireActivity())
}
webdavFileListBinding.fileList.layoutManager = LinearLayoutManager(context)
webdavFileListBinding.fileList.adapter = webDavListAdapter
webDAVViewModel.getWebDAVFileList(requireActivity())
requireActivity().onBackPressedDispatcher.addCallback(this){
val data = webDAVViewModel.davList.value
data?.let {
Log.d(TAG,"Display Name = ${it[0].displayName}")
val uri = File(it[0].href.path)
Log.d(TAG,"URI Parent : ${uri.parent}")
if (it[0].displayName == "root"){
// webDAVViewModel.getWebDAVFileList(requireActivity())
requireActivity().finish()
}else{
webDAVViewModel.getWebDAVFileList(requireActivity(),uri.parent)
}
}
}
return webdavFileListBinding.root
}
@Subscribe(threadMode = ThreadMode.BACKGROUND)
fun onGetDavResEvent(davResEvent: DavResEvent) {
Log.d(TAG,"onGetDavResEvent")
if (davResEvent.getActionCode() != DavResEvent.ActionCode.CLICK) {
return
}
val davResource = davResEvent.getDavResource()
if (davResource.isDirectory) {
webDAVViewModel.getWebDAVFileList(requireActivity(),davResource.path)
}else{
val downloadUrl = webDAVViewModel.getDownloadUrl(davResource.path)
val startVLCIntent = Intent(requireContext(),VLCPlayerActivity::class.java)
startVLCIntent.putExtra("url",downloadUrl)
startActivity(startVLCIntent)
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onLoadResult(loadResult: LoadResult){
if (loadResult.errorCode == LoadResult.TIMEOUT){
LoadingDialog.hide(requireActivity())
}
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/view/WebDAVFileFragment.kt
|
2306472759
|
package com.gotkicry.netplayer.service
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import com.gotkicry.netplayer.event.MsgEvent
import com.gotkicry.netplayer.util.LogUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.videolan.libvlc.LibVLC.Event
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
class CacheTempVideoService : Service() {
private val binder = CacheTempVideoServiceBinder()
private val buffCache = ByteArray(1024 * 512)
private var canCache = false
inner class CacheTempVideoServiceBinder : Binder(){
fun getService(): CacheTempVideoService{
return this@CacheTempVideoService
}
}
override fun onBind(intent: Intent): IBinder {
LogUtil.d("onBind")
return binder
}
override fun onCreate() {
LogUtil.d("on Service Create")
super.onCreate()
}
fun stopCache(){
canCache = false
}
fun createTempVideoFile(inputStream:InputStream,onCache:(filePath:String)->Unit){
Log.d("GotKiCry","LoadTemp")
canCache = true
val cacheDir = this.applicationContext.cacheDir
if (cacheDir.exists().not()){
cacheDir.mkdirs()
}
val file = File(cacheDir, "cacheVideo")
if (file.exists()){
file.deleteRecursively()
file.createNewFile()
}
val outputStream = file.outputStream()
CoroutineScope(Dispatchers.IO).launch {
inputStream.use { input->
val buffer = ByteArray(1024)
var bytesRead: Int
outputStream.use {output->
while (input.read(buffer).also { bytesRead = it } != -1) {
// 在这里处理读取到的数据,例如打印到控制台
output.write(buffer, 0, bytesRead)
onCache(file.absolutePath)
}
}
}
}
}
override fun onDestroy() {
super.onDestroy()
val cacheDir = this.applicationContext.cacheDir
val file = File(cacheDir, "cacheVideo")
file.deleteRecursively()
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/service/CacheTempVideoService.kt
|
1490591126
|
package com.gotkicry.netplayer
import com.thegrizzlylabs.sardineandroid.DavResource
import com.thegrizzlylabs.sardineandroid.impl.OkHttpSardine
import okhttp3.OkHttpClient
import java.util.concurrent.TimeUnit
object Test {
var USERNAME = "lzh"
var PASSWORD = "lzh1103."
var IS_ENABLE_SSL = true
var BASE_URL = "gotkicry.com"
var SUFFIX = "dav"
var PORT = -1
fun getDAVFile(dirName:String? = null) : List<DavResource>{
return try {
val okHttpSardine = OkHttpSardine(
OkHttpClient.Builder()
.callTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.build()
)
okHttpSardine.setCredentials(USERNAME,PASSWORD)
if (dirName != null){
SUFFIX = dirName
if (SUFFIX.first() == '/'){
SUFFIX = SUFFIX.removeRange(0,1)
}
}
val url = "${getStartHttp()}://$BASE_URL:${getPORT()}/$SUFFIX"
okHttpSardine.list(url)
}catch (e : Exception){
e.printStackTrace()
listOf()
}
}
fun getStartHttp():String{
return if (IS_ENABLE_SSL){
"https"
}else{
"http"
}
}
fun getPORT():String{
return if (PORT == -1){
if (IS_ENABLE_SSL){
"443"
}else{
""
}
}else{
"$PORT"
}
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/Test.kt
|
1776315868
|
package com.gotkicry.netplayer.event
data class MsgEvent (val msg:String,val msgData:Any? = null){
companion object{
const val CACHE = "cache"
const val CACHING = "caching"
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/event/MsgEvent.kt
|
1577630698
|
package com.gotkicry.netplayer.event
data class LoadResult(
val errorCode:Int,
val errorMessage:String ? = null
) {
companion object{
const val TIMEOUT = 10504
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/event/LoadResult.kt
|
118234812
|
package com.gotkicry.netplayer.event
import com.thegrizzlylabs.sardineandroid.DavResource
data class DavResEvent(
private val actionCode : ActionCode,
private val davResource: DavResource
){
enum class ActionCode{
CLICK,OPEN
}
fun getActionCode() = actionCode
fun getDavResource() = davResource
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/event/DavResEvent.kt
|
2008410114
|
package com.gotkicry.netplayer.base
import android.os.Bundle
import androidx.annotation.CallSuper
import androidx.appcompat.app.AppCompatActivity
import com.gotkicry.netplayer.event.MsgEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
abstract class BaseActivity : AppCompatActivity() {
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
EventBus.getDefault().register(this)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun getMsg(event: MsgEvent){
onGetMsgEvent(event)
}
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
fun getStickyMsg(event: MsgEvent){
onGetMsgEvent(event,true)
}
abstract fun onGetMsgEvent(event: MsgEvent,isSticky :Boolean = false)
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/base/BaseActivity.kt
|
2330225831
|
package com.gotkicry.netplayer.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.fragment.app.Fragment
import org.greenrobot.eventbus.EventBus
open class BaseFragment : Fragment(){
@CallSuper
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
EventBus.getDefault().register(this)
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/base/BaseFragment.kt
|
2926935113
|
package com.gotkicry.netplayer
import android.app.Application
import org.videolan.libvlc.LibVLC
class PlayerApplication : Application() {
companion object{
lateinit var application: Application
}
override fun onCreate() {
super.onCreate()
application = this
}
}
|
NetPlayer/app/src/main/java/com/gotkicry/netplayer/PlayerApplication.kt
|
3847131200
|
package poc.cx.trackingapp.handler
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.shouldBe
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import poc.cx.shared.message.DispatchCompleted
import poc.cx.shared.message.DispatchPreparing
import poc.cx.trackingapp.service.TrackingService
import poc.cx.trackingapp.util.beforeWhen
import java.util.*
class DispatchTrackingHandlerTest : BehaviorSpec({
lateinit var handler: DispatchTrackingHandler
lateinit var service: TrackingService
beforeWhen {
service = mockk(relaxed = true)
handler = DispatchTrackingHandler(service)
}
Given("A tracking handler and a mocked tracking service") {
When("The dispatch preparing event is processed normally") {
coEvery { service.process(ofType<DispatchPreparing>()) } returns Unit
handler.listenDispatchTracking(mockk<DispatchPreparing>())
Then("The tracking service is called") {
coVerify(exactly = 1) { service.process(ofType<DispatchPreparing>()) }
}
}
When("The dispatch preparing event is processed with an exception") {
coEvery { service.process(ofType<DispatchCompleted>()) } throws RuntimeException("test")
handler.listenDispatchTracking(mockk<DispatchCompleted>())
Then("An exception is thrown and captured") {
coVerify(exactly = 1) { service.process(ofType<DispatchCompleted>()) }
}
}
When("The dispatch completed event is processed normally") {
coEvery { service.process(ofType<DispatchCompleted>()) } returns Unit
handler.listenDispatchTracking(mockk<DispatchCompleted>())
Then("The tracking service is called") {
coVerify(exactly = 1) { service.process(ofType<DispatchCompleted>()) }
}
}
When("The dispatch completed event is processed with an exception") {
coEvery { service.process(ofType<DispatchCompleted>()) } throws RuntimeException("test")
handler.listenDispatchTracking(mockk<DispatchCompleted>())
Then("An exception is thrown and captured") {
coVerify(exactly = 1) { service.process(ofType<DispatchCompleted>()) }
}
}
}
})
|
udemy-spring-kafka-practice/tracking-service/src/test/kotlin/poc/cx/trackingapp/handler/DispatchTrackingHandlerTest.kt
|
3579075602
|
package poc.cx.trackingapp.util
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.core.test.TestCase
import io.kotest.extensions.spring.SpringTestExtension
import io.kotest.extensions.spring.SpringTestLifecycleMode
abstract class SpringShouldSpec(body: ShouldSpec.() -> Unit = {}) : ShouldSpec(body) {
override fun extensions() = listOf(SpringTestExtension(SpringTestLifecycleMode.Root))
}
fun BehaviorSpec.beforeGiven(initialization: (TestCase) -> Unit) = beforeTest {
if (it.name.prefix?.startsWith("Given") == true) initialization(it)
}
fun BehaviorSpec.beforeWhen(initialization: (TestCase) -> Unit) = beforeTest {
if (it.name.prefix?.startsWith("When") == true) initialization(it)
}
|
udemy-spring-kafka-practice/tracking-service/src/test/kotlin/poc/cx/trackingapp/util/TestUtil.kt
|
1498477288
|
package poc.cx.trackingapp.it
import mikufan.cx.inlinelogging.KInlineLogging
import org.awaitility.Awaitility
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.kafka.config.KafkaListenerEndpointRegistry
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.kafka.test.EmbeddedKafkaBroker
import org.springframework.kafka.test.context.EmbeddedKafka
import org.springframework.kafka.test.utils.ContainerTestUtils
import org.springframework.messaging.handler.annotation.Payload
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.context.ActiveProfiles
import poc.cx.shared.constant.Topics
import poc.cx.shared.message.DispatchCompleted
import poc.cx.shared.message.DispatchPreparing
import poc.cx.trackingapp.message.TrackingStatusUpdated
import poc.cx.trackingapp.service.TrackingService
import poc.cx.trackingapp.util.SpringShouldSpec
import java.time.Duration
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
@SpringBootTest
@ActiveProfiles("test")
@EmbeddedKafka(controlledShutdown = true)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class TrackingServiceIT(
private val testKafkaListener: TestKafkaListener,
private val kafkaTemplate: KafkaTemplate<String, Any>,
private val embeddedKafkaBroker: EmbeddedKafkaBroker,
private val kafkaListenerEndpointRegistry: KafkaListenerEndpointRegistry,
) : SpringShouldSpec({
beforeTest {
testKafkaListener.statusUpdatedCounter.set(0)
kafkaListenerEndpointRegistry.listenerContainers.forEach {
ContainerTestUtils.waitForAssignment(it, embeddedKafkaBroker.partitionsPerTopic)
}
}
context("the tracking service") {
should("send tracking status update messages, upon receiving dispatching preparing tracking message") {
val dispatchPreparing = DispatchPreparing(UUID.randomUUID())
kafkaTemplate.send(Topics.DISPATCH_TRACKING, dispatchPreparing).get()
Awaitility.await().atMost(3, TimeUnit.SECONDS).pollDelay(Duration.ofMillis(100))
.until { testKafkaListener.statusUpdatedCounter.get() == 1 }
}
should("send tracking status update messages, upon receiving dispatching completed tracking message") {
val dispatchCompleted = DispatchCompleted(UUID.randomUUID(), "test item")
kafkaTemplate.send(Topics.DISPATCH_TRACKING, dispatchCompleted).get()
Awaitility.await().atMost(3, TimeUnit.SECONDS).pollDelay(Duration.ofMillis(100))
.until { testKafkaListener.statusUpdatedCounter.get() == 1 }
}
}
}) {
// for some reason, TestComponent is not working here, so we have to use TestConfiguration
@TestConfiguration
class TestConfig {
@Bean
fun testKafkaListener() = TestKafkaListener()
}
class TestKafkaListener {
val statusUpdatedCounter: AtomicInteger = AtomicInteger(0)
@KafkaListener(groupId = "KafkaIntegrationTest", topics = [TrackingService.TRACKING_STATUS_TOPIC])
fun receiveStatusUpdated(@Payload payload: TrackingStatusUpdated) {
log.debug { "Received TrackingStatusUpdated: $payload" }
statusUpdatedCounter.incrementAndGet()
}
}
}
private val log = KInlineLogging.logger()
|
udemy-spring-kafka-practice/tracking-service/src/test/kotlin/poc/cx/trackingapp/it/TrackingServiceIT.kt
|
2953927170
|
package poc.cx.trackingapp.service
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.shouldBe
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import org.springframework.kafka.core.KafkaTemplate
import poc.cx.shared.message.DispatchPreparing
import poc.cx.trackingapp.message.TrackingStatus
import poc.cx.trackingapp.message.TrackingStatusUpdated
import poc.cx.trackingapp.util.beforeGiven
import java.util.*
class TrackingServiceTest : BehaviorSpec({
lateinit var trackingService: TrackingService
lateinit var kafkaTemplate: KafkaTemplate<String, Any>
beforeGiven {
kafkaTemplate = mockk(relaxed = true)
trackingService = TrackingService(kafkaTemplate)
}
Given("A dispatch preparing message and a mocked kafka template") {
val testPreparing = DispatchPreparing(UUID.randomUUID())
coEvery { kafkaTemplate.send(eq(TrackingService.TRACKING_STATUS_TOPIC), any()) } returns mockk {
coEvery { get() } returns mockk()
}
When("The message is processed") {
trackingService.process(testPreparing)
Then("A tracking status message is sent") {
coVerify(exactly = 1) { kafkaTemplate.send(eq(TrackingService.TRACKING_STATUS_TOPIC), ofType<TrackingStatusUpdated>()) }
}
}
}
Given("A dispatch preparing message and a mocked kafka template that throws an exception") {
val testPreparing = DispatchPreparing(UUID.randomUUID())
coEvery { kafkaTemplate.send(eq(TrackingService.TRACKING_STATUS_TOPIC), any()) } throws Exception("test exception")
When("The message is processed") {
val throwFunc = { trackingService.process(testPreparing) }
Then("An exception is thrown") {
shouldThrow<Exception> {
throwFunc()
}.message shouldBe "test exception"
}
}
}
Given("A dispatch completed message and a mocked kafka template") {
val testCompleted = DispatchPreparing(UUID.randomUUID())
coEvery { kafkaTemplate.send(eq(TrackingService.TRACKING_STATUS_TOPIC), any()) } returns mockk {
coEvery { get() } returns mockk()
}
When("The message is processed") {
trackingService.process(testCompleted)
Then("A tracking status message is sent") {
coVerify(exactly = 1) { kafkaTemplate.send(eq(TrackingService.TRACKING_STATUS_TOPIC), ofType<TrackingStatusUpdated>()) }
}
}
}
Given("A dispatch completed message and a mocked kafka template that throws an exception") {
val testCompleted = DispatchPreparing(UUID.randomUUID())
coEvery { kafkaTemplate.send(eq(TrackingService.TRACKING_STATUS_TOPIC), any()) } throws Exception("test exception")
When("The message is processed") {
val throwFunc = { trackingService.process(testCompleted) }
Then("An exception is thrown") {
shouldThrow<Exception> {
throwFunc()
}.message shouldBe "test exception"
}
}
}
})
|
udemy-spring-kafka-practice/tracking-service/src/test/kotlin/poc/cx/trackingapp/service/TrackingServiceTest.kt
|
3638125406
|
package poc.cx.trackingapp.handler
import mikufan.cx.inlinelogging.KInlineLogging
import org.springframework.kafka.annotation.KafkaHandler
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.stereotype.Component
import poc.cx.shared.constant.Topics
import poc.cx.shared.message.DispatchCompleted
import poc.cx.shared.message.DispatchPreparing
import poc.cx.trackingapp.service.TrackingService
@Component
@KafkaListener(
id = "dispatchTrackingConsumerClient",
topics = [Topics.DISPATCH_TRACKING],
groupId = "tracking.dispatch.tracking"
)
class DispatchTrackingHandler(
private val trackingService: TrackingService
) {
@KafkaHandler
fun listenDispatchTracking(payload: DispatchPreparing) {
try {
trackingService.process(payload)
} catch (e: Exception) {
log.error(e) { "Processing failed" }
}
}
@KafkaHandler
fun listenDispatchTracking(payload: DispatchCompleted) {
try {
trackingService.process(payload)
} catch (e: Exception) {
log.error(e) { "Processing failed" }
}
}
}
private val log = KInlineLogging.logger()
|
udemy-spring-kafka-practice/tracking-service/src/main/kotlin/poc/cx/trackingapp/handler/DispatchTrackingHandler.kt
|
3621319771
|
package poc.cx.trackingapp
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class TrackingApplication
fun main(args: Array<String>) {
runApplication<TrackingApplication>(*args)
}
|
udemy-spring-kafka-practice/tracking-service/src/main/kotlin/poc/cx/trackingapp/TrackingApplication.kt
|
1995179479
|
package poc.cx.trackingapp.message
import java.util.*
data class TrackingStatusUpdated(
val orderId: UUID,
val status: TrackingStatus
)
enum class TrackingStatus {
PREPARING, COMPLETED,
}
|
udemy-spring-kafka-practice/tracking-service/src/main/kotlin/poc/cx/trackingapp/message/TrackingStatusUpdated.kt
|
124747782
|
package poc.cx.trackingapp.service
import mikufan.cx.inlinelogging.KInlineLogging
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.stereotype.Service
import poc.cx.shared.message.DispatchCompleted
import poc.cx.shared.message.DispatchPreparing
import poc.cx.trackingapp.message.TrackingStatus
import poc.cx.trackingapp.message.TrackingStatusUpdated
@Service
class TrackingService(
private val kafkaTemplate: KafkaTemplate<String, Any>
) {
companion object {
const val TRACKING_STATUS_TOPIC = "tracking.status"
}
fun process(payload: DispatchPreparing) {
log.info { "Received dispatch preparing message: $payload" }
val statusUpdated = TrackingStatusUpdated(payload.orderId, TrackingStatus.PREPARING)
kafkaTemplate.send(TRACKING_STATUS_TOPIC, statusUpdated).get()
}
fun process(payload: DispatchCompleted) {
log.info { "Received dispatch completed message: $payload" }
val statusUpdated = TrackingStatusUpdated(payload.orderId, TrackingStatus.COMPLETED)
kafkaTemplate.send(TRACKING_STATUS_TOPIC, statusUpdated).get()
}
}
private val log = KInlineLogging.logger()
|
udemy-spring-kafka-practice/tracking-service/src/main/kotlin/poc/cx/trackingapp/service/TrackingService.kt
|
221488926
|
package poc.cx.shared.message
import java.util.*
data class DispatchCompleted(
val orderId: UUID,
val data: String
)
|
udemy-spring-kafka-practice/shared-module/src/main/kotlin/poc/cx/shared/message/DispatchedCompleted.kt
|
1318887424
|
package poc.cx.shared.message
import java.util.UUID
data class DispatchPreparing(
val orderId: UUID
)
|
udemy-spring-kafka-practice/shared-module/src/main/kotlin/poc/cx/shared/message/DispatchPreparing.kt
|
1925717437
|
package poc.cx.shared.constant
object Topics {
const val DISPATCH_TRACKING = "dispatch.tracking"
}
|
udemy-spring-kafka-practice/shared-module/src/main/kotlin/poc/cx/shared/constant/Topics.kt
|
706107505
|
package poc.cx.dispatchapp.handler
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.shouldBe
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import poc.cx.dispatchapp.message.OrderCreated
import poc.cx.dispatchapp.service.DispatchService
import poc.cx.dispatchapp.util.beforeGiven
import java.util.*
class OrderCreatedHandlerTest : BehaviorSpec({
lateinit var handler: OrderCreatedHandler
lateinit var dispatchService: DispatchService
beforeGiven {
dispatchService = mockk(relaxed = true)
handler = OrderCreatedHandler(dispatchService)
}
Given("A test created order and a mocked dispatch service") {
val testEvent = OrderCreated(UUID.randomUUID(), "test item")
val randomKey = UUID.randomUUID().toString()
When("The event is processed") {
handler.listen(randomKey, 0, testEvent)
Then("The dispatch service is called") {
coVerify(exactly = 1) { dispatchService.process(randomKey, testEvent) }
}
}
}
Given("A test created order and a mocked dispatch service that throws an exception") {
val testEvent = OrderCreated(UUID.randomUUID(), "test item")
val key = UUID.randomUUID().toString()
coEvery { dispatchService.process(key, any()) } throws Exception("test exception")
When("The event is processed") {
handler.listen(key, 0, testEvent)
Then("An exception is thrown and captured") {
coVerify(exactly = 1) { dispatchService.process(key, testEvent) }
}
}
}
})
|
udemy-spring-kafka-practice/dispatcher-service/src/test/kotlin/poc/cx/dispatchapp/handler/OrderCreatedHandlerTest.kt
|
3569723657
|
package poc.cx.dispatchapp.util
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.core.test.TestCase
import io.kotest.extensions.spring.SpringExtension
import io.kotest.extensions.spring.SpringTestExtension
import io.kotest.extensions.spring.SpringTestLifecycleMode
abstract class SpringShouldSpec(body: ShouldSpec.() -> Unit = {}) : ShouldSpec(body) {
override fun extensions() = listOf(SpringTestExtension(SpringTestLifecycleMode.Root))
}
fun BehaviorSpec.beforeGiven(initialization: (TestCase) -> Unit) = beforeTest {
if (it.name.prefix?.startsWith("Given") == true) initialization(it)
}
fun BehaviorSpec.beforeWhen(initialization: (TestCase) -> Unit) = beforeTest {
if (it.name.prefix?.startsWith("When") == true) initialization(it)
}
|
udemy-spring-kafka-practice/dispatcher-service/src/test/kotlin/poc/cx/dispatchapp/util/TestUtils.kt
|
3002327575
|
package poc.cx.dispatchapp.it
import io.kotest.matchers.nulls.beNull
import io.kotest.matchers.shouldNot
import io.kotest.matchers.string.beBlank
import mikufan.cx.inlinelogging.KInlineLogging
import org.awaitility.Awaitility.await
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.kafka.annotation.KafkaHandler
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.kafka.config.KafkaListenerEndpointRegistry
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.kafka.support.KafkaHeaders
import org.springframework.kafka.test.EmbeddedKafkaBroker
import org.springframework.kafka.test.context.EmbeddedKafka
import org.springframework.kafka.test.utils.ContainerTestUtils
import org.springframework.messaging.handler.annotation.Header
import org.springframework.messaging.handler.annotation.Payload
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.context.ActiveProfiles
import poc.cx.dispatchapp.handler.OrderCreatedHandler
import poc.cx.dispatchapp.message.OrderCreated
import poc.cx.dispatchapp.message.OrderDispatched
import poc.cx.dispatchapp.service.DispatchService.Companion.ORDER_DISPATCHED_TOPIC
import poc.cx.dispatchapp.util.SpringShouldSpec
import poc.cx.shared.constant.Topics
import poc.cx.shared.message.DispatchCompleted
import poc.cx.shared.message.DispatchPreparing
import java.time.Duration
import java.util.UUID
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
@SpringBootTest
@ActiveProfiles("test")
// add partitions = 1 when if using Spring Boot 3.2.0, 3.2.1, and 3.2.2
// caused by https://github.com/spring-projects/spring-kafka/issues/2978
// see https://github.com/lydtechconsulting/introduction-to-kafka-with-spring-boot/wiki#error-running-integration-tests-with-spring-boot-32
@EmbeddedKafka(controlledShutdown = true)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class OrderDispatchIT(
private val orderDispatchedListener: OrderDispatchedListener,
private val dispatchTrackingListener: DispatchTrackingListener,
private val kafkaTemplate: KafkaTemplate<String, Any>,
private val embeddedKafkaBroker: EmbeddedKafkaBroker,
private val kafkaListenerEndpointRegistry: KafkaListenerEndpointRegistry,
) : SpringShouldSpec({
beforeTest {
dispatchTrackingListener.dispatchPreparingCounter.set(0)
orderDispatchedListener.orderDispatchedCounter.set(0)
dispatchTrackingListener.dispatchCompletedCounter.set(0)
kafkaListenerEndpointRegistry.listenerContainers.forEach {
ContainerTestUtils.waitForAssignment(it, embeddedKafkaBroker.partitionsPerTopic)
}
}
context("the dispatcher service") {
should("send dispatch preparing and order dispatched messages, upon receiving order created message") {
val orderCreated = OrderCreated(UUID.randomUUID(), "an item")
val key = UUID.randomUUID().toString()
kafkaTemplate.send(OrderCreatedHandler.ORDER_CREATED_TOPIC, key, orderCreated).get()
await().atMost(3, TimeUnit.SECONDS).pollDelay(Duration.ofMillis(100))
.until { dispatchTrackingListener.dispatchPreparingCounter.get() == 1 }
await().atMost(1, TimeUnit.SECONDS).pollDelay(Duration.ofMillis(100))
.until { orderDispatchedListener.orderDispatchedCounter.get() == 1 }
await().atMost(1, TimeUnit.SECONDS).pollDelay(Duration.ofMillis(100))
.until { dispatchTrackingListener.dispatchCompletedCounter.get() == 1 }
}
}
}) {
// for some reason, TestComponent is not working here, so we have to use TestConfiguration
@TestConfiguration
class TestConfig {
@Bean
fun orderDispatchedListener() = OrderDispatchedListener()
@Bean
fun dispatchTrackingListener() = DispatchTrackingListener()
}
class OrderDispatchedListener {
val orderDispatchedCounter: AtomicInteger = AtomicInteger(0)
@KafkaListener(groupId = "KafkaIntegrationTest", topics = [ORDER_DISPATCHED_TOPIC])
fun receiveOrderDispatched(
@Header(KafkaHeaders.RECEIVED_KEY) key: String,
@Payload payload: OrderDispatched
) {
log.debug { "Received OrderDispatched: $payload with key $key" }
key shouldNot beBlank()
payload shouldNot beNull()
orderDispatchedCounter.incrementAndGet()
}
}
@KafkaListener(groupId = "KafkaIntegrationTest", topics = [Topics.DISPATCH_TRACKING])
class DispatchTrackingListener {
val dispatchPreparingCounter: AtomicInteger = AtomicInteger(0)
val dispatchCompletedCounter: AtomicInteger = AtomicInteger(0)
@KafkaHandler
fun receiveDispatchPreparing(
@Header(KafkaHeaders.RECEIVED_KEY) key: String,
@Payload payload: DispatchPreparing
) {
log.debug { "Received DispatchPreparing: $payload with key $key" }
key shouldNot beBlank()
payload shouldNot beNull()
dispatchPreparingCounter.incrementAndGet()
}
@KafkaHandler
fun receiveDispatchCompleted(
@Header(KafkaHeaders.RECEIVED_KEY) key: String,
@Payload payload: DispatchCompleted
) {
log.debug { "Received DispatchCompleted: $payload with key $key" }
key shouldNot beBlank()
payload shouldNot beNull()
dispatchCompletedCounter.incrementAndGet()
}
}
}
private val log = KInlineLogging.logger()
|
udemy-spring-kafka-practice/dispatcher-service/src/test/kotlin/poc/cx/dispatchapp/it/OrderDispatchIT.kt
|
1885551652
|
package poc.cx.dispatchapp
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class DispatchApplicationTests {
@Test
fun contextLoads() {
}
}
|
udemy-spring-kafka-practice/dispatcher-service/src/test/kotlin/poc/cx/dispatchapp/DispatchApplicationTests.kt
|
489953790
|
package poc.cx.dispatchapp.service
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.shouldBe
import io.mockk.*
import org.springframework.kafka.core.KafkaTemplate
import poc.cx.dispatchapp.message.OrderCreated
import poc.cx.dispatchapp.message.OrderDispatched
import poc.cx.dispatchapp.util.beforeGiven
import poc.cx.shared.constant.Topics
import poc.cx.shared.message.DispatchCompleted
import poc.cx.shared.message.DispatchPreparing
import java.util.*
import java.util.concurrent.CompletableFuture
class DispatchServiceTest : BehaviorSpec({
lateinit var mockedKafkaTemplate: KafkaTemplate<String, Any>
lateinit var service: DispatchService
beforeGiven {
mockedKafkaTemplate = mockk<KafkaTemplate<String, Any>>(relaxed = true)
service = DispatchService(mockedKafkaTemplate)
}
Given("A test created order and a mocked kafka template") {
val testEvent = OrderCreated(UUID.randomUUID(), "test item")
val key = UUID.randomUUID().toString()
coEvery { mockedKafkaTemplate.send(any(), any(), any()) } returns mockk(relaxed = true) {
coEvery { get() } returns mockk()
}
When("The event is processed") {
service.process(key, testEvent)
Then("Two dispatched events are sent") {
coVerify(exactly = 1) { mockedKafkaTemplate.send(eq(DispatchService.ORDER_DISPATCHED_TOPIC), eq(key), ofType<OrderDispatched>()) }
coVerify(exactly = 1) { mockedKafkaTemplate.send(eq(Topics.DISPATCH_TRACKING), eq(key), ofType<DispatchPreparing>()) }
coVerify(exactly = 1) { mockedKafkaTemplate.send(eq(Topics.DISPATCH_TRACKING), eq(key), ofType<DispatchCompleted>()) }
}
}
}
Given("A test created order and a mocked kafka template that throws an exception") {
val testEvent = OrderCreated(UUID.randomUUID(), "test item")
val key = UUID.randomUUID().toString()
coEvery { mockedKafkaTemplate.send(any(), any(), ofType<OrderDispatched>()) } throws Exception("test exception")
When("The event is processed") {
val throwFunc = { service.process(key, testEvent) }
Then("An exception is thrown") {
shouldThrow<Exception> {
throwFunc()
}.message shouldBe "test exception"
}
}
}
})
|
udemy-spring-kafka-practice/dispatcher-service/src/test/kotlin/poc/cx/dispatchapp/service/DispatchServiceTest.kt
|
3390930161
|
package poc.cx.dispatchapp.handler
import mikufan.cx.inlinelogging.KInlineLogging
import org.springframework.kafka.annotation.KafkaHandler
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.kafka.support.KafkaHeaders
import org.springframework.messaging.handler.annotation.Header
import org.springframework.stereotype.Component
import poc.cx.dispatchapp.message.OrderCreated
import poc.cx.dispatchapp.service.DispatchService
@Component
@KafkaListener(
id = "orderConsumerClient",
topics = [OrderCreatedHandler.ORDER_CREATED_TOPIC],
groupId = "\${spring.kafka.consumer.group-id}"
)
class OrderCreatedHandler(
private val dispatchService: DispatchService
) {
companion object {
const val ORDER_CREATED_TOPIC = "order.created"
}
@KafkaHandler()
fun listen(
@Header(KafkaHeaders.RECEIVED_KEY) key: String,
@Header(KafkaHeaders.RECEIVED_PARTITION) partition: Int,
payload: OrderCreated
) {
log.info { "Received order created event: $payload by $key from partition $partition" }
try {
dispatchService.process(key, payload)
} catch (e: Exception) {
log.error(e) { "Processing failed" }
}
}
}
private val log = KInlineLogging.logger()
|
udemy-spring-kafka-practice/dispatcher-service/src/main/kotlin/poc/cx/dispatchapp/handler/OrderCreatedHandler.kt
|
1039118671
|
package poc.cx.dispatchapp.config
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.support.serializer.ErrorHandlingDeserializer;
import org.springframework.kafka.support.serializer.JsonDeserializer;
import org.springframework.kafka.support.serializer.JsonSerializer;
import poc.cx.dispatchapp.message.OrderCreated
/**
* Showcasing the manual configuration of Kafka consumers and producers
*
* See [KafkaAutoConfiguration] for all autoconfiguration options
*/
//@Configuration
//class DispatchConfig {
//
// @Bean
// fun kafkaListenerContainerFactory(consumerFactory: ConsumerFactory<String, Any>): ConcurrentKafkaListenerContainerFactory<String, Any> {
// val factory = ConcurrentKafkaListenerContainerFactory<String, Any>()
// factory.consumerFactory = consumerFactory
// return factory
// }
//
// @Bean
// fun consumerFactory(@Value("\${kafka.bootstrap-servers}") bootstrapServers: String): ConsumerFactory<String, Any> {
// val config: MutableMap<String, Any> = HashMap()
// config[ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG] = bootstrapServers
// config[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = ErrorHandlingDeserializer::class.java
// config[ErrorHandlingDeserializer.VALUE_DESERIALIZER_CLASS] = JsonDeserializer::class.java
// config[JsonDeserializer.VALUE_DEFAULT_TYPE] = OrderCreated::class.java.canonicalName
// config[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java
// return DefaultKafkaConsumerFactory(config)
// }
//
// @Bean
// fun kafkaTemplate(producerFactory: ProducerFactory<String, Any>): KafkaTemplate<String, Any> {
// return KafkaTemplate(producerFactory)
// }
//
// @Bean
// fun producerFactory(@Value("\${kafka.bootstrap-servers}") bootstrapServers: String): ProducerFactory<String, Any> {
// val config: MutableMap<String, Any> = HashMap()
// config[ProducerConfig.BOOTSTRAP_SERVERS_CONFIG] = bootstrapServers
// config[ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG] = JsonSerializer::class.java
// config[ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG] = StringSerializer::class.java
// return DefaultKafkaProducerFactory(config)
// }
//}
|
udemy-spring-kafka-practice/dispatcher-service/src/main/kotlin/poc/cx/dispatchapp/config/DispatchConfig.kt
|
3392591120
|
package poc.cx.dispatchapp
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class DispatchApplication
fun main(args: Array<String>) {
runApplication<DispatchApplication>(*args)
}
|
udemy-spring-kafka-practice/dispatcher-service/src/main/kotlin/poc/cx/dispatchapp/DispatchApplication.kt
|
1977507751
|
package poc.cx.dispatchapp.message
import java.util.UUID
data class OrderCreated(
val orderId: UUID,
val item: String,
)
|
udemy-spring-kafka-practice/dispatcher-service/src/main/kotlin/poc/cx/dispatchapp/message/OrderCreated.kt
|
626722992
|
package poc.cx.dispatchapp.message
import java.util.*
data class OrderDispatched(
val orderId: UUID,
val processedBy: UUID,
val notes: String
)
|
udemy-spring-kafka-practice/dispatcher-service/src/main/kotlin/poc/cx/dispatchapp/message/OrderDispatched.kt
|
3242068728
|
package poc.cx.dispatchapp.service
import mikufan.cx.inlinelogging.KInlineLogging
import org.springframework.kafka.core.KafkaTemplate
import org.springframework.stereotype.Service
import poc.cx.dispatchapp.message.OrderCreated
import poc.cx.dispatchapp.message.OrderDispatched
import poc.cx.shared.constant.Topics
import poc.cx.shared.message.DispatchCompleted
import poc.cx.shared.message.DispatchPreparing
import java.util.UUID
@Service
class DispatchService(
private val kafkaTemplate: KafkaTemplate<String, Any>
) {
companion object {
const val ORDER_DISPATCHED_TOPIC = "order.dispatched"
val APP_ID = UUID.randomUUID()
}
fun process(key: String, payload: OrderCreated) {
sendDispatched(key, payload)
sendPreparing(key, payload)
sendDispatchCompleted(key, payload)
}
private fun sendDispatched(key: String, payload: OrderCreated) {
val orderDispatched = OrderDispatched(payload.orderId, APP_ID, "Dispatched: ${payload.item}")
log.info { "Sending dispatched event: $orderDispatched by $APP_ID at key $key" }
kafkaTemplate.send(ORDER_DISPATCHED_TOPIC, key, orderDispatched).get()
}
private fun sendPreparing(key: String, payload: OrderCreated) {
val dispatchPreparing = DispatchPreparing(payload.orderId)
kafkaTemplate.send(Topics.DISPATCH_TRACKING, key, dispatchPreparing).get()
}
private fun sendDispatchCompleted(key: String, payload: OrderCreated) {
val dispatchCompleted = DispatchCompleted(payload.orderId, "Completed: ${payload.item}")
kafkaTemplate.send(Topics.DISPATCH_TRACKING, key, dispatchCompleted).get()
}
}
private val log = KInlineLogging.logger()
|
udemy-spring-kafka-practice/dispatcher-service/src/main/kotlin/poc/cx/dispatchapp/service/DispatchService.kt
|
215201827
|
package nonozi.freefamilytracking
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("nonozi.freefamilytracking", appContext.packageName)
}
}
|
FreeFamilyTracking/app/src/androidTest/java/nonozi/freefamilytracking/ExampleInstrumentedTest.kt
|
2894510523
|
package nonozi.freefamilytracking
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)
}
}
|
FreeFamilyTracking/app/src/test/java/nonozi/freefamilytracking/ExampleUnitTest.kt
|
3360020797
|
package nonozi.freefamilytracking
import android.util.Log
import retrofit2.Call
class ApiCalls(private val apiInterface: ApiInterface) {
val heros: Call<List<GetRequestModel?>?>?
get() = apiInterface.heros
fun postHeros(postRequestModel: PostRequestModel?): Call<PostResponseModel?>? {
return apiInterface.postHeros(postRequestModel)
}
fun getCoordinates(postRequestMap: PostRequestMap?): Call<List<PostResponseMap?>?> {
return apiInterface.getCoordinates(postRequestMap)
}
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/ApiCalls.kt
|
1583196953
|
package nonozi.freefamilytracking
import androidx.appcompat.widget.Toolbar
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat.startActivity
import org.osmdroid.config.Configuration
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.Marker
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import nonozi.freefamilytracking.PostRequestMap
class MapActivity : AppCompatActivity() {
private lateinit var mapView: MapView
private var retrofitBuilder: RetrofitBuilder? = RetrofitBuilder.instance
private val handler = Handler(Looper.getMainLooper())
private val refreshInterval = 5 * 1000L // 15 secondes
private fun refreshActivity() {
// Mettez à jour vos données ou effectuez d'autres opérations nécessaires
fetchCoordinatesFromAPI()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_map)
val toolbar: Toolbar = findViewById(R.id.my_toolbar)
setSupportActionBar(toolbar)
// Initialiser osmdroid
val ctx = applicationContext
Configuration.getInstance().load(ctx, getSharedPreferences("osmdroid", MODE_PRIVATE))
// Récupérer la référence de la MapView
mapView = findViewById(R.id.mapView)
// Configurer le centre et le zoom de la carte
val mapController = mapView.controller
val startPoint = GeoPoint(48.8583, 2.2944) // Coordonnées de Paris (par défaut)
mapController.setCenter(startPoint)
mapController.setZoom(3.0)
// Appel à l'API pour récupérer les coordonnées
// fetchCoordinatesFromAPI()
startPeriodicRefresh()
}
// Fonction pour démarrer la planification des actualisations
private fun startPeriodicRefresh() {
// Utilisez le Handler pour exécuter la fonction de rafraîchissement toutes les 15 secondes
handler.postDelayed(object : Runnable {
override fun run() {
refreshActivity() // Appeler la fonction de rafraîchissement
handler.postDelayed(this, refreshInterval) // Planifier la prochaine actualisation
}
}, refreshInterval)
}
private fun fetchCoordinatesFromAPI() {
retrofitBuilder?.build(retrofitBuilder?.BASE_URL_POST)
val postRequestMap = PostRequestMap("nonozi", "HQ7dJ9uw")
val call: Call<List<PostResponseMap?>?> = retrofitBuilder!!.callApi().getCoordinates(postRequestMap)
call!!.enqueue(object : Callback<List<PostResponseMap?>?> {
override fun onResponse(
call: Call<List<PostResponseMap?>?>,
response: Response<List<PostResponseMap?>?>
) {
val responseBody = response.body()
if (response.isSuccessful && responseBody != null) {
Log.d("Response", "$responseBody")
// Traiter la réponse et afficher les marqueurs sur la carte
displayMarkers(responseBody)
centerMapOnMarkers(responseBody)
} else {
Log.d("Response", "Response Erreur")
// Ici, vous pouvez mettre le code pour gérer l'erreur
}
}
override fun onFailure(call: Call<List<PostResponseMap?>?>, t: Throwable) {
t.printStackTrace()
// Enregistrer l'exception dans les logs
Log.e("MapActivity", "Erreur lors de la requête API", t)
// Vous pouvez également afficher un message Toast pour informer l'utilisateur de l'échec de la requête
Toast.makeText(this@MapActivity, "Erreur lors de la requête API: ${t.message}", Toast.LENGTH_SHORT).show()
}
})
}
private fun getMarkerColor(name: String): Int {
return when (name) {
"nonozi" -> Color.BLUE
"celine" -> Color.RED
"Clara" -> Color.MAGENTA // Rose
else -> Color.GRAY
}
}
fun createMarkerIcon(color: Int, size: Int): Drawable {
// Créer un bitmap avec la couleur spécifiée et la taille donnée
val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.color = color
// Dessiner un cercle dans le bitmap avec le rayon approprié
val radius = size / 2f
canvas.drawCircle(radius, radius, radius * 0.8f, paint) // Ajustez le rayon selon votre besoin
// Convertir le bitmap en Drawable
return BitmapDrawable(bitmap)
}
private fun displayMarkers(responseBody: List<PostResponseMap?>) {
// Supprimer les marqueurs existants
mapView.overlays.clear()
// Ajouter des marqueurs pour chaque point avec des descriptifs
for (point in responseBody) {
val latitude = point?.latitude ?: continue
val longitude = point?.longitude ?: continue
val name = point?.name ?: continue
val color = getMarkerColor(name)
val markerIcon = createMarkerIcon(color,200)
val marker = Marker(mapView)
marker.position = GeoPoint(latitude, longitude)
marker.title = name
marker.snippet = "Latitude: $latitude, Longitude: $longitude"
Log.i("DisplayMarkers","Marker=Name:$name et lat=$latitude - long=$longitude")
marker.icon = markerIcon
mapView.overlays.add(marker)
}
// Rafraîchir la carte pour afficher les nouveaux marqueurs
mapView.invalidate()
}
fun centerMapOnMarkers(markers: List<PostResponseMap?>) {
val mapController = mapView.controller
val points = mutableListOf<GeoPoint>()
var totalLat = 0.0
var totalLon = 0.0
// Ajoutez les marqueurs sur la carte et collectez les GeoPoint
for (marker in markers) {
val latitude = marker?.latitude ?: continue
val longitude = marker.longitude ?: continue
val geoPoint = GeoPoint(latitude, longitude)
points.add(geoPoint)
totalLat += latitude
totalLon += longitude
}
if (points.isNotEmpty()) {
// Calcul de la moyenne des coordonnées
val avgLat = totalLat / points.size
val avgLon = totalLon / points.size
val center = GeoPoint(avgLat, avgLon)
// Centrer la carte sur la moyenne de tous les points
mapController.setCenter(center)
// Détermination du niveau de zoom en fonction de l'éloignement total de tous les points
val zoomLevel = determineZoomLevel(points)
// Appliquer le niveau de zoom
mapController.setZoom(zoomLevel.toDouble())
// Ajout du marqueur pour afficher la distance totale
val totalDistance = calculateTotalDistance(points)
val totalDistanceMarker = Marker(mapView)
// Définir la position du marqueur en haut à droite de la carte
totalDistanceMarker.position = GeoPoint(mapView.boundingBox.latNorth, mapView.boundingBox.lonEast)
totalDistanceMarker.setAnchor(Marker.ANCHOR_RIGHT, Marker.ANCHOR_TOP)
totalDistanceMarker.title = "Distance totale"
totalDistanceMarker.snippet = "Distance: $totalDistance m"
// A RETRAVAILLER mapView.overlays.add(totalDistanceMarker)
} else {
// Si aucun point n'est disponible, laisser la carte avec le centre et le zoom par défaut
mapController.setZoom(14.0)
}
}
// Calculer le centre des marqueurs
fun calculateCenter(markers: List<PostResponseMap?>): GeoPoint {
var totalLat = 0.0
var totalLon = 0.0
for (marker in markers) {
totalLat += marker!!.latitude!!
totalLon += marker.longitude!!
}
val avgLat = totalLat / markers.size
val avgLon = totalLon / markers.size
return GeoPoint(avgLat, avgLon)
}
fun determineZoomLevel(points: List<GeoPoint>): Int {
val totalDistance = calculateTotalDistance(points)
return when {
totalDistance <= 1000 -> 15 // Distance totale <= 1km
totalDistance <= 5000 -> 14
totalDistance <= 15000 -> 13
totalDistance <= 30000 -> 12 // OK
totalDistance <= 50000 -> 11
totalDistance <= 100000 -> 10
else -> 8 // Distance totale > 10km
}
}
fun calculateTotalDistance(points: List<GeoPoint>): Double {
var totalDistance = 0.0
for (i in 0 until points.size - 1) {
totalDistance += points[i].distanceToAsDouble(points[i + 1])
}
return totalDistance
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.toolbar, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_favorite -> {
// Ouvrir l'activité correspondante à l'icône "Accueil"
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
true
}
R.id.action_configuration -> {
// Ouvrir l'activité correspondante à l'icône "Parameters"
val intent = Intent(this, ConfigurationActivity::class.java)
startActivity(intent)
true
}
R.id.action_map -> {
// Ouvrir l'activité correspondante à l'icône "Map"
val intent = Intent(this, MapActivity::class.java)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onDestroy() {
super.onDestroy()
// Arrêtez la planification des actualisations
handler.removeCallbacksAndMessages(null)
}
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/MapActivity.kt
|
1401531127
|
package nonozi.freefamilytracking
import android.content.pm.PackageManager
import android.Manifest
import android.content.Context
import android.content.Intent
import android.location.Location
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.activity.viewModels
import androidx.core.app.ActivityCompat
import com.google.android.gms.location.LocationServices
import java.util.Timer
import com.google.android.gms.location.FusedLocationProviderClient
import androidx.appcompat.app.AppCompatActivity
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import java.text.SimpleDateFormat
import java.util.Date
import retrofit2.Callback
import retrofit2.Call
import retrofit2.Response
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
// import androidx.compose.runtime.Composable
// import androidx.compose.runtime.mutableStateOf
// import androidx.compose.runtime.*
import nonozi.freefamilytracking.DataStoreManager
import nonozi.freefamilytracking.MyBackgroundService.Companion.EXTRA_PERIOD
const val LOCATION_PERMISSION_REQUEST = 1001
private lateinit var txtResultValue: TextView
class MainActivity : AppCompatActivity() {
private lateinit var dataStoreManager: DataStoreManager
//private lateinit var dataStoreManager: DataStoreManager // Instance unique du DataStoreManager
private var retrofitBuilder: RetrofitBuilder? = RetrofitBuilder.instance
private val handler = Handler()
private val timer = Timer()
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var txtSavedValue: TextView
private var currentLatitude: Double = 0.0
private var currentLongitude: Double = 0.0
//val PERIOD_KEY = intPreferencesKey("period")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar =findViewById(R.id.my_toolbar)
setSupportActionBar(toolbar)
// Initialiser le DataStoreManager en tant que singleton
// dataStoreManager = DataStoreManager.getInstance(this)
dataStoreManager = DataStoreManager.getInstance(this)
txtResultValue = findViewById(R.id.txtResultValue)
// txtResultValue.text = "Service stopped"
updateServiceStatus(txtResultValue)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
//val sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE)
//val editor = sharedPreferences.edit()
val btnStartService = findViewById<TextView>(R.id.btnStartService)
val btnStopService = findViewById<TextView>(R.id.btnStopService)
//val phonename = "Arno_Code1234"
//editor.putString("phonename", phonename)
//editor.apply()
if (!checkLocationPermission()) {
requestLocationPermission()
}
btnStartService.setOnClickListener {
lifecycleScope.launch {
try {
// Récupérer la période depuis le DataStore
val savedPeriod = dataStoreManager.readPeriod().first()
// Récupérer savedName et savedGroupName depuis le DataStore
val savedName = dataStoreManager.readName().first() ?: "Unknown"
val savedGroupName = dataStoreManager.readGroupName().first() ?: "Unknown"
// Démarrer le service avec l'intervalle récupéré et les valeurs de savedName et savedGroupName
val serviceIntent = Intent(this@MainActivity, MyBackgroundService::class.java).apply {
putExtra(EXTRA_PERIOD, savedPeriod)
putExtra(NAME_KEY, savedName)
putExtra(GROUP_NAME_KEY, savedGroupName)
}
startService(serviceIntent)
updateServiceStatus(txtResultValue)
} catch (e: Exception) {
Log.e("BTNSTARTSERVICE", "Error retrieving period from DataStore: ${e.message}")
}
}
}
btnStopService.setOnClickListener {
stopService(Intent(this, MyBackgroundService::class.java))
updateServiceStatus(txtResultValue)
}
} // end fun OnCreate
companion object {
const val NAME_KEY = "name"
const val GROUP_NAME_KEY = "groupName"
}
private fun checkLocationPermission(): Boolean {
return ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
private fun requestLocationPermission() {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
LOCATION_PERMISSION_REQUEST
)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == LOCATION_PERMISSION_REQUEST) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// La permission a été accordée, vous pouvez maintenant accéder à la localisation
} else {
// La permission a été refusée, vous pouvez informer l'utilisateur ou prendre d'autres mesures
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.toolbar, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_favorite -> {
// Ouvrir l'activité correspondante à l'icône "Accueil"
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
true
}
R.id.action_configuration -> {
// Ouvrir l'activité correspondante à l'icône "Parameters"
val intent = Intent(this, ConfigurationActivity::class.java)
startActivity(intent)
true
}
R.id.action_map -> {
// Ouvrir l'activité correspondante à l'icône "Map"
val intent = Intent(this, MapActivity::class.java)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun updateServiceStatus(textView: TextView) {
if (MyBackgroundService.isServiceRunning(this)) {
textView.text = "Service is running"
} else {
textView.text = "Service stopped"
}
}
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/MainActivity.kt
|
1498224301
|
package nonozi.freefamilytracking
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.FormUrlEncoded
import android.util.Log
interface ApiInterface {
@get:GET("/api/index.php")
val heros: Call<List<GetRequestModel?>?>?
@POST("/api/index.php")
fun postHeros(@Body postRequestModel: PostRequestModel?): Call<PostResponseModel?>?
@POST("/api/getcoordinates.php")
fun getCoordinates(@Body postRequestMap: PostRequestMap?): Call<List<PostResponseMap?>?>
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/ApiInterface.kt
|
2780362423
|
package nonozi.freefamilytracking
import android.content.Context
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class DataStoreManager(private val context: Context) {
val IMAGE_PATH_KEY = stringPreferencesKey("imagePath")
suspend fun saveImagePath(imagePath: String) {
Log.d("DataStoreManager", "Enregistrement du chemin de l'image $imagePath dans le DataStore")
context.dataStore.edit { preferences ->
preferences[IMAGE_PATH_KEY] = imagePath
}
}
suspend fun readImagePath(): Flow<String?> {
return context.dataStore.data.map { preferences ->
preferences[IMAGE_PATH_KEY]
}
}
suspend fun readPeriod(): Flow<Int> {
return context.dataStore.data.map { preferences ->
preferences[PERIOD_KEY] ?: 0
}
}
suspend fun readName(): Flow<String?> {
return context.dataStore.data.map { preferences ->
preferences[NAME_KEY]
}
}
suspend fun readGroupName(): Flow<String?> {
return context.dataStore.data.map { preferences ->
preferences[GROUP_NAME_KEY]
}
}
suspend fun savePeriod(period: Int) {
Log.d("DataStoreManager", "Stockage dans le DataStore de $period")
context.dataStore.edit { preferences ->
preferences[PERIOD_KEY] = period
}
}
suspend fun saveName(name: String) {
Log.d("DataStoreManager", "Enregistrement du nom $name dans le DataStore")
context.dataStore.edit { preferences ->
preferences[NAME_KEY] = name
}
}
suspend fun saveGroupName(groupName: String) {
Log.d("DataStoreManager", "Enregistrement du nom du groupe $groupName dans le DataStore")
context.dataStore.edit { preferences ->
preferences[GROUP_NAME_KEY] = groupName
}
}
suspend fun observePeriodChanges(): Flow<Int> {
return context.dataStore.data.map { preferences ->
preferences[PERIOD_KEY] ?: 0
}
}
suspend fun saveConfiguration(period: Int, name: String, groupName: String) {
Log.d("DataStoreManager", "Enregistrement des valeurs $period, $name et $groupName dans le DataStore")
context.dataStore.edit { preferences ->
preferences[PERIOD_KEY] = period
preferences[NAME_KEY] = name
preferences[GROUP_NAME_KEY] = groupName
}
}
companion object {
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "PreferenceDataStore")
private val PERIOD_KEY = intPreferencesKey("period")
val NAME_KEY = stringPreferencesKey("name")
val GROUP_NAME_KEY = stringPreferencesKey("groupName")
@Volatile
private var instance: DataStoreManager? = null
fun getInstance(context: Context): DataStoreManager {
return instance ?: synchronized(this) {
instance ?: DataStoreManager(context.applicationContext).also { instance = it }
}
}
}
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/DataStoreManager.kt
|
980654131
|
package nonozi.freefamilytracking
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import nonozi.freefamilytracking.DataStoreManager
class ConfigurationActivity : AppCompatActivity() {
private lateinit var dataStoreManager: DataStoreManager
// private lateinit var txtLocation: TextView
private lateinit var edtPeriod: EditText
private lateinit var btnSavePeriod: Button
private lateinit var txtSavedValue: TextView
private lateinit var txtResultValue: TextView
private lateinit var txtName: TextView
private lateinit var txtGroupName: TextView
private lateinit var edtName: EditText
private lateinit var edtGroupName: EditText
// image
private lateinit var btnChooseImage: Button
private lateinit var imgSelectedImage: ImageView
val PERIOD_KEY = intPreferencesKey("period")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_configuration)
btnChooseImage = findViewById(R.id.btnChooseImage)
val toolbar: Toolbar =findViewById(R.id.my_toolbar)
setSupportActionBar(toolbar)
dataStoreManager = DataStoreManager(this)
val sharedPreferences = getSharedPreferences("config", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
// Initialiser les vues
edtPeriod = findViewById(R.id.edtPeriod)
btnSavePeriod = findViewById(R.id.btnSavePeriod)
txtSavedValue = findViewById(R.id.txtSavedValue)
txtName = findViewById(R.id.txtName)
txtGroupName = findViewById(R.id.txtGroupName)
edtName = findViewById(R.id.edtName) // Initialiser le champ name
edtGroupName = findViewById(R.id.edtGroupName)
// Lire les valeurs enregistrées et les afficher
lifecycleScope.launchWhenStarted {
val savedValue = dataStoreManager.readPeriod().first()
txtSavedValue.text = "$savedValue"
val savedName = dataStoreManager.readName().first()
val savedGroupName = dataStoreManager.readGroupName().first()
// Mise à jour des TextView avec les valeurs lues
txtName.text = savedName
txtGroupName.text = savedGroupName
btnSavePeriod.setOnClickListener {
val period = edtPeriod.text.toString().toIntOrNull()
val name = edtName.text.toString()
val groupName = edtGroupName.text.toString()
// Vérifiez la validité de chaque champ individuellement
val isPeriodValid = period != null
val isNameValid = name.isNotEmpty()
val isGroupNameValid = groupName.isNotEmpty()
// Si au moins un champ requis est vide, affichez un message d'erreur
if (!(isPeriodValid || isNameValid || isGroupNameValid)) {
Toast.makeText(this@ConfigurationActivity, "Veuillez remplir au moins un champ correctement", Toast.LENGTH_SHORT).show()
} else {
// Si tous les champs requis sont remplis, procédez à la mise à jour
lifecycleScope.launch {
if (isPeriodValid) {
dataStoreManager.savePeriod(period!!)
txtSavedValue.text = "$period"
}
if (isNameValid) {
dataStoreManager.saveName(name)
txtName.text = name
}
if (isGroupNameValid) {
dataStoreManager.saveGroupName(groupName)
txtGroupName.text = groupName
}
}
}
}
} // lifecycleScope
} // OnCreate
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.toolbar, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_favorite -> {
// Ouvrir l'activité correspondante à l'icône "Accueil"
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
true
}
R.id.action_configuration -> {
// Ouvrir l'activité correspondante à l'icône "Parameters"
val intent = Intent(this, ConfigurationActivity::class.java)
startActivity(intent)
true
}
R.id.action_map -> {
// Ouvrir l'activité correspondante à l'icône "Map"
val intent = Intent(this, MapActivity::class.java)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
}
companion object {
private const val PICK_IMAGE_REQUEST = 1
}
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/ConfigurationActivity.kt
|
947729861
|
package nonozi.freefamilytracking
import android.util.Log
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.FormUrlEncoded
import retrofit2.converter.scalars.ScalarsConverterFactory
import retrofit2.create
class RetrofitBuilder private constructor() {
var BASE_URL_POST = "https://nonozi2.ddns.net"
private var builder: Retrofit.Builder? = null
public var apiInterface: ApiInterface? = null
companion object {
var instance: RetrofitBuilder? = null
get() {
if(field == null) {
field = RetrofitBuilder()
}
return field
}
private set
}
//builder!!.addConverterFactory(GsonConverterFactory.create())
//builder!!.addConverterFactory(ScalarsConverterFactory.create())
fun build(url: String?) {
builder = Retrofit.Builder()
builder!!.baseUrl(url.toString())
builder!!.addConverterFactory(GsonConverterFactory.create())
val retrofit = builder!!.build()
apiInterface = retrofit.create(ApiInterface::class.java)
Log.d("RetrofitBuilder", "build")
}
fun callApi(): ApiCalls {
Log.d("RetrofitBuilder", "Creating ApiCalls instance")
return ApiCalls(apiInterface!!)
}
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/RetrofitBuilder.kt
|
1673020285
|
package nonozi.freefamilytracking
class PostResponseModel(
private var latitude: String,
private var longitude: String,
private var phonename: String,
) {
override fun toString(): String {
return "Résponse du POST:\n" +
"\t" + "phonename=" + phonename + "\n" +
"\t" + "lat=" + latitude + "\n" +
"\t" + "lon=" + longitude
}
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/PostResponseModel.kt
|
3195056213
|
package nonozi.freefamilytracking
class PostResponseMap(
var id: Int,
var latitude: Double?,
var longitude: Double?,
var name: String
) {
override fun toString(): String {
return "id=$id\n" +
"\t" + "name=$name\n" +
"\t" + "latitude=$latitude\n" +
"\t" + "longitude=$longitude"
}
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/PostResponseMap.kt
|
1034307194
|
package nonozi.freefamilytracking
import android.Manifest
import android.app.ActivityManager
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.PowerManager
import android.util.Log
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import kotlinx.coroutines.flow.first
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.*
class MyBackgroundService : Service() {
var timer: Timer? = null
private lateinit var fusedLocationClient: FusedLocationProviderClient
private var retrofitBuilder: RetrofitBuilder? = RetrofitBuilder.instance
private var currentLatitude: Double = 0.0
private var currentLongitude: Double = 0.0
private val channelId = "MyForegroundServiceChannel"
private val handler = Handler()
private var INTERVAL = 60000L
val dataStoreManager = DataStoreManager(this)
private lateinit var savedName: String
private lateinit var savedGroupName: String
companion object {
fun isServiceRunning(context: Context): Boolean {
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
for (service in manager.getRunningServices(Int.MAX_VALUE)) {
if (MyBackgroundService::class.java.name == service.service.className) {
return true
}
}
return false
}
const val ACTION_UPDATE_PERIOD = "nonozi.freefamilytracking.UPDATE_PERIOD"
const val EXTRA_PERIOD = "period"
const val NAME_KEY = "name"
const val GROUP_NAME_KEY = "groupName"
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.d("MyBackgroundService", "Starting service...")
startForeground(1, createNotification()) // Ajoutez cette ligne pour démarrer le service en mode foreground
val savedPeriod = intent?.getIntExtra(EXTRA_PERIOD, 60000) ?: 60000 // default 60 sec
INTERVAL = savedPeriod.toLong()
savedName = intent?.getStringExtra(NAME_KEY) ?: "Unknown"
savedGroupName = intent?.getStringExtra(GROUP_NAME_KEY) ?: "Unknown"
Log.d("MyBackgroundService", "savedName=$savedName, savedGroupName=$savedGroupName")
// Initialize fusedLocationClient
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
if (intent != null && intent.action == ACTION_UPDATE_PERIOD) {
var newPeriod = intent.getIntExtra(EXTRA_PERIOD, 3000)
//var newPeriod = intent?.getIntExtra(EXTRA_PERIOD, INTERVAL)?: INTERVAL.toLong()
handler.removeCallbacksAndMessages(null)
Log.d("MyBackgroundService", "Update INTERVAL to newperiod = $newPeriod")
INTERVAL = newPeriod.toLong()
}
startSendingLocationUpdates()
return START_STICKY
} // OnStartCoomand
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onDestroy() {
Log.d("MyBackgroundService","Arrêt du service demandé, destruction des différentes instances")
/* if (wakeLock.isHeld) {
wakeLock.release()
Log.d("MyBackgroundService", "Wake lock libéré")
} */
super.onDestroy()
stopSendingLocationUpdates()
timer?.cancel()
}
/* private fun startSendingLocationUpdates() {
val newtimer = Timer()
newtimer.scheduleAtFixedRate(object : TimerTask() {
override fun run() {
Log.d("MyBackgroundService", "Sending location update...")
if (checkLocationPermission()) {
getLastLocation { location ->
location?.let {
currentLatitude = location.latitude
currentLongitude = location.longitude
Log.d("MyBackgroundService", "Latitude: $currentLatitude, Longitude: $currentLongitude")
sendPostRequest()
}
}
}
}
}, 0, INTERVAL)
} */
private val locationUpdateRunnable = object : Runnable {
override fun run() {
Log.d("MyBackgroundService", "Sending location update...")
if (checkLocationPermission()) {
getLastLocation { location ->
location?.let {
currentLatitude = location.latitude
currentLongitude = location.longitude
Log.d("MyBackgroundService", "Latitude: $currentLatitude, Longitude: $currentLongitude")
sendPostRequest()
}
}
}
handler.postDelayed(this, INTERVAL)
}
}
private fun startSendingLocationUpdates() {
// wakeLock.acquire()
Log.d("MyBackgroundService", "Wake lock acquired")
handler.post(locationUpdateRunnable)
}
private fun checkLocationPermission(): Boolean {
return ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) == PackageManager.PERMISSION_GRANTED
}
private fun stopSendingLocationUpdates() {
handler.removeCallbacksAndMessages(null)
}
interface LocationUpdateListener {
fun onLocationUpdate(dateTime: String)
}
// Interface de rappel pour mon activité principale
interface PostRequestListener {
fun onPostRequest(dateTime: String)
}
private fun sendPostRequest() {
val currentDateTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())
retrofitBuilder?.build(retrofitBuilder?.BASE_URL_POST)
val postRequestModel = PostRequestModel(savedName, savedGroupName, currentLatitude.toString(), currentLongitude.toString(), currentDateTime)
val call = retrofitBuilder!!.callApi().postHeros(postRequestModel)
Log.d("ApiCall", "Appel de l'API PostRequestModel")
call!!.enqueue(object : Callback<PostResponseModel?> {
override fun onResponse(call: Call<PostResponseModel?>, response: Response<PostResponseModel?>) {
val responseBody = response.body()
if (response.isSuccessful && responseBody != null) {
// Ici, vous pouvez mettre le code pour traiter la réponse
} else {
// Ici, vous pouvez mettre le code pour gérer l'erreur
}
}
override fun onFailure(call: Call<PostResponseModel?>, t: Throwable) {
// Ici, vous pouvez mettre le code pour gérer l'échec de la requête
}
})
}
/* private fun createNotification(): Notification {
createNotificationChannel()
val intent = Intent(this, MainActivity::class.java)
intent.action = Intent.ACTION_MAIN
intent.addCategory(Intent.CATEGORY_LAUNCHER)
val pendingIntent = PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
return NotificationCompat.Builder(this, channelId)
.setContentTitle("Free Family Tracking")
.setContentText("Start service")
.setSmallIcon(R.drawable.ic_launcher_breizh)
.setContentIntent(pendingIntent)
.build()
} */
private fun createNotification(): Notification {
createNotificationChannel()
val intent = Intent(this, MainActivity::class.java)
intent.action = Intent.ACTION_MAIN
intent.addCategory(Intent.CATEGORY_LAUNCHER)
val pendingIntent = PendingIntent.getActivity(
this,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
return NotificationCompat.Builder(this, channelId)
.setContentTitle("Free Family Tracking")
.setContentText("Start service")
.setSmallIcon(R.drawable.ic_launcher_breizh)
.setContentIntent(pendingIntent)
.build()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
channelId,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
private fun getLastLocation(callback: (Location?) -> Unit) {
if (checkLocationPermission()) {
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
callback.invoke(location)
}
} else {
callback.invoke(null)
}
}
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/BackgroundService.kt
|
2275969026
|
package nonozi.freefamilytracking
data class PostRequestModel(
val name: String,
val groupName: String,
val latitude: String,
val longitude: String,
val timestamp: String
)
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/PostRequestModel.kt
|
3761505780
|
package nonozi.freefamilytracking
data class PostRequestMap(
val name: String,
val groupname: String
)
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/PostRequestMap.kt
|
3434949417
|
package nonozi.freefamilytracking
class GetRequestModel (
private var name: String, private var id: String
){
override fun toString(): String {
return "GetRequestModel{" +
"name=" + name + '\'' +
"id=" + id + '\'' +
'}'
}
}
|
FreeFamilyTracking/app/src/main/java/nonozi/freefamilytracking/GetRequestModel.kt
|
3942389064
|
package io.github.theunic.kcommand.core
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.shouldBe
class SimpleMessageBusTest : BehaviorSpec({
given("A Simple Message Bus") {
val messageBus = SimpleMessageBus<String, Int>()
`when`("A subscription is done") {
messageBus.subscribe(String::class) { it.length }
and("A message is sent to the bus") {
val message = "Hello, world!"
val result = messageBus.handle(message).await()
then("The result should be the length of the message") {
result shouldBe message.length
}
}
}
}
})
|
kcommand/kcommand-core/src/test/kotlin/io/github/theunic/kcommand/core/SimpleMessageBusTest.kt
|
527682068
|
package io.github.theunic.kcommand.core
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.BehaviorSpec
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.test.runTest
class DefaultMessageBusTest : BehaviorSpec({
val messageBus = DefaultMessageBus<String, Int>()
given("A message bus with no subscriptions") {
`when`("a message is sent to the bus") {
val message = "testCommand"
then("it should throw an exception") {
runTest {
shouldThrow<IllegalArgumentException> {
val result = messageBus.handle(message)
result.await()
}
}
}
}
}
given("A message bus with a subscription") {
val messageHandler: suspend (String) -> Int = { it.length }
messageBus.subscribe(String::class, messageHandler)
`when`("a message sent to the message bus") {
val message = "hello"
then("it should handle the message using the subscribed handler") {
runTest {
val result = messageBus.handle(message)
result.await() shouldBe 5
}
}
}
}
given("a message bus with middleware") {
val modifyingMiddleware =
object : Middleware<String, String> {
override suspend fun handle(
message: String,
next: suspend (String) -> CompletableDeferred<String>,
): CompletableDeferred<String> {
return next(message.uppercase())
}
}
val newMessageBus = DefaultMessageBus(listOf(modifyingMiddleware))
val messageHandler = { command: String -> command }
newMessageBus.subscribe(String::class, messageHandler)
`when`("A message goes through middleware") {
val message = "hello"
then("it should be modified by the middleware before handling") {
runTest {
val result = newMessageBus.handle(message)
result.await() shouldBe "HELLO"
}
}
}
}
})
|
kcommand/kcommand-core/src/test/kotlin/io/github/theunic/kcommand/core/DefaultMessageBusTest.kt
|
1862054431
|
package io.github.theunic.kcommand.core
import kotlinx.coroutines.CompletableDeferred
import kotlin.reflect.KClass
interface MessageBus<M : Any, R> {
suspend fun handle(message: M): CompletableDeferred<R>
fun subscribe(
messageType: KClass<out M>,
messageHandler: suspend (M) -> R,
)
}
|
kcommand/kcommand-core/src/main/kotlin/io/github/theunic/kcommand/core/MessageBus.kt
|
850941450
|
package io.github.theunic.kcommand.core
import kotlinx.coroutines.CompletableDeferred
class SimpleMessageBus<M : Any, R : Any>(
middlewares: List<Middleware<M, R>> = listOf(),
) : AbstractMessageBus<M, R>(middlewares) {
override suspend fun handle(message: M): CompletableDeferred<R> {
val deferred = CompletableDeferred<R>()
processCommand(message, deferred)
return deferred
}
}
|
kcommand/kcommand-core/src/main/kotlin/io/github/theunic/kcommand/core/SimpleMessageBus.kt
|
2479266554
|
package io.github.theunic.kcommand.core
import kotlinx.coroutines.CompletableDeferred
interface Middleware<M, R> {
suspend fun handle(
message: M,
next: suspend (M) -> CompletableDeferred<R>,
): CompletableDeferred<R>
}
|
kcommand/kcommand-core/src/main/kotlin/io/github/theunic/kcommand/core/Middleware.kt
|
737443887
|
package io.github.theunic.kcommand.core
import kotlinx.coroutines.CompletableDeferred
import kotlin.reflect.KClass
abstract class AbstractMessageBus<M : Any, R : Any>(
private val middlewares: List<Middleware<M, R>> = listOf(),
) : MessageBus<M, R> {
private val subscriptions: MutableMap<KClass<out M>, suspend (M) -> R> = mutableMapOf()
override fun subscribe(
messageType: KClass<out M>,
messageHandler: suspend (M) -> R,
) {
synchronized(subscriptions) {
subscriptions[messageType] = messageHandler
}
}
protected suspend fun processCommand(
command: M,
deferred: CompletableDeferred<R>,
) {
val next: suspend (M) -> CompletableDeferred<R> = { cmd ->
try {
deferred.complete(handleCommand(cmd))
deferred
} catch (e: Exception) {
deferred.completeExceptionally(e)
deferred
}
}
val chain =
middlewares.foldRight(next) { middleware, proceed ->
{ cmd -> middleware.handle(cmd, proceed) }
}
chain(command)
}
private suspend fun handleCommand(command: M): R {
return getCommandHandler(command::class)(command)
}
private fun getCommandHandler(commandClass: KClass<out M>): suspend (M) -> R {
synchronized(subscriptions) {
return subscriptions[commandClass]
?: throw IllegalArgumentException("No handler found for command: $commandClass")
}
}
}
|
kcommand/kcommand-core/src/main/kotlin/io/github/theunic/kcommand/core/AbstractMessageBus.kt
|
3169892613
|
package io.github.theunic.kcommand.core
import arrow.core.Either
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.flow.Flow
interface Transport<M : Any, R : Any> {
suspend fun send(message: M): Either<Unit, CompletableDeferred<R>>
fun receive(): Flow<Pair<M, Either<Unit, CompletableDeferred<R>>>>
}
|
kcommand/kcommand-core/src/main/kotlin/io/github/theunic/kcommand/core/Transport.kt
|
3440937080
|
package io.github.theunic.kcommand.core
import arrow.core.getOrElse
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
class DefaultMessageBus<M : Any, R : Any>(
middlewares: List<Middleware<M, R>> = listOf(),
private val transport: Transport<M, R> = LocalTransport(),
) : AbstractMessageBus<M, R>(middlewares) {
init {
transport
.receive()
.onEach { processCommand(it.first, it.second.getOrElse { CompletableDeferred() }) }
.launchIn(CoroutineScope(Dispatchers.Default))
}
override suspend fun handle(message: M): CompletableDeferred<R> =
transport
.send(message)
.getOrElse { CompletableDeferred() }
}
|
kcommand/kcommand-core/src/main/kotlin/io/github/theunic/kcommand/core/DefaultMessageBus.kt
|
274518623
|
package io.github.theunic.kcommand.core
import arrow.core.Either
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
class LocalTransport<M : Any, R : Any> : Transport<M, R> {
private val commandEmitter: MutableSharedFlow<Pair<M, Either<Unit, CompletableDeferred<R>>>> = MutableSharedFlow()
override suspend fun send(message: M): Either<Unit, CompletableDeferred<R>> {
val result = Either.Right(CompletableDeferred<R>())
commandEmitter.emit(message to result)
return result
}
override fun receive(): Flow<Pair<M, Either<Unit, CompletableDeferred<R>>>> = commandEmitter.asSharedFlow()
}
|
kcommand/kcommand-core/src/main/kotlin/io/github/theunic/kcommand/core/LocalTransport.kt
|
279888016
|
package com.example.ktlintstudy
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.ktlintstudy", appContext.packageName)
}
}
|
KtlintStudy/app/src/androidTest/java/com/example/ktlintstudy/ExampleInstrumentedTest.kt
|
13821971
|
package com.example.ktlintstudy
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)
}
}
|
KtlintStudy/app/src/test/java/com/example/ktlintstudy/ExampleUnitTest.kt
|
1699229838
|
package com.example.ktlintstudy.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)
|
KtlintStudy/app/src/main/java/com/example/ktlintstudy/ui/theme/Color.kt
|
1805432868
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.