content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.funny.compose.ai.chat
import com.funny.compose.ai.bean.ChatMessageReq
import com.funny.compose.ai.bean.Model
import com.funny.compose.ai.service.AskStreamRequest
import com.funny.compose.ai.service.aiService
import com.funny.compose.ai.service.asFlow
import com.funny.compose.ai.token.TokenCounter
import com.funny.compose.ai.token.TokenCounters
import com.funny.translation.ai.BuildConfig
import com.funny.translation.helper.Log
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import org.json.JSONObject
open class ModelChatBot(
val model: Model
) : ChatBot() {
private val verbose = BuildConfig.DEBUG
override val args: HashMap<String, Any?> by lazy { hashMapOf() }
override suspend fun sendRequest(
prompt: String,
messages: List<ChatMessageReq>,
args: Map<String, Any?>
): Flow<String> {
return try {
aiService.askStream(
AskStreamRequest(
modelId = model.chatBotId,
messages = messages,
prompt = prompt,
args = JSONObject(args)
)
).asFlow()
} catch (e: Exception) {
e.printStackTrace()
flowOf("<<error>>$e")
}
}
fun log(msg: Any?) {
if (verbose) {
Log.d(name, msg.toString())
}
}
override val id: Int by model::chatBotId
override val name: String by model::name
override val avatar by model::avatar
override val maxContextTokens: Int by model::maxContextTokens
override val tokenCounter: TokenCounter
get() = TokenCounters.findById(model.tokenCounterId)
companion object {
val Empty = ModelChatBot(Model.Empty)
}
}
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/chat/ModelChatBot.kt
|
845125370
|
package com.funny.compose.ai.chat
import com.funny.compose.ai.bean.ChatMessageReq
import com.funny.compose.ai.bean.Model
import com.funny.compose.ai.token.TokenCounter
import com.funny.compose.ai.token.TokenCounters
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
const val LONG_TEXT_TRANS_PROMPT = """"你现在是一名优秀的翻译人员,现在在翻译长文中的某个片段。请根据给定的术语表,将输入文本翻译成中文,并找出可能存在的新术语,以JSON的形式返回(如果没有,请返回[])。
示例输入:{"text":"XiaoHong and XiaoMing are studying DB class.","keywords":[["DB","数据库"],["XiaoHong","萧红"]]}
示例输出:{"text":"萧红和晓明正在学习数据库课程","keywords":[["XiaoMing","晓明"]]}。
你的输出必须为JSON格式"""
class TestLongTextChatBot: ModelChatBot(Model.Empty) {
override var args: HashMap<String, Any?> = hashMapOf()
override suspend fun sendRequest(
prompt: String,
messages: List<ChatMessageReq>,
args: Map<String, Any?>
): Flow<String> {
return flow {
// emit("{\"text\":\"晓明告诉萧红,这个班级里最优秀的学生是晓张。\",\"keywords\":[[\"XiaoZhang\",\"晓张\"]]}")
// 分几次 emit,每次 emit json 的一小部分
emit("{\"text")
delay(500)
emit("\":\"晓明告诉萧红")
delay(500)
emit("这个班级里最优秀的学生是晓张。\",")
delay(500)
emit("\"keywords\":[[\"XiaoZhang\",\"晓张\"]]}")
}
}
// override fun getFormattedText(
// systemPrompt: String,
// includedMessages: List<ChatMessage>
// ): String {
// // {"text":"XiaoMing told XiaoHong, the best student in this class is XiaoZhang."}
// return buildString {
// append("System: ")
// append(systemPrompt)
// append("\n")
// val obj = JSONObject()
// obj.put("text", includedMessages.last().content)
// val keywords = args["keywords"] as? List<List<String>>
// if (keywords != null) {
// obj.put("keywords", JSONArray(keywords))
// }
// append("Input: ")
// append(obj.toString())
// }
// }
override val id: Int = 0
override val name: String = "Test"
override val avatar: String = "https://c-ssl.duitang.com/uploads/blog/202206/12/20220612164733_72d8b.jpg"
override val tokenCounter: TokenCounter = TokenCounters.defaultTokenCounter
override val maxContextTokens = 1024
}
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/chat/TestLongTextChatBot.kt
|
916982358
|
package com.funny.compose.ai.bean
import com.funny.translation.database.ChatHistory
import com.funny.translation.helper.now
import java.util.UUID
const val SENDER_ME = "Me"
typealias ChatMessage = ChatHistory
// 自定义 constructor
fun ChatMessage(
botId: Int,
conversationId: String,
sender: String,
content: String,
type: Int = ChatMessageTypes.TEXT,
error: String? = null,
): ChatMessage {
return ChatMessage(
id = UUID.randomUUID().toString(),
botId = botId,
conversationId = conversationId,
sender = sender,
content = content,
type = type,
error = error,
timestamp = now()
)
}
val ChatMessage.sendByMe: Boolean
get() = sender == SENDER_ME
object ChatMessageTypes {
const val TEXT = 0
const val IMAGE = 1
const val ERROR = 99
}
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/bean/ChatMessage.kt
|
950163459
|
package com.funny.compose.ai.bean
import androidx.annotation.Keep
import androidx.compose.runtime.Stable
import com.funny.translation.helper.BigDecimalSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.math.BigDecimal
/**
* 可供选择的模型列表,包含模型名称、模型描述、模型价格(每千字符)
* @constructor
*/
@Serializable
@Stable
@Keep
data class Model(
@SerialName("chat_bot_id")
val chatBotId: Int,
@Serializable(with = BigDecimalSerializer::class)
@SerialName("cost_1k_tokens")
val cost1kTokens: BigDecimal,
val name: String,
val description: String,
val avatar: String = "",
@SerialName("max_context_tokens")
// 最大上下文长度,单位 token
val maxContextTokens: Int,
@SerialName("max_output_tokens")
val maxOutputTokens: Int,
@SerialName("token_counter_id")
val tokenCounterId: String,
) {
companion object {
val Empty = Model(0, BigDecimal.ZERO, "Test", "", "", 0, 0, "default")
}
}
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/bean/Model.kt
|
2402811892
|
package com.funny.compose.ai.bean
import com.funny.translation.helper.JsonX
import kotlinx.serialization.Serializable
@Serializable
data class ChatMessageReq(
val role: String,
val content: String
) {
companion object {
fun text(content: String, role: String = "user") = ChatMessageReq(role, content)
fun vision(content: Vision, role: String = "user") = ChatMessageReq(role, JsonX.toJson(content))
}
/*
"content": [
{"type": "text", "text": "What’s in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
},
},
],
*/
class Vision(
val content: List<Content>,
) {
@Serializable
class Content(
val type: String,
val text: String? = null,
val image_url: ImageUrl? = null,
) {
@Serializable
class ImageUrl(
val url: String,
)
}
}
}
fun ChatMessage.toChatMessageReq() = ChatMessageReq(
role = if (sendByMe) "user" else "assistant",
content = content
)
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/bean/ChatMessageReq.kt
|
3608573750
|
package com.funny.compose.ai.bean
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/bean/BaseLanguageModel.kt
|
359442199
|
package com.funny.compose.ai.bean
class Prompt(
val text: String,
val inputKeys: List<String>,
) {
fun format(vararg args: Any): String {
return String.format(text, *args)
}
}
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/bean/BasePromot.kt
|
4246646598
|
package com.funny.compose.ai.bean
import com.funny.compose.ai.token.TokenCounters
import java.util.Date
import java.util.LinkedList
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
abstract class ChatMemory {
/**
* 获取实际要发送的消息,注意不包含最初的 Prompt
* @param list List<ChatMessage>
* @return List<ChatMessage>
*/
abstract suspend fun getIncludedMessages(list: List<ChatMessage>) : List<ChatMessage>
companion object {
val Saver = { chatMemory: ChatMemory ->
when(chatMemory) {
is ChatMemoryFixedMsgLength -> "chat_memory#fixed_length#${chatMemory.length}"
is ChatMemoryFixedDuration -> "chat_memory#fixed_duration#${chatMemory.duration.inWholeMilliseconds}"
else -> ""
}
}
val Restorer = lambda@ { str: String ->
val parts = str.split("#")
if (parts.size != 3 || parts[0] != "chat_memory") {
return@lambda DEFAULT_CHAT_MEMORY
}
when(parts[1]) {
"fixed_length" -> ChatMemoryFixedMsgLength(parts[2].toInt())
"fixed_duration" -> ChatMemoryFixedDuration(parts[2].toLong().milliseconds)
else -> DEFAULT_CHAT_MEMORY
}
}
}
}
class ChatMemoryFixedMsgLength(val length: Int) : ChatMemory() {
override suspend fun getIncludedMessages(list: List<ChatMessage>): List<ChatMessage> {
val linkedList = LinkedList<ChatMessage>()
// 反向遍历 list
var i = list.lastIndex
while (i >= 0) {
val item = list[i]
// 如果这是错误消息,且前面有我发的消息,那么就跳过这条消息和我的那一条
if (item.error != null) {
if (i > 0 && list[i-1].sendByMe) {
i -= 2;
continue
}
}
linkedList.addFirst(item)
if (linkedList.size >= length) {
break
}
i--
}
return linkedList
}
}
class ChatMemoryFixedDuration(val duration: Duration) : ChatMemory() {
override suspend fun getIncludedMessages(list: List<ChatMessage>): List<ChatMessage> {
val now = Date()
val last = list.lastOrNull { it.timestamp > now.time - duration.inWholeMilliseconds }
return if (last == null) {
emptyList()
} else {
list.dropWhile { it.timestamp < last.timestamp }
}
}
}
class ChatMemoryMaxContextSize(var maxContextSize: Int, var systemPrompt: String): ChatMemory() {
override suspend fun getIncludedMessages(list: List<ChatMessage>): List<ChatMessage> {
var idx = list.size - 1
var curLength = systemPrompt.length
while (curLength < maxContextSize && idx >= 0) {
curLength += list[idx].content.length
idx--
}
return list.subList(idx + 1, list.size)
}
}
class ChatMemoryMaxToken(val model: Model, var systemPrompt: String): ChatMemory() {
private val tokenCounter = TokenCounters.findById(model.tokenCounterId)
private val maxAllTokens = (model.maxContextTokens * 0.95).toInt()
private val maxInputToken = maxAllTokens / 2
override suspend fun getIncludedMessages(list: List<ChatMessage>): List<ChatMessage> {
val remainingInputTokens = maxInputToken - tokenCounter.countMessages(listOf(
ChatMessageReq.text(systemPrompt, "system")
))
var idx = list.size - 1
var curInputTokens = 0
while (curInputTokens < remainingInputTokens && idx >= 0) {
curInputTokens += tokenCounter.countMessages(listOf(list[idx].toChatMessageReq()))
idx--
}
return list.subList(idx + 1, list.size)
}
}
private val DEFAULT_CHAT_MEMORY = ChatMemoryFixedMsgLength(2)
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/bean/ChatMemory.kt
|
3309797259
|
package com.funny.compose.ai.bean
import com.funny.translation.helper.BigDecimalSerializer
import kotlinx.serialization.Serializable
import java.math.BigDecimal
@Serializable
sealed class StreamMessage(val type: Int = ChatMessageTypes.TEXT) {
data object Start: StreamMessage()
@Serializable
data class End(
val input_tokens: Int = 0,
val output_tokens: Int = 0,
@Serializable(with = BigDecimalSerializer::class)
val consumption: BigDecimal = BigDecimal.ZERO
): StreamMessage()
data class Part(val part: String): StreamMessage()
data class Error(val error: String): StreamMessage()
}
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/bean/StreamMessage.kt
|
3350063437
|
package com.funny.compose.ai.utils
import com.funny.compose.ai.service.aiService
import com.funny.translation.helper.lazyPromise
object ModelManager {
val models by lazyPromise {
aiService.getChatModels()
}
}
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/utils/ModelManager.kt
|
2034313978
|
package com.funny.compose.ai.service
import com.funny.compose.ai.bean.ChatMessageReq
import com.funny.compose.ai.bean.Model
import com.funny.compose.ai.bean.StreamMessage
import com.funny.translation.AppConfig
import com.funny.translation.helper.JSONObjectSerializer
import com.funny.translation.helper.JsonX
import com.funny.translation.helper.LocaleUtils
import com.funny.translation.helper.getLanguageCode
import com.funny.translation.helper.toastOnUi
import com.funny.translation.kmp.appCtx
import com.funny.translation.network.CommonData
import com.funny.translation.network.DynamicTimeout
import com.funny.translation.network.ServiceCreator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.withContext
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.http.Body
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Query
import retrofit2.http.Streaming
private const val TAG = "AIService"
private val EmptyJsonObject = JSONObject()
@Serializable
data class AskStreamRequest(
@SerialName("model_id") val modelId: Int,
@SerialName("messages") val messages: List<ChatMessageReq>,
@SerialName("prompt") val prompt: String,
// args
@Serializable(with = JSONObjectSerializer::class)
@SerialName("args") val args: JSONObject = EmptyJsonObject,
)
@Serializable
data class CountTokenMessagesRequest(
@SerialName("token_counter_id") val tokenCounterId: String,
@SerialName("messages") val messages: List<ChatMessageReq>,
)
interface AIService {
/**
* 会返回流,包括开始的 <<start>> 、<<error>> 和结束的 <<end>>
* @param req AskStreamRequest
* @return ResponseBody
*/
@POST("ai/ask_stream")
// 设置超时时间
@Streaming
@DynamicTimeout(connectTimeout = 30, readTimeout = 120, writeTimeout = 30)
suspend fun askStream(@Body req: AskStreamRequest): ResponseBody
@GET("ai/get_models")
suspend fun getChatModels(
// 这个 lang 并不实际使用,主要是区分 url,避免 nginx 缓存带来的问题
@Query("lang") lang: String = LocaleUtils.getLanguageCode()
) : List<Model>
@POST("ai/count_tokens_text")
@FormUrlEncoded
suspend fun countTokensText(
@Field("token_counter_id") tokenCounterId: String,
@Field("text") text: String,
@Field("max_length") maxLength: Int? = null,
): CommonData<Int>
@POST("ai/count_tokens_messages")
suspend fun countTokensMessages(
@Body req: CountTokenMessagesRequest
): CommonData<Int>
@GET("ai/truncate_text")
suspend fun truncateText(
@Query("token_counter_id") tokenCounterId: String,
@Query("text") text: String,
@Query("max_length") maxLength: Int,
): CommonData<String>
}
val aiService by lazy {
ServiceCreator.create(AIService::class.java)
}
suspend fun AIService.askAndParseStream(req: AskStreamRequest): Flow<StreamMessage> {
return askStream(req).asFlow().asStreamMessageFlow()
}
/**
问一个问题并直接返回结果,默认处理掉 `<<start>>` 和 `<<end>>`,返回中间的部分,并且自动完成扣费
*/
suspend fun AIService.askAndProcess(
req: AskStreamRequest,
onError: (String) -> Unit = { appCtx.toastOnUi(it) },
): String {
val output = StringBuilder()
askAndParseStream(req).collect {
when (it) {
is StreamMessage.Error -> {
onError(it.error)
}
is StreamMessage.Part -> {
output.append(it.part)
}
else -> Unit
}
}
return output.toString()
}
suspend fun ResponseBody.asFlow() = withContext(Dispatchers.IO) {
flow {
val response = this@asFlow
response.source().use { inputStream ->
val buffer = ByteArray(256)
try {
while (true) {
val read = inputStream.read(buffer)
if (read == -1) {
break
}
emit(String(buffer, 0, read))
}
} catch (e: Exception) {
e.printStackTrace()
emit("<<error>>" + e.message)
}
}
}
}
/**
* 将一个字符串流转换为 StreamMessage 的流,并自动完成扣费
* @receiver Flow<String>
* @return Flow<StreamMessage>
*/
suspend fun Flow<String>.asStreamMessageFlow() = map {
when {
it.startsWith("<<error>>") -> {
val remaining = it.removePrefix("<<error>>")
StreamMessage.Error(remaining)
}
it.startsWith("<<start>>") -> StreamMessage.Start
it.startsWith("<<end>>") -> {
val remaining = it.removePrefix("<<end>>")
if (remaining != "") {
JsonX.fromJson<StreamMessage.End>(remaining).also {
AppConfig.subAITextPoint(it.consumption)
}
} else {
StreamMessage.End()
}
}
else -> StreamMessage.Part(it)
}
}.onCompletion { err ->
if (err != null) {
emit(StreamMessage.Error(err.message ?: "Unknown error"))
}
}
|
Transtation-KMP/ai/src/commonMain/kotlin/com/funny/compose/ai/service/AIService.kt
|
2692796489
|
package com.funny.jetsetting.core.ui
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import com.funny.translation.kmp.painterDrawableRes
import com.funny.translation.ui.FixedSizeIcon
class FunnyIcon(
private val imageVector: ImageVector?= null,
private val resourceName: String? = null
){
fun get() = imageVector ?: resourceName
}
@Composable
fun IconWidget(
modifier: Modifier = Modifier,
funnyIcon : FunnyIcon,
tintColor : Color = MaterialTheme.colorScheme.secondary,
contentDescription: String? = null,
) {
val icon = funnyIcon.get()
if (icon is ImageVector){
FixedSizeIcon(imageVector = icon, contentDescription = contentDescription, tint = tintColor, modifier = modifier)
}else if(icon is String){
// error("show icon by resource id is not supported yet in KMP")
FixedSizeIcon(painter = painterDrawableRes(icon), contentDescription = contentDescription, tint = tintColor, modifier = modifier)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/jetsetting/core/ui/IconWidgets.kt
|
4117381584
|
package com.funny.jetsetting.core.ui
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import com.funny.translation.kmp.base.strings.ResStrings
@Composable
fun SimpleDialog(
openDialog: Boolean,
updateOpenDialog: (Boolean) -> Unit,
title: String? = null,
content: (@Composable () -> Unit)? = null,
confirmButtonAction: (() -> Unit)? = null,
confirmButtonText : String = ResStrings.confirm,
dismissButtonAction: (() -> Unit)? = null,
dismissButtonText : String = ResStrings.cancel,
closeable: Boolean = true
) {
if (openDialog) {
AlertDialog(
onDismissRequest = {
if (closeable) updateOpenDialog(false)
},
title = {
if (title != null) Text(text = title)
},
text = content,
confirmButton = {
if(confirmButtonText.isNotEmpty()) {
TextButton(
onClick = {
updateOpenDialog(false)
confirmButtonAction?.invoke()
}) {
Text(confirmButtonText)
}
}
},
dismissButton = {
if(dismissButtonText.isNotEmpty()) {
TextButton(
onClick = {
updateOpenDialog(false)
dismissButtonAction?.invoke()
}) {
Text(dismissButtonText)
}
}
}
)
}
}
@Composable
fun SimpleDialog(
openDialogState: MutableState<Boolean>,
title: String? = null,
message: String = "message",
confirmButtonAction: (() -> Unit)? = {},
confirmButtonText : String = ResStrings.confirm,
dismissButtonAction: (() -> Unit)? = {},
dismissButtonText : String = ResStrings.cancel,
closeable: Boolean = true
) {
val (openDialog, updateOpenDialog) = openDialogState
SimpleDialog(openDialog, updateOpenDialog, title, message, confirmButtonAction, confirmButtonText, dismissButtonAction, dismissButtonText, closeable)
}
@Composable
fun SimpleDialog(
openDialogState: MutableState<Boolean>,
title: String? = null,
content: (@Composable () -> Unit)? = null,
confirmButtonAction: (() -> Unit)? = null,
confirmButtonText : String = ResStrings.confirm,
dismissButtonAction: (() -> Unit)? = null,
dismissButtonText : String = ResStrings.cancel,
closeable: Boolean = true
) {
val (openDialog, updateOpenDialog) = openDialogState
SimpleDialog(openDialog, updateOpenDialog, title, content, confirmButtonAction, confirmButtonText, dismissButtonAction, dismissButtonText, closeable)
}
@Composable
fun SimpleDialog(
openDialog: Boolean,
updateOpenDialog: (Boolean) -> Unit,
title: String? = null,
message: String = "message",
confirmButtonAction: (() -> Unit)? = null,
confirmButtonText : String = ResStrings.confirm,
dismissButtonAction: (() -> Unit)? = null,
dismissButtonText : String = ResStrings.cancel,
closeable: Boolean = true
) {
SimpleDialog(openDialog, updateOpenDialog, title, content = { Text(text = message)}, confirmButtonAction, confirmButtonText, dismissButtonAction, dismissButtonText, closeable)
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/jetsetting/core/ui/SimpleDialog.kt
|
45805930
|
package com.funny.jetsetting.core.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
// modified from https://github.com/re-ovo/compose-setting
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun SettingBaseItem(
modifier: Modifier = Modifier,
icon: (@Composable () -> Unit)? = null,
title: @Composable () -> Unit,
text: (@Composable () -> Unit)? = null,
action: (@Composable () -> Unit)? = null,
onClick: () -> Unit = {}
) {
val throttleHandler =
rememberSaveable(300, saver = ThrottleHandler.Saver) { ThrottleHandler(1000) }
Surface(
onClick = {
throttleHandler.process(onClick)
},
color = Color.Unspecified,
shape = RoundedCornerShape(16.dp)
) {
Row(
modifier = modifier
.padding(
horizontal = MenuTokens.ContentPaddingHorizontal,
vertical = MenuTokens.ContentPaddingVertical
)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(MenuTokens.ElementHorizontalSpace)
) {
icon?.invoke()
Column(
modifier = Modifier.weight(1f)
) {
ProvideTextStyle(
MaterialTheme.typography.titleLarge.copy(
fontSize = 16.sp, fontWeight = FontWeight.Normal
)
) {
title()
}
ProvideTextStyle(
MaterialTheme.typography.bodySmall.copy(
fontSize = 14.sp,
lineHeight = 16.sp,
fontWeight = FontWeight.W400,
color = LocalContentColor.current.copy(alpha = 0.8f)
)
) {
text?.invoke()
}
}
action?.invoke()
}
}
}
internal object MenuTokens {
val ContentPaddingHorizontal = 24.dp
val ContentPaddingVertical = 12.dp
val ElementHorizontalSpace = 24.dp
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/jetsetting/core/ui/SettingBaseItem.kt
|
4182151701
|
package com.funny.jetsetting.core.ui
import androidx.compose.foundation.Indication
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.platform.debugInspectorInfo
import androidx.compose.ui.semantics.Role
import com.funny.translation.helper.now
fun Modifier.throttleClick(
timeout: Int = 1000,
onClick: () -> Unit
) = composed {
val interactionSource = remember { MutableInteractionSource() }
val indication = LocalIndication.current
Modifier.throttleClick(
interactionSource = interactionSource,
indication = indication,
timeout = timeout,
onClick = onClick
)
}
// from emo
// 防抖点击
fun Modifier.throttleClick(
interactionSource: MutableInteractionSource,
indication: Indication?,
timeout: Int = 250,
enabled: Boolean = true,
onClickLabel: String? = null,
role: Role? = null,
onClick: () -> Unit
) = composed(
inspectorInfo = debugInspectorInfo {
name = "throttleClick"
properties["timeout"] = timeout
properties["enabled"] = enabled
properties["onClickLabel"] = onClickLabel
properties["role"] = role
properties["onClick"] = onClick
properties["indication"] = indication
properties["interactionSource"] = interactionSource
}
) {
val throttleHandler = rememberSaveable(timeout, saver = ThrottleHandler.Saver) { ThrottleHandler(timeout) }
Modifier.clickable(
interactionSource = interactionSource,
indication = indication,
enabled = enabled,
onClickLabel = onClickLabel,
role = role,
onClick = { throttleHandler.process(onClick) }
)
}
internal class ThrottleHandler(private val timeout: Int = 500) {
private var last: Long = 0
fun process(event: () -> Unit) {
val now = now()
if (now - last > timeout) {
event.invoke()
}
last = now
}
companion object {
val Saver = Saver<ThrottleHandler, Long>(
save = { it.last },
restore = { ThrottleHandler().apply { last = it } }
)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/jetsetting/core/ui/ClickEx.kt
|
1798836924
|
package com.funny.jetsetting.core.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@Composable
fun SettingItemCategory(
modifier: Modifier = Modifier,
title: @Composable () -> Unit,
content: @Composable ColumnScope.() -> Unit
) {
Column(
modifier = modifier
) {
Box(modifier = Modifier.padding(SettingItemCategoryTokens.TitlePadding)) {
ProvideTextStyle(
MaterialTheme.typography.titleMedium.copy(color = MaterialTheme.colorScheme.primary)
) {
title()
}
}
content()
}
}
internal object SettingItemCategoryTokens {
val TitlePadding = PaddingValues(start = 20.dp, end = 16.dp, top = 24.dp, bottom = 8.dp)
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/jetsetting/core/ui/SettingItemCategory.kt
|
2064575351
|
package com.funny.jetsetting.core
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import com.funny.data_saver.core.rememberDataSaverState
import com.funny.jetsetting.core.ui.FunnyIcon
import com.funny.jetsetting.core.ui.IconWidget
import com.funny.jetsetting.core.ui.SettingBaseItem
import com.funny.translation.kmp.base.strings.ResStrings
import kotlinx.collections.immutable.ImmutableList
private val EmptyAction = {}
@Composable
fun JetSettingSwitch(
modifier: Modifier = Modifier,
state: MutableState<Boolean>,
imageVector: ImageVector? = null,
resourceName: String? = null,
text: String,
description: String? = null,
interceptor: () -> Boolean = { true },
onCheck: (Boolean) -> Unit = {}
) {
SettingBaseItem(
modifier = modifier,
icon = {
val icon = FunnyIcon(imageVector, resourceName)
IconWidget(funnyIcon = icon, tintColor = MaterialTheme.colorScheme.onSurface)
},
title = {
Text(text = text)
},
text = {
description?.let {
Text(text = it)
}
},
action = {
Switch(checked = state.value, onCheckedChange = {
if (interceptor.invoke()) {
state.value = it
onCheck(it)
}
})
},
onClick = {
if (interceptor.invoke()) {
state.value = !state.value
onCheck(state.value)
}
}
)
}
@Composable
fun JetSettingSwitch(
modifier: Modifier = Modifier,
key: String,
default: Boolean = false,
imageVector: ImageVector? = null,
resourceName: String? = null,
text: String,
description: String? = null,
interceptor: () -> Boolean = { true },
onCheck: (Boolean) -> Unit
) {
val state = rememberDataSaverState<Boolean>(key = key, initialValue = default)
JetSettingSwitch(
modifier = modifier,
state = state,
imageVector = imageVector,
resourceName = resourceName,
text = text,
description = description,
interceptor = interceptor,
onCheck = onCheck
)
}
@Composable
fun JetSettingTile(
modifier: Modifier = Modifier,
imageVector: ImageVector? = null,
resourceName: String? = null,
text: String,
description: String? = null,
interceptor: () -> Boolean = { true },
onClick: () -> Unit
) {
SettingBaseItem(
modifier = modifier.padding(vertical = 4.dp),
title = {
Text(text = text)
},
action = {
// FixedSizeIcon(Icons.Default.KeyboardArrowRight, "Goto", )
},
icon = {
val icon = FunnyIcon(imageVector, resourceName)
IconWidget(funnyIcon = icon, tintColor = MaterialTheme.colorScheme.onSurface)
},
onClick = {
if (interceptor.invoke()) {
onClick()
}
},
text = {
description?.let {
Text(text = it)
}
}
)
}
@Composable
fun JetSettingDialog(
modifier: Modifier = Modifier,
imageVector: ImageVector? = null,
resourceName: String? = null,
text: String,
description: String? = null,
dialogTitle: String = ResStrings.hint,
confirmButtonAction: (() -> Unit)? = EmptyAction,
confirmButtonText: String = ResStrings.confirm,
dismissButtonAction: (() -> Unit)? = EmptyAction,
dismissButtonText: String = ResStrings.cancel,
dialogContent: @Composable () -> Unit
) {
var openDialogState by remember {
mutableStateOf(false)
}
if (openDialogState) {
AlertDialog(
title = {
Text(text = dialogTitle)
},
text = dialogContent,
onDismissRequest = { openDialogState = false },
confirmButton = {
if (confirmButtonAction != EmptyAction)
TextButton(
onClick = {
openDialogState = false
confirmButtonAction?.invoke()
}) {
Text(confirmButtonText)
}
},
dismissButton = {
if (dismissButtonText.isNotEmpty())
TextButton(
onClick = {
openDialogState = false
dismissButtonAction?.invoke()
}
) {
Text(dismissButtonText)
}
}
)
}
JetSettingTile(
modifier = modifier,
text = text,
description = description,
imageVector = imageVector,
resourceName = resourceName
) {
openDialogState = true
}
}
@Composable
fun <E> JetSettingListDialog(
modifier: Modifier = Modifier,
list: ImmutableList<E>,
text: String,
description: String? = null,
imageVector: ImageVector? = null,
resourceName: String? = null,
selected: E,
updateSelected: (E) -> Unit,
confirmButtonAction: (() -> Unit)? = EmptyAction,
confirmButtonText: String = ResStrings.confirm,
dismissButtonAction: (() -> Unit)? = EmptyAction,
dismissButtonText: String = ResStrings.cancel,
) {
JetSettingDialog(
modifier = modifier,
text = text,
description = description,
resourceName = resourceName,
imageVector = imageVector,
confirmButtonAction = confirmButtonAction,
confirmButtonText = confirmButtonText,
dismissButtonAction = dismissButtonAction,
dismissButtonText = dismissButtonText,
) {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
itemsIndexed(list) { i, item ->
ListItem(
modifier = Modifier.clickable { updateSelected(item) },
headlineContent = {
Text(text = item.toString())
},
trailingContent = {
RadioButton(selected = selected == item, onClick = { updateSelected(item) })
},
)
}
}
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/jetsetting/core/JetSettingWidgets.kt
|
247785357
|
package com.funny.translation
import com.funny.translation.kmp.KMPContext
expect class WebViewActivity: BaseActivity {
companion object {
fun start(context: KMPContext, url: String)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/WebViewActivity.kt
|
3443368574
|
package com.funny.translation.ui
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.PressInteraction
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
@Stable
fun Modifier.touchToScale(
scaleRatio: Float = 0.9f,
onClick: () -> Unit = {}
): Modifier = composed {
val interactionSource = remember {
MutableInteractionSource()
}
var isPressed by remember {
mutableStateOf(false)
}
val realScaleRation by animateFloatAsState(
if (isPressed) scaleRatio else 1f
)
LaunchedEffect(interactionSource) {
interactionSource.interactions.collect { interaction ->
when (interaction) {
is PressInteraction.Press -> isPressed = true
is PressInteraction.Release -> isPressed = false
is PressInteraction.Cancel -> isPressed = false
}
}
}
this.then(Modifier.clickable(interactionSource = interactionSource, indication = null, onClick = onClick).graphicsLayer {
scaleX = realScaleRation
scaleY = realScaleRation
transformOrigin = TransformOrigin.Center
})
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/TouchToScaleModifier.kt
|
137075944
|
package com.funny.translation.ui
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import com.funny.translation.helper.Log
import com.funny.translation.helper.SimpleAction
private const val TAG = "SnackbarHostEx"
suspend fun SnackbarHostState.showSnackbar(
message: String,
actionLabel: String? = null,
withDismissAction: Boolean = false,
duration: SnackbarDuration =
if (actionLabel == null) SnackbarDuration.Short else SnackbarDuration.Indefinite,
onClick: SimpleAction = {}
): SnackbarResult {
val res = showSnackbar(message, actionLabel, withDismissAction, duration)
Log.d(TAG, "showSnackbar: res: $res")
if (res == SnackbarResult.ActionPerformed) onClick()
return res
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/SnackbarHostEx.kt
|
409004561
|
package com.funny.translation.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.funny.data_saver.core.LocalDataSaver
import com.funny.translation.helper.DataSaverUtils
import com.funny.translation.ui.theme.TransTheme
import com.funny.translation.ui.theme.calcDark
import com.funny.translation.ui.toast.Toast
import com.seiko.imageloader.ImageLoader
import com.seiko.imageloader.LocalImageLoader
import moe.tlaster.precompose.PreComposeApp
/**
* Wraps the content, include
* - CompositionLocalProvider: [LocalDataSaver], [LocalImageLoader]
* - [PreComposeApp]
* - [TransTheme]
* - [Toast]
* @param content [@androidx.compose.runtime.Composable] [@kotlin.ExtensionFunctionType] Function1<BoxWithConstraintsScope, Unit>
*/
@Composable
fun App(content: @Composable () -> Unit = {}) {
CompositionLocalProvider(
LocalDataSaver provides DataSaverUtils,
LocalImageLoader provides remember { generateImageLoader() },
) {
PreComposeApp {
TransTheme(dark = calcDark()) {
Box(modifier = Modifier.fillMaxSize()) {
content()
Toast(
modifier = Modifier.align(Alignment.BottomEnd)
)
}
}
}
}
}
@Composable
expect fun Toast(modifier: Modifier = Modifier)
expect fun generateImageLoader(): ImageLoader
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/App.kt
|
2847908654
|
package com.funny.translation.ui
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.InfiniteRepeatableSpec
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
@Stable
fun Modifier.animatedGradientBackground(
color1: Color,
color2: Color,
) = composed {
val infiniteTransition = rememberInfiniteTransition()
val offset by infiniteTransition.animateFloat(
initialValue = 0.3f,
targetValue = 0.7f,
animationSpec = InfiniteRepeatableSpec(
animation = TweenSpec(
durationMillis = 10000,
easing = FastOutSlowInEasing
),
repeatMode = RepeatMode.Reverse,
)
)
Modifier.drawWithContent {
drawRect(
brush = Brush.linearGradient(
0f to color1,
offset to color2,
1f to color1,
)
)
drawContent()
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/AnimatedGradientBackground.kt
|
2290144491
|
package com.funny.translation.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.funny.translation.kmp.base.strings.ResStrings
@Composable
fun Working() {
CommonPage(
title = "Working"
) {
Column(
Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(text = ResStrings.working, style = MaterialTheme.typography.displaySmall)
Spacer(Modifier.height(8.dp))
Text(text = ResStrings.please_wait, style = MaterialTheme.typography.bodyLarge)
}
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/Working.kt
|
1627090052
|
package com.funny.translation.ui
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.IntOffset
fun IntOffset.asOffset() = Offset(x.toFloat(), y.toFloat())
fun Offset.asIntOffset() = IntOffset(x.toInt(), y.toInt())
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/OffsetEx.kt
|
4038695076
|
package com.funny.translation.ui
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
// Adapted from https://github.com/TheMelody/AnyPopDialog-Compose/blob/main/any_pop_dialog_library/src/main/java/com/melody/dialog/any_pop/AnyPopDialog.kt
internal const val DefaultDurationMillis: Int = 250
@Composable
internal expect fun DialogFullScreen(
isActiveClose: Boolean,
onDismissRequest: () -> Unit,
properties: AnyPopDialogProperties,
content: @Composable () -> Unit
)
/**
* @author 被风吹过的夏天
* @see <a href="https://github.com/TheMelody/AnyPopDialog-Compose">https://github.com/TheMelody/AnyPopDialog-Compose</a>
* @param isActiveClose 设置为true可触发动画关闭Dialog,动画完自动触发[onDismissRequest]
* @param properties Dialog相关配置
* @param onDismissRequest Dialog关闭的回调
* @param content 可组合项视图
*/
@Composable
fun AnyPopDialog(
modifier: Modifier = Modifier,
isActiveClose: Boolean = false,
properties: AnyPopDialogProperties = AnyPopDialogProperties(direction = DirectionState.BOTTOM),
onDismissRequest: () -> Unit,
content: @Composable () -> Unit
) {
DialogFullScreen(
isActiveClose = isActiveClose,
onDismissRequest = onDismissRequest,
properties = properties
) {
Box(modifier = modifier.navigationBarsPadding()) {
content()
}
}
}
/**
* @param dismissOnBackPress 是否支持返回关闭Dialog
* @param dismissOnClickOutside 是否支持空白区域点击关闭Dialog
* @param isAppearanceLightNavigationBars 导航栏前景色是不是亮色
* @param direction 当前对话框弹出的方向
* @param backgroundDimEnabled 背景渐入检出开关
* @param durationMillis 弹框消失和进入的时长
* @param securePolicy 屏幕安全策略
*/
@Immutable
expect class AnyPopDialogProperties(direction: DirectionState)
enum class DirectionState {
TOP,
LEFT,
RIGHT,
BOTTOM
}
internal fun Modifier.clickOutSideModifier(
dismissOnClickOutside: Boolean,
onTap:()->Unit
) = this.then(
if (dismissOnClickOutside) {
Modifier.pointerInput(Unit) {
detectTapGestures(onTap = {
onTap()
})
}
} else Modifier
)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/AnyPopDialog.kt
|
944303090
|
package com.funny.translation.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
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.unit.dp
import com.funny.translation.helper.SimpleAction
import com.funny.translation.kmp.NavHostController
import com.funny.translation.kmp.Platform
import com.funny.translation.kmp.base.strings.ResStrings
import com.funny.translation.kmp.currentPlatform
import com.funny.translation.translate.LocalNavController
/**
* CommonPage,有一个 TopBar 以及剩余内容,被 Column 包裹
* @param modifier Modifier
* @param title String?
* @param navController NavHostController
* @param navigationIcon [@androidx.compose.runtime.Composable] Function0<Unit>
* @param actions TopBar 的 actions
* @param content 主要内容
*/
@Composable
fun CommonPage(
modifier: Modifier = Modifier,
title: String? = null,
addNavPadding: Boolean = true,
navController: NavHostController = LocalNavController.current,
navigationIcon: @Composable () -> Unit = { CommonNavBackIcon(navController) },
actions: @Composable RowScope.() -> Unit = { },
topBar: @Composable () -> Unit = {
CommonTopBar(title = title, navigationIcon = navigationIcon, navController = navController, actions = actions)
},
content: @Composable ColumnScope.() -> Unit
) {
Column(
modifier
.fillMaxSize()
.windowInsetsPadding(WindowInsets.safeMain.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top)),
horizontalAlignment = Alignment.CenterHorizontally
) {
topBar()
content()
if (addNavPadding) {
NavPaddingItem()
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CommonTopBar(
modifier: Modifier = Modifier,
title: String?,
navController: NavHostController = LocalNavController.current,
navigationIcon: @Composable () -> Unit = { CommonNavBackIcon(navController) },
actions: @Composable RowScope.() -> Unit = { },
) {
TopAppBar(
modifier = modifier,
title = {
if (title != null) {
Text(text = title, Modifier.padding(start = 12.dp))
}
},
navigationIcon = navigationIcon,
actions = {
actions()
Spacer(modifier = Modifier.width(12.dp))
}
)
}
// TopBar that without background
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TransparentTopBar(
modifier: Modifier = Modifier,
title: String? = null,
navController: NavHostController = LocalNavController.current,
navigationIcon: @Composable () -> Unit = { CommonNavBackIcon(navController) },
actions: @Composable RowScope.() -> Unit = { },
) {
TopAppBar(
modifier = modifier,
title = {
if (title != null) {
Text(text = title, Modifier.padding(start = 12.dp))
}
},
navigationIcon = navigationIcon,
actions = {
actions()
Spacer(modifier = Modifier.width(12.dp))
},
colors = TopAppBarDefaults.topAppBarColors(
containerColor = Color.Transparent,
scrolledContainerColor = Color.Transparent
)
)
}
@Composable
fun CommonNavBackIcon(
navController: NavHostController = LocalNavController.current,
navigateBackAction: SimpleAction = { navController.popBackStack() }
) {
IconButton(onClick = navigateBackAction) {
FixedSizeIcon(
Icons.Default.ArrowBack,
contentDescription = ResStrings.back
)
}
}
/**
* 纵向的空白,高度为底部导航栏的高度
* 仅 Android 有效
*/
@Composable
fun NavPaddingItem() {
if (currentPlatform == Platform.Android) {
Spacer(modifier = Modifier.windowInsetsPadding(WindowInsets.safeMain.only(WindowInsetsSides.Bottom)))
} else {
// add some padding for Desktop
Spacer(modifier = Modifier.height(8.dp))
}
}
fun LazyListScope.navPaddingItem() {
item {
NavPaddingItem()
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/CommonComposables.kt
|
134500563
|
package com.funny.translation.ui
import androidx.compose.runtime.Composable
@Composable
expect fun SystemBarSettings(
hideStatusBar: Boolean = false,
)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/SystemBarSettings.kt
|
2487656499
|
package com.funny.translation.ui.toast
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.EaseOut
import androidx.compose.animation.core.calculateTargetValue
import androidx.compose.animation.core.tween
import androidx.compose.animation.splineBasedDecay
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.verticalDrag
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.Info
import androidx.compose.material.icons.rounded.Notifications
import androidx.compose.material.icons.rounded.Warning
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.platform.AccessibilityManager
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlin.math.absoluteValue
import kotlin.math.roundToInt
public interface ToastData {
public val message: String
public val icon: ImageVector?
public val animationDuration: StateFlow<Int?>
public val type: ToastModel.Type?
public suspend fun run(accessibilityManager: AccessibilityManager?)
public fun pause()
public fun resume()
public fun dismiss()
public fun dismissed()
}
data class ToastModel(
val message: String,
val type: Type
){
enum class Type {
Normal, Success, Info, Warning, Error,
}
}
private data class ColorData(
val backgroundColor: Color,
val textColor: Color,
val iconColor: Color,
val icon: ImageVector? = null,
)
@Composable
public fun Toast(
toastData: ToastData,
) {
val animateDuration by toastData.animationDuration.collectAsState()
val color = LocalContentColor.current
val colorData = when (toastData.type) {
ToastModel.Type.Normal -> ColorData(
backgroundColor = MaterialTheme.colorScheme.background,
textColor = color,
iconColor = color,
icon = Icons.Rounded.Notifications,
)
ToastModel.Type.Success -> ColorData(
backgroundColor = MaterialTheme.colorScheme.primary,
textColor = MaterialTheme.colorScheme.onSurface,
iconColor = MaterialTheme.colorScheme.onSurface,
icon = Icons.Rounded.Check,
)
ToastModel.Type.Info -> ColorData(
backgroundColor = MaterialTheme.colorScheme.primaryContainer,
textColor = MaterialTheme.colorScheme.onErrorContainer,
iconColor = MaterialTheme.colorScheme.onErrorContainer,
icon = Icons.Rounded.Info
)
ToastModel.Type.Warning -> ColorData(
backgroundColor = MaterialTheme.colorScheme.errorContainer.copy(0.8f),
textColor = MaterialTheme.colorScheme.onErrorContainer,
iconColor = MaterialTheme.colorScheme.onErrorContainer,
icon = Icons.Rounded.Warning
)
ToastModel.Type.Error -> ColorData(
backgroundColor = MaterialTheme.colorScheme.error,
textColor = MaterialTheme.colorScheme.onError,
iconColor = MaterialTheme.colorScheme.onError,
icon = Icons.Rounded.Warning,
)
else -> ColorData(
backgroundColor = MaterialTheme.colorScheme.primaryContainer,
textColor = color,
iconColor = color,
icon = Icons.Rounded.Notifications,
)
}
val icon = toastData.icon ?: colorData.icon
key(toastData) {
Toast(
message = toastData.message,
icon = icon,
backgroundColor = colorData.backgroundColor,
iconColor = colorData.iconColor,
textColor = colorData.textColor,
animateDuration = animateDuration,
onPause = toastData::pause,
onResume = toastData::resume,
onDismissed = toastData::dismissed,
)
}
}
@Composable
private fun Toast(
message: String,
icon: ImageVector?,
backgroundColor: Color,
iconColor: Color,
textColor: Color,
animateDuration: Int? = 0,
onPause: () -> Unit = {},
onResume: () -> Unit = {},
onDismissed: () -> Unit = {},
) {
val roundedValue = 26.dp
Surface(
modifier = Modifier
.systemBarsPadding()
.padding(8.dp)
.widthIn(max = 520.dp)
.fillMaxWidth()
.toastGesturesDetector(onPause, onResume, onDismissed),
color = backgroundColor,
shape = RoundedCornerShape(roundedValue),
tonalElevation = 2.dp,
) {
val progress = remember { Animatable(0f) }
LaunchedEffect(animateDuration) {
// Do not run animation when animations are turned off.
if (coroutineContext.durationScale == 0f) return@LaunchedEffect
if (animateDuration == null) {
progress.stop()
} else {
progress.animateTo(
targetValue = 1f,
animationSpec = tween(
durationMillis = animateDuration,
easing = EaseOut,
),
)
}
}
val color = LocalContentColor.current
Row(
Modifier
.drawBehind {
val fraction = progress.value * size.width
drawRoundRect(
color = color,
size = Size(width = fraction, height = size.height),
cornerRadius = CornerRadius(roundedValue.toPx()),
alpha = 0.1f,
)
}
.padding(12.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
if (icon != null) {
Icon(
icon,
contentDescription = null,
Modifier.size(24.dp),
tint = iconColor
)
}
Text(message, color = textColor)
}
}
}
private fun Modifier.toastGesturesDetector(
onPause: () -> Unit,
onResume: () -> Unit,
onDismissed: () -> Unit,
): Modifier = composed {
val offsetY = remember { Animatable(0f) }
val alpha = remember { Animatable(1f) }
pointerInput(Unit) {
val decay = splineBasedDecay<Float>(this)
coroutineScope {
while (true) {
awaitPointerEventScope {
// Detect a touch down event.
val down = awaitFirstDown()
onPause()
val pointerId = down.id
val velocityTracker = VelocityTracker()
// Stop any ongoing animation.
launch(start = CoroutineStart.UNDISPATCHED) {
offsetY.stop()
alpha.stop()
}
verticalDrag(pointerId) { change ->
onPause()
// Update the animation value with touch events.
val changeY = (offsetY.value + change.positionChange().y).coerceAtMost(0f)
launch {
offsetY.snapTo(changeY)
}
if (changeY == 0f) {
velocityTracker.resetTracking()
} else {
velocityTracker.addPosition(
change.uptimeMillis,
change.position,
)
}
}
onResume()
// No longer receiving touch events. Prepare the animation.
val velocity = velocityTracker.calculateVelocity().y
val targetOffsetY = decay.calculateTargetValue(
offsetY.value,
velocity,
)
// The animation stops when it reaches the bounds.
offsetY.updateBounds(
lowerBound = -size.height.toFloat() * 3,
upperBound = size.height.toFloat(),
)
launch {
if (velocity >= 0 || targetOffsetY.absoluteValue <= size.height) {
// Not enough velocity; Slide back.
offsetY.animateTo(
targetValue = 0f,
initialVelocity = velocity,
)
} else {
// The element was swiped away.
launch { offsetY.animateDecay(velocity, decay) }
launch {
alpha.animateTo(targetValue = 0f, animationSpec = tween(300))
onDismissed()
}
}
}
}
}
}
}
.offset {
IntOffset(0, offsetY.value.roundToInt())
}
.alpha(alpha.value)
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/toast/Toast.kt
|
226572079
|
package com.funny.translation.ui.toast
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.MotionDurationScale
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.AccessibilityManager
import androidx.compose.ui.platform.LocalAccessibilityManager
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.resume
import kotlin.math.roundToLong
@Stable
class ToastUIState {
private val mutex = Mutex()
public var currentData: ToastData? by mutableStateOf(null)
private set
public suspend fun show(
message: String,
icon: ImageVector? = null,
): Unit = mutex.withLock {
try {
return suspendCancellableCoroutine { cont ->
currentData = ToastDataImpl(
message,
icon,
cont,
)
}
} finally {
currentData = null
}
}
public suspend fun show(
toastModel: ToastModel
): Unit = mutex.withLock {
try {
return suspendCancellableCoroutine { cont ->
currentData = ToastDataImpl(
toastModel.message,
null,
cont,
toastModel.type
)
}
} finally {
currentData = null
}
}
@Stable
private class ToastDataImpl(
override val message: String,
override val icon: ImageVector?,
private val continuation: CancellableContinuation<Unit>,
override val type: ToastModel.Type? = ToastModel.Type.Normal,
) : ToastData {
private var elapsed = 0L
private var started = 0L
private var duration = 0L
private val _state = MutableStateFlow<Int?>(null)
override val animationDuration: StateFlow<Int?> = _state.asStateFlow()
override suspend fun run(accessibilityManager: AccessibilityManager?) {
duration = durationTimeout(
hasIcon = icon != null,
accessibilityManager = accessibilityManager,
)
// Accessibility decided to show forever
// Let's await explicit dismiss, do not run animation.
if (duration == Long.MAX_VALUE) {
delay(duration)
return
}
resume()
supervisorScope {
launch {
animationDuration.collectLatest { duration ->
val animationScale = coroutineContext.durationScale
if (duration != null) {
started = System.currentTimeMillis()
// 关闭动画后,只需显示、等待和隐藏即可。
val finalDuration = when (animationScale) {
0f -> duration.toLong()
else -> (duration.toLong() * animationScale).roundToLong()
}
delay(finalDuration)
[email protected]()
} else {
elapsed += System.currentTimeMillis() - started
delay(Long.MAX_VALUE)
}
}
}
}
}
override fun pause() {
_state.value = null
}
override fun resume() {
val remains = (duration - elapsed).toInt()
if (remains > 0) {
_state.value = remains
} else {
dismiss()
}
}
override fun dismiss() {
_state.value = 0
}
override fun dismissed() {
if (continuation.isActive) {
continuation.resume(Unit)
}
}
}
}
@OptIn(ExperimentalAnimationApi::class)
@Composable
public fun ToastUI(
hostState: ToastUIState,
modifier: Modifier = Modifier,
toast: @Composable (ToastData) -> Unit = { Toast(it) },
) {
val accessibilityManager = LocalAccessibilityManager.current
val currentData = hostState.currentData ?: return
key(currentData) {
var state by remember { mutableStateOf(false) }
val transition = updateTransition(targetState = state, label = "toast")
LaunchedEffect(Unit) {
state = true
currentData.run(accessibilityManager)
state = false
}
transition.AnimatedVisibility(
visible = { it },
modifier = modifier,
enter = fadeIn() + slideInVertically(),
exit = fadeOut() + slideOutVertically(),
) {
toast(currentData)
}
// Await dismiss animation and dismiss the Toast completely.
// This animation workaround instead of nulling the toast data is to prevent
// relaunching another Toast when the dismiss animation has not completed yet.
LaunchedEffect(state, transition.currentState, transition.isRunning) {
if (!state && !transition.currentState && !transition.isRunning) {
currentData.dismissed()
}
}
}
}
internal fun durationTimeout(
hasIcon: Boolean,
accessibilityManager: AccessibilityManager?,
): Long {
val timeout = 3000L
if (accessibilityManager == null) return timeout
return accessibilityManager.calculateRecommendedTimeoutMillis(
originalTimeoutMillis = timeout,
containsIcons = hasIcon,
containsText = true,
containsControls = false,
)
}
internal val CoroutineContext.durationScale: Float
get() {
val scale = this[MotionDurationScale]?.scaleFactor ?: 1f
check(scale >= 0f)
return scale
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/toast/ToastUIState.kt
|
2637137705
|
package com.funny.translation.ui
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.SubcomposeLayout
import androidx.compose.ui.unit.Constraints
@Composable
fun SubcomposeBottomFirstLayout(modifier: Modifier, bottom: @Composable () -> Unit, other: @Composable () -> Unit) {
SubcomposeLayout(modifier) { constraints: Constraints ->
var bottomHeight = 0
val bottomPlaceables = subcompose("bottom", bottom).map {
val placeable = it.measure(constraints.copy(minWidth = 0, minHeight = 0))
bottomHeight += placeable.height
placeable
}
val h = constraints.maxHeight - bottomHeight
val otherPlaceables = subcompose("other", other).map {
it.measure(constraints.copy(minHeight = 0, maxHeight = h))
}
layout(constraints.maxWidth, constraints.maxHeight) {
var y = h
bottomPlaceables.forEach {
it.placeRelative(0, y)
y += it.height
}
y = 0
otherPlaceables.forEach {
it.placeRelative(0, y)
y += it.height
}
}
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/SubcomposeBottomFirstLayout.kt
|
1713089262
|
package com.funny.translation.ui
import androidx.compose.animation.core.Animatable
import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.node.LayoutModifierNode
import androidx.compose.ui.node.ModifierNodeElement
import androidx.compose.ui.unit.Constraints
import com.funny.translation.helper.rememberSaveableStateOf
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
@Stable
fun Modifier.floatingActionBarModifier(
initialOffset: Offset = Offset(-64f, -100f)
) = composed {
var offset by rememberSaveableStateOf(
value = initialOffset,
saver = OffsetSaver,
)
this
.fillMaxSize()
.wrapContentSize(Alignment.BottomEnd)
.offset { offset.asIntOffset() }
.pointerInput(Unit) {
detectDragGesturesAfterLongPress { change, dragAmount ->
offset += dragAmount
}
}
}
private val OffsetSaver = listSaver<Offset, Float>(
save = { listOf(it.x, it.y) },
restore = { Offset(it[0], it[1]) }
)
@Stable
fun Modifier.slideIn() = this.then(SlideInElement())
//composed {
// val animatable = Animatable(1f)
// val scope = rememberCoroutineScope()
// DisposableEffect(Unit) {
// scope.launch {
// animatable.animateTo(0f)
// }
// onDispose {
// scope.launch {
// animatable.snapTo(1f)
// }
// }
// }
// this.graphicsLayer {
// val width = size.width
// translationX = (width * animatable.value)
// }
//}
private class SlideInNode: LayoutModifierNode, Modifier.Node() {
private val animatable = Animatable(1f)
override fun onAttach() {
super.onAttach()
coroutineScope.launch {
animatable.animateTo(0f)
}
}
override fun onDetach() {
super.onDetach()
coroutineScope.launch {
animatable.snapTo(1f)
}
}
override fun onReset() {
super.onReset()
coroutineScope.launch {
animatable.snapTo(1f)
}
}
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
val placeable = measurable.measure(constraints)
val width = placeable.width
return layout(width, placeable.height) {
placeable.place((width * animatable.value).roundToInt(), 0)
}
}
}
private class SlideInElement: ModifierNodeElement<SlideInNode>() {
override fun create(): SlideInNode {
return SlideInNode()
}
override fun update(node: SlideInNode) {
TODO("Not yet implemented")
}
override fun equals(other: Any?): Boolean {
return other is SlideInElement
}
override fun hashCode(): Int {
return javaClass.hashCode()
}
override fun toString(): String {
return "SlideInElement"
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/Modifiers.kt
|
2106688913
|
package com.funny.translation.ui
import androidx.compose.runtime.Composable
@Composable
expect fun Permission(
permission: String,
description: String,
content: @Composable () -> Unit = { }
)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/Permission.kt
|
3556933642
|
package com.funny.translation.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Shapes
import androidx.compose.ui.unit.dp
val Shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(8.dp),
large = RoundedCornerShape(16.dp)
)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/theme/Shape.kt
|
4232677343
|
package com.funny.translation.ui.theme
import androidx.compose.ui.graphics.Color
import com.funny.cmaterialcolors.MaterialColors
import kotlinx.collections.immutable.persistentListOf
val ThemeStaticColors by lazy {
persistentListOf(
MaterialColors.Red500, MaterialColors.Red700, MaterialColors.Red900, MaterialColors.Pink500, MaterialColors.Pink700, MaterialColors.Pink900, MaterialColors.Purple500, MaterialColors.Purple700, MaterialColors.Purple900, MaterialColors.DeepPurple500, MaterialColors.DeepPurple700, MaterialColors.DeepPurple900, MaterialColors.Indigo500, MaterialColors.Indigo700, MaterialColors.Indigo900, MaterialColors.Blue500, MaterialColors.Blue700, MaterialColors.Blue900, MaterialColors.LightBlue500, MaterialColors.LightBlue700, MaterialColors.LightBlue900, MaterialColors.Cyan500, MaterialColors.Cyan700, MaterialColors.Cyan900, MaterialColors.Teal500, MaterialColors.Teal700, MaterialColors.Teal900, MaterialColors.Green500, MaterialColors.Green700, MaterialColors.Green900, MaterialColors.LightGreen500, MaterialColors.LightGreen700, MaterialColors.LightGreen900, MaterialColors.Lime500, MaterialColors.Lime700, MaterialColors.Lime900, MaterialColors.Yellow500, MaterialColors.Yellow700, MaterialColors.Yellow900, MaterialColors.Amber500, MaterialColors.Amber700, MaterialColors.Amber900, MaterialColors.Orange500, MaterialColors.Orange700, MaterialColors.Orange900, MaterialColors.DeepOrange500, MaterialColors.DeepOrange700, MaterialColors.DeepOrange900, MaterialColors.Brown500, MaterialColors.Brown700, MaterialColors.Brown900, MaterialColors.Grey500, MaterialColors.Grey700, MaterialColors.Grey900, MaterialColors.BlueGrey500, MaterialColors.BlueGrey700, MaterialColors.BlueGrey900
)
}
val md_theme_light_primary = Color(0xFF0061A4)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFD1E4FF)
val md_theme_light_onPrimaryContainer = Color(0xFF001D36)
val md_theme_light_secondary = Color(0xFF006493)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFCAE6FF)
val md_theme_light_onSecondaryContainer = Color(0xFF001E30)
val md_theme_light_tertiary = Color(0xFF006970)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFF7DF4FF)
val md_theme_light_onTertiaryContainer = Color(0xFF002022)
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(0xFFFDFCFF)
val md_theme_light_onBackground = Color(0xFF1A1C1E)
val md_theme_light_surface = Color(0xFFFDFCFF)
val md_theme_light_onSurface = Color(0xFF1A1C1E)
val md_theme_light_surfaceVariant = Color(0xFFDFE2EB)
val md_theme_light_onSurfaceVariant = Color(0xFF43474E)
val md_theme_light_outline = Color(0xFF73777F)
val md_theme_light_inverseOnSurface = Color(0xFFF1F0F4)
val md_theme_light_inverseSurface = Color(0xFF2F3033)
val md_theme_light_inversePrimary = Color(0xFF9ECAFF)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF0061A4)
val md_theme_dark_primary = Color(0xFF9ECAFF)
val md_theme_dark_onPrimary = Color(0xFF003258)
val md_theme_dark_primaryContainer = Color(0xFF00497D)
val md_theme_dark_onPrimaryContainer = Color(0xFFD1E4FF)
val md_theme_dark_secondary = Color(0xFF8DCDFF)
val md_theme_dark_onSecondary = Color(0xFF00344F)
val md_theme_dark_secondaryContainer = Color(0xFF004B70)
val md_theme_dark_onSecondaryContainer = Color(0xFFCAE6FF)
val md_theme_dark_tertiary = Color(0xFF4DD9E4)
val md_theme_dark_onTertiary = Color(0xFF00363A)
val md_theme_dark_tertiaryContainer = Color(0xFF004F54)
val md_theme_dark_onTertiaryContainer = Color(0xFF7DF4FF)
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(0xFF1A1C1E)
val md_theme_dark_onBackground = Color(0xFFE2E2E6)
val md_theme_dark_surface = Color(0xFF1A1C1E)
val md_theme_dark_onSurface = Color(0xFFE2E2E6)
val md_theme_dark_surfaceVariant = Color(0xFF43474E)
val md_theme_dark_onSurfaceVariant = Color(0xFFC3C7CF)
val md_theme_dark_outline = Color(0xFF8D9199)
val md_theme_dark_inverseOnSurface = Color(0xFF1A1C1E)
val md_theme_dark_inverseSurface = Color(0xFFE2E2E6)
val md_theme_dark_inversePrimary = Color(0xFF0061A4)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFF9ECAFF)
val seed = Color(0xFF2196F3)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/theme/Color.kt
|
810599384
|
package com.funny.translation.ui.theme
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.getValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import com.funny.cmaterialcolors.MaterialColors
import com.funny.translation.kmp.base.strings.ResStrings
val LightColors = lightColorScheme(
surfaceTint = md_theme_light_surfaceTint,
onErrorContainer = md_theme_light_onErrorContainer,
onError = md_theme_light_onError,
errorContainer = md_theme_light_errorContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
tertiary = md_theme_light_tertiary,
error = md_theme_light_error,
outline = md_theme_light_outline,
onBackground = md_theme_light_onBackground,
background = md_theme_light_background,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
surface = md_theme_light_surface,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
secondary = md_theme_light_secondary,
inversePrimary = md_theme_light_inversePrimary,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
primary = md_theme_light_primary,
)
val DarkColors = darkColorScheme(
surfaceTint = md_theme_dark_surfaceTint,
onErrorContainer = md_theme_dark_onErrorContainer,
onError = md_theme_dark_onError,
errorContainer = md_theme_dark_errorContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
tertiary = md_theme_dark_tertiary,
error = md_theme_dark_error,
outline = md_theme_dark_outline,
onBackground = md_theme_dark_onBackground,
background = md_theme_dark_background,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
surface = md_theme_dark_surface,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
secondary = md_theme_dark_secondary,
inversePrimary = md_theme_dark_inversePrimary,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
primary = md_theme_dark_primary,
)
val SpringFestivalColorPalette = lightColorScheme(
primary = MaterialColors.Red500,
tertiary = MaterialColors.Red700,
secondary = MaterialColors.RedA400,
onSecondary = Color.White,
primaryContainer = MaterialColors.Red200.copy(alpha = 0.7f),
onPrimaryContainer = MaterialColors.RedA700
)
sealed class ThemeType(val id: Int) {
object StaticDefault: ThemeType(-1)
object DynamicNative : ThemeType(0)
class DynamicFromImage(val color: Color) : ThemeType(1)
class StaticFromColor(val color: Color): ThemeType(2)
val isDynamic get() = this is DynamicNative || this is DynamicFromImage
override fun toString(): String {
return when(this){
StaticDefault -> "StaticDefault"
DynamicNative -> "DynamicNative"
is DynamicFromImage -> "DynamicFromImage#${this.color}"
is StaticFromColor -> "StaticFromColor${this.color}"
}
}
companion object {
val Saver = { themeType: ThemeType ->
when(themeType){
StaticDefault -> "-1#0"
DynamicNative -> "0#0"
is DynamicFromImage -> "1#${themeType.color.toArgb()}"
is StaticFromColor -> "2#${themeType.color.toArgb()}"
}
}
val Restorer = { str: String ->
val (id, color) = str.split("#")
when(id){
"-1" -> StaticDefault
"0" -> DynamicNative
"1" -> DynamicFromImage(Color(color.toInt()))
"2" -> StaticFromColor(Color(color.toInt()))
else -> throw IllegalArgumentException("Unknown ThemeType: $str")
}
}
}
}
enum class LightDarkMode(val desc: String) {
Light(ResStrings.always_light), Dark(ResStrings.always_dark), System(ResStrings.follow_system);
override fun toString(): String {
return desc
}
}
expect object ThemeConfig {
val TAG: String
val defaultThemeType: ThemeType
val sThemeType: MutableState<ThemeType>
val lightDarkMode: MutableState<LightDarkMode>
fun updateThemeType(new: ThemeType)
fun updateLightDarkMode(new: LightDarkMode)
}
@Composable
@ReadOnlyComposable
internal fun calcDark(): Boolean {
val lightDarkMode by ThemeConfig.lightDarkMode
return when(lightDarkMode) {
LightDarkMode.Light -> false
LightDarkMode.Dark -> true
LightDarkMode.System -> isSystemInDarkTheme()
}
}
// 由于系统的 isSystemInDarkTheme 在 Desktop 报错 java.lang.UnsatisfiedLinkError: 'int org.jetbrains.skiko.SystemTheme_awtKt.getCurrentSystemTheme()
// 自己实现一个
@ReadOnlyComposable
@Composable
expect fun isSystemInDarkTheme(): Boolean
@Composable
expect fun TransTheme(
dark: Boolean = calcDark(),
hideStatusBar: Boolean = false,
content: @Composable () -> Unit
)
val ColorScheme.isLight: Boolean
@Composable
@ReadOnlyComposable
get() = !calcDark()
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/theme/Theme.kt
|
1819815142
|
package com.funny.translation.ui.theme
import androidx.compose.material3.Typography
// Set of Material typography styles to start with
val Typography = Typography(
/*
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/theme/Type.kt
|
3616444905
|
package com.funny.translation.ui
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
private const val TAG = "FixedSizeIcon"
/**
* 当没有设置 size 时,无论对于 vector 还是 Bitmap 都设置默认的 24.dp 大小
*/
@Composable
fun FixedSizeIcon(
painter: Painter,
contentDescription: String?,
modifier: Modifier = Modifier,
tint: Color = LocalContentColor.current
) {
val sizedModifier =
if (modifier.all { it.javaClass.simpleName != "SizeElement" }) {
modifier.size(24.dp)
} else modifier
Icon(painter, contentDescription, sizedModifier, tint)
}
@Composable
fun FixedSizeIcon(
imageVector: ImageVector,
contentDescription: String?,
modifier: Modifier = Modifier,
tint: Color = LocalContentColor.current
) = Icon(imageVector, contentDescription, modifier, tint)
private fun Modifier.defaultSizeFor(painter: Painter) =
this.then(
if (painter.intrinsicSize == Size.Unspecified || painter.intrinsicSize.isInfinite()) {
DefaultIconSizeModifier
} else {
// if we haven't set a size, we give it a default size
if (this.all {
// replace with `it !is SizeElement`, I use reflection here because it's private
it.javaClass.simpleName != "SizeElement"
}) {
DefaultIconSizeModifier
} else Modifier
}
)
private fun Size.isInfinite() = width.isInfinite() && height.isInfinite()
// Default icon size, for icons with no intrinsic size information
private val DefaultIconSizeModifier = Modifier.size(24.dp)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/Icon.kt
|
858208004
|
package com.funny.translation.ui
/**
* https://github.com/jeziellago/compose-markdown
*/
// TODO Change it to
// to get more customized
// https://github.com/takahirom/jetpack-compose-markdown/blob/master/app/src/main/java/com/github/takahirom/jetpackcomposemarkdown/Markdown.kt
import androidx.compose.material3.LocalTextStyle
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.TextUnit
import com.funny.translation.WebViewActivity
import com.funny.translation.helper.Context
@Composable
expect fun MarkdownText(
markdown: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
textAlign: TextAlign? = TextAlign.Center,
maxLines: Int = Int.MAX_VALUE,
selectable: Boolean = false,
style: TextStyle = LocalTextStyle.current,
onClick: (() -> Unit)? = null,
// this option will disable all clicks on links, inside the markdown text
// it also enable the parent view to receive the click event
disableLinkMovementMethod: Boolean = false,
onLinkClicked: ((Context, String) -> Unit)? = { context, url ->
WebViewActivity.start(context, url)
},
onTextLayout: ((numLines: Int) -> Unit)? = null
)
@Composable
private fun PreviewMDText() {
val markdown = "### 注音 \nhəˈlō \n### 定义 \n**惊叹词** \n- used as a greeting or to begin a phone conversation. \n - hello there, Katie! \n \n**名词** \n- an utterance of “hello”; a greeting. \n - she was getting polite nods and hellos from people \n \n**动词** \n- say or shout “hello”; greet someone. \n - I pressed the phone button and helloed \n"
MarkdownText(markdown = markdown)
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/MarkdownText.kt
|
4184562106
|
package com.funny.translation.ui
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.displayCutout
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.NonRestartableComposable
import androidx.compose.ui.Modifier
/**
* WindowInsets.safeDrawing, Exclude ime
*/
val WindowInsets.Companion.safeMain: WindowInsets
@Composable
@NonRestartableComposable
get() = WindowInsets.systemBars.union(WindowInsets.displayCutout)
@Composable
fun Modifier.safeMainPadding() = windowInsetsPadding(WindowInsets.safeMain)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/ui/WindowInsetsEx.kt
|
435866198
|
package com.funny.translation.database
import app.cash.sqldelight.ColumnAdapter
import com.funny.translation.bean.EditablePrompt
import com.funny.translation.helper.JsonX
import com.funny.translation.translate.Language
import com.funny.translation.translate.findLanguageById
private typealias Term = Pair<String, String>
object LanguageListAdapter : ColumnAdapter<List<Language>, String> {
override fun encode(value: List<Language>): String = JsonX.toJson(value)
override fun decode(databaseValue: String): List<Language> = JsonX.fromJson(databaseValue)
}
object StringListAdapter : ColumnAdapter<List<String>, String> {
override fun encode(value: List<String>): String = JsonX.toJson(value)
override fun decode(databaseValue: String): List<String> = JsonX.fromJson(databaseValue)
}
object TermListAdapter : ColumnAdapter<List<Term>, String> {
override fun encode(value: List<Term>): String = JsonX.toJson(value)
override fun decode(databaseValue: String): List<Term> = JsonX.fromJson(databaseValue)
}
object EditablePromptAdapter : ColumnAdapter<EditablePrompt, String> {
override fun encode(value: EditablePrompt): String = JsonX.toJson(value)
override fun decode(databaseValue: String): EditablePrompt = JsonX.fromJson(databaseValue)
}
object IntListAdapter : ColumnAdapter<List<Int>, String> {
override fun encode(value: List<Int>): String = JsonX.toJson(value)
override fun decode(databaseValue: String): List<Int> = JsonX.fromJson(databaseValue)
}
object LanguageAdapter: ColumnAdapter<Language, Long> {
override fun encode(value: Language) = value.id.toLong()
override fun decode(databaseValue: Long) = findLanguageById(databaseValue.toInt())
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/database/Adapters.kt
|
3594017855
|
package com.funny.translation.database
// 仿 Room 的 annotations
// Dao
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.BINARY)
annotation class Dao
// Query
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.BINARY)
annotation class Query(val value: String)
// Insert
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.BINARY)
annotation class Insert
// Delete
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.BINARY)
annotation class Delete
// Upsert
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.BINARY)
annotation class Upsert
// Update
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.BINARY)
annotation class Update
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/database/Annotations.kt
|
3086988092
|
package com.funny.translation.database
import app.cash.sqldelight.Query
import app.cash.sqldelight.coroutines.asFlow
import app.cash.sqldelight.coroutines.mapToList
import com.funny.translation.helper.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
private const val TAG = "DaoProxy"
/**
* 转换 Dao 的调用为 SqlDelight 的调用
* @author [FunnySaltyFish](https://github.com/FunnySaltyFish)
*
*/
class DaoProxy(private val sqlDelightQueries: Any) : InvocationHandler {
override fun invoke(proxy: Any, method: Method, args: Array<out Any>?): Any? {
return callAppropriateMethod(method, args)
}
private fun callAppropriateMethod(
method: Method,
args: Array<out Any>?
): Any? {
val sqldelightMethod = sqlDelightQueries.javaClass.methods.find {
it.name == method.name && it.parameterCount == method.parameterCount
}
sqldelightMethod ?: throw UnsupportedOperationException("Method ${method.name} not found")
Log.d(TAG, "find sqldelightMethod: $sqldelightMethod")
val returnType = method.returnType
// 强转成类型 Query<ExpectedGenericType>
val query = sqldelightMethod.invoke(sqlDelightQueries, *args.orEmpty()) as? Query<*> ?: return null
// 调用 Query 的 executeAsList 方法
return when (returnType) {
List::class.java -> query.executeAsList()
Flow::class.java -> query.executeAsFlowList()
else -> callAndConvert(returnType, query)
}
}
/**
* 调用方法并进行适当的类型转换,目前做的有
* 1. 如果返回值是 Long 而 Dao 的返回值是 Int(count方法),那么就转为 Int
*/
private fun callAndConvert(
daoReturnType: Class<*>,
query: Query<*>
): Any? {
val executedQuery = query.executeAsOneOrNull() ?: return null
return when {
daoReturnType == Int::class.java && executedQuery is Long -> {
executedQuery.toInt()
}
else -> {
executedQuery
}
}
}
}
// 工厂函数创建代理
inline fun <reified T : Any> createDaoProxy(sqlDelightQueries: Any): T {
val handler = DaoProxy(sqlDelightQueries)
return Proxy.newProxyInstance(
T::class.java.classLoader,
arrayOf(T::class.java),
handler
) as T
}
inline fun <reified RowType : Any> Query<RowType>.executeAsFlowList(): Flow<List<RowType>> {
return this.asFlow().mapToList(Dispatchers.IO)
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/database/Proxy.kt
|
4099872216
|
package com.funny.translation.translate
import androidx.annotation.Keep
import com.funny.translation.helper.DataSaverUtils
import com.funny.translation.kmp.base.strings.ResStrings
import kotlinx.coroutines.flow.MutableStateFlow
@Keep
@kotlinx.serialization.Serializable
enum class Language(val id : Int,var displayText : String = "") {
AUTO(0),
CHINESE(1),
ENGLISH(2),
JAPANESE(3),
KOREAN(4),
FRENCH(5),
RUSSIAN(6),
GERMANY(7),
WENYANWEN(8),
THAI(9),
PORTUGUESE(10),
VIETNAMESE(11),
ITALIAN(12),
CHINESE_YUE(13), // 粤语
// 西班牙语
SPANISH(14),
;
val selectedKey get() = this.name + "_selected"
val imgSelectedKey get() = this.name + "_img_selected"
companion object {
fun fromId(id: String?) = id?.toIntOrNull()?.let { findLanguageById(it) }
}
}
fun findLanguageById(id : Int, default: Language = Language.AUTO) = if(id in allLanguages.indices) {
allLanguages[id]
} else {
default
}
val allLanguages = Language.entries
val enabledLanguages = MutableStateFlow(allLanguages.filter { DataSaverUtils.readData(it.selectedKey, true) })
fun initLanguageDisplay(){
Language.AUTO.displayText = ResStrings.language_auto
Language.CHINESE.displayText = ResStrings.language_chinese
Language.ENGLISH.displayText = ResStrings.language_english
Language.JAPANESE.displayText = ResStrings.language_japanese
Language.KOREAN.displayText = ResStrings.language_korean
Language.FRENCH.displayText = ResStrings.language_french
Language.RUSSIAN.displayText = ResStrings.language_russian
Language.GERMANY.displayText = ResStrings.language_germany
Language.WENYANWEN.displayText = ResStrings.language_wenyanwen
Language.THAI.displayText = ResStrings.language_thai
Language.PORTUGUESE.displayText = ResStrings.language_portuguese
Language.VIETNAMESE.displayText = ResStrings.language_vietnamese
Language.ITALIAN.displayText = ResStrings.language_italian
Language.CHINESE_YUE.displayText = ResStrings.language_chinese_yue
Language.SPANISH.displayText = ResStrings.language_spanish
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/translate/Languages.kt
|
4080936251
|
package com.funny.translation.translate
import com.funny.translation.kmp.base.strings.ResStrings
import kotlinx.serialization.SerialName
@kotlinx.serialization.Serializable
data class ImageTranslationPart(
val source: String,
var target: String,
val x: Int = 0,
val y: Int = 0,
val width: Int = 100,
val height: Int = 100
) {
/**
* 合并产生新的矩形框
* @param other ImageTranslationPart 只使用 x, y, width, height
* @param newSource String
* @param newTarget String
* @return ImageTranslationPart
*/
fun combineWith(other: ImageTranslationPart): ImageTranslationPart {
val x1 = minOf(x, other.x)
val y1 = minOf(y, other.y)
val x2 = maxOf(x + width, other.x + other.width)
val y2 = maxOf(y + height, other.y + other.height)
return this.copy(
x = x1,
y = y1,
width = x2 - x1,
height = y2 - y1
)
}
}
@kotlinx.serialization.Serializable
data class ImageTranslationResult(
@SerialName("erased_img")
val erasedImgBase64: String? = null,
val source: String = "",
val target: String = "",
val content: List<ImageTranslationPart> = arrayListOf()
)
abstract class ImageTranslationTask(
var sourceImg: ByteArray = byteArrayOf(),
) : CoreTranslationTask() {
var result = ImageTranslationResult()
@Throws(TranslationException::class)
open suspend fun translate(){
if (!supportLanguages.contains(sourceLanguage) || !supportLanguages.contains(targetLanguage)){
throw TranslationException(ResStrings.unsupported_language)
}
if (sourceLanguage == targetLanguage) return
}
abstract val isOffline: Boolean
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/translate/ImageTranslationTask.kt
|
2522087903
|
package com.funny.translation.translate
import androidx.annotation.Keep
import com.funny.translation.helper.Log
/**
*
* @property engineName String 翻译引擎
* @property basicResult Translation 基本翻译结果,见[Translation]
* @property sourceString String 源语言
* @property detailText String? 详细翻译结果,Markdown形式
* @property targetLanguage Language? 目标语言
* @constructor
*/
@Keep
class TranslationResult(
var engineName: String = "",
var basicResult: Translation = Translation(""),
var sourceString: String = "",
var detailText : String? = null,
var targetLanguage: Language? = Language.AUTO
) {
/**
* 设置 basicResult 的 trans 为 text
* @param text String
*/
init {
Log.d(TAG, "init is called! ${hashCode()}")
}
fun setBasicResult(text: String) {
Log.d(TAG, "setBasicResult is called! ${hashCode()}")
basicResult.trans = text
//该方法调用次数正常
}
override fun toString(): String {
return "TranslationResult(engineName='$engineName', basicResult=$basicResult, sourceString='$sourceString', detailText=$detailText, targetLanguage=$targetLanguage)"
}
companion object {
private const val TAG = "TranslationResult"
}
}
/**
* 翻译bean
* @property trans String 基本的翻译内容
* @property phoneticNotation String? 音标
* @property partOfSpeech String? 词性
* @constructor
*/
@Keep
data class Translation(
var trans: String,
var phoneticNotation: String? = null,//注音
var partOfSpeech: String? = null //词性
)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/translate/TranslationResult.kt
|
2290317817
|
package com.funny.translation.translate
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
abstract class CoreTranslationTask(
var sourceLanguage: Language = Language.AUTO,
var targetLanguage: Language = Language.ENGLISH
) : TranslationEngine
abstract class CoreTextTranslationTask(
var sourceString: String = "",
) : CoreTranslationTask() {
val result by lazy { TranslationResult() }
var mutex: Mutex? = null
@Throws(TranslationException::class)
abstract fun getBasicText(url: String): String
@Throws(TranslationException::class)
abstract fun getFormattedResult(basicText: String)
abstract fun madeURL(): String
abstract val isOffline: Boolean
@Throws(TranslationException::class)
abstract suspend fun translate()
/**
* 检查是否有 mutex,是的话加锁,否则直接执行
* @param mutex Mutex?
* @param block Function0<Unit>
*/
suspend inline fun doWithMutex(block: () -> Unit) = if (mutex == null) {
block()
} else {
mutex?.withLock {
block()
}
}
override fun equals(other: Any?): Boolean {
return (other is TranslationEngine && other.name == name)
}
override fun hashCode(): Int {
return name.hashCode() + 1
}
override fun toString(): String = "Engine[$name]"
companion object {
private const val TAG = "BasicTranslationTask"
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/translate/CoreTranslationTask.kt
|
2914029877
|
package com.funny.translation.translate
import kotlin.reflect.KClass
/**
* 翻译引擎
* @property name String 引擎名称,全应用唯一
* @property supportLanguages List<Language> 该引擎支持的语言
* @property languageMapping Map<Language, String> 各语言对应的code,如"zh-CN"等
* @property selected Boolean 记录当前引擎是否被选择
* @property taskClass KClass<out CoreTranslationTask> 引擎运行时生成的任务,通过反射动态生成
*/
interface TranslationEngine {
val name : String
val supportLanguages: List<Language>
val languageMapping : Map<Language , String>
var selected : Boolean
val taskClass : KClass<out CoreTranslationTask>
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/translate/TranslationEngine.kt
|
980381007
|
package com.funny.translation.translate
open class TranslationException(override val message:String) : Exception() {
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/translate/TranslationException.kt
|
3828757276
|
package com.funny.translation.js.core
import androidx.annotation.Keep
import com.funny.translation.debug.Debug
import com.funny.translation.js.JsManager
import com.funny.translation.js.extentions.show
import com.funny.translation.network.OkHttpUtils
import org.mozilla.javascript.NativeArray
import org.mozilla.javascript.NativeObject
@Keep
interface JsInterface {
fun get(
url : String,
headersMap : HashMap<String,String>? = null
) = OkHttpUtils.get(url = url,headersMap = headersMap)
fun getRaw(
url : String,
headersMap : HashMap<String,String>? = null
) = OkHttpUtils.getRaw(url = url,headersMap = headersMap)
fun getResponse(
url : String,
headersMap : HashMap<String,String>? = null
) = OkHttpUtils.getResponse(url, headersMap)
fun post(
url : String,
json : String,
headersMap : HashMap<String,String>? = null
) = OkHttpUtils.postJSON(url, json, headersMap)
fun post(
url : String,
data : HashMap<String,String>,
headersMap : HashMap<String,String>? = null
) = OkHttpUtils.postForm(url, data, headersMap)
fun getOkHttpClient(timeout: IntArray? = null) = OkHttpUtils.getClient(timeout)
fun log(obj : Any){
val logStr = when(obj){
is NativeArray -> obj.show
is NativeObject -> obj.show()
else -> obj.toString()
}
Debug.log(
logStr,
tempSource = "log",
JsManager.currentRunningJsEngine?.jsBean?.debugMode?:false
)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/js/core/JsInterface.kt
|
1705071621
|
package com.funny.translation.js.core
import com.funny.translation.debug.Debug
import com.funny.translation.js.JsEngine
import com.funny.translation.js.extentions.messageWithDetail
import com.funny.translation.translate.CoreTextTranslationTask
import com.funny.translation.translate.Language
import com.funny.translation.translate.TranslationException
import com.funny.translation.translate.allLanguages
import javax.script.ScriptException
import kotlin.reflect.KClass
private const val TAG = "JsTranslateTask"
class JsTranslateTaskText(
val jsEngine: JsEngine,
):
CoreTextTranslationTask(){
override val languageMapping: Map<Language, String>
get() = mapOf()
override var selected: Boolean = false
override val supportLanguages: List<Language>
get() = allLanguages
override val name: String
get() = jsEngine.jsBean.fileName
override val taskClass: KClass<out CoreTextTranslationTask>
get() = this::class
override fun getBasicText(url: String): String {
val obj = jsEngine.scriptEngine.invokeMethod(jsEngine.funnyJS, "getBasicText", url)
//Log.d(TAG, "getBasicText: ${obj is String}")
return obj as String
}
override fun getFormattedResult(basicText: String) {
jsEngine.scriptEngine.invokeMethod(
jsEngine.funnyJS,
"getFormattedResult",
basicText
)
}
override fun madeURL(): String {
val obj = jsEngine.scriptEngine.invokeMethod(jsEngine.funnyJS, "madeURL")
return obj as String
}
override val isOffline: Boolean
get() =
try {
jsEngine.scriptEngine.invokeMethod(jsEngine.funnyJS,"isOffline") as Boolean
} catch (e: Exception) {
true
}
override suspend fun translate() {
fun String.emptyString() = this.ifEmpty { " [空字符串]" }
result.engineName = name
result.sourceString = sourceString
try {
doWithMutex { eval() }
Debug.log("sourceString:$sourceString $sourceLanguage -> $targetLanguage ")
Debug.log("开始执行 madeURL 方法……")
val url = madeURL()
Debug.log("成功!url:${url.emptyString()}")
Debug.log("开始执行 getBasicText 方法……")
val basicText = getBasicText(url)
Debug.log("成功!basicText:${basicText.emptyString()}")
Debug.log("开始执行 getFormattedResult 方法……")
getFormattedResult(basicText)
Debug.log("成功!result:$result")
Debug.log("插件执行完毕!")
} catch (exception: ScriptException) {
Debug.log(exception.messageWithDetail)
doWithMutex { result.setBasicResult("翻译错误:${exception.messageWithDetail}") }
return
} catch (exception: TranslationException) {
Debug.log("翻译过程中发生错误!原因如下:\n${exception.message}")
doWithMutex { result.setBasicResult("翻译错误:${exception.message}") }
return
} catch (e: Exception) {
Debug.log("出错:${e.message}")
doWithMutex { result.setBasicResult("翻译错误:${e.message}") }
return
}
}
private fun eval() {
with(jsEngine.scriptEngine){
put("sourceLanguage", sourceLanguage)
put("targetLanguage", targetLanguage)
put("sourceString", sourceString)
put("result", result)
}
jsEngine.eval()
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/js/core/JsTranslateTaskText.kt
|
510561592
|
package com.funny.translation.js
import androidx.annotation.Keep
import com.funny.translation.debug.Debug
import com.funny.translation.helper.Log
import com.funny.translation.helper.ScriptEngineDelegate
import com.funny.translation.js.bean.JsBean
import com.funny.translation.js.config.JsConfig
import com.funny.translation.js.core.JsInterface
import com.funny.translation.js.extentions.messageWithDetail
import com.funny.translation.network.OkHttpUtils
import com.funny.translation.network.ServiceCreator
import com.funny.translation.translate.Language
import com.funny.translation.translate.allLanguages
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.mozilla.javascript.NativeArray
import org.mozilla.javascript.NativeObject
import org.mozilla.javascript.RhinoException
import javax.script.ScriptException
@Keep
class JsEngine(val code: String) : JsInterface {
constructor(jsBean: JsBean) : this(jsBean.code) {
this.jsBean = jsBean
}
private val patternResult = Regex("(\\W)result(\\W)")
lateinit var funnyJS: NativeObject
lateinit var jsBean: JsBean
internal val scriptEngine by lazy {
ScriptEngineDelegate(fileName).also {
Log.d("JsEngine", "get ScriptEngine with fileName = $fileName")
}
}
@Throws(ScriptException::class)
fun eval() {
with(scriptEngine) {
put("funny", this@JsEngine)
put("http", OkHttpUtils)
put("BASE_URL", ServiceCreator.BASE_URL)
Language.entries.forEach {
put("LANGUAGE_${it.name}", it)
}
}
// 为了实现多引擎同步翻译,替换 result 为 result_${engineName.hashCode()}
// val code = jsBean.code.replace(patternResult,"\$1result_${jsBean.fileName.hashCode().absoluteValue}\$2")
scriptEngine.eval(code)
funnyJS = scriptEngine.get("FunnyJS") as NativeObject
}
@Throws(ScriptException::class, NoSuchMethodException::class)
fun evalFunction(name: String, vararg arguments: Any): Any? {
return try {
scriptEngine.invokeFunction(name, arguments)
} catch (e: NoSuchMethodException) {
log("函数[$name]不存在!")
throw e
} catch (e: ScriptException) {
log(e.messageWithDetail)
throw e
} catch (e: Exception) {
log("执行函数[${name}]时产生错误!\n${e.message}")
throw e
}
}
fun getId() = jsBean.id
val fileName: String
// 如果 jsBean 初始化了,就用 jsBean 的 fileName,否则用 Unknown
get() = if (::jsBean.isInitialized) jsBean.fileName else "Unknown"
val isOffline
get() = jsBean.isOffline
suspend fun loadBasicConfigurations(
onSuccess: () -> Unit,
onError: (Throwable) -> Unit
) {
withContext(Dispatchers.IO) {
kotlin.runCatching {
JsManager.currentRunningJsEngine = this@JsEngine
with(scriptEngine) {
put("funny", this@JsEngine)
}
log("插件引擎v${JsConfig.JS_ENGINE_VERSION}启动完成")
log("开始加载插件……")
//log("源代码:\n${jsBean.code}")
eval()
/**
* FunnyJS : IdScriptableObject
* isOffline : Iter...Function
*/
jsBean = JsBean(
author = funnyJS["author"] as String,
description = funnyJS["description"] as String,
fileName = funnyJS["name"] as String,
version = (funnyJS["version"] as Double).toInt(),
minSupportVersion = getFunnyOrDefault("minSupportVersion", 2),
maxSupportVersion = getFunnyOrDefault("maxSupportVersion", 9999),
targetSupportVersion =
getFunnyOrDefault("targetSupportVersion", JsConfig.JS_ENGINE_VERSION),
debugMode = getFunnyOrDefault("debugMode", false),
isOffline = getFunnyOrDefault("isOffline", false),
supportLanguages = getFunnyListOrDefault("supportLanguages", allLanguages),
id = 999,
code = code,
enabled = 1
)
}.onSuccess {
log("插件加载完毕!")
log(JsConfig.DEBUG_DIVIDER)
log(" 【${jsBean.fileName}】 版本号:${jsBean.version} 作者:${jsBean.author}")
log(" ---> ${jsBean.description}")
log("支持的语言:${jsBean.supportLanguages}")
log(JsConfig.DEBUG_DIVIDER)
onSuccess()
}.onFailure { e ->
when (e) {
is RhinoException -> log("加载插件时出错!${e.messageWithDetail}")
is TypeCastException -> log("加载插件时出错!${e.message}\n【建议检查配置文件名称及返回值是否正确】")
is NullPointerException -> log("加载插件时出错!${e.message}\n【建议检查配置文件名称及返回值是否正确】")
is Exception -> log("加载插件时出错!${e.message}")
}
e.printStackTrace()
onError(e)
}
}
}
private fun <T> getFunnyOrDefault(key: String, default: T): T {
return try {
(funnyJS[key] ?: default) as T
} catch (e: Exception) {
default
}
}
private fun <E> getFunnyListOrDefault(key: String, default: List<E>): List<E> {
return try {
funnyJS[key] ?: return default
val nativeArray = funnyJS[key] as NativeArray
val result = arrayListOf<E>()
for (each in nativeArray) {
result.add(each as E)
}
result
} catch (e: Exception) {
e.printStackTrace()
default
}
}
private fun log(text: String) = Debug.log(text, "[DebugLog-${fileName}]")
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/js/JsEngine.kt
|
1339649996
|
package com.funny.translation.js.config
class JsConfig {
companion object{
val DEBUG_DIVIDER = "=" * 18
const val JS_ENGINE_VERSION = 7
}
}
private operator fun String.times(times: Int): String {
val stringBuilder = StringBuilder()
for(i in 0 until times){
stringBuilder.append(this)
}
return stringBuilder.toString()
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/js/config/JsConfig.kt
|
4151757735
|
package com.funny.translation.js
import com.funny.translation.database.Dao
import com.funny.translation.database.Delete
import com.funny.translation.database.Insert
import com.funny.translation.database.Query
import com.funny.translation.database.Update
import com.funny.translation.js.bean.JsBean
import kotlinx.coroutines.flow.Flow
@Dao
interface JsDao {
@Query("select * from table_js")
fun getAllJsFlow() : Flow<List<JsBean>>
@Query("select * from table_js")
fun getAllJs() : List<JsBean>
@Query("select * from table_js where enabled > 0")
fun getEnabledJs() : Flow<List<JsBean>>
@Query("select count(*) from table_js")
fun getJsCount() : Int
@Query("select * from table_js where fileName=(:name)")
fun queryJsByName(name : String) : JsBean?
@Insert
fun insertJs(jsBean: JsBean)
@Insert
fun insertJsList(jsBeans: List<JsBean>)
@Delete
fun deleteJs(jsBean: JsBean)
@Query("delete from table_js where fileName = (:fileName)")
fun deleteJsByName(fileName: String)
@Update
fun updateJs(jsBean: JsBean)
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/js/JsDao.kt
|
3105867719
|
package com.funny.translation.js.bean
import com.funny.translation.translate.Language
@kotlinx.serialization.Serializable
data class SerializableJsBean(
val id : Int = 0,
val fileName : String = "Plugin",
val code : String = "",
val author : String = "Author",
val version : Int = 1,
val description : String = "",
val enabled : Int = 1,
val minSupportVersion : Int = 2,
val maxSupportVersion : Int = 999, // 自 version 4 起弃用
val targetSupportVersion : Int = 4,
val isOffline : Boolean = false,
val debugMode : Boolean = true,
val supportLanguages: List<Language> = arrayListOf()
){
fun toSQL() = """
insert into table_js($fileName,$code,$author,$version,$description,$enabled,
$minSupportVersion,$maxSupportVersion,$isOffline,$debugMode)
)
""".trimIndent()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as JsBean
if (id != other.id) return false
if (fileName != other.fileName) return false
return true
}
override fun hashCode(): Int {
var result = fileName.hashCode()
result = 31 * result + code.hashCode()
result = 31 * result + version
return result
}
}
typealias JsBean = com.funny.translation.database.Plugin
fun SerializableJsBean.toJsBean() = JsBean(
id = id,
fileName = fileName,
code = code,
author = author,
version = version,
description = description,
enabled = enabled,
minSupportVersion = minSupportVersion,
maxSupportVersion = maxSupportVersion,
targetSupportVersion = targetSupportVersion,
isOffline = isOffline,
debugMode = debugMode,
supportLanguages = supportLanguages
)
//// https://github.com/Kotlin/kotlinx.serialization/blob/v1.6.2/docs/serializers.md#deriving-external-serializer-for-another-kotlin-class-experimental
//@OptIn(ExperimentalSerializationApi::class)
//@Serializer(forClass = JsBean::class)
//object JsBeanSerializer
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/js/bean/JsBean.kt
|
4005360898
|
package com.funny.translation.js
object JsManager {
private val jsMap : HashMap<Int,JsEngine> = HashMap()
var currentRunningJsEngine : JsEngine? = null
fun getJsEngineById(id : Int) : JsEngine? = jsMap[id]
fun addJSEngine(jsEngine: JsEngine){
jsMap[jsEngine.getId()] = jsEngine
}
fun clear(){
jsMap.clear()
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/js/JsManager.kt
|
3227154331
|
package com.funny.translation.js.extentions
import org.mozilla.javascript.NativeArray
import org.mozilla.javascript.NativeObject
import org.mozilla.javascript.RhinoException
import javax.script.ScriptException
val ScriptException.messageWithDetail
get() = "第${this.lineNumber}行、第${this.columnNumber}列发生错误:\n${this.message}"
val RhinoException.messageWithDetail
get() = "第${this.lineNumber()}行、第${this.columnNumber()}列发生错误:\n${this.message}"
val NativeArray.show
get() = this.toArray().joinToString(prefix = "[",postfix = "]")
fun NativeObject.show(
deep : Int = 1
) : String{
val stringBuilder = StringBuilder("{\n")
this.ids.forEach { id->
if (id is String){
val v = this[id]
val value = when(v){
is NativeObject -> v.show(deep+1)
is NativeArray -> v.show
else -> v?.javaClass?.name
}
//println("$id->${this[id]?.javaClass?.name}")
for (i in 0 until deep)stringBuilder.append("\t")
stringBuilder.append("${id}:${value},\n") //删去多余的","
}
}
stringBuilder.deleteCharAt(stringBuilder.length-2)
for (i in 0 until deep-1)stringBuilder.append("\t")
stringBuilder.append("}")
return stringBuilder.toString()
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/js/extentions/JsExtensions.kt
|
2833165003
|
package com.funny.translation.bean
import com.funny.translation.BuildConfig
import java.math.BigDecimal
import java.math.RoundingMode
typealias Price = BigDecimal
fun Price.show(scale: Int = 2): String {
return this.setScale(scale, RoundingMode.HALF_UP).toString()
}
fun Price.showWithUnit(scale: Int = 2): String {
val unit = if (BuildConfig.FLAVOR == "google") "$" else "¥"
return "$unit${this.setScale(scale, RoundingMode.HALF_UP)}"
}
operator fun Price.times(num: Double): Price {
return this.multiply(num.toBigDecimal())
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/bean/Price.kt
|
150379913
|
package com.funny.translation.bean
import com.funny.translation.kmp.base.strings.ResStrings
import java.util.Locale
enum class AppLanguage(val description: String) {
FOLLOW_SYSTEM(ResStrings.follow_system),
ENGLISH("English"),
CHINESE("简体中文");
fun toLocale(): Locale = when (this) {
FOLLOW_SYSTEM -> Locale.getDefault()
ENGLISH -> Locale.ENGLISH
CHINESE -> Locale.CHINESE
}
override fun toString(): String {
return description
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/bean/AppLanguage.kt
|
3432857215
|
package com.funny.translation.bean
import com.funny.translation.translate.Language
data class TranslationConfig(
var sourceString: String? = null,
var sourceLanguage: Language? = null,
var targetLanguage: Language? = null
){
fun clear(){
sourceLanguage = null
sourceString = null
targetLanguage = null
}
fun isValid(): Boolean {
return sourceString?.isNotEmpty() == true && sourceLanguage != null && targetLanguage != null
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/bean/TranslationConfig.kt
|
980774129
|
package com.funny.translation.bean
import kotlinx.serialization.Serializable
@Serializable
data class EditablePrompt(val prefix: String, val suffix: String) {
fun toPrompt(): String {
return prefix + suffix
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/bean/EditablePrompt.kt
|
665185289
|
package com.funny.translation.bean
import androidx.annotation.Keep
import com.funny.translation.helper.BigDecimalSerializer
import com.funny.translation.helper.DateSerializerType1
import com.funny.translation.helper.TimeUtils
import kotlinx.serialization.Serializable
import java.math.BigDecimal
import java.util.*
import kotlin.time.Duration.Companion.days
@Keep
@Serializable
data class UserInfoBean(
val uid: Int = -1,
val username: String = "",
val password: String = "",
val email: String = "",
val phone: String = "",
val password_type: String = "1",
val avatar_url: String = "",
val vip_level: Int = 0,
@Serializable(with = DateSerializerType1::class) val vip_start_time: Date? = null,
val vip_duration: Long = -1,
val jwt_token: String = "",
val img_remain_points: Float = 0.0f,
@Serializable(with = DateSerializerType1::class) val lastChangeUsernameTime: Date? = null,
val invite_code: String = "",
val inviter_uid: Int = -1,
@Serializable(with = BigDecimalSerializer::class)
val ai_text_point: BigDecimal = BigDecimal.ZERO,
@Serializable(with = BigDecimalSerializer::class)
val ai_voice_point: BigDecimal = BigDecimal.ZERO,
) {
fun isValid() = uid >= 0 && jwt_token != ""
fun isValidVip() =
isValid() && (vip_level > 0) && vip_start_time?.time != null
&& vip_start_time.time + vip_duration * 86400 * 1000 > System.currentTimeMillis()
fun vipEndTimeStr() = if (isValidVip()) {
val endTime = vip_start_time!!.time + vip_duration * 86400 * 1000
TimeUtils.formatTime(endTime)
} else {
"--"
}
fun isSoonExpire() =
isValidVip() && vip_start_time!!.time + vip_duration * 86400 * 1000 - System.currentTimeMillis() < 5.days.inWholeMilliseconds
fun canChangeUsername() =
lastChangeUsernameTime?.time == null || System.currentTimeMillis() - lastChangeUsernameTime.time > 30.days.inWholeMilliseconds
fun nextChangeUsernameTimeStr() = if (canChangeUsername()) {
"--"
} else {
val nextTime = lastChangeUsernameTime!!.time + 30.days.inWholeMilliseconds
TimeUtils.formatTime(nextTime)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/bean/UserInfoBean.kt
|
3623291491
|
package com.funny.translation
import com.funny.translation.kmp.KMPActivity
expect open class BaseActivity() : KMPActivity
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/BaseActivity.kt
|
2720132703
|
package com.funny.translation.network
expect object NetworkHelper {
fun isConnected(): Boolean
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/NetworkHelper.kt
|
1314645870
|
package com.funny.translation.network
import androidx.annotation.Keep
import com.funny.translation.kmp.base.strings.ResStrings
@Keep
@kotlinx.serialization.Serializable
data class CommonData<T>(val code: Int, val message: String? = null, val data: T? = null, val error_msg:String? = null) {
val displayErrorMsg get() = error_msg ?: message ?: ResStrings.unknown_error
fun getOrDefault(default: T?): T? = if (code == CODE_SUCCESS) data ?: default else default
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/CommonData.kt
|
1150535018
|
package com.funny.translation.network
import com.funny.translation.helper.toastOnUi
import com.funny.translation.kmp.KMPMain
import com.funny.translation.kmp.appCtx
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import kotlin.reflect.KFunction
import kotlin.reflect.full.callSuspend
const val CODE_SUCCESS = 50
@OptIn(ExperimentalContracts::class)
class Api<T>(
private val func: KFunction<CommonData<T>?>,
private val args: Array<out Any?>,
private val dispatcher: CoroutineDispatcher
) {
private var successFunc = { resp: CommonData<T> ->
appCtx.toastOnUi(resp.message)
}
private var failFunc = { resp: CommonData<T> ->
appCtx.toastOnUi(resp.error_msg ?: resp.message)
}
private var respNullFunc = {
}
private var errorFunc = { err: Throwable ->
appCtx.toastOnUi(err.message)
}
fun success(block: (resp: CommonData<T>) -> Unit) {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
this.successFunc = block
}
fun addSuccess(block: (resp: CommonData<T>) -> Unit) {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
val old = this.successFunc
this.successFunc = { resp ->
old(resp)
block(resp)
}
}
fun fail(block: (resp: CommonData<T>) -> Unit) {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
this.failFunc = block
}
fun addFail(block: (resp: CommonData<T>) -> Unit) {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
val old = this.failFunc
this.failFunc = { resp ->
old(resp)
block(resp)
}
}
fun error(block: (Throwable) -> Unit) {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
this.errorFunc = block
}
fun addError(block: (Throwable) -> Unit) {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
val old = this.errorFunc
this.errorFunc = { err ->
old(err)
block(err)
}
}
suspend fun call(rethrowErr: Boolean = false): T? = withContext(dispatcher) {
try {
val resp = if (func.isSuspend) func.callSuspend(*args) else func.call(*args)
if (resp == null) {
withContext(Dispatchers.KMPMain) {
respNullFunc()
}
return@withContext null
}
if (resp.code == CODE_SUCCESS) {
withContext(Dispatchers.KMPMain) {
successFunc(resp)
}
} else {
withContext(Dispatchers.KMPMain) {
failFunc(resp)
}
}
resp.data
} catch (e: Exception) {
withContext(Dispatchers.KMPMain) {
errorFunc(e)
}
e.printStackTrace()
if (rethrowErr) throw e
null
}
}
}
inline fun <reified T : Any?> apiNoCall(
func: KFunction<CommonData<T>?>,
vararg args: Any?,
dispatcher: CoroutineDispatcher = Dispatchers.IO,
block: Api<T>.() -> Unit = {},
) = Api(func, args = args, dispatcher).apply(block)
suspend inline fun <reified T : Any?> api(
func: KFunction<CommonData<T>?>,
vararg args: Any?,
dispatcher: CoroutineDispatcher = Dispatchers.IO,
rethrowErr: Boolean = false,
block: Api<T>.() -> Unit = {},
) = apiNoCall(func, *args, dispatcher = dispatcher, block = block).call(rethrowErr)
//suspend inline fun <reified T> api(
// noinline func: (args: Array<out Any>) -> CommonData<T>?,
// vararg args: Any?,
// dispatcher: CoroutineDispatcher = Dispatchers.IO,
// block: Api<T>.() -> Unit = {},
//) {
// // Api(func = ::func, args = args, dispatcher = dispatcher).apply(block).call()
//}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/Api.kt
|
2009835108
|
package com.funny.translation.network
import com.funny.translation.AppConfig
import com.funny.translation.helper.ApplicationUtil
import com.funny.translation.helper.DataSaverUtils
import com.funny.translation.helper.JsonX
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type
/** from https://github.com/zhujiang521/PlayAndroid
* 版权:Zhujiang 个人版权
* @author zhujiang
* 版本:1.5
* 创建日期:2021/4/30
* 描述:ServiceCreator
*
* 有修改
*/
object ServiceCreator {
const val TRANS_PATH = "/trans/v1/"
private const val DEFAULT_BASE_URL = "https://api.funnysaltyfish.fun/trans/v1/"
var BASE_URL = readBaseURL()
set(value) {
if (!AppConfig.developerMode.value) return
if (!value.isValidUrl()) return
field = value
DataSaverUtils.saveData("BASE_URL", value)
ApplicationUtil.restartApp()
}
private val retrofit by lazy {
val okHttpClient = OkHttpUtils.okHttpClient
RetrofitBuild(
url = BASE_URL,
client = okHttpClient,
).retrofit
}
private fun readBaseURL(): String {
val url = if (AppConfig.developerMode.value) {
var readUrl = DataSaverUtils.readData("BASE_URL", DEFAULT_BASE_URL)
if (!readUrl.endsWith("/")) readUrl += "/"
if (!readUrl.isValidUrl()) {
readUrl = DEFAULT_BASE_URL
DataSaverUtils.saveData("BASE_URL", readUrl)
}
readUrl
} else DEFAULT_BASE_URL
return url
}
/**
* get ServiceApi
*/
fun <T> create(service: Class<T>): T = retrofit.create(service)
}
/**
* 当相应体为空时直接返回null
*/
class NullOnEmptyConverterFactory : Converter.Factory() {
override fun responseBodyConverter(
type: Type,
annotations: Array<Annotation>,
retrofit: Retrofit
): Converter<ResponseBody, *> {
val delegate: Converter<ResponseBody, *> =
retrofit.nextResponseBodyConverter<Any>(this, type, annotations)
return Converter { body ->
val contentLength = body.contentLength()
if (contentLength == 0L) {
null
} else delegate.convert(body)
}
}
}
class RetrofitBuild(
url: String, client: OkHttpClient,
) {
val retrofit: Retrofit = Retrofit.Builder().apply {
baseUrl(url)
client(client)
addConverterFactory(NullOnEmptyConverterFactory())
addConverterFactory(JsonX.asConverterFactory("application/json".toMediaType()))
}.build()
}
/**
* save cookie string
*/
fun encodeCookie(cookies: List<String>): String {
val sb = StringBuilder()
val set = HashSet<String>()
cookies
.map { cookie ->
cookie.split(";".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
}
.forEach { it ->
it.filterNot { set.contains(it) }.forEach { set.add(it) }
}
val ite = set.iterator()
while (ite.hasNext()) {
val cookie = ite.next()
sb.append(cookie).append(";")
}
val last = sb.lastIndexOf(";")
if (sb.length - 1 == last) {
sb.deleteCharAt(last)
}
return sb.toString()
}
private fun String.isValidUrl() = "https?://[\\w-]+(\\.[\\w-]+)+(:\\d{2,})?([\\w-.,@?^=%&:/~+#]*[\\w@?^=%&/~+#])?".toRegex()
.matches(this)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/ServiceCreator.kt
|
3579163634
|
package com.funny.translation.network
import com.funny.translation.helper.Log
import com.funny.translation.helper.toastOnUi
import com.funny.translation.kmp.appCtx
import com.funny.translation.kmp.base.strings.ResStrings
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
class HttpCacheInterceptor : Interceptor {
companion object{
const val TAG = "HttpCacheInterceptor"
}
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
var request: Request = chain.request()
val connected = NetworkHelper.isConnected()
Log.d(TAG, "intercept: connected:$connected")
if (!connected) {
appCtx.toastOnUi(ResStrings.no_network)
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build()
}
val response: Response = chain.proceed(request)
if (connected) {
val maxAge = 5*60 // read from cache for 5 minute
response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, max-age=$maxAge")
.build()
} else {
val maxStale = 60 * 60 * 24 * 28 // tolerate 4-weeks stale
response.newBuilder()
.removeHeader("Pragma")
.header("Cache-Control", "public, only-if-cached, max-stale=$maxStale")
.build()
}
return response
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/HttpCacheInterceptor.kt
|
2092249121
|
package com.funny.translation.network
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/NetworkConfig.kt
|
4228183737
|
package com.funny.translation.network
import com.funny.translation.helper.Log
import okhttp3.Interceptor
import okhttp3.Response
import retrofit2.Invocation
import java.util.concurrent.TimeUnit
/**
* @Override
* public Response intercept(Chain chain) throws IOException {
* Request request = chain.request();
* //核心代码!!!
* final Invocation tag = request.tag(Invocation.class);
* final Method method = tag != null ? tag.method() : null;
* final DynamicTimeout timeout = method != null ? method.getAnnotation(DynamicTimeout.class) : null;
*
* XLog.d("invocation",tag!= null ? tag.toString() : "");
*
* if(timeout !=null && timeout.timeout() > 0){
*
* Response proceed = chain.withConnectTimeout(timeout.timeout(), TimeUnit.SECONDS)
* .withReadTimeout(timeout.timeout(), TimeUnit.SECONDS)
* .withWriteTimeout(timeout.timeout(), TimeUnit.SECONDS)
* .proceed(request);
* return proceed;
* }
*
* return chain.proceed(request);
* }
*
*/
class DynamicTimeoutInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val tag = request.tag(Invocation::class.java)
val method = tag?.method()
val timeout = method?.getAnnotation(DynamicTimeout::class.java)
if (timeout != null) {
// 大于 0 才设置超时时间,否则使用默认值
Log.i("DynamicTimeoutInterceptor", "reset dynamic timeout: $timeout for url: ${request.url}")
var newChain = chain
if (timeout.connectTimeout > 0) {
newChain = newChain.withConnectTimeout(timeout.connectTimeout, TimeUnit.SECONDS)
}
if (timeout.readTimeout > 0) {
newChain = newChain.withReadTimeout(timeout.readTimeout, TimeUnit.SECONDS)
}
if (timeout.writeTimeout > 0) {
newChain = newChain.withWriteTimeout(timeout.writeTimeout, TimeUnit.SECONDS)
}
Log.d("DynamicTimeoutInterceptor", "proceed timeout: (${newChain.connectTimeoutMillis()}, ${newChain.readTimeoutMillis()}, ${newChain.writeTimeoutMillis()})")
return newChain.proceed(request)
}
return chain.proceed(request)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/DynamicTimeoutInterceptor.kt
|
560678509
|
package com.funny.translation.network
// 动态设置超时时间,包括
// CONNECT_TIMEOUT: 连接超时时间
// READ_TIMEOUT: 读取超时时间
// WRITE_TIMEOUT: 写入超时时间
// 默认为 -1,表示不设置,用默认值
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class DynamicTimeout(
val connectTimeout: Int = -1,
val readTimeout: Int = -1,
val writeTimeout: Int = -1,
)
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/DynamicTimeout.kt
|
2703320041
|
package com.funny.translation.network
//class LoggingInterceptor(
// val print: Boolean = true
//): Interceptor {
// override fun intercept(chain: Interceptor.Chain): Response {
// val request = chain.request()
// // 打印
// log(LINE_SEP)
// log("【Request】")
// log("- Url: ${request.url}")
// log("- Method: ${request.method}")
// log("- Headers: ${request.headers}")
//
// log(LINE_SEP)
// val response = chain.proceed(request)
// // 非流请求打印结果
// log("【Response】")
// log("- Code: ${response.code}, Message: ${response.message}")
// log("- Headers: ${response.headers}")
//
// return response
// }
//
// private fun log(msg: String) {
// if (print) {
// Log.d("LoggingInterceptor", msg)
// }
// }
//
// companion object {
// private val LINE_SEP = "=".repeat(10)
// }
//}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/LoggingInterceptor.kt
|
2766400231
|
package com.funny.translation.network
import androidx.annotation.Keep
import cn.netdiscovery.http.interceptor.LoggingInterceptor
import cn.netdiscovery.http.interceptor.log.LogManager
import cn.netdiscovery.http.interceptor.log.LogProxy
import com.funny.translation.AppConfig
import com.funny.translation.BaseActivity
import com.funny.translation.BuildConfig
import com.funny.translation.GlobalTranslationConfig
import com.funny.translation.helper.CacheManager
import com.funny.translation.helper.DataSaverUtils
import com.funny.translation.helper.LocaleUtils
import com.funny.translation.helper.Log
import com.funny.translation.helper.toastOnUi
import com.funny.translation.kmp.ActivityManager
import com.funny.translation.kmp.appCtx
import com.funny.translation.kmp.base.strings.ResStrings
import com.funny.translation.network.ServiceCreator.TRANS_PATH
import com.funny.translation.sign.SignUtils
import okhttp3.*
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import java.net.URL
import java.util.concurrent.TimeUnit
@Keep
object OkHttpUtils {
private const val SET_COOKIE_KEY = "set-cookie"
private const val COOKIE_NAME = "Cookie"
private const val CONNECT_TIMEOUT = 15L
private const val READ_TIMEOUT = 20L
private const val TAG = "OkHttpUtils"
private fun saveCookie(url: String?, domain: String?, cookies: String) {
url ?: return
DataSaverUtils.saveData(url, cookies)
domain ?: return
DataSaverUtils.saveData(domain, cookies)
}
private val cache = Cache(CacheManager.cacheDir, 1024 * 1024 * 20L)
init {
Log.d(TAG, "cache path: ${CacheManager.cacheDir}")
}
private fun createBaseClient() = OkHttpClient().newBuilder().apply {
connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
cache(cache)
addInterceptor(HttpCacheInterceptor())
// set request cookie
// 添加自定义请求头
addInterceptor {
val request = it.request()
val builder = request.newBuilder()
var newUrl = URL(removeExtraSlashOfUrl(request.url.toString()))
val domain = request.url.host
// get domain cookie
if (domain.isNotEmpty()) {
val spDomain: String = DataSaverUtils.readData(domain, "")
val cookie: String = spDomain.ifEmpty { "" }
if (cookie.isNotEmpty()) {
builder.addHeader(COOKIE_NAME, cookie)
}
}
// 对所有向本项目请求的域名均加上应用名称
if (newUrl.toString().startsWith(ServiceCreator.BASE_URL)){
builder.addHeader("Referer", "FunnyTranslation")
builder.addHeader("User-Agent", "FunnyTranslation/${AppConfig.versionCode}")
builder.addHeader("App-Build-Type", BuildConfig.BUILD_TYPE)
builder.addHeader("App-Flavor", BuildConfig.FLAVOR)
builder.addHeader("Accept-Language", LocaleUtils.getAppLanguage().toLocale().language)
}
// val invocation = request.tag(Invocation::class.java)
// if (invocation != null) {
// // 对 JwtTokenRequired 的注解加上请求头
// val shouldAddToken = invocation.method().getAnnotation(JwtTokenRequired::class.java) != null
// if (shouldAddToken) {
// val jwt = AppConfig.jwtToken
// if (jwt != "") builder.addHeader("Authorization", "Bearer $jwt")
// }
// }
// 访问 trans/v1下的所有api均带上请求头-jwt
if (newUrl.path.startsWith(TRANS_PATH)){
val jwt = AppConfig.jwtToken
if (jwt != "") builder.addHeader("Authorization", "Bearer $jwt")
}
if (newUrl.path.startsWith(TRANS_PATH + "api/translate")){
if (GlobalTranslationConfig.isValid()) {
builder.addHeader("sign", SignUtils.encodeSign(
uid = AppConfig.uid.toLong(), appVersionCode = AppConfig.versionCode,
sourceLanguageCode = GlobalTranslationConfig.sourceLanguage!!.id,
targetLanguageCode = GlobalTranslationConfig.targetLanguage!!.id,
text = GlobalTranslationConfig.sourceString!!,
extra = ""
).also {
Log.d(TAG, "createBaseClient: add sign: $it")
})
// 对于文本翻译,如果是 vip 且开启了显示详细结果,那么加上 show_detail=true
if (!newUrl.path.endsWith("translate_image") && AppConfig.isVip() && AppConfig.sShowDetailResult.value) {
newUrl = URL("$newUrl&show_detail=true")
}
}
}
builder.url(newUrl)
it.proceed(builder.build())
}
addInterceptor(DynamicTimeoutInterceptor())
// get response cookie
addInterceptor { chain ->
val request = chain.request()
val response = chain.proceed(request)
val requestUrl = request.url.toString()
val domain = request.url.host
// token 过期了
// 422: jwt 校验错误
if (response.code in intArrayOf(401, 422) && requestUrl.startsWith(ServiceCreator.BASE_URL)){
val clazz = Class.forName("com.funny.trans.login.LoginActivity")
ActivityManager.start(clazz as Class<BaseActivity>, )
AppConfig.logout()
appCtx.toastOnUi(ResStrings.login_status_expired)
return@addInterceptor response
}
// set-cookie maybe has multi, login to save cookie
if (response.headers(SET_COOKIE_KEY).isNotEmpty()) {
val cookies = response.headers(SET_COOKIE_KEY)
val cookie = encodeCookie(cookies)
saveCookie(requestUrl, domain, cookie)
}
response
}
// 如果不是流式请求,才添加日志拦截器
// if (!response
// addInterceptor(LoggingInterceptor.Builder()
// .setLevel(if (BuildConfig.DEBUG) Level.BASIC else Level.NONE)
// .log(DEBUG)
// .build())
addInterceptor(
LoggingInterceptor.Builder()
.loggable(BuildConfig.DEBUG)
.request()
.response()
.excludePath(TRANS_PATH + "ai/ask_stream")
.build()
)
LogManager.logProxy(object: LogProxy {
override fun d(tag: String, msg: String) {
Log.d(tag, msg)
}
override fun e(tag: String, msg: String) {
Log.e(tag, msg)
}
override fun i(tag: String, msg: String) {
Log.i(tag, msg)
}
override fun w(tag: String, msg: String) {
Log.w(tag, msg)
}
})
}.build()
val okHttpClient by lazy {
createBaseClient()
}
@JvmOverloads
fun get(
url: String,
headersMap: HashMap<String, String>? = null,
params: HashMap<String, String>? = null,
timeout: IntArray? = null // [connectTimeout, readTimeout, writeTimeout]
): String {
val response = getResponse(url, headersMap, params, timeout)
return response.body?.string() ?: ""
}
@JvmOverloads
fun getRaw(
url: String,
headersMap: HashMap<String, String>? = null,
params: HashMap<String, String>? = null,
timeout: IntArray? = null // [connectTimeout, readTimeout, writeTimeout]
): ByteArray {
val response = getResponse(url, headersMap, params, timeout)
return response.body?.bytes() ?: ByteArray(0)
}
@JvmOverloads
fun getResponse(
url: String,
headersMap: HashMap<String, String>? = null,
params: HashMap<String, String>? = null,
timeout: IntArray? = null // [connectTimeout, readTimeout, writeTimeout]
): Response {
val urlBuilder = url.toHttpUrl().newBuilder()
params?.let {
for ((key, value) in it) {
urlBuilder.addQueryParameter(key, value)
}
}
val requestBuilder = Request.Builder().url(urlBuilder.build()).get()
headersMap?.let {
requestBuilder.addHeaders(it)
}
val client = getClient(timeout)
return client.newCall(requestBuilder.build()).execute()
}
@Throws(IOException::class)
@JvmOverloads
fun postJSON(
url: String,
json: String,
headers: HashMap<String, String>? = null,
timeout: IntArray? = null
): String {
val JSON = "application/json; charset=utf-8".toMediaTypeOrNull()
val body: RequestBody = json.toRequestBody(JSON)
val requestBuilder = Request.Builder()
.url(url)
.post(body)
headers?.let {
requestBuilder.addHeaders(headers)
}
val response: Response = getClient(timeout).newCall(requestBuilder.build()).execute()
return response.body?.string() ?: ""
}
@JvmOverloads
fun postForm(
url: String,
form: HashMap<String, String>,
headers: HashMap<String, String>? = null,
timeout: IntArray? = null
): String {
val builder = FormBody.Builder()
for ((key, value) in form) {
builder.add(key, value)
}
val body: RequestBody = builder.build()
val requestBuilder = Request.Builder()
.url(url)
.post(body)
headers?.let {
requestBuilder.addHeaders(headers)
}
val response: Response = getClient(timeout).newCall(requestBuilder.build()).execute()
return response.body?.string() ?: ""
}
@JvmOverloads
fun postMultiForm(
url: String,
body: RequestBody,
headers: HashMap<String, String>? = null,
timeout: IntArray? = null
): String {
val requestBuilder = Request.Builder()
.url(url)
.post(body)
headers?.let {
requestBuilder.addHeaders(headers)
}
val response: Response = getClient(timeout).newCall(requestBuilder.build()).execute()
return response.body?.string() ?: ""
}
@JvmOverloads
fun getClient(timeout: IntArray? = null): OkHttpClient {
var client = okHttpClient
timeout?.let {
if (it.size == 3) {
Log.d(TAG, "getClient: reset timeout: ${it.joinToString()}")
client = okHttpClient.newBuilder()
.connectTimeout(it[0].toLong(), TimeUnit.SECONDS)
.readTimeout(it[1].toLong(), TimeUnit.SECONDS)
.writeTimeout(it[2].toLong(), TimeUnit.SECONDS)
.build()
}
}
return client
}
private fun Request.Builder.addHeaders(headers: Map<String, String>) {
headers.forEach {
addHeader(it.key, it.value)
}
}
fun removeExtraSlashOfUrl(url: String): String {
return if (url.isEmpty()) {
url
} else url.replace("(?<!(http:|https:))/+".toRegex(), "/")
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/OkHttpUtils.kt
|
2621665581
|
package com.funny.translation.network.service
import com.funny.translation.bean.UserInfoBean
import com.funny.translation.network.CommonData
import kotlinx.serialization.Serializable
import okhttp3.MultipartBody
import retrofit2.http.Body
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
@Serializable
data class InvitedUser(
val uid: Int,
val register_time: String
)
interface UserService {
@POST("user/verify_email")
@FormUrlEncoded
suspend fun verifyEmail(
@Field("email") email: String,
@Field("verify_code") verifyCode: String
): CommonData<Unit>
@POST("user/send_verify_email")
@FormUrlEncoded
suspend fun sendVerifyEmail(
@Field("username") username: String,
@Field("email") email: String
): CommonData<Unit>
// sendFindUsernameEmail
@POST("user/send_find_username_email")
@FormUrlEncoded
suspend fun sendFindUsernameEmail(
@Field("email") email: String
): CommonData<Unit>
// sendResetPasswordEmail
@POST("user/send_reset_password_email")
@FormUrlEncoded
suspend fun sendResetPasswordEmail(
@Field("username") username: String,
@Field("email") email: String
): CommonData<Unit>
// fun sendCancelAccountEmail(username: String, email: String)
@POST("user/send_cancel_account_email")
@FormUrlEncoded
suspend fun sendCancelAccountEmail(
@Field("username") username: String,
@Field("email") email: String
): CommonData<Unit>
@POST("user/register")
@FormUrlEncoded
suspend fun register(
@Field("username") username: String,
@Field("password") password: String,
@Field("password_type") passwordType: String,
@Field("email") email: String,
@Field("phone") phone: String,
@Field("invite_code") inviteCode: String
): CommonData<Unit>
@POST("user/login")
@FormUrlEncoded
suspend fun login(
@Field("username") username: String,
@Field("password") password: String,
@Field("password_type") passwordType: String,
@Field("email") email: String,
@Field("phone") phone: String,
@Field("verify_code") verifyCode: String,
@Field("did") did: String
): CommonData<UserInfoBean>
@POST("user/logout")
@FormUrlEncoded
// uid: Int, did: String
suspend fun logout(
@Field("uid") uid: Int,
@Field("did") did: String
): CommonData<Unit>
@POST("user/get_user_info")
@FormUrlEncoded
suspend fun getInfo(
@Field("uid") uid: Int
): CommonData<UserInfoBean>
@POST("user/get_user_email")
@FormUrlEncoded
suspend fun getUserEmail(
@Field("username") username: String
): CommonData<String>
@POST("user/refresh_token")
@FormUrlEncoded
suspend fun refreshToken(
@Field("uid") uid: Int
): CommonData<String>
@POST("user/change_avatar")
suspend fun uploadAvatar(
@Body body: MultipartBody
): CommonData<String>
// resetPassword
@POST("user/reset_password")
@FormUrlEncoded
suspend fun resetPassword(
@Field("username") username: String,
@Field("password") password: String,
@Field("code") code: String
): CommonData<Unit>
// findUsername
@POST("user/find_username_by_email")
@FormUrlEncoded
suspend fun findUsername(
@Field("email") email: String,
@Field("code") code: String
): CommonData<List<String>>
// changeUsername
@POST("user/change_username")
@FormUrlEncoded
suspend fun changeUsername(
@Field("uid") uid: Int,
@Field("new_username") username: String,
): CommonData<Unit>
// cancelUser
@POST("user/cancel_account")
@FormUrlEncoded
suspend fun cancelAccount(
@Field("verify_code") verifyCode: String,
): CommonData<Unit>
// generateInviteCode
@POST("user/generate_invite_code")
suspend fun generateInviteCode(): CommonData<String>
// getInviteUsers
@POST("user/get_invite_users")
suspend fun getInviteUsers(): CommonData<List<InvitedUser>>
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/network/service/UserService.kt
|
435760077
|
package com.funny.translation.kmp
import com.eygraber.uri.Uri as KMPUri
expect fun KMPUri.writeText(text: String)
expect fun KMPUri.readText(): String
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/Uri.kt
|
3728629686
|
package com.funny.translation.kmp
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.graphics.painter.Painter
import org.jetbrains.compose.resources.DrawableResource
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.imageResource
@OptIn(ExperimentalResourceApi::class)
@Composable
fun painterDrawableRes(name: String, suffix: String = "png"): Painter {
val res = if (name.contains('.')) name else "$name.$suffix"
return painterResource("drawable/$res")
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun painterResource(resource: String): Painter {
return BitmapPainter(imageResource(DrawableResource(resource)))
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/Resources.kt
|
1966360995
|
package com.funny.translation.kmp
import androidx.compose.runtime.Composable
import com.eygraber.uri.Uri
/**
* KMP Launcher
* @author FunnySaltyFish
*/
abstract class Launcher<Input, Output> {
abstract fun launch(input: Input)
}
expect class FileLauncher<Input>: Launcher<Input, Uri?> {
override fun launch(input: Input)
}
@Composable
expect fun rememberCreateFileLauncher(
mimeType: String = "*/*",
onResult: (Uri?) -> Unit = {},
): FileLauncher<String>
@Composable
expect fun rememberOpenFileLauncher(
onResult: (Uri?) -> Unit = {},
): FileLauncher<Array<String>>
//@Composable
//expect fun <Input> rememberSelectPhotoUriLauncher(
// onResult: (Uri?) -> Unit = {},
//): FileLauncher<Input>
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/Launcher.kt
|
1884252932
|
package com.funny.translation.kmp
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.FiniteAnimationSpec
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.slideOutVertically
import androidx.compose.ui.unit.IntOffset
// 由于原本的 slideInHorizontally 和 slideOutHorizontally 只在 AnimatedContentTransitionScope 里提供
// PreCompose 提供的函数并没有这玩意儿,所以这里没办法自己实现
fun slideIntoContainer(
direction: AnimatedContentTransitionScope.SlideDirection,
animationSpec: FiniteAnimationSpec<IntOffset> = tween()
): EnterTransition {
return when (direction) {
AnimatedContentTransitionScope.SlideDirection.Left, AnimatedContentTransitionScope.SlideDirection.Start -> {
slideInHorizontally(
initialOffsetX = { it },
animationSpec = animationSpec,
)
}
AnimatedContentTransitionScope.SlideDirection.Right, AnimatedContentTransitionScope.SlideDirection.End -> {
slideInHorizontally(
initialOffsetX = { -it },
animationSpec = animationSpec,
)
}
AnimatedContentTransitionScope.SlideDirection.Up -> {
slideInVertically(
initialOffsetY = { it },
animationSpec = animationSpec,
)
}
AnimatedContentTransitionScope.SlideDirection.Down -> {
slideInVertically(
initialOffsetY = { -it },
animationSpec = animationSpec,
)
}
else -> error("no such case")
}
}
fun slideOutOfContainer(
direction: AnimatedContentTransitionScope.SlideDirection,
animationSpec: FiniteAnimationSpec<IntOffset> = tween()
): ExitTransition {
return when (direction) {
AnimatedContentTransitionScope.SlideDirection.Left, AnimatedContentTransitionScope.SlideDirection.Start -> {
slideOutHorizontally(
targetOffsetX = { it },
animationSpec = animationSpec,
)
}
AnimatedContentTransitionScope.SlideDirection.Right, AnimatedContentTransitionScope.SlideDirection.End -> {
slideOutHorizontally(
targetOffsetX = { -it },
animationSpec = animationSpec,
)
}
AnimatedContentTransitionScope.SlideDirection.Up -> {
slideOutVertically(
targetOffsetY = { it },
animationSpec = animationSpec,
)
}
AnimatedContentTransitionScope.SlideDirection.Down -> {
slideOutVertically(
targetOffsetY = { -it },
animationSpec = animationSpec,
)
}
else -> error("no such case")
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/Animation.kt
|
961805792
|
package com.funny.translation.kmp
enum class Platform {
Android, Desktop
}
expect fun getPlatform(): Platform
val currentPlatform: Platform by lazy { getPlatform() }
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/Platform.kt
|
3863447228
|
package com.funny.translation.kmp
import androidx.compose.runtime.Composable
import com.funny.translation.helper.Log
import moe.tlaster.precompose.viewmodel.ViewModel
// 为了方便的使用 PreCompose 提供的 ViewModel
@Composable
inline fun <reified T: ViewModel> viewModel(): T {
return moe.tlaster.precompose.viewmodel.viewModel(listOf()) {
Log.d("ViewModel", "create ${T::class.java.simpleName}")
T::class.java.getConstructor().newInstance()
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/ViewModel.kt
|
3603252646
|
package com.funny.translation.kmp
import androidx.compose.runtime.ProvidableCompositionLocal
import java.io.InputStream
expect abstract class KMPContext {
fun getString(id: Int): String
fun getString(id: Int, vararg args: Any?): String
}
expect fun KMPContext.openAssetsFile(fileName: String): InputStream
expect fun KMPContext.readAssetsFile(fileName: String): String
expect val LocalKMPContext: ProvidableCompositionLocal<KMPContext>
expect val appCtx: KMPContext
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/Context.kt
|
3971723328
|
package com.funny.translation.kmp
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.compositeOver
import androidx.compose.ui.graphics.luminance
// SharedCode
// copied from accompanist
@Stable
interface SystemUiController {
var systemBarsBehavior: Int
var isStatusBarVisible: Boolean
var isNavigationBarVisible: Boolean
var isSystemBarsVisible: Boolean
get() = isNavigationBarVisible && isStatusBarVisible
set(value) {
isStatusBarVisible = value
isNavigationBarVisible = value
}
fun setStatusBarColor(
color: Color,
darkIcons: Boolean = color.luminance() > 0.5f,
transformColorForLightContent: (Color) -> Color = { it }
)
fun setNavigationBarColor(
color: Color,
darkIcons: Boolean = color.luminance() > 0.5f,
navigationBarContrastEnforced: Boolean = true,
transformColorForLightContent: (Color) -> Color = { it }
)
var statusBarDarkContentEnabled: Boolean
var navigationBarDarkContentEnabled: Boolean
public var systemBarsDarkContentEnabled: Boolean
get() = statusBarDarkContentEnabled && navigationBarDarkContentEnabled
set(value) {
statusBarDarkContentEnabled = value
navigationBarDarkContentEnabled = value
}
var isNavigationBarContrastEnforced: Boolean
public fun setSystemBarsColor(
color: Color,
darkIcons: Boolean = color.luminance() > 0.5f,
isNavigationBarContrastEnforced: Boolean = true,
transformColorForLightContent: (Color) -> Color = BlackScrimmed
) {
setStatusBarColor(color, darkIcons, transformColorForLightContent)
setNavigationBarColor(
color,
darkIcons,
isNavigationBarContrastEnforced,
transformColorForLightContent
)
}
}
private val BlackScrim = Color(0f, 0f, 0f, 0.3f) // 30% opaque black
private val BlackScrimmed: (Color) -> Color = { original ->
BlackScrim.compositeOver(original)
}
@Composable
expect fun rememberSystemUiController(): SystemUiController
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/SystemUiController.kt
|
3735983651
|
package com.funny.translation.kmp
import androidx.compose.ui.Modifier
expect fun Modifier.kmpImeNestedScroll(): Modifier
fun Modifier.ifThen(condition: Boolean, then: Modifier): Modifier {
return if (condition) then else this
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/Modifiers.kt
|
745721980
|
package com.funny.translation.kmp
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import moe.tlaster.precompose.navigation.BackStackEntry
import moe.tlaster.precompose.navigation.Navigator
import moe.tlaster.precompose.navigation.RouteBuilder
import moe.tlaster.precompose.navigation.rememberNavigator
import moe.tlaster.precompose.navigation.transition.NavTransition
// adapt androidx.navigation to precompose's navigation
typealias NavController = Navigator
typealias NavHostController = Navigator
typealias NavGraphBuilder = RouteBuilder
typealias NavDeepLink = String
typealias NavBackStackEntry = BackStackEntry
typealias NamedNavArgument = String
@Composable
fun rememberNavController() = rememberNavigator()
fun NavController.navigateUp() {
popBackStack()
}
fun NavBackStackEntry.getQueryString(key: String, default: String? = null): String? {
return queryString?.map?.get(key)?.firstOrNull() ?: return default
}
fun NavBackStackEntry.getQueryInt(key: String, default: Int? = null): Int? {
return queryString?.map?.get(key)?.firstOrNull()?.toIntOrNull() ?: return default
}
fun NavBackStackEntry.getQueryBoolean(key: String, default: Boolean = false): Boolean {
return queryString?.map?.get(key)?.firstOrNull()?.toBoolean() ?: return default
}
// Long
fun NavBackStackEntry.getQueryLong(key: String, default: Long? = null): Long? {
return queryString?.map?.get(key)?.firstOrNull()?.toLongOrNull() ?: return default
}
fun NavGraphBuilder.composable(
route: String,
arguments: List<NamedNavArgument> = emptyList(),
deepLinks: List<NavDeepLink> = emptyList(),
enterTransition: (() -> EnterTransition) =
{ fadeIn(animationSpec = tween(700)) },
exitTransition: (() -> ExitTransition) =
{ fadeOut(animationSpec = tween(700)) },
popEnterTransition: (() -> EnterTransition) =
enterTransition,
popExitTransition: (() -> ExitTransition) =
exitTransition,
content: @Composable (NavBackStackEntry) -> Unit,
) {
scene(
route,
deepLinks,
navTransition = NavTransition(
createTransition = enterTransition(),
destroyTransition = exitTransition(),
pauseTransition = popExitTransition(),
resumeTransition = popEnterTransition(),
),
) {
content(it)
}
}
// navigation(
// startDestination = TranslateScreen.LongTextTransScreen.route,
// route = "nav_1_long_text_trans"
// ) {
fun NavGraphBuilder.navigation(
startDestination: String,
route: String,
builder: NavGraphBuilder.() -> Unit,
) {
group(
route,
initialRoute = startDestination,
) {
builder()
}
}
@Composable
fun NavHost(
navController: NavController,
startDestination: String,
modifier: Modifier = Modifier,
enterTransition: (() -> EnterTransition) =
{ slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Left) },
exitTransition: (() -> ExitTransition) =
{ slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Left) },
popEnterTransition: (() -> EnterTransition) =
{ slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Right) },
popExitTransition: (() -> ExitTransition) =
{ slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Right) },
builder: NavGraphBuilder.() -> Unit,
) {
moe.tlaster.precompose.navigation.NavHost(
navigator = navController,
initialRoute = startDestination,
modifier = modifier,
navTransition = NavTransition(
createTransition = enterTransition(),
destroyTransition = exitTransition(),
pauseTransition = popExitTransition(),
resumeTransition = popEnterTransition(),
),
builder = builder,
)
}
const val NAV_ANIM_DURATION = 500
fun NavGraphBuilder.animateComposable(
route: String,
animDuration: Int = NAV_ANIM_DURATION,
arguments: List<NamedNavArgument> = emptyList(),
deepLinks: List<NavDeepLink> = emptyList(),
content: @Composable (NavBackStackEntry) -> Unit
) {
composable(
route,
arguments = arguments,
deepLinks = deepLinks,
enterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(animDuration)
)
},
exitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(animDuration)
)
},
popEnterTransition = {
slideIntoContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(animDuration)
)
},
popExitTransition = {
slideOutOfContainer(
AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(animDuration)
)
}
) { entry ->
content(entry)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/Navigation.kt
|
1299967660
|
package com.funny.translation.kmp.paging
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.paging.CombinedLoadStates
import androidx.paging.DifferCallback
import androidx.paging.ItemSnapshotList
import androidx.paging.LoadState
import androidx.paging.LoadStates
import androidx.paging.NullPaddedList
import androidx.paging.PagingData
import androidx.paging.PagingDataDiffer
import com.funny.translation.kmp.KMPMain
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
/**
* The class responsible for accessing the data from a [Flow] of [PagingData].
* In order to obtain an instance of [LazyPagingItems] use the [collectAsLazyPagingItems] extension
* method of [Flow] with [PagingData].
* This instance can be used for Lazy foundations such as [LazyListScope.items] to display data
* received from the [Flow] of [PagingData].
*
* Previewing [LazyPagingItems] is supported on a list of mock data. See sample for how to preview
* mock data.
*
* @sample androidx.paging.compose.samples.PagingPreview
*
* @param T the type of value used by [PagingData].
*/
public class LazyPagingItems<T : Any> internal constructor(
/**
* the [Flow] object which contains a stream of [PagingData] elements.
*/
private val flow: Flow<PagingData<T>>
) {
private val mainDispatcher = Dispatchers.KMPMain
private val differCallback: DifferCallback = object : DifferCallback {
override fun onChanged(position: Int, count: Int) {
if (count > 0) {
updateItemSnapshotList()
}
}
override fun onInserted(position: Int, count: Int) {
if (count > 0) {
updateItemSnapshotList()
}
}
override fun onRemoved(position: Int, count: Int) {
if (count > 0) {
updateItemSnapshotList()
}
}
}
/**
* If the [flow] is a SharedFlow, it is expected to be the flow returned by from
* pager.flow.cachedIn(scope) which could contain a cached PagingData. We pass the cached
* PagingData to the differ so that if the PagingData contains cached data, the differ can be
* initialized with the data prior to collection on pager.
*/
private val pagingDataDiffer = object : PagingDataDiffer<T>(
differCallback = differCallback,
mainContext = mainDispatcher,
cachedPagingData = if (flow is SharedFlow<PagingData<T>>) flow.replayCache.firstOrNull() else null
) {
override suspend fun presentNewList(
previousList: NullPaddedList<T>,
newList: NullPaddedList<T>,
lastAccessedIndex: Int,
onListPresentable: () -> Unit
): Int? {
onListPresentable()
updateItemSnapshotList()
return null
}
}
/**
* Contains the immutable [ItemSnapshotList] of currently presented items, including any
* placeholders if they are enabled.
* Note that similarly to [peek] accessing the items in a list will not trigger any loads.
* Use [get] to achieve such behavior.
*/
var itemSnapshotList by mutableStateOf(
pagingDataDiffer.snapshot()
)
private set
/**
* The number of items which can be accessed.
*/
val itemCount: Int get() = itemSnapshotList.size
private fun updateItemSnapshotList() {
itemSnapshotList = pagingDataDiffer.snapshot()
}
/**
* Returns the presented item at the specified position, notifying Paging of the item access to
* trigger any loads necessary to fulfill prefetchDistance.
*
* @see peek
*/
operator fun get(index: Int): T? {
pagingDataDiffer[index] // this registers the value load
return itemSnapshotList[index]
}
/**
* Returns the presented item at the specified position, without notifying Paging of the item
* access that would normally trigger page loads.
*
* @param index Index of the presented item to return, including placeholders.
* @return The presented item at position [index], `null` if it is a placeholder
*/
fun peek(index: Int): T? {
return itemSnapshotList[index]
}
/**
* Retry any failed load requests that would result in a [LoadState.Error] update to this
* [LazyPagingItems].
*
* Unlike [refresh], this does not invalidate [PagingSource], it only retries failed loads
* within the same generation of [PagingData].
*
* [LoadState.Error] can be generated from two types of load requests:
* * [PagingSource.load] returning [PagingSource.LoadResult.Error]
* * [RemoteMediator.load] returning [RemoteMediator.MediatorResult.Error]
*/
fun retry() {
pagingDataDiffer.retry()
}
/**
* Refresh the data presented by this [LazyPagingItems].
*
* [refresh] triggers the creation of a new [PagingData] with a new instance of [PagingSource]
* to represent an updated snapshot of the backing dataset. If a [RemoteMediator] is set,
* calling [refresh] will also trigger a call to [RemoteMediator.load] with [LoadType] [REFRESH]
* to allow [RemoteMediator] to check for updates to the dataset backing [PagingSource].
*
* Note: This API is intended for UI-driven refresh signals, such as swipe-to-refresh.
* Invalidation due repository-layer signals, such as DB-updates, should instead use
* [PagingSource.invalidate].
*
* @see PagingSource.invalidate
*/
fun refresh() {
pagingDataDiffer.refresh()
}
/**
* A [CombinedLoadStates] object which represents the current loading state.
*/
public var loadState: CombinedLoadStates by mutableStateOf(
pagingDataDiffer.loadStateFlow.value
?: CombinedLoadStates(
refresh = InitialLoadStates.refresh,
prepend = InitialLoadStates.prepend,
append = InitialLoadStates.append,
source = InitialLoadStates
)
)
private set
internal suspend fun collectLoadState() {
pagingDataDiffer.loadStateFlow.filterNotNull().collect {
loadState = it
}
}
internal suspend fun collectPagingData() {
flow.collectLatest {
pagingDataDiffer.collectFrom(it)
}
}
private companion object {
}
}
private val IncompleteLoadState = LoadState.NotLoading(false)
private val InitialLoadStates = LoadStates(
LoadState.Loading,
IncompleteLoadState,
IncompleteLoadState
)
/**
* Collects values from this [Flow] of [PagingData] and represents them inside a [LazyPagingItems]
* instance. The [LazyPagingItems] instance can be used for lazy foundations such as
* [LazyListScope.items] in order to display the data obtained from a [Flow] of [PagingData].
*
* @sample androidx.paging.compose.samples.PagingBackendSample
*
* @param context the [CoroutineContext] to perform the collection of [PagingData]
* and [CombinedLoadStates].
*/
@Composable
public fun <T : Any> Flow<PagingData<T>>.collectAsLazyPagingItems(
context: CoroutineContext = EmptyCoroutineContext
): LazyPagingItems<T> {
val lazyPagingItems = remember(this) { LazyPagingItems(this) }
LaunchedEffect(lazyPagingItems) {
if (context == EmptyCoroutineContext) {
lazyPagingItems.collectPagingData()
} else {
withContext(context) {
lazyPagingItems.collectPagingData()
}
}
}
LaunchedEffect(lazyPagingItems) {
if (context == EmptyCoroutineContext) {
lazyPagingItems.collectLoadState()
} else {
withContext(context) {
lazyPagingItems.collectLoadState()
}
}
}
return lazyPagingItems
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/paging/LazyPagingItems.kt
|
1046921280
|
package com.funny.translation.kmp.paging
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import androidx.compose.foundation.lazy.grid.LazyGridScope
import androidx.paging.PagingConfig
/**
* Returns a factory of stable and unique keys representing the item.
*
* Keys are generated with the key lambda that is passed in. If null is passed in, keys will
* default to a placeholder key. If [PagingConfig.enablePlaceholders] is true,
* LazyPagingItems may return null items. Null items will also automatically default to
* a placeholder key.
*
* This factory can be applied to Lazy foundations such as [LazyGridScope.items] or Pagers.
* Examples:
* @sample androidx.paging.compose.samples.PagingWithHorizontalPager
* @sample androidx.paging.compose.samples.PagingWithLazyGrid
*
* @param [key] a factory of stable and unique keys representing the item. Using the same key
* for multiple items in the list is not allowed. Type of the key should be saveable
* via Bundle on Android. When you specify the key the scroll position will be maintained
* based on the key, which means if you add/remove items before the current visible item the
* item with the given key will be kept as the first visible one.
*/
@Suppress("PrimitiveInLambda")
fun <T : Any> LazyPagingItems<T>.itemKey(
key: ((item: @JvmSuppressWildcards T) -> Any)? = null
): (index: Int) -> Any {
return { index ->
if (key == null) {
PagingPlaceholderKey(index)
} else {
val item = peek(index)
if (item == null) PagingPlaceholderKey(index) else key(item)
}
}
}
/**
* Returns a factory for the content type of the item.
*
* ContentTypes are generated with the contentType lambda that is passed in. If null is passed in,
* contentType of all items will default to `null`.
* If [PagingConfig.enablePlaceholders] is true, LazyPagingItems may return null items. Null
* items will automatically default to placeholder contentType.
*
* This factory can be applied to Lazy foundations such as [LazyGridScope.items] or Pagers.
* Examples:
* @sample androidx.paging.compose.samples.PagingWithLazyGrid
* @sample androidx.paging.compose.samples.PagingWithLazyList
*
* @param [contentType] a factory of the content types for the item. The item compositions of
* the same type could be reused more efficiently. Note that null is a valid type and items of
* such type will be considered compatible.
*/
@Suppress("PrimitiveInLambda")
fun <T : Any> LazyPagingItems<T>.itemContentType(
contentType: ((item: @JvmSuppressWildcards T) -> Any?)? = null
): (index: Int) -> Any? {
return { index ->
if (contentType == null) {
null
} else {
val item = peek(index)
if (item == null) PagingPlaceholderContentType else contentType(item)
}
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/paging/LazyFoundationExtensions.kt
|
1438293105
|
package com.funny.translation.kmp.paging
import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.runtime.Composable
fun <T: Any> LazyListScope.items(
items: LazyPagingItems<T>,
key: ( (T) -> Any )? = null,
contentType: ( (T) -> Any )? = null,
itemContent: @Composable LazyItemScope.(T) -> Unit
) {
items(
items.itemCount,
key = items.itemKey(key),
contentType = items.itemContentType(contentType)
) loop@ { i ->
val item = items[i] ?: return@loop
itemContent(item)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/paging/ItemsEx.kt
|
2779006235
|
package com.funny.translation.kmp.paging
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
internal expect class PagingPlaceholderKey(index: Int) {
val index: Int
}
internal object PagingPlaceholderContentType
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/paging/PagingPlaceHolderContentType.kt
|
986032074
|
package com.funny.translation.kmp
import com.funny.translation.BaseActivity
import moe.tlaster.precompose.navigation.NavOptions
// KMP Activity Manager, used to manage the activity stack
// in Android, it will manage the android.app.Activity
// in Desktop, it will manage the Window
typealias DataType = Map<String, Any?>
expect object ActivityManager {
val activityStack : MutableList<BaseActivity>
fun addActivity(activity: BaseActivity)
fun removeActivity(activity: BaseActivity)
fun currentActivity(): BaseActivity?
fun start(targetClass: Class<out BaseActivity>, data: MutableMap<String, Any?> = hashMapOf(), options: NavOptions = NavOptions(), onBack: (result: Map<String, Any?>?) -> Unit = {})
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/ActivityManager.kt
|
4281078641
|
package com.funny.translation.kmp
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import androidx.annotation.AnimRes
import androidx.annotation.AnimatorRes
import androidx.annotation.IdRes
import moe.tlaster.precompose.navigation.NavOptions
import moe.tlaster.precompose.navigation.PopUpTo
@DslMarker
public annotation class NavOptionsDsl
/**
* Construct a new [NavOptions]
*/
public fun navOptions(optionsBuilder: NavOptionsBuilder.() -> Unit): NavOptions =
NavOptionsBuilder().apply(optionsBuilder).build()
/**
* DSL for constructing a new [NavOptions]
*/
@NavOptionsDsl
public class NavOptionsBuilder {
private var options = NavOptions()
/**
* Whether this navigation action should launch as single-top (i.e., there will be at most
* one copy of a given destination on the top of the back stack).
*
* This functions similarly to how [android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP]
* works with activites.
*/
public var launchSingleTop: Boolean = false
/**
* Whether this navigation action should restore any state previously saved
* by [PopUpToBuilder.saveState] or the `popUpToSaveState` attribute. If no state was
* previously saved with the destination ID being navigated to, this has no effect.
*/
@get:Suppress("GetterOnBuilder", "GetterSetterNames")
@set:Suppress("SetterReturnsThis", "GetterSetterNames")
public var restoreState: Boolean = false
/**
* Returns the current destination that the builder will pop up to.
*/
@IdRes
public var popUpToId: Int = -1
internal set(value) {
field = value
inclusive = false
}
/**
* Pop up to a given destination before navigating. This pops all non-matching destinations
* from the back stack until this destination is found.
*/
@Deprecated("Use the popUpToId property.")
public var popUpTo: Int
get() = popUpToId
@Deprecated("Use the popUpTo function and passing in the id.")
set(value) {
popUpTo(value)
}
/**
* Pop up to a given destination before navigating. This pops all non-matching destinations
* from the back stack until this destination is found.
*/
public var popUpToRoute: String? = null
private set(value) {
if (value != null) {
require(value.isNotBlank()) { "Cannot pop up to an empty route" }
field = value
inclusive = false
}
}
private var inclusive = false
private var saveState = false
/**
* Pop up to a given destination before navigating. This pops all non-matching destinations
* from the back stack until this destination is found.
*/
public fun popUpTo(@IdRes id: Int, popUpToBuilder: PopUpToBuilder.() -> Unit = {}) {
popUpToId = id
popUpToRoute = null
val builder = PopUpToBuilder().apply(popUpToBuilder)
inclusive = builder.inclusive
saveState = builder.saveState
}
/**
* Pop up to a given destination before navigating. This pops all non-matching destination routes
* from the back stack until the destination with a matching route is found.
*
* @param route route for the destination
* @param popUpToBuilder builder used to construct a popUpTo operation
*/
public fun popUpTo(route: String, popUpToBuilder: PopUpToBuilder.() -> Unit = {}) {
popUpToRoute = route
popUpToId = -1
val builder = PopUpToBuilder().apply(popUpToBuilder)
inclusive = builder.inclusive
saveState = builder.saveState
}
internal fun build(): NavOptions {
options = options.copy(
launchSingleTop = this.launchSingleTop,
popUpTo = PopUpTo(
route = popUpToRoute ?: "",
inclusive = this.inclusive,
)
)
return options
}
}
/**
* DSL for customizing [NavOptionsBuilder.popUpTo] operations.
*/
@NavOptionsDsl
public class PopUpToBuilder {
/**
* Whether the `popUpTo` destination should be popped from the back stack.
*/
public var inclusive: Boolean = false
/**
* Whether the back stack and the state of all destinations between the
* current destination and the [NavOptionsBuilder.popUpTo] ID should be saved for later
* restoration via [NavOptionsBuilder.restoreState] or the `restoreState` attribute using
* the same [NavOptionsBuilder.popUpTo] ID (note: this matching ID is true whether
* [inclusive] is true or false).
*/
@get:Suppress("GetterOnBuilder", "GetterSetterNames")
@set:Suppress("SetterReturnsThis", "GetterSetterNames")
public var saveState: Boolean = false
}
/**
* DSL for setting custom Animation or Animator resources on a [NavOptionsBuilder]
*/
@NavOptionsDsl
public class AnimBuilder {
/**
* The custom Animation or Animator resource for the enter animation.
*
* Note: Animator resources are not supported for navigating to a new Activity
*/
@AnimRes
@AnimatorRes
public var enter: Int = -1
/**
* The custom Animation or Animator resource for the exit animation.
*
* Note: Animator resources are not supported for navigating to a new Activity
*/
@AnimRes
@AnimatorRes
public var exit: Int = -1
/**
* The custom Animation or Animator resource for the enter animation
* when popping off the back stack.
*
* Note: Animator resources are not supported for navigating to a new Activity
*/
@AnimRes
@AnimatorRes
public var popEnter: Int = -1
/**
* The custom Animation or Animator resource for the exit animation
* when popping off the back stack.
*
* Note: Animator resources are not supported for navigating to a new Activity
*/
@AnimRes
@AnimatorRes
public var popExit: Int = -1
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/NavOptions.kt
|
332904724
|
package com.funny.translation.kmp
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
// JVM 平台没有 Main Dispatcher
val Dispatchers.KMPMain: CoroutineDispatcher
get() = if (currentPlatform == Platform.Android) Main else Default
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/Dispatchers.kt
|
1599630976
|
package com.funny.translation.kmp
expect open class KMPActivity()
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/kmp/Activity.kt
|
3316060146
|
package com.funny.translation
import androidx.annotation.Keep
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.funny.data_saver.core.mutableDataSaverStateOf
import com.funny.translation.bean.TranslationConfig
import com.funny.translation.bean.UserInfoBean
import com.funny.translation.helper.DataSaverUtils
import com.funny.translation.translate.Language
import com.funny.translation.ui.theme.ThemeConfig
import java.math.BigDecimal
private const val TAG = "AppConfig"
internal expect fun getDid(): String
internal expect fun getVersionCode(): Int
internal expect fun getVersionName(): String
@Keep
object AppConfig {
var SCREEN_WIDTH = 0
var SCREEN_HEIGHT = 0
var userInfo = mutableDataSaverStateOf(DataSaverUtils, "user_info", UserInfoBean())
val uid by derivedStateOf { userInfo.value.uid }
val jwtToken by derivedStateOf { userInfo.value.jwt_token }
val versionCode: Int = getVersionCode()
val versionName: String = getVersionName()
// 隐私合规,延迟获取
val androidId: String by lazy { getDid() }
// 下面为可设置的状态
val sTextMenuFloatingWindow = mutableDataSaverStateOf(DataSaverUtils, "KEY_TEXT_MENU_FLOATING_WINDOW", false)
val sSpringFestivalTheme = mutableDataSaverStateOf(DataSaverUtils, Consts.KEY_SPRING_THEME, true)
val sEnterToTranslate = mutableDataSaverStateOf(DataSaverUtils, Consts.KEY_ENTER_TO_TRANSLATE, false)
val sHideBottomNavBar = mutableDataSaverStateOf(DataSaverUtils, Consts.KEY_CRASH_MSG, false)
val sAutoFocus = mutableDataSaverStateOf(DataSaverUtils, "KEY_AUTO_FOCUS", false)
val sShowFloatWindow = mutableDataSaverStateOf(DataSaverUtils, Consts.KEY_SHOW_FLOAT_WINDOW, false)
val sDefaultSourceLanguage = mutableDataSaverStateOf(DataSaverUtils, "KEY_DEFAULT_SOURCE_LANGUAGE", Language.AUTO)
val sDefaultTargetLanguage = mutableDataSaverStateOf(DataSaverUtils, "KEY_DEFAULT_TARGET_LANGUAGE", Language.CHINESE)
val sAITransExplain = mutableDataSaverStateOf(DataSaverUtils, Consts.KEY_AI_TRANS_EXPLAIN, true)
// 以下为Pro专享
val sParallelTrans = mutableDataSaverStateOf(DataSaverUtils, "KEY_PARALLEL_TRANS", false)
val sShowDetailResult = mutableDataSaverStateOf(DataSaverUtils, "KEY_SHOW_DETAIL_RESULT", false)
val sExpandDetailByDefault = mutableDataSaverStateOf(DataSaverUtils, "KEY_EXPAND_DETAIL_BY_DEFAULT", false)
//
val developerMode = mutableDataSaverStateOf(DataSaverUtils, "KEY_DEVELOPER_MODE", false)
fun updateJwtToken(newToken: String) {
userInfo.value = userInfo.value.copy(jwt_token = newToken)
}
fun subAITextPoint(amount: BigDecimal) {
if (amount == BigDecimal.ZERO) return
val user = userInfo.value
userInfo.value = user.copy(ai_text_point = user.ai_text_point - amount)
}
fun subAIVoicePoint(amount: BigDecimal) {
if (amount == BigDecimal.ZERO) return
val user = userInfo.value
userInfo.value = user.copy(ai_voice_point = user.ai_voice_point - amount)
}
fun isVip() = userInfo.value.isValidVip()
// 开启 VIP 的一些功能,供体验
fun enableVipFeatures(){
sParallelTrans.value = true
sShowDetailResult.value = true
}
private fun disableVipFeatures(){
sParallelTrans.value = false
sShowDetailResult.value = false
ThemeConfig.updateThemeType(ThemeConfig.defaultThemeType)
}
fun logout(){
userInfo.value = UserInfoBean()
disableVipFeatures()
}
fun login(userInfoBean: UserInfoBean, updateVipFeatures: Boolean = false) {
userInfo.value = userInfoBean
if (updateVipFeatures) {
if (userInfoBean.isValidVip()) enableVipFeatures()
else disableVipFeatures()
}
}
}
val GlobalTranslationConfig = TranslationConfig()
// 外部 intent 导致,表示待会儿需要做翻译
// 不用 DeepLink
var NeedToTransConfig by mutableStateOf(TranslationConfig())
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/AppConfig.kt
|
877599783
|
package com.funny.translation
import com.funny.translation.kmp.base.strings.ResStrings
object Consts {
const val INTENT_ACTION_CLICK_FLOAT_WINDOW_TILE = "action_click_float_window_tile"
const val INTENT_EXTRA_OPEN_FLOAT_WINDOW = "extra_open_float_window"
const val EXTRA_OPEN_IN_APP = "extra_open_in_app"
const val KEY_CRASH_MSG = "crash_message"
const val KEY_SHOW_HISTORY = "show_history"
const val KEY_EMAIL = "email"
const val KEY_USER_UID = "uid"
const val KEY_ENTER_TO_TRANSLATE = "enter_to_trans"
const val KEY_TRANS_PAGE_INPUT_BOTTOM = "trans_page_input_bottom"
const val KEY_USER_INFO = "user_info"
const val KEY_APP_CURRENT_SCREEN = "key_app_nav_current_screen"
const val KEY_APP_LANGUAGE = "app_language"
const val KEY_AI_TRANS_EXPLAIN = "ai_trans_explain"
const val EXTRA_USER_INFO = "extra_user_info"
//错误常量
val ERROR_UNKNOWN = ResStrings.err_translate_unknown
val ERROR_JSON = ResStrings.err_parse_json
val ERROR_IO = ResStrings.err_io
const val ERROR_ILLEGAL_DATA = "数据不合法!"
const val ERROR_ONLY_CHINESE_SUPPORT = "当前翻译模式仅支持中文!"
val ERROR_NO_BV_OR_AV = "未检测到有效的Bv号或Av号"
const val MODE_EACH_LINE = 1
// 百度翻译常量
// 为避免不必要的麻烦,开源部分不包含此部分,请您谅解
// 您可以访问 https://api.fanyi.baidu.com/ 免费注册该项服务
private val DEFAULT_BAIDU_APP_ID: String = ""
private val DEFAULT_BAIDU_SECURITY_KEY: String = ""
const val DEFAULT_BAIDU_SLEEP_TIME = 1000L
var BAIDU_APP_ID = DEFAULT_BAIDU_APP_ID
var BAIDU_SECURITY_KEY = DEFAULT_BAIDU_SECURITY_KEY
var BAIDU_SLEEP_TIME = DEFAULT_BAIDU_SLEEP_TIME
const val KEY_SOURCE_LANGUAGE = "sourceLanguage"
const val KEY_TARGET_LANGUAGE = "targetLanguage"
const val KEY_APP_CHANNEL = "app_channel"
const val KEY_HIDE_NAVIGATION_BAR = "hide_nav_bar"
const val KEY_HIDE_STATUS_BAR = "hide_status_bar"
const val KEY_SHOW_FLOAT_WINDOW = "show_float_window"
const val KEY_SPRING_THEME: String = "spring_theme_2024"
const val KEY_SORT_RESULT = "sort_result"
const val KEY_CUSTOM_NAVIGATION = "custom_nav"
const val KEY_FIRST_OPEN_APP = "first_open_app_v2"
val MAX_SELECT_ENGINES get() = if (AppConfig.isVip()) 8 else 5
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/Consts.kt
|
2842586961
|
package com.funny.translation.helper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
/*
* 异步懒加载,by FunnySaltyFish
*
* @param T 要加载的数据类型
* @param scope 加载时的协程作用域
* @param block 加载代码跨
* @return Lazy<Deferred<T>>
*/
fun <T> lazyPromise(scope: CoroutineScope = CoroutineScope(Dispatchers.IO), block: suspend CoroutineScope.() -> T) =
lazy {
scope.async(start = CoroutineStart.LAZY) {
block.invoke(this)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/helper/CoroutineEx.kt
|
2239473235
|
package com.funny.translation.helper
import java.lang.ref.WeakReference
object DataHolder {
private val map by lazy {
HashMap<String, WeakReference<Any?>>()
}
fun put(key: String, value: Any?) {
map[key] = WeakReference(value)
}
fun <T> get(key: String): T? {
return map[key]?.get() as? T
}
fun remove(key: String) {
map.remove(key)
}
fun contains(key: String): Boolean {
return map.containsKey(key)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/helper/DataHolder.kt
|
854215242
|
package com.funny.translation.helper
object TextSplitter {
// 适合作为句子结尾的分隔符,比如 。!?及其变种
// private val punctuationsRegex = Regex("[,,.。!?!?…;;“))\\\\]】}」』)]")
// 从上到下,粒度逐渐变细
private val hierarchyPunctuations = listOf(
listOf("\n", "\r\n"),
listOf("。", "!", "?", "…", ";", ";"),
listOf("”", ")", ")", "]", "】", "}", "」", "』"),
listOf(",", ","),
listOf(" ", "\t", "\r")
)
private val allPunctuations = hierarchyPunctuations.flatten()
/**
* 尝试按自然语言的规范,分割长度不大于 maxLength 的文本。多余的部分舍弃
* @param text String
* @param maxLength Int
* @param start Int
*/
fun splitTextNaturally(text: String, maxLength: Int): String {
if (text.length < maxLength) return text
// 从后向前处理,以减少计算基础
val textLength = text.length
var i = 0 // 上一次处理到哪里了
var j = textLength - 1 // 结尾的 index
for (puncs in hierarchyPunctuations) {
j = textLength - 1
while (j >= 0) {
val last = text.rfind(puncs, i, j)
if (last == -1) {
break
}
// 找到了
// 如果长度够了,则直接返回
if (last <= maxLength) return text.substring(0, last + 1)
// 否则往前找
j = last - 1
}
}
if (j == 0)
return text.substring(0, maxLength)
return text.substring(0, minOf(j + 1, textLength))
}
/**
* 尝试按自然语言的规范,对文本的最后进行裁剪,尽量保证裁剪后的文本是完整的句子,且长度大于等于 ratio * length
* @param text String
* @return String
*/
fun cutTextNaturally(text: String, ratio: Float = 0.9f): String {
for(puncs in hierarchyPunctuations) {
val idx = text.rfind(puncs, 0, text.length - 1)
if (idx >= text.length * ratio) {
return text.substring(0, idx + 1)
}
}
return text
}
/**
* 尝试按自然语言的规范,分割长度不大于 maxLength 的文本
* @param text String
* @param maxLength Int
* @param start Int
*/
// fun splitTextNaturally(text: String, maxLength: Int): String {
// if (text.length < maxLength) return text
//
// val separators = listOf("\n", ".", "。", "!", "!", "?", "?", "…", ";", ";", "”", ")", ")", "]", "】", "}", "」", "』", ",", ",")
// val result = StringBuilder()
//
// for (separator in separators) {
// val chunks = text.split(separator, result.length)
//
// for (chunk in chunks) {
// if (result.length + chunk.length <= maxLength) {
// result.append(chunk + separator)
//
// if (result.length >= maxLength) {
// return result.toString()
// }
// } else {
// return result.toString()
// }
// }
// }
//
// return result.toString()
// }
private fun String.split(separator: String, start: Int): List<String> {
val result = mutableListOf<String>()
var last = start
while (true) {
val idx = this.indexOf(separator, last)
if (idx == -1) {
result.add(this.substring(last))
break
} else {
result.add(this.substring(last, idx + separator.length))
last = idx + separator.length
}
}
return result
}
/**
* find from right to left, [start, end]
* @receiver String
* @param separators List<String>
* @param start Int
* @param end Int
* @return Int
*/
private fun String.rfind(separators: List<String>, start: Int, end: Int): Int {
for (i in end downTo start) {
if (separators.contains(this[i].toString())) {
return i
}
}
return -1
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/helper/TextSplitter.kt
|
4282216793
|
package com.funny.translation.helper
import java.security.MessageDigest
val String.md5: String
get() {
// 创建MessageDigest对象
val digest = MessageDigest.getInstance("MD5")
// 对明文进行加密
val temp = digest.digest(this.toByteArray())
// 准备StringBuilder用于保存结果
val builder = StringBuilder()
// 遍历字节数组, 一个字节转换为长度为2的字符串
for (b in temp) {
// 去除负数
val s = Integer.toHexString(b.toInt() and (0xff))
// 补零
if (s.length == 1) {
builder.append(0)
}
builder.append(s)
}
return builder.toString()
}
val String.trimLineStart
get() = this.splitToSequence("\n").map { it.trim() }.joinToString("\n")
fun String.safeSubstring(start: Int, end: Int = length) = substring(start, minOf(end, length))
fun String.formatBraceStyle(vararg items: Pair<String, Any>): String {
var txt = this
items.forEach {
txt = txt.replace("{${it.first}}", it.second.toString())
}
return txt
}
fun String.formatQueryStyle(vararg items: Pair<String, Any>): String {
var txt = this
items.forEach {
txt = txt.replace("{${it.first}}", it.second.toString())
}
return txt
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/helper/StringExtentions.kt
|
1407189771
|
package com.funny.translation.helper
import java.util.Calendar
import java.util.TimeZone
data class FunnyDate(var year: Int = 0, var month: Int = 0, var day: Int = 0)
object DateUtils {
const val TAG = "DateUtils"
val isSpringFestival: Boolean by lazy{
val time = today
Log.d(TAG, "isSpringFestival: today is $time")
when (time.year) {
2022 -> when (time.month) {
1 -> time.day == 31
2 -> time.day in 1..7
else -> false
}
2023 -> when (time.month) {
1 -> time.day in 21..28
else -> false
}
2024 -> when (time.month) {
2 -> time.day in 9..16
else -> false
}
2025 -> when (time.month) {
1 -> time.day in 28..31
2 -> time.day in 1..4
else -> false
}
2026 -> when (time.month) {
2 -> time.day in 16..23
else -> false
}
else -> false
}
}
private val today = FunnyDate().apply {
val date = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"))
day = date.get(Calendar.DATE)
month = date.get(Calendar.MONTH) + 1
year = date.get(Calendar.YEAR)
}
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/helper/DateUtils.kt
|
2172370998
|
package com.funny.translation.helper
import com.funny.translation.bean.AppLanguage
import com.funny.translation.kmp.KMPContext
import java.util.Locale
expect object LocaleUtils {
fun init(context: KMPContext)
fun getWarpedContext(context: KMPContext, locale: Locale): KMPContext
fun saveAppLanguage(appLanguage: AppLanguage)
fun getAppLanguage(): AppLanguage
// 不经过获取 AppLanguage -> Locale 的过程,直接获取 Locale
// 这个方法会在 attachBaseContext() 里调用,所以不能使用 AppLanguage 这个类
fun getLocaleDirectly(): Locale
}
fun LocaleUtils.getLanguageCode() = getAppLanguage().toLocale().isO3Language
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/helper/LocaleUtils.kt
|
3311466376
|
package com.funny.translation.helper
expect object DeviceUtils {
fun is64Bit(): Boolean
fun isMute(): Boolean
fun getSystemVolume(): Int
}
|
Transtation-KMP/base-kmp/src/commonMain/kotlin/com/funny/translation/helper/DeviceUtils.kt
|
634152778
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.