feat: LPT Android 客户端首版(学习会话 + 悬浮窗)
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.android.application)
|
||||
alias(libs.plugins.kotlin.android)
|
||||
alias(libs.plugins.kotlin.compose)
|
||||
alias(libs.plugins.kotlin.serialization)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.catshark.lpt"
|
||||
compileSdk = 36
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.catshark.lpt"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 1
|
||||
versionName = "0.1.0"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
isMinifyEnabled = false
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
}
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(platform(libs.androidx.compose.bom))
|
||||
|
||||
implementation(libs.androidx.core.ktx)
|
||||
implementation(libs.androidx.activity.compose)
|
||||
implementation(libs.androidx.lifecycle.runtime.ktx)
|
||||
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||
implementation(libs.androidx.lifecycle.viewmodel.compose)
|
||||
implementation(libs.androidx.lifecycle.service)
|
||||
implementation(libs.androidx.datastore.preferences)
|
||||
|
||||
implementation(libs.androidx.compose.ui)
|
||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||
implementation(libs.androidx.compose.material3)
|
||||
|
||||
implementation(libs.okhttp)
|
||||
implementation(libs.retrofit)
|
||||
implementation(libs.retrofit.serialization)
|
||||
implementation(libs.kotlinx.serialization.json)
|
||||
implementation(libs.kotlinx.coroutines.android)
|
||||
|
||||
debugImplementation(libs.androidx.compose.ui.tooling)
|
||||
}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
# 保持 Retrofit / kotlinx.serialization 相关元数据(当前未开启混淆,保留备用)
|
||||
-keepattributes Signature, *Annotation*
|
||||
-keep class kotlinx.serialization.** { *; }
|
||||
-dontwarn okhttp3.**
|
||||
-dontwarn retrofit2.**
|
||||
@@ -0,0 +1,50 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
|
||||
<application
|
||||
android:name=".LptApp"
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.LPT">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTask"
|
||||
android:taskAffinity="com.catshark.lpt"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".ui.FragmentInputActivity"
|
||||
android:excludeFromRecents="true"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTop"
|
||||
android:noHistory="true"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/Theme.LPT.InputDialog" />
|
||||
|
||||
<service
|
||||
android:name=".service.StudySessionService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="floating_study_session_timer" />
|
||||
</service>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.catshark.lpt
|
||||
|
||||
import android.app.Application
|
||||
import com.catshark.lpt.data.ApiClient
|
||||
import com.catshark.lpt.data.LptRepository
|
||||
import com.catshark.lpt.data.TokenStore
|
||||
import com.catshark.lpt.session.SessionController
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class LptApp : Application() {
|
||||
|
||||
lateinit var container: AppContainer
|
||||
private set
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
container = AppContainer(this)
|
||||
}
|
||||
}
|
||||
|
||||
/** 手写依赖容器,不引 Hilt,减少构建复杂度 */
|
||||
class AppContainer(private val app: Application) {
|
||||
|
||||
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
val tokenStore = TokenStore(app)
|
||||
val apiClient = ApiClient()
|
||||
val repository = LptRepository(apiClient)
|
||||
val session = SessionController(repository, scope)
|
||||
|
||||
private val _ready = MutableStateFlow(false)
|
||||
val ready: StateFlow<Boolean> = _ready.asStateFlow()
|
||||
|
||||
private val _loggedIn = MutableStateFlow(false)
|
||||
val loggedIn: StateFlow<Boolean> = _loggedIn.asStateFlow()
|
||||
|
||||
private val _username = MutableStateFlow<String?>(null)
|
||||
val username: StateFlow<String?> = _username.asStateFlow()
|
||||
|
||||
private val _baseUrl = MutableStateFlow(ApiClient.DEFAULT_BASE_URL)
|
||||
val baseUrl: StateFlow<String> = _baseUrl.asStateFlow()
|
||||
|
||||
init {
|
||||
scope.launch {
|
||||
val settings = tokenStore.load()
|
||||
apiClient.setBaseUrl(settings.baseUrl)
|
||||
apiClient.token = settings.token
|
||||
_baseUrl.value = settings.baseUrl
|
||||
_username.value = settings.username
|
||||
_loggedIn.value = !settings.token.isNullOrBlank()
|
||||
_ready.value = true
|
||||
if (_loggedIn.value) session.reconcile()
|
||||
}
|
||||
}
|
||||
|
||||
fun login(username: String, password: String, baseUrl: String, onResult: (String?) -> Unit) {
|
||||
scope.launch {
|
||||
apiClient.setBaseUrl(baseUrl)
|
||||
repository.login(username, password)
|
||||
.onSuccess { token ->
|
||||
apiClient.token = token
|
||||
tokenStore.saveLogin(token, username, baseUrl)
|
||||
_baseUrl.value = baseUrl
|
||||
_username.value = username
|
||||
_loggedIn.value = true
|
||||
session.reconcile()
|
||||
onResult(null)
|
||||
}
|
||||
.onFailure { onResult(it.message ?: "登录失败") }
|
||||
}
|
||||
}
|
||||
|
||||
fun logout() {
|
||||
scope.launch {
|
||||
repository.logout()
|
||||
tokenStore.clearLogin()
|
||||
apiClient.token = null
|
||||
session.clear()
|
||||
_loggedIn.value = false
|
||||
}
|
||||
}
|
||||
|
||||
fun updateBaseUrl(url: String) {
|
||||
scope.launch {
|
||||
apiClient.setBaseUrl(url)
|
||||
tokenStore.saveBaseUrl(url)
|
||||
_baseUrl.value = url
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package com.catshark.lpt
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.provider.Settings
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
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.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import com.catshark.lpt.data.TaskItem
|
||||
import com.catshark.lpt.service.StudySessionService
|
||||
import com.catshark.lpt.ui.LoginScreen
|
||||
import com.catshark.lpt.ui.PermissionScreen
|
||||
import com.catshark.lpt.ui.SessionScreen
|
||||
import com.catshark.lpt.ui.SettingsScreen
|
||||
import com.catshark.lpt.ui.TaskListScreen
|
||||
import com.catshark.lpt.ui.theme.LptTheme
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
|
||||
private val openEndRequest = mutableStateOf(false)
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
handleIntent(intent)
|
||||
setContent {
|
||||
LptTheme {
|
||||
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
|
||||
AppRoot(openEndRequest)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
handleIntent(intent)
|
||||
}
|
||||
|
||||
private fun handleIntent(intent: Intent?) {
|
||||
if (intent?.getBooleanExtra(EXTRA_OPEN_END, false) == true) {
|
||||
openEndRequest.value = true
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_OPEN_END = "open_end"
|
||||
}
|
||||
}
|
||||
|
||||
private enum class Screen { Tasks, Session, Permissions, Settings }
|
||||
|
||||
@Composable
|
||||
private fun AppRoot(openEndRequest: androidx.compose.runtime.MutableState<Boolean>) {
|
||||
val container = (LocalContext.current.applicationContext as LptApp).container
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
val ready by container.ready.collectAsState()
|
||||
val loggedIn by container.loggedIn.collectAsState()
|
||||
val username by container.username.collectAsState()
|
||||
val baseUrl by container.baseUrl.collectAsState()
|
||||
val sessionState by container.session.state.collectAsState()
|
||||
val openEnd by openEndRequest
|
||||
|
||||
var screen by remember { mutableStateOf(Screen.Tasks) }
|
||||
var tasks by remember { mutableStateOf<List<TaskItem>>(emptyList()) }
|
||||
var tasksLoading by remember { mutableStateOf(false) }
|
||||
var tasksError by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
fun refreshTasks() {
|
||||
tasksLoading = true
|
||||
tasksError = null
|
||||
scope.launch {
|
||||
container.repository.tasks()
|
||||
.onSuccess {
|
||||
tasks = it
|
||||
tasksLoading = false
|
||||
}
|
||||
.onFailure {
|
||||
tasksError = it.message ?: "加载任务失败"
|
||||
tasksLoading = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(loggedIn) {
|
||||
if (loggedIn) {
|
||||
refreshTasks()
|
||||
if (!Settings.canDrawOverlays(context)) screen = Screen.Permissions
|
||||
} else {
|
||||
tasks = emptyList()
|
||||
screen = Screen.Tasks
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(sessionState.hasSession) {
|
||||
if (sessionState.hasSession) {
|
||||
screen = Screen.Session
|
||||
} else if (screen == Screen.Session) {
|
||||
screen = Screen.Tasks
|
||||
}
|
||||
}
|
||||
|
||||
// 会话存在就把前台服务拉起来(重装/重启/被系统杀掉后恢复浮窗)
|
||||
LaunchedEffect(ready, loggedIn, sessionState.hasSession) {
|
||||
if (ready && loggedIn && sessionState.hasSession) {
|
||||
StudySessionService.start(context)
|
||||
}
|
||||
}
|
||||
|
||||
when {
|
||||
!ready -> LoadingScreen()
|
||||
|
||||
!loggedIn -> LoginScreen(initialBaseUrl = baseUrl) { user, password, url, onResult ->
|
||||
container.login(user, password, url, onResult)
|
||||
}
|
||||
|
||||
else -> when (screen) {
|
||||
Screen.Tasks -> TaskListScreen(
|
||||
tasks = tasks,
|
||||
loading = tasksLoading,
|
||||
error = tasksError,
|
||||
username = username,
|
||||
onRefresh = { refreshTasks() },
|
||||
onStart = { task ->
|
||||
container.session.startOrContinue(task.taskNum) {
|
||||
StudySessionService.start(context)
|
||||
}
|
||||
},
|
||||
onOpenSettings = { screen = Screen.Settings },
|
||||
onOpenPermissions = { screen = Screen.Permissions },
|
||||
onLogout = {
|
||||
StudySessionService.stop(context)
|
||||
container.logout()
|
||||
},
|
||||
)
|
||||
|
||||
Screen.Session -> SessionScreen(
|
||||
state = sessionState,
|
||||
openEndDialog = openEnd,
|
||||
onConsumeOpenEnd = { openEndRequest.value = false },
|
||||
onTogglePause = {
|
||||
if (sessionState.status == com.catshark.lpt.session.SessionController.Status.ONGOING) {
|
||||
container.session.pause()
|
||||
} else {
|
||||
container.session.resume()
|
||||
}
|
||||
},
|
||||
onEnd = { sections ->
|
||||
container.session.end(sections) {
|
||||
StudySessionService.stop(context)
|
||||
refreshTasks()
|
||||
}
|
||||
},
|
||||
onAbort = { phrase ->
|
||||
container.session.abort(phrase) {
|
||||
StudySessionService.stop(context)
|
||||
refreshTasks()
|
||||
}
|
||||
},
|
||||
onSaveExpectation = { container.session.saveExpectation(it) },
|
||||
onAddFragment = { container.session.addFragment(it) },
|
||||
onShowOverlay = { StudySessionService.showOverlay(context) },
|
||||
onBack = { screen = Screen.Tasks },
|
||||
)
|
||||
|
||||
Screen.Permissions -> PermissionScreen(onBack = { screen = Screen.Tasks })
|
||||
|
||||
Screen.Settings -> SettingsScreen(
|
||||
baseUrl = baseUrl,
|
||||
onSave = { container.updateBaseUrl(it) },
|
||||
onLogout = {
|
||||
StudySessionService.stop(context)
|
||||
container.logout()
|
||||
},
|
||||
onBack = { screen = Screen.Tasks },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LoadingScreen() {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.catshark.lpt.data
|
||||
|
||||
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
|
||||
import kotlinx.serialization.json.Json
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import retrofit2.Retrofit
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* 网络客户端。baseUrl 与 token 都可在运行时切换(设置页 / 登录),
|
||||
* token 通过拦截器以 `satoken` 请求头注入,不依赖 Cookie。
|
||||
*/
|
||||
class ApiClient {
|
||||
|
||||
@Volatile
|
||||
var token: String? = null
|
||||
|
||||
@Volatile
|
||||
private var baseUrl: String? = null
|
||||
|
||||
@Volatile
|
||||
private var retrofit: Retrofit? = null
|
||||
|
||||
private val json = Json {
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
coerceInputValues = true
|
||||
}
|
||||
|
||||
private val okHttp: OkHttpClient = OkHttpClient.Builder()
|
||||
.addInterceptor { chain ->
|
||||
val builder = chain.request().newBuilder()
|
||||
token?.takeIf { it.isNotBlank() }?.let { builder.header("satoken", it) }
|
||||
chain.proceed(builder.build())
|
||||
}
|
||||
.connectTimeout(20, TimeUnit.SECONDS)
|
||||
.readTimeout(300, TimeUnit.SECONDS)
|
||||
.writeTimeout(60, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
fun setBaseUrl(url: String) {
|
||||
val normalized = url.trim().let { if (it.endsWith("/")) it else "$it/" }
|
||||
if (normalized == baseUrl && retrofit != null) return
|
||||
baseUrl = normalized
|
||||
retrofit = Retrofit.Builder()
|
||||
.baseUrl(normalized)
|
||||
.client(okHttp)
|
||||
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
|
||||
.build()
|
||||
}
|
||||
|
||||
val currentBaseUrl: String get() = baseUrl ?: DEFAULT_BASE_URL
|
||||
|
||||
val api: LptApi
|
||||
get() = (retrofit ?: throw IllegalStateException("ApiClient 尚未设置 baseUrl")).create(LptApi::class.java)
|
||||
|
||||
companion object {
|
||||
const val DEFAULT_BASE_URL = "https://lpt-dev.cat-shark.xyz/api"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.catshark.lpt.data
|
||||
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import retrofit2.http.Body
|
||||
import retrofit2.http.GET
|
||||
import retrofit2.http.POST
|
||||
import retrofit2.http.PUT
|
||||
import retrofit2.http.Path
|
||||
import retrofit2.http.Query
|
||||
|
||||
/**
|
||||
* lpt-be 学习会话相关接口(不含复习模块)。
|
||||
* 认证走请求头 `satoken`,由 ApiClient 的拦截器注入。
|
||||
*/
|
||||
interface LptApi {
|
||||
|
||||
@POST("login")
|
||||
suspend fun login(@Body body: LoginRequest): ApiEnvelope<JsonElement>
|
||||
|
||||
@POST("logout")
|
||||
suspend fun logout(): ApiEnvelope<JsonElement>
|
||||
|
||||
@GET("tasks")
|
||||
suspend fun tasks(): ApiEnvelope<TaskPage>
|
||||
|
||||
@GET("study-sessions/active")
|
||||
suspend fun activeSession(
|
||||
@Query("excludeTaskNum") excludeTaskNum: String? = null,
|
||||
): ApiEnvelope<ActiveSession>
|
||||
|
||||
@GET("tasks/{taskNum}/study-sessions/start-or-continue")
|
||||
suspend fun startOrContinue(@Path("taskNum") taskNum: String): ApiEnvelope<SessionDetail>
|
||||
|
||||
@GET("study-sessions/{sessionNum}")
|
||||
suspend fun sessionDetail(@Path("sessionNum") sessionNum: String): ApiEnvelope<SessionDetail>
|
||||
|
||||
@GET("study-sessions/{sessionNum}/expectation")
|
||||
suspend fun getExpectation(@Path("sessionNum") sessionNum: String): ApiEnvelope<Expectation>
|
||||
|
||||
@PUT("study-sessions/{sessionNum}/expectation")
|
||||
suspend fun putExpectation(
|
||||
@Path("sessionNum") sessionNum: String,
|
||||
@Body body: ExpectationRequest,
|
||||
): ApiEnvelope<Expectation>
|
||||
|
||||
@POST("study-sessions/{sessionNum}/study-sessions/continue")
|
||||
suspend fun continueSession(@Path("sessionNum") sessionNum: String): ApiEnvelope<JsonElement>
|
||||
|
||||
@POST("study-sessions/{sessionNum}/study-sessions/pause")
|
||||
suspend fun pauseSession(
|
||||
@Path("sessionNum") sessionNum: String,
|
||||
@Query("endTime") endTime: String? = null,
|
||||
): ApiEnvelope<JsonElement>
|
||||
|
||||
@POST("study-sessions/{sessionNum}/study-sessions/ended")
|
||||
suspend fun endSession(
|
||||
@Path("sessionNum") sessionNum: String,
|
||||
@Body body: EndSessionRequest,
|
||||
): ApiEnvelope<JsonElement>
|
||||
|
||||
@POST("study-sessions/{sessionNum}/study-sessions/abort")
|
||||
suspend fun abortSession(
|
||||
@Path("sessionNum") sessionNum: String,
|
||||
@Body body: AbortRequest,
|
||||
): ApiEnvelope<JsonElement>
|
||||
|
||||
@POST("report-fragments")
|
||||
suspend fun createFragment(@Body body: CreateFragmentRequest): ApiEnvelope<JsonElement>
|
||||
|
||||
@GET("report-fragments/session/{sessionNum}")
|
||||
suspend fun fragmentsBySession(@Path("sessionNum") sessionNum: String): ApiEnvelope<List<FragmentItem>>
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.catshark.lpt.data
|
||||
|
||||
/** 业务错误:把后端的 message 直接带给 UI */
|
||||
class ApiException(message: String) : Exception(message)
|
||||
|
||||
/**
|
||||
* 学习会话仓库:把 Retrofit 调用包成 Result,并把 `code != 200` 转成 ApiException。
|
||||
*/
|
||||
class LptRepository(private val apiClient: ApiClient) {
|
||||
|
||||
private val api get() = apiClient.api
|
||||
|
||||
private inline fun <T> envelope(env: ApiEnvelope<T>, action: String): T {
|
||||
if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "${action}失败")
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return env.data as T
|
||||
}
|
||||
|
||||
suspend fun login(username: String, password: String): Result<String> = runCatching {
|
||||
val env = api.login(LoginRequest(username, password))
|
||||
if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "登录失败")
|
||||
extractToken(env.data)?.takeIf { it.isNotBlank() } ?: throw ApiException("登录响应缺少 token")
|
||||
}
|
||||
|
||||
suspend fun logout(): Result<Unit> = runCatching { api.logout() }
|
||||
|
||||
suspend fun tasks(): Result<List<TaskItem>> = runCatching {
|
||||
envelope(api.tasks(), "获取任务").records
|
||||
}
|
||||
|
||||
suspend fun activeSession(): Result<ActiveSession?> = runCatching {
|
||||
api.activeSession().takeIf { it.code == 200 }?.data
|
||||
}
|
||||
|
||||
suspend fun startOrContinue(taskNum: String): Result<SessionDetail> = runCatching {
|
||||
envelope(api.startOrContinue(taskNum), "开始学习会话")
|
||||
}
|
||||
|
||||
suspend fun sessionDetail(sessionNum: String): Result<SessionDetail> = runCatching {
|
||||
envelope(api.sessionDetail(sessionNum), "获取会话")
|
||||
}
|
||||
|
||||
suspend fun getExpectation(sessionNum: String): Result<String> = runCatching {
|
||||
api.getExpectation(sessionNum).takeIf { it.code == 200 }?.data?.description.orEmpty()
|
||||
}
|
||||
|
||||
suspend fun putExpectation(sessionNum: String, description: String): Result<Unit> = runCatching {
|
||||
envelope(api.putExpectation(sessionNum, ExpectationRequest(description)), "保存学习预期")
|
||||
Unit
|
||||
}
|
||||
|
||||
suspend fun continueSession(sessionNum: String): Result<Unit> = runCatching {
|
||||
envelope(api.continueSession(sessionNum), "继续学习会话")
|
||||
Unit
|
||||
}
|
||||
|
||||
suspend fun pauseSession(sessionNum: String): Result<Unit> = runCatching {
|
||||
envelope(api.pauseSession(sessionNum), "暂停学习会话")
|
||||
Unit
|
||||
}
|
||||
|
||||
/** 结束会话;后端可能返回一条提示(如有效时间不足),作为 message 带回 */
|
||||
suspend fun endSession(sessionNum: String, sections: ReportSections): Result<String?> = runCatching {
|
||||
val env = api.endSession(
|
||||
sessionNum,
|
||||
EndSessionRequest(
|
||||
content = sections.asLegacyContent(),
|
||||
sessionSummary = sections.sessionSummary.ifBlank { null },
|
||||
expectationVerdict = sections.expectationVerdict.ifBlank { null },
|
||||
freeSummary = sections.freeSummary.ifBlank { null },
|
||||
),
|
||||
)
|
||||
if (env.code != 200) throw ApiException(env.message?.takeIf { it.isNotBlank() } ?: "结束学习会话失败")
|
||||
env.message
|
||||
}
|
||||
|
||||
suspend fun abortSession(sessionNum: String, confirmation: String): Result<Unit> = runCatching {
|
||||
envelope(api.abortSession(sessionNum, AbortRequest(confirmation)), "误操作结束")
|
||||
Unit
|
||||
}
|
||||
|
||||
suspend fun createFragment(sessionNum: String, content: String): Result<Unit> = runCatching {
|
||||
envelope(
|
||||
api.createFragment(CreateFragmentRequest(contextNum = sessionNum, sessionNum = sessionNum, content = content)),
|
||||
"记录碎片",
|
||||
)
|
||||
Unit
|
||||
}
|
||||
|
||||
suspend fun fragments(sessionNum: String): Result<List<FragmentItem>> = runCatching {
|
||||
api.fragmentsBySession(sessionNum).takeIf { it.code == 200 }?.data.orEmpty()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.catshark.lpt.data
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
|
||||
/** lpt-be 的统一响应包装:{ code, message, data } */
|
||||
@Serializable
|
||||
data class ApiEnvelope<T>(
|
||||
val code: Int = 0,
|
||||
val message: String? = null,
|
||||
val data: T? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class LoginRequest(
|
||||
val username: String,
|
||||
val password: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TaskItem(
|
||||
val id: Long = 0,
|
||||
val taskNum: String = "",
|
||||
val taskName: String = "",
|
||||
val taskDescription: String? = null,
|
||||
val materialUrl: String? = null,
|
||||
val taskPriority: Double = 0.0,
|
||||
val lastLearningStatus: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class TaskPage(
|
||||
val records: List<TaskItem> = emptyList(),
|
||||
val total: Int = 0,
|
||||
val size: Int = 0,
|
||||
val current: Int = 0,
|
||||
val pages: Int = 0,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class SessionDetail(
|
||||
val sessionNum: String = "",
|
||||
val taskNum: String? = null,
|
||||
val taskName: String? = null,
|
||||
val taskId: Long? = null,
|
||||
val materialUrl: String? = null,
|
||||
val startTime: String? = null,
|
||||
val lastStartTime: String? = null,
|
||||
val endTime: String? = null,
|
||||
val actualTime: Double = 0.0,
|
||||
val effectiveTime: Double = 0.0,
|
||||
val effectivenessRatio: Double = 0.0,
|
||||
val sessionState: String = "",
|
||||
val pointerPosition: Double = 0.0,
|
||||
val systemMessage: String? = null,
|
||||
val autoConverged: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ActiveSession(
|
||||
val taskNum: String = "",
|
||||
val sessionNum: String = "",
|
||||
val taskName: String? = null,
|
||||
val sessionState: String? = null,
|
||||
val autoConverged: Boolean = false,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Expectation(
|
||||
val description: String = "",
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class ExpectationRequest(
|
||||
val description: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class EndSessionRequest(
|
||||
/** 旧版后端(部署版)要的单段报告正文 */
|
||||
val content: String? = null,
|
||||
val sessionSummary: String? = null,
|
||||
val expectationVerdict: String? = null,
|
||||
val freeSummary: String? = null,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class AbortRequest(
|
||||
val confirmation: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class CreateFragmentRequest(
|
||||
/** 新版后端(本地源码)用 contextNum;旧版后端(部署版)用 sessionNum,两个都发 */
|
||||
val contextNum: String,
|
||||
val sessionNum: String,
|
||||
val content: String,
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class FragmentItem(
|
||||
val id: Int = 0,
|
||||
val contextNum: String = "",
|
||||
val contextType: String = "SESSION",
|
||||
val ownerTaskNum: String? = null,
|
||||
val content: String = "",
|
||||
val createdTime: String? = null,
|
||||
)
|
||||
|
||||
/** 结束会话时提交的三段报告文本 */
|
||||
data class ReportSections(
|
||||
val sessionSummary: String,
|
||||
val expectationVerdict: String,
|
||||
val freeSummary: String,
|
||||
) {
|
||||
val allBlank: Boolean
|
||||
get() = sessionSummary.isBlank() && expectationVerdict.isBlank() && freeSummary.isBlank()
|
||||
|
||||
/**
|
||||
* 旧版后端(部署版)只要一段 content。把三段拼成一段,并保留小标题,
|
||||
* 这样旧后端的报告页也能看出结构;全空时给一个占位,避免被「请填写学习报告内容」拦下。
|
||||
*/
|
||||
fun asLegacyContent(): String = buildString {
|
||||
if (sessionSummary.isNotBlank()) appendLine("【会话摘要】$sessionSummary")
|
||||
if (expectationVerdict.isNotBlank()) appendLine("【预期达成判断】$expectationVerdict")
|
||||
if (freeSummary.isNotBlank()) appendLine("【自由总结】$freeSummary")
|
||||
}.trim().ifBlank { "(在手机上结束了本次学习,未填写总结)" }
|
||||
}
|
||||
|
||||
/** 从登录响应里取 token:线上实际返回纯字符串,源码契约是 {token, aiAdmin},两者都兼容 */
|
||||
fun extractToken(element: JsonElement?): String? {
|
||||
if (element == null) return null
|
||||
return when {
|
||||
element is JsonElement && element.toString().trim().startsWith("\"") ->
|
||||
element.toString().trim().trim('"')
|
||||
else -> {
|
||||
val obj = element as? kotlinx.serialization.json.JsonObject
|
||||
obj?.get("token")?.let { token ->
|
||||
if (token.toString().trim().startsWith("\"")) token.toString().trim().trim('"') else token.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.catshark.lpt.data
|
||||
|
||||
import android.content.Context
|
||||
import androidx.datastore.preferences.core.Preferences
|
||||
import androidx.datastore.preferences.core.edit
|
||||
import androidx.datastore.preferences.core.stringPreferencesKey
|
||||
import androidx.datastore.preferences.preferencesDataStore
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
|
||||
private val Context.dataStore by preferencesDataStore(name = "lpt_settings")
|
||||
|
||||
/** 本地持久化:token / baseUrl / username */
|
||||
class TokenStore(private val context: Context) {
|
||||
|
||||
private val keyToken: Preferences.Key<String> = stringPreferencesKey("token")
|
||||
private val keyBaseUrl: Preferences.Key<String> = stringPreferencesKey("base_url")
|
||||
private val keyUsername: Preferences.Key<String> = stringPreferencesKey("username")
|
||||
|
||||
val tokenFlow: Flow<String?> = context.dataStore.data.map { it[keyToken] }
|
||||
val baseUrlFlow: Flow<String> = context.dataStore.data.map { it[keyBaseUrl] ?: ApiClient.DEFAULT_BASE_URL }
|
||||
val usernameFlow: Flow<String?> = context.dataStore.data.map { it[keyUsername] }
|
||||
|
||||
suspend fun load(): Settings = context.dataStore.data.first().let {
|
||||
Settings(
|
||||
token = it[keyToken],
|
||||
baseUrl = it[keyBaseUrl] ?: ApiClient.DEFAULT_BASE_URL,
|
||||
username = it[keyUsername],
|
||||
)
|
||||
}
|
||||
|
||||
suspend fun saveLogin(token: String, username: String, baseUrl: String) {
|
||||
context.dataStore.edit {
|
||||
it[keyToken] = token
|
||||
it[keyUsername] = username
|
||||
it[keyBaseUrl] = baseUrl
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveBaseUrl(baseUrl: String) {
|
||||
context.dataStore.edit { it[keyBaseUrl] = baseUrl }
|
||||
}
|
||||
|
||||
suspend fun clearLogin() {
|
||||
context.dataStore.edit {
|
||||
it.remove(keyToken)
|
||||
it.remove(keyUsername)
|
||||
}
|
||||
}
|
||||
|
||||
data class Settings(
|
||||
val token: String?,
|
||||
val baseUrl: String,
|
||||
val username: String?,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
package com.catshark.lpt.service
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Color
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
import android.text.TextUtils
|
||||
import android.view.Gravity
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.view.WindowManager
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import com.catshark.lpt.session.SessionController
|
||||
import com.catshark.lpt.util.formatDuration
|
||||
import kotlin.math.abs
|
||||
|
||||
/**
|
||||
* 系统级悬浮窗(经典 View 实现)。
|
||||
*
|
||||
* 三种形态:
|
||||
* - 浏览:完整条(任务名 + 计时 + 暂停 + 展开),FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL,不抢焦点、浮窗外触摸透传。
|
||||
* - 半隐藏:只剩一个「● 计时」小胶囊,贴边并部分滑出屏幕;点一下恢复。12 秒无操作自动进入。
|
||||
*
|
||||
* 窗口带 FLAG_LAYOUT_NO_LIMITS,否则 WindowManager 会把越界位置夹回屏幕内(半隐藏会失效)。
|
||||
*
|
||||
* 碎片输入不在这里做:App 不在前台时系统不允许后台窗口弹软键盘,
|
||||
* 所以「+ 记一条碎片」回调给 Service,由它拉起 FragmentInputActivity。
|
||||
*/
|
||||
class OverlayView(private val context: Context) {
|
||||
|
||||
private val wm = context.getSystemService(WindowManager::class.java)
|
||||
|
||||
private var root: LinearLayout? = null
|
||||
private var params: WindowManager.LayoutParams? = null
|
||||
private var shown = false
|
||||
private var expanded = false
|
||||
private var halfHidden = false
|
||||
private var lastState: SessionController.State? = null
|
||||
|
||||
private lateinit var headerRow: LinearLayout
|
||||
private lateinit var dotView: View
|
||||
private lateinit var nameView: TextView
|
||||
private lateinit var timeView: TextView
|
||||
private lateinit var pauseView: TextView
|
||||
private lateinit var expandView: TextView
|
||||
private lateinit var compactView: LinearLayout
|
||||
private lateinit var compactDot: View
|
||||
private lateinit var compactTime: TextView
|
||||
private lateinit var expandedPanel: LinearLayout
|
||||
private lateinit var expectationView: TextView
|
||||
private lateinit var fragmentView: TextView
|
||||
private lateinit var latestFragmentView: TextView
|
||||
private lateinit var addFragmentView: TextView
|
||||
private lateinit var endView: TextView
|
||||
private lateinit var openAppView: TextView
|
||||
private lateinit var hideView: TextView
|
||||
|
||||
var onTogglePause: (() -> Unit)? = null
|
||||
var onEnd: (() -> Unit)? = null
|
||||
var onOpenApp: (() -> Unit)? = null
|
||||
var onRequestFragmentInput: (() -> Unit)? = null
|
||||
|
||||
val isShown: Boolean get() = shown
|
||||
|
||||
private val autoHideTask = Runnable {
|
||||
if (shown && !expanded) setHalfHidden(true)
|
||||
}
|
||||
|
||||
private fun dp(value: Int): Int = (value * context.resources.displayMetrics.density).toInt()
|
||||
|
||||
private fun rounded(color: Int, radiusDp: Int): GradientDrawable = GradientDrawable().apply {
|
||||
setColor(color)
|
||||
cornerRadius = dp(radiusDp).toFloat()
|
||||
}
|
||||
|
||||
private fun pill(label: String, bg: Int, textColor: Int = Color.WHITE): TextView = TextView(context).apply {
|
||||
text = label
|
||||
textSize = 13f
|
||||
setTextColor(textColor)
|
||||
gravity = Gravity.CENTER
|
||||
background = rounded(bg, 10)
|
||||
setPadding(dp(12), dp(6), dp(12), dp(6))
|
||||
isClickable = true
|
||||
isFocusable = false
|
||||
}
|
||||
|
||||
private fun label(text: String, color: Int, size: Float = 12f): TextView = TextView(context).apply {
|
||||
this.text = text
|
||||
textSize = size
|
||||
setTextColor(color)
|
||||
maxLines = 2
|
||||
ellipsize = TextUtils.TruncateAt.END
|
||||
}
|
||||
|
||||
fun show() {
|
||||
if (shown) return
|
||||
if (!Settings.canDrawOverlays(context)) return
|
||||
val view = buildRoot()
|
||||
val p = createParams()
|
||||
root = view
|
||||
params = p
|
||||
runCatching { wm.addView(view, p) }.onFailure {
|
||||
root = null
|
||||
params = null
|
||||
return
|
||||
}
|
||||
shown = true
|
||||
scheduleAutoHide()
|
||||
}
|
||||
|
||||
/** 彻底移除(仅在会话结束/服务停止时调用) */
|
||||
fun hide() {
|
||||
if (!shown) return
|
||||
cancelAutoHide()
|
||||
root?.let { runCatching { wm.removeView(it) } }
|
||||
root = null
|
||||
params = null
|
||||
shown = false
|
||||
}
|
||||
|
||||
/** 恢复/重建浮窗(App 内「显示悬浮窗」入口) */
|
||||
fun restore() {
|
||||
if (!shown) {
|
||||
show()
|
||||
return
|
||||
}
|
||||
if (halfHidden) setHalfHidden(false)
|
||||
scheduleAutoHide()
|
||||
}
|
||||
|
||||
fun render(state: SessionController.State) {
|
||||
lastState = state
|
||||
if (!shown) return
|
||||
val ongoing = state.status == SessionController.Status.ONGOING
|
||||
val text = formatDuration(state.effectiveSeconds())
|
||||
|
||||
nameView.text = state.taskName?.takeIf { it.isNotBlank() } ?: "学习会话"
|
||||
timeView.text = text
|
||||
compactTime.text = text
|
||||
dotView.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
|
||||
compactDot.background = rounded(if (ongoing) COLOR_ONGOING else COLOR_PAUSED, 4)
|
||||
pauseView.text = if (ongoing) "暂停" else "继续"
|
||||
pauseView.background = rounded(if (ongoing) COLOR_ACTION else COLOR_RESUME, 10)
|
||||
|
||||
expectationView.text =
|
||||
if (state.expectation.isBlank()) "预期:未填写" else "预期:${state.expectation}"
|
||||
fragmentView.text = "本次碎片 ${state.fragments.size} 条"
|
||||
latestFragmentView.text = state.fragments.lastOrNull()?.content?.let { "最新:$it" } ?: ""
|
||||
|
||||
headerRow.visibility = if (halfHidden) View.GONE else View.VISIBLE
|
||||
compactView.visibility = if (halfHidden) View.VISIBLE else View.GONE
|
||||
expandedPanel.visibility = if (!halfHidden && expanded) View.VISIBLE else View.GONE
|
||||
expandView.text = if (expanded) "▴" else "▾"
|
||||
}
|
||||
|
||||
private fun toggleExpanded() {
|
||||
expanded = !expanded
|
||||
lastState?.let { render(it) }
|
||||
scheduleAutoHide()
|
||||
}
|
||||
|
||||
// ---- 半隐藏 / 自动隐藏 ----
|
||||
|
||||
fun setHalfHidden(hidden: Boolean) {
|
||||
val view = root ?: return
|
||||
val p = params ?: return
|
||||
if (hidden) expanded = false
|
||||
halfHidden = hidden
|
||||
view.alpha = if (hidden) 0.6f else 1f
|
||||
lastState?.let { render(it) }
|
||||
|
||||
val screenWidth = context.resources.displayMetrics.widthPixels
|
||||
// 等布局完成拿到新宽度后再贴边
|
||||
view.post {
|
||||
val width = view.width.takeIf { it > 0 } ?: dp(220)
|
||||
if (hidden) {
|
||||
val toRight = (p.x + width / 2) > screenWidth / 2
|
||||
// 收向最近的屏幕边缘,只留约七成在屏幕内
|
||||
p.x = if (toRight) screenWidth - (width * 0.7).toInt() else -(width * 0.3).toInt()
|
||||
} else {
|
||||
p.x = (screenWidth - width - dp(12)).coerceIn(dp(0), (screenWidth - width).coerceAtLeast(0))
|
||||
scheduleAutoHide()
|
||||
}
|
||||
runCatching { wm.updateViewLayout(view, p) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun scheduleAutoHide() {
|
||||
root?.removeCallbacks(autoHideTask)
|
||||
if (!halfHidden && !expanded) root?.postDelayed(autoHideTask, AUTO_HIDE_DELAY_MS)
|
||||
}
|
||||
|
||||
private fun cancelAutoHide() {
|
||||
root?.removeCallbacks(autoHideTask)
|
||||
}
|
||||
|
||||
private fun baseFlags(): Int =
|
||||
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
|
||||
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
|
||||
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
|
||||
|
||||
private fun buildRoot(): LinearLayout {
|
||||
val container = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
background = rounded(COLOR_BG, 16)
|
||||
setPadding(dp(12), dp(10), dp(12), dp(10))
|
||||
elevation = dp(10).toFloat()
|
||||
}
|
||||
|
||||
// ---- 完整条 ----
|
||||
headerRow = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
}
|
||||
dotView = View(context).apply {
|
||||
background = rounded(COLOR_ONGOING, 4)
|
||||
layoutParams = LinearLayout.LayoutParams(dp(8), dp(8))
|
||||
}
|
||||
nameView = TextView(context).apply {
|
||||
setTextColor(Color.WHITE)
|
||||
textSize = 13f
|
||||
maxLines = 1
|
||||
ellipsize = TextUtils.TruncateAt.END
|
||||
layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
|
||||
.apply { marginStart = dp(8) }
|
||||
}
|
||||
timeView = TextView(context).apply {
|
||||
setTextColor(Color.WHITE)
|
||||
textSize = 16f
|
||||
typeface = Typeface.MONOSPACE
|
||||
setPadding(dp(8), 0, dp(8), 0)
|
||||
}
|
||||
pauseView = pill("暂停", COLOR_ACTION)
|
||||
expandView = pill("▾", COLOR_NEUTRAL).apply {
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { marginStart = dp(6) }
|
||||
}
|
||||
headerRow.addView(dotView)
|
||||
headerRow.addView(nameView)
|
||||
headerRow.addView(timeView)
|
||||
headerRow.addView(pauseView)
|
||||
headerRow.addView(expandView)
|
||||
container.addView(headerRow)
|
||||
|
||||
// ---- 半隐藏小胶囊 ----
|
||||
compactView = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER_VERTICAL
|
||||
visibility = View.GONE
|
||||
setPadding(dp(4), dp(2), dp(4), dp(2))
|
||||
isClickable = true
|
||||
}
|
||||
compactDot = View(context).apply {
|
||||
background = rounded(COLOR_ONGOING, 4)
|
||||
layoutParams = LinearLayout.LayoutParams(dp(8), dp(8))
|
||||
}
|
||||
compactTime = TextView(context).apply {
|
||||
setTextColor(Color.WHITE)
|
||||
textSize = 14f
|
||||
typeface = Typeface.MONOSPACE
|
||||
setPadding(dp(6), 0, 0, 0)
|
||||
}
|
||||
compactView.addView(compactDot)
|
||||
compactView.addView(compactTime)
|
||||
compactView.setOnClickListener { setHalfHidden(false) }
|
||||
container.addView(compactView)
|
||||
|
||||
// ---- 展开面板 ----
|
||||
expandedPanel = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.VERTICAL
|
||||
visibility = View.GONE
|
||||
}
|
||||
expectationView = label("预期:", Color.parseColor("#C9D1D9")).apply {
|
||||
setPadding(0, dp(10), 0, dp(2))
|
||||
}
|
||||
fragmentView = label("本次碎片 0 条", Color.parseColor("#8B949E"), 12f)
|
||||
latestFragmentView = label("", Color.parseColor("#8B949E"), 12f)
|
||||
|
||||
addFragmentView = pill("+ 记一条碎片", COLOR_ACTION).apply {
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { topMargin = dp(8) }
|
||||
}
|
||||
addFragmentView.setOnClickListener {
|
||||
// 输入弹窗要占屏幕,先把浮窗收成小胶囊,避免遮挡
|
||||
setHalfHidden(true)
|
||||
onRequestFragmentInput?.invoke()
|
||||
}
|
||||
|
||||
val actions = LinearLayout(context).apply {
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
setPadding(0, dp(10), 0, 0)
|
||||
}
|
||||
endView = pill("结束", COLOR_END)
|
||||
openAppView = pill("打开 App", COLOR_NEUTRAL).apply {
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { marginStart = dp(8) }
|
||||
}
|
||||
hideView = pill("隐藏", COLOR_NEUTRAL).apply {
|
||||
layoutParams = LinearLayout.LayoutParams(
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
LinearLayout.LayoutParams.WRAP_CONTENT,
|
||||
).apply { marginStart = dp(8) }
|
||||
}
|
||||
actions.addView(endView)
|
||||
actions.addView(openAppView)
|
||||
actions.addView(hideView)
|
||||
|
||||
expandedPanel.addView(expectationView)
|
||||
expandedPanel.addView(fragmentView)
|
||||
expandedPanel.addView(latestFragmentView)
|
||||
expandedPanel.addView(addFragmentView)
|
||||
expandedPanel.addView(actions)
|
||||
container.addView(expandedPanel)
|
||||
|
||||
pauseView.setOnClickListener {
|
||||
scheduleAutoHide()
|
||||
onTogglePause?.invoke()
|
||||
}
|
||||
expandView.setOnClickListener { toggleExpanded() }
|
||||
endView.setOnClickListener {
|
||||
scheduleAutoHide()
|
||||
onEnd?.invoke()
|
||||
}
|
||||
openAppView.setOnClickListener {
|
||||
scheduleAutoHide()
|
||||
onOpenApp?.invoke()
|
||||
}
|
||||
hideView.setOnClickListener { setHalfHidden(true) }
|
||||
|
||||
attachDrag(headerRow)
|
||||
return container
|
||||
}
|
||||
|
||||
/** 拖动移动;未移动的单击 = 切换半隐藏/恢复 */
|
||||
private fun attachDrag(handle: View) {
|
||||
var startX = 0
|
||||
var startY = 0
|
||||
var downRawX = 0f
|
||||
var downRawY = 0f
|
||||
var moved = false
|
||||
handle.setOnTouchListener { _, event ->
|
||||
val p = params ?: return@setOnTouchListener false
|
||||
when (event.action) {
|
||||
MotionEvent.ACTION_DOWN -> {
|
||||
startX = p.x
|
||||
startY = p.y
|
||||
downRawX = event.rawX
|
||||
downRawY = event.rawY
|
||||
moved = false
|
||||
cancelAutoHide()
|
||||
true
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
val dx = (event.rawX - downRawX).toInt()
|
||||
val dy = (event.rawY - downRawY).toInt()
|
||||
if (abs(dx) > dp(4) || abs(dy) > dp(4)) {
|
||||
moved = true
|
||||
val view = root
|
||||
val width = view?.width ?: dp(200)
|
||||
val height = view?.height ?: dp(60)
|
||||
val screenWidth = context.resources.displayMetrics.widthPixels
|
||||
val screenHeight = context.resources.displayMetrics.heightPixels
|
||||
p.x = (startX + dx).coerceIn(dp(0), (screenWidth - width).coerceAtLeast(dp(0)))
|
||||
p.y = (startY + dy).coerceIn(dp(0), (screenHeight - height).coerceAtLeast(dp(0)))
|
||||
view?.let { runCatching { wm.updateViewLayout(it, p) } }
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
if (moved) {
|
||||
scheduleAutoHide()
|
||||
} else {
|
||||
setHalfHidden(!halfHidden)
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun createParams(): WindowManager.LayoutParams {
|
||||
val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
WindowManager.LayoutParams.TYPE_PHONE
|
||||
}
|
||||
return WindowManager.LayoutParams(
|
||||
WindowManager.LayoutParams.WRAP_CONTENT,
|
||||
WindowManager.LayoutParams.WRAP_CONTENT,
|
||||
type,
|
||||
baseFlags(),
|
||||
PixelFormat.TRANSLUCENT,
|
||||
).apply {
|
||||
gravity = Gravity.TOP or Gravity.START
|
||||
x = dp(12)
|
||||
y = dp(160)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val AUTO_HIDE_DELAY_MS = 12_000L
|
||||
|
||||
private const val COLOR_BG = 0xCC1B1F27.toInt()
|
||||
private const val COLOR_ONGOING = 0xFF34D399.toInt()
|
||||
private const val COLOR_PAUSED = 0xFFF59E0B.toInt()
|
||||
private const val COLOR_ACTION = 0xFF1F6FEB.toInt()
|
||||
private const val COLOR_RESUME = 0xFF238636.toInt()
|
||||
private const val COLOR_END = 0xFFB62324.toInt()
|
||||
private const val COLOR_NEUTRAL = 0xFF30363D.toInt()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package com.catshark.lpt.service
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.provider.Settings
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import com.catshark.lpt.MainActivity
|
||||
import com.catshark.lpt.R
|
||||
import com.catshark.lpt.session.SessionController
|
||||
import com.catshark.lpt.util.formatDuration
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
/**
|
||||
* 学习会话前台服务:持有悬浮窗与常驻通知,会话结束自动停止。
|
||||
* 悬浮窗只做「显示 + 控制」,不承载文本输入,因此不会抢焦点。
|
||||
*/
|
||||
class StudySessionService : Service() {
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
|
||||
private lateinit var overlay: OverlayView
|
||||
private lateinit var controller: SessionController
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
val container = (application as com.catshark.lpt.LptApp).container
|
||||
controller = container.session
|
||||
overlay = OverlayView(this).apply {
|
||||
onTogglePause = { togglePause() }
|
||||
onEnd = { openApp(openEnd = true) }
|
||||
onOpenApp = { openApp(openEnd = false) }
|
||||
onRequestFragmentInput = { openFragmentInput() }
|
||||
}
|
||||
createChannel()
|
||||
|
||||
// 状态变化:更新通知 / 悬浮窗;会话没了就停服务
|
||||
scope.launch {
|
||||
controller.state.collect { state ->
|
||||
if (!state.hasSession) {
|
||||
overlay.hide()
|
||||
stopSelf()
|
||||
return@collect
|
||||
}
|
||||
ensureForeground(state)
|
||||
if (Settings.canDrawOverlays(this@StudySessionService)) {
|
||||
overlay.show()
|
||||
}
|
||||
overlay.render(state)
|
||||
}
|
||||
}
|
||||
|
||||
// 每秒刷新悬浮窗与通知上的计时
|
||||
scope.launch {
|
||||
while (isActive) {
|
||||
delay(1000)
|
||||
val state = controller.state.value
|
||||
if (state.hasSession) {
|
||||
// 权限可能是服务启动后才被授予的,这里持续兜底
|
||||
if (!overlay.isShown && Settings.canDrawOverlays(this@StudySessionService)) {
|
||||
overlay.show()
|
||||
}
|
||||
overlay.render(state)
|
||||
notify(buildNotification(state))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
when (intent?.action) {
|
||||
ACTION_PAUSE -> controller.pause()
|
||||
ACTION_RESUME -> controller.resume()
|
||||
ACTION_END -> openApp(openEnd = true)
|
||||
ACTION_SHOW_OVERLAY -> overlay.restore()
|
||||
ACTION_STOP -> stopSelf()
|
||||
}
|
||||
// 必须在 5 秒内 startForeground,先用当前状态占位
|
||||
ensureForeground(controller.state.value)
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
overlay.hide()
|
||||
scope.coroutineContext[kotlinx.coroutines.Job]?.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
private fun togglePause() {
|
||||
if (controller.state.value.status == SessionController.Status.ONGOING) {
|
||||
controller.pause()
|
||||
} else {
|
||||
controller.resume()
|
||||
}
|
||||
}
|
||||
|
||||
private fun openApp(openEnd: Boolean) {
|
||||
val intent = Intent(this, MainActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
if (openEnd) putExtra(MainActivity.EXTRA_OPEN_END, true)
|
||||
}
|
||||
startActivity(intent)
|
||||
}
|
||||
|
||||
/** 从浮窗拉起碎片输入弹窗(后台弹 Activity 靠 SYSTEM_ALERT_WINDOW 豁免) */
|
||||
private fun openFragmentInput() {
|
||||
// 独立 task:保存后回到用户原本在用的 App,而不是跳到 LPT 主界面
|
||||
val intent = Intent(this, com.catshark.lpt.ui.FragmentInputActivity::class.java)
|
||||
.addFlags(
|
||||
Intent.FLAG_ACTIVITY_NEW_TASK or
|
||||
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS or
|
||||
Intent.FLAG_ACTIVITY_NO_ANIMATION,
|
||||
)
|
||||
runCatching { startActivity(intent) }
|
||||
}
|
||||
|
||||
private fun ensureForeground(state: SessionController.State) {
|
||||
val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
|
||||
} else {
|
||||
0
|
||||
}
|
||||
val notification = if (state.hasSession) buildNotification(state) else buildIdleNotification()
|
||||
runCatching {
|
||||
ServiceCompat.startForeground(this, NOTIFICATION_ID, notification, type)
|
||||
}
|
||||
}
|
||||
|
||||
private fun notify(notification: Notification) {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
manager.notify(NOTIFICATION_ID, notification)
|
||||
}
|
||||
|
||||
private fun buildNotification(state: SessionController.State): Notification {
|
||||
val ongoing = state.status == SessionController.Status.ONGOING
|
||||
val toggleLabel = if (ongoing) "暂停" else "继续"
|
||||
val toggleAction = if (ongoing) ACTION_PAUSE else ACTION_RESUME
|
||||
|
||||
val contentIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
Intent(this, MainActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
},
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
return NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(state.taskName ?: "学习会话")
|
||||
.setContentText("${if (ongoing) "进行中" else "已暂停"} · 有效 ${formatDuration(state.effectiveSeconds())}")
|
||||
.setContentIntent(contentIntent)
|
||||
.setOngoing(true)
|
||||
.setOnlyAlertOnce(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||
.addAction(0, toggleLabel, servicePendingIntent(toggleAction, 1))
|
||||
.addAction(0, "结束", activityPendingIntent(2))
|
||||
.build()
|
||||
}
|
||||
|
||||
private fun buildIdleNotification(): Notification =
|
||||
NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle("学习会话")
|
||||
.setContentText("正在恢复会话状态…")
|
||||
.setOngoing(true)
|
||||
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||
.build()
|
||||
|
||||
private fun servicePendingIntent(action: String, requestCode: Int): PendingIntent =
|
||||
PendingIntent.getService(
|
||||
this,
|
||||
requestCode,
|
||||
Intent(this, StudySessionService::class.java).setAction(action),
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun activityPendingIntent(requestCode: Int): PendingIntent =
|
||||
PendingIntent.getActivity(
|
||||
this,
|
||||
requestCode,
|
||||
Intent(this, MainActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
||||
putExtra(MainActivity.EXTRA_OPEN_END, true)
|
||||
},
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun createChannel() {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
if (manager.getNotificationChannel(CHANNEL_ID) != null) return
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"学习会话",
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
).apply {
|
||||
description = "显示正在进行的 LPT 学习会话与计时"
|
||||
setShowBadge(false)
|
||||
}
|
||||
manager.createNotificationChannel(channel)
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val CHANNEL_ID = "study_session"
|
||||
const val NOTIFICATION_ID = 1001
|
||||
|
||||
const val ACTION_PAUSE = "com.catshark.lpt.action.PAUSE"
|
||||
const val ACTION_RESUME = "com.catshark.lpt.action.RESUME"
|
||||
const val ACTION_END = "com.catshark.lpt.action.END"
|
||||
const val ACTION_STOP = "com.catshark.lpt.action.STOP"
|
||||
const val ACTION_SHOW_OVERLAY = "com.catshark.lpt.action.SHOW_OVERLAY"
|
||||
|
||||
fun start(context: Context) {
|
||||
val intent = Intent(context, StudySessionService::class.java)
|
||||
androidx.core.content.ContextCompat.startForegroundService(context, intent)
|
||||
}
|
||||
|
||||
/** 从 App 里恢复被半隐藏/被系统收起的浮窗 */
|
||||
fun showOverlay(context: Context) {
|
||||
val intent = Intent(context, StudySessionService::class.java).setAction(ACTION_SHOW_OVERLAY)
|
||||
runCatching { androidx.core.content.ContextCompat.startForegroundService(context, intent) }
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
context.stopService(Intent(context, StudySessionService::class.java))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package com.catshark.lpt.session
|
||||
|
||||
import android.os.SystemClock
|
||||
import com.catshark.lpt.data.FragmentItem
|
||||
import com.catshark.lpt.data.LptRepository
|
||||
import com.catshark.lpt.data.ReportSections
|
||||
import com.catshark.lpt.data.SessionDetail
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import kotlinx.coroutines.launch
|
||||
import java.time.Duration
|
||||
import java.time.LocalDateTime
|
||||
|
||||
/**
|
||||
* 学习会话状态机(Application 级单例)。
|
||||
*
|
||||
* 计时口径:显示值 = 服务端 effectiveTime(基准)+ 用 SystemClock.elapsedRealtime() 做锚点的增量。
|
||||
* 不使用 tick 累加,因此进程被杀、Doze、锁屏都不会让时间失真;恢复时以服务端时间戳重新对锚。
|
||||
*/
|
||||
class SessionController(
|
||||
private val repo: LptRepository,
|
||||
private val scope: CoroutineScope,
|
||||
) {
|
||||
|
||||
enum class Status { NONE, ONGOING, PAUSED, ENDED }
|
||||
|
||||
data class State(
|
||||
val sessionNum: String? = null,
|
||||
val taskNum: String? = null,
|
||||
val taskName: String? = null,
|
||||
val status: Status = Status.NONE,
|
||||
val baseEffectiveSeconds: Double = 0.0,
|
||||
val anchorRealtimeMs: Long = 0L,
|
||||
val expectation: String = "",
|
||||
val fragments: List<FragmentItem> = emptyList(),
|
||||
val busy: Boolean = false,
|
||||
val error: String? = null,
|
||||
val notice: String? = null,
|
||||
) {
|
||||
val hasSession: Boolean
|
||||
get() = status == Status.ONGOING || status == Status.PAUSED
|
||||
|
||||
fun effectiveSeconds(nowMs: Long = SystemClock.elapsedRealtime()): Double =
|
||||
if (status == Status.ONGOING) {
|
||||
baseEffectiveSeconds + (nowMs - anchorRealtimeMs) / 1000.0
|
||||
} else {
|
||||
baseEffectiveSeconds
|
||||
}
|
||||
}
|
||||
|
||||
private val _state = MutableStateFlow(State())
|
||||
val state: StateFlow<State> = _state.asStateFlow()
|
||||
|
||||
fun consumeError() = _state.update { it.copy(error = null) }
|
||||
|
||||
fun consumeNotice() = _state.update { it.copy(notice = null) }
|
||||
|
||||
/** 启动或恢复某任务的学习会话;成功后回调(UI 用它拉起前台服务) */
|
||||
fun startOrContinue(taskNum: String, onSuccess: () -> Unit = {}) {
|
||||
if (_state.value.busy) return
|
||||
_state.update { it.copy(busy = true, error = null) }
|
||||
scope.launch {
|
||||
repo.startOrContinue(taskNum)
|
||||
.onSuccess { detail ->
|
||||
applyDetail(detail)
|
||||
loadAuxiliary(detail.sessionNum)
|
||||
_state.update { it.copy(busy = false) }
|
||||
onSuccess()
|
||||
}
|
||||
.onFailure { e ->
|
||||
_state.update { it.copy(busy = false, error = e.message ?: "开始学习会话失败") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun pause() {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.busy) return
|
||||
_state.update { it.copy(busy = true) }
|
||||
scope.launch {
|
||||
repo.pauseSession(num)
|
||||
.onSuccess { refreshDetail(num) }
|
||||
.onFailure { e -> _state.update { it.copy(error = e.message ?: "暂停失败") } }
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
}
|
||||
|
||||
fun resume() {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.busy) return
|
||||
_state.update { it.copy(busy = true) }
|
||||
scope.launch {
|
||||
repo.continueSession(num)
|
||||
.onSuccess { refreshDetail(num) }
|
||||
.onFailure { e -> _state.update { it.copy(error = e.message ?: "继续失败") } }
|
||||
_state.update { it.copy(busy = false) }
|
||||
}
|
||||
}
|
||||
|
||||
fun saveExpectation(text: String) {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
scope.launch {
|
||||
repo.putExpectation(num, text)
|
||||
.onSuccess {
|
||||
_state.update { it.copy(expectation = text, notice = "学习预期已保存") }
|
||||
}
|
||||
.onFailure { e -> _state.update { it.copy(error = e.message ?: "保存学习预期失败") } }
|
||||
}
|
||||
}
|
||||
|
||||
fun addFragment(content: String) {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (content.isBlank()) return
|
||||
scope.launch {
|
||||
repo.createFragment(num, content)
|
||||
.onSuccess {
|
||||
repo.fragments(num).onSuccess { list ->
|
||||
_state.update { it.copy(fragments = list, notice = "已记录一条碎片") }
|
||||
}
|
||||
}
|
||||
.onFailure { e -> _state.update { it.copy(error = e.message ?: "记录碎片失败") } }
|
||||
}
|
||||
}
|
||||
|
||||
fun end(sections: ReportSections, onDone: () -> Unit = {}) {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.busy) return
|
||||
_state.update { it.copy(busy = true) }
|
||||
scope.launch {
|
||||
repo.endSession(num, sections)
|
||||
.onSuccess { message ->
|
||||
_state.value = State(notice = message ?: "学习会话已结束")
|
||||
onDone()
|
||||
}
|
||||
.onFailure { e ->
|
||||
_state.update { it.copy(busy = false, error = e.message ?: "结束学习会话失败") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun abort(confirmation: String, onDone: () -> Unit = {}) {
|
||||
val num = _state.value.sessionNum ?: return
|
||||
if (_state.value.busy) return
|
||||
_state.update { it.copy(busy = true) }
|
||||
scope.launch {
|
||||
repo.abortSession(num, confirmation)
|
||||
.onSuccess {
|
||||
_state.value = State(notice = "已放弃该会话,未产生任何数据")
|
||||
onDone()
|
||||
}
|
||||
.onFailure { e ->
|
||||
_state.update { it.copy(busy = false, error = e.message ?: "放弃会话失败") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** App 启动时与服务端对账:把未结束的会话恢复出来 */
|
||||
fun reconcile() {
|
||||
scope.launch {
|
||||
repo.activeSession()
|
||||
.onSuccess { active ->
|
||||
if (active == null || active.sessionNum.isBlank()) {
|
||||
if (!_state.value.hasSession) _state.update { it.copy(status = Status.NONE) }
|
||||
return@onSuccess
|
||||
}
|
||||
// 详情接口的 taskName 为 null,先用 active 里的任务信息兜底
|
||||
_state.update {
|
||||
it.copy(
|
||||
sessionNum = active.sessionNum,
|
||||
taskNum = active.taskNum.ifBlank { it.taskNum },
|
||||
taskName = active.taskName ?: it.taskName,
|
||||
)
|
||||
}
|
||||
refreshDetail(active.sessionNum)
|
||||
loadAuxiliary(active.sessionNum)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
_state.value = State()
|
||||
}
|
||||
|
||||
// ---- 内部 ----
|
||||
|
||||
private suspend fun refreshDetail(sessionNum: String) {
|
||||
repo.sessionDetail(sessionNum).onSuccess { applyDetail(it) }
|
||||
}
|
||||
|
||||
private suspend fun loadAuxiliary(sessionNum: String) {
|
||||
repo.getExpectation(sessionNum).onSuccess { text ->
|
||||
_state.update { it.copy(expectation = text) }
|
||||
}
|
||||
repo.fragments(sessionNum).onSuccess { list ->
|
||||
_state.update { it.copy(fragments = list) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyDetail(detail: SessionDetail) {
|
||||
val status = when (detail.sessionState) {
|
||||
"ONGOING" -> Status.ONGOING
|
||||
"PAUSED" -> Status.PAUSED
|
||||
"ENDED" -> Status.ENDED
|
||||
else -> Status.NONE
|
||||
}
|
||||
val anchor = if (status == Status.ONGOING) {
|
||||
SystemClock.elapsedRealtime() - secondsSince(detail.lastStartTime) * 1000L
|
||||
} else {
|
||||
SystemClock.elapsedRealtime()
|
||||
}
|
||||
_state.update {
|
||||
it.copy(
|
||||
sessionNum = detail.sessionNum.ifBlank { it.sessionNum },
|
||||
taskNum = detail.taskNum ?: it.taskNum,
|
||||
taskName = detail.taskName ?: it.taskName,
|
||||
status = status,
|
||||
baseEffectiveSeconds = detail.effectiveTime,
|
||||
anchorRealtimeMs = anchor,
|
||||
error = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun secondsSince(iso: String?): Long {
|
||||
if (iso.isNullOrBlank()) return 0
|
||||
return runCatching {
|
||||
val start = LocalDateTime.parse(iso)
|
||||
Duration.between(start, LocalDateTime.now()).seconds.coerceAtLeast(0)
|
||||
}.getOrDefault(0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
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.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.catshark.lpt.LptApp
|
||||
import com.catshark.lpt.ui.theme.LptTheme
|
||||
|
||||
/**
|
||||
* 从悬浮窗拉起的一条碎片输入弹窗。
|
||||
*
|
||||
* 之所以不复用悬浮窗内输入:App 不在前台时,系统不允许后台窗口弹软键盘
|
||||
* (实测浮窗的 EditText 能拿到输入连接,但 IME 窗口 mViewVisibility=GONE)。
|
||||
* 带 SYSTEM_ALERT_WINDOW 的 App 有后台启动 Activity 的豁免,所以这里用 Activity 输入。
|
||||
*/
|
||||
class FragmentInputActivity : ComponentActivity() {
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContent {
|
||||
LptTheme {
|
||||
FragmentInputDialog(
|
||||
sessionNum = (application as LptApp).container.session.state.value.sessionNum,
|
||||
onSubmit = { text ->
|
||||
(application as LptApp).container.session.addFragment(text)
|
||||
finish()
|
||||
},
|
||||
onDismiss = { finish() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FragmentInputDialog(
|
||||
sessionNum: String?,
|
||||
onSubmit: (String) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var text by remember { mutableStateOf("") }
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
val context = LocalContext.current
|
||||
|
||||
LaunchedEffect(Unit) { focusRequester.requestFocus() }
|
||||
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp),
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 6.dp,
|
||||
shadowElevation = 12.dp,
|
||||
) {
|
||||
Column(modifier = Modifier.padding(18.dp)) {
|
||||
Text("记一条知识碎片", style = MaterialTheme.typography.titleMedium)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
sessionNum?.let { "归属会话:$it" } ?: "当前没有进行中的会话",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
OutlinedTextField(
|
||||
value = text,
|
||||
onValueChange = { text = it },
|
||||
label = { Text("这条碎片记了什么?") },
|
||||
minLines = 2,
|
||||
maxLines = 4,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.focusRequester(focusRequester),
|
||||
)
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = onDismiss) { Text("取消") }
|
||||
Spacer(Modifier.height(0.dp))
|
||||
Button(
|
||||
onClick = { onSubmit(text.trim()) },
|
||||
enabled = text.isNotBlank() && sessionNum != null,
|
||||
modifier = Modifier.padding(start = 8.dp),
|
||||
) { Text("保存") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package com.catshark.lpt.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.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun LoginScreen(
|
||||
initialBaseUrl: String,
|
||||
onLogin: (username: String, password: String, baseUrl: String, onResult: (String?) -> Unit) -> Unit,
|
||||
) {
|
||||
var username by remember { mutableStateOf("") }
|
||||
var password by remember { mutableStateOf("") }
|
||||
var baseUrl by remember { mutableStateOf(initialBaseUrl) }
|
||||
var showAdvanced by remember { mutableStateOf(false) }
|
||||
var loading by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(24.dp),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text("LPT 学习", style = MaterialTheme.typography.headlineMedium)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"移动端学习会话 · 悬浮窗计时",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = username,
|
||||
onValueChange = { username = it },
|
||||
label = { Text("账号") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(12.dp))
|
||||
OutlinedTextField(
|
||||
value = password,
|
||||
onValueChange = { password = it },
|
||||
label = { Text("密码") },
|
||||
singleLine = true,
|
||||
visualTransformation = PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
if (showAdvanced) {
|
||||
Spacer(Modifier.height(12.dp))
|
||||
OutlinedTextField(
|
||||
value = baseUrl,
|
||||
onValueChange = { baseUrl = it },
|
||||
label = { Text("API 地址") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
} else {
|
||||
TextButton(onClick = { showAdvanced = true }) { Text("高级:修改 API 地址") }
|
||||
}
|
||||
|
||||
if (error != null) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(error!!, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(20.dp))
|
||||
Button(
|
||||
onClick = {
|
||||
error = null
|
||||
loading = true
|
||||
onLogin(username.trim(), password, baseUrl.trim()) { message ->
|
||||
loading = false
|
||||
error = message
|
||||
}
|
||||
},
|
||||
enabled = !loading && username.isNotBlank() && password.isNotBlank(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
if (loading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.height(18.dp),
|
||||
strokeWidth = 2.dp,
|
||||
color = MaterialTheme.colorScheme.onPrimary,
|
||||
)
|
||||
} else {
|
||||
Text("登录")
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text(
|
||||
"提示:dev 环境默认 https://lpt-dev.cat-shark.xyz/api",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(24.dp))
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
"LPT",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
|
||||
@Composable
|
||||
fun PermissionScreen(onBack: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
var refreshKey by remember { mutableIntStateOf(0) }
|
||||
|
||||
// 从系统设置页返回时自动刷新权限状态
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
DisposableEffect(lifecycleOwner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_RESUME) refreshKey++
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
|
||||
val overlayGranted = remember(refreshKey) { Settings.canDrawOverlays(context) }
|
||||
val batteryIgnored = remember(refreshKey) { isIgnoringBatteryOptimizations(context) }
|
||||
val notificationGranted = remember(refreshKey) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) ==
|
||||
android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("权限与后台", style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))
|
||||
TextButton(onClick = onBack) { Text("返回") }
|
||||
}
|
||||
Text(
|
||||
"悬浮窗是核心功能:没有悬浮窗权限,跨应用计时就不成立。MIUI 还需要额外放行后台。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
PermissionCard(
|
||||
title = "悬浮窗权限(必须)",
|
||||
description = "允许 LPT 在其他应用之上显示学习计时浮窗。",
|
||||
granted = overlayGranted,
|
||||
actionLabel = "去开启",
|
||||
onAction = { openOverlaySettings(context) },
|
||||
)
|
||||
|
||||
PermissionCard(
|
||||
title = "通知权限",
|
||||
description = "前台服务需要一条常驻通知;Android 13+ 需要授权。",
|
||||
granted = notificationGranted,
|
||||
actionLabel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) "去开启" else "无需(本机低于 13)",
|
||||
onAction = { openAppNotificationSettings(context) },
|
||||
)
|
||||
|
||||
PermissionCard(
|
||||
title = "电池优化白名单",
|
||||
description = "避免长时间学习时被系统冻结计时。",
|
||||
granted = batteryIgnored,
|
||||
actionLabel = "去设置",
|
||||
onAction = { requestIgnoreBatteryOptimizations(context) },
|
||||
)
|
||||
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Text("小米 / MIUI 额外设置", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
"MIUI 会限制后台启动与后台弹窗,需要手动放行「自启动」和「其他权限 → 后台弹出界面」,并把省电策略设为「无限制」。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
OutlinedButton(onClick = { openMiuiAutostart(context) }) { Text("自启动管理") }
|
||||
OutlinedButton(onClick = { openAppDetailSettings(context) }) { Text("应用详情") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Button(onClick = onBack, modifier = Modifier.fillMaxWidth()) { Text("完成") }
|
||||
Spacer(Modifier.height(16.dp))
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PermissionCard(
|
||||
title: String,
|
||||
description: String,
|
||||
granted: Boolean,
|
||||
actionLabel: String,
|
||||
onAction: () -> Unit,
|
||||
) {
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, modifier = Modifier.weight(1f))
|
||||
Text(
|
||||
if (granted) "已授权" else "未授权",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = if (granted) MaterialTheme.colorScheme.secondary else MaterialTheme.colorScheme.error,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
description,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
if (!granted) {
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Button(onClick = onAction) { Text(actionLabel) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun openOverlaySettings(context: Context) {
|
||||
val intent = Intent(
|
||||
Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
|
||||
Uri.parse("package:${context.packageName}"),
|
||||
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
.onFailure { runCatching { context.startActivity(Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)) } }
|
||||
}
|
||||
|
||||
private fun openAppNotificationSettings(context: Context) {
|
||||
val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
.onFailure { openAppDetailSettings(context) }
|
||||
}
|
||||
|
||||
private fun openAppDetailSettings(context: Context) {
|
||||
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
|
||||
.setData(Uri.parse("package:${context.packageName}"))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
}
|
||||
|
||||
private fun requestIgnoreBatteryOptimizations(context: Context) {
|
||||
val intent = Intent(
|
||||
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
|
||||
Uri.parse("package:${context.packageName}"),
|
||||
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
runCatching { context.startActivity(intent) }
|
||||
.onFailure { runCatching { context.startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)) } }
|
||||
}
|
||||
|
||||
private fun openMiuiAutostart(context: Context) {
|
||||
val candidates = listOf(
|
||||
ComponentName(
|
||||
"com.miui.securitycenter",
|
||||
"com.miui.permcenter.autostart.AutoStartManagementActivity",
|
||||
),
|
||||
ComponentName(
|
||||
"com.miui.securitycenter",
|
||||
"com.miui.powercenter.PowerSettings",
|
||||
),
|
||||
)
|
||||
for (component in candidates) {
|
||||
val intent = Intent().setComponent(component).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
if (runCatching { context.startActivity(intent) }.isSuccess) return
|
||||
}
|
||||
openAppDetailSettings(context)
|
||||
}
|
||||
|
||||
private fun isIgnoringBatteryOptimizations(context: Context): Boolean {
|
||||
val powerManager = context.getSystemService(PowerManager::class.java) ?: return false
|
||||
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableLongStateOf
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.catshark.lpt.data.ReportSections
|
||||
import com.catshark.lpt.session.SessionController
|
||||
import com.catshark.lpt.util.formatDuration
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
private const val MISOPERATION_PHRASE = "我误操作导致开启了本次学习"
|
||||
|
||||
@Composable
|
||||
fun SessionScreen(
|
||||
state: SessionController.State,
|
||||
openEndDialog: Boolean,
|
||||
onConsumeOpenEnd: () -> Unit,
|
||||
onTogglePause: () -> Unit,
|
||||
onEnd: (ReportSections) -> Unit,
|
||||
onAbort: (String) -> Unit,
|
||||
onSaveExpectation: (String) -> Unit,
|
||||
onAddFragment: (String) -> Unit,
|
||||
onShowOverlay: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
var nowMs by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }
|
||||
LaunchedEffect(state.status) {
|
||||
while (true) {
|
||||
delay(1000)
|
||||
nowMs = SystemClock.elapsedRealtime()
|
||||
}
|
||||
}
|
||||
val seconds = state.effectiveSeconds(nowMs)
|
||||
val ongoing = state.status == SessionController.Status.ONGOING
|
||||
|
||||
var expectationDraft by remember { mutableStateOf(state.expectation) }
|
||||
LaunchedEffect(state.expectation) { expectationDraft = state.expectation }
|
||||
|
||||
var fragmentDraft by remember { mutableStateOf("") }
|
||||
var showEnd by remember { mutableStateOf(false) }
|
||||
var showAbort by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(openEndDialog) {
|
||||
if (openEndDialog) {
|
||||
showEnd = true
|
||||
onConsumeOpenEnd()
|
||||
}
|
||||
}
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
TextButton(onClick = onBack) { Text("‹ 任务") }
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text(
|
||||
state.taskName ?: "学习会话",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
Text(
|
||||
state.sessionNum ?: "",
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
if (state.busy) CircularProgressIndicator(modifier = Modifier.height(18.dp), strokeWidth = 2.dp)
|
||||
}
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(rememberScrollState())
|
||||
.padding(horizontal = 16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
// 计时卡片
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
if (ongoing) "有效学习时间" else "已暂停 · 有效学习时间",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(6.dp))
|
||||
Text(
|
||||
formatDuration(seconds),
|
||||
fontSize = 44.sp,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = if (ongoing) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
"状态:${statusLabel(state.status)}",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 控制按钮
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Button(
|
||||
onClick = onTogglePause,
|
||||
enabled = !state.busy,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Text(if (ongoing) "暂停" else "继续")
|
||||
}
|
||||
Button(
|
||||
onClick = { showEnd = true },
|
||||
enabled = !state.busy,
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Text("结束")
|
||||
}
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = { showAbort = true },
|
||||
enabled = !state.busy && state.fragments.isEmpty(),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(if (state.fragments.isEmpty()) "误操作结束(零数据)" else "误操作结束(已产生碎片,不可用)")
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = onShowOverlay,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text("显示 / 恢复悬浮窗")
|
||||
}
|
||||
|
||||
// 学习预期
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Text("本次学习预期", style = MaterialTheme.typography.titleSmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = expectationDraft,
|
||||
onValueChange = { expectationDraft = it },
|
||||
label = { Text("开始前写下这次想学会什么") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
|
||||
Button(onClick = { onSaveExpectation(expectationDraft) }) { Text("保存预期") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 碎片
|
||||
Card(modifier = Modifier.fillMaxWidth()) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Text("知识碎片(${state.fragments.size})", style = MaterialTheme.typography.titleSmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
OutlinedTextField(
|
||||
value = fragmentDraft,
|
||||
onValueChange = { fragmentDraft = it },
|
||||
label = { Text("记一条…") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Spacer(Modifier.height(0.dp))
|
||||
TextButton(
|
||||
onClick = {
|
||||
onAddFragment(fragmentDraft)
|
||||
fragmentDraft = ""
|
||||
},
|
||||
enabled = fragmentDraft.isNotBlank(),
|
||||
) { Text("记录") }
|
||||
}
|
||||
state.fragments.forEachIndexed { index, fragment ->
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row {
|
||||
Text(
|
||||
"${index + 1}.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(0.dp))
|
||||
Text(
|
||||
fragment.content,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.padding(start = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (state.error != null) {
|
||||
Text(state.error, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
if (state.notice != null) {
|
||||
Text(state.notice, color = MaterialTheme.colorScheme.secondary, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
Spacer(Modifier.height(24.dp))
|
||||
}
|
||||
}
|
||||
|
||||
if (showEnd) {
|
||||
EndSessionDialog(
|
||||
defaultSummary = "",
|
||||
busy = state.busy,
|
||||
onDismiss = { showEnd = false },
|
||||
onConfirm = { sections ->
|
||||
showEnd = false
|
||||
onEnd(sections)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (showAbort) {
|
||||
AbortSessionDialog(
|
||||
busy = state.busy,
|
||||
onDismiss = { showAbort = false },
|
||||
onConfirm = { phrase ->
|
||||
showAbort = false
|
||||
onAbort(phrase)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun EndSessionDialog(
|
||||
defaultSummary: String,
|
||||
busy: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: (ReportSections) -> Unit,
|
||||
) {
|
||||
var summary by remember { mutableStateOf(defaultSummary) }
|
||||
var verdict by remember { mutableStateOf("") }
|
||||
var free by remember { mutableStateOf("") }
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("结束本次学习") },
|
||||
text = {
|
||||
Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
|
||||
Text(
|
||||
"三段都可留空,但至少要写一段。全空时会记为「未填写总结」。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = summary,
|
||||
onValueChange = { summary = it },
|
||||
label = { Text("会话摘要(这次实际学了什么)") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = verdict,
|
||||
onValueChange = { verdict = it },
|
||||
label = { Text("预期达成判断") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
OutlinedTextField(
|
||||
value = free,
|
||||
onValueChange = { free = it },
|
||||
label = { Text("自由总结") },
|
||||
minLines = 2,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = {
|
||||
val sections = if (summary.isBlank() && verdict.isBlank() && free.isBlank()) {
|
||||
ReportSections("", "", "(在手机上结束了本次学习,未填写总结)")
|
||||
} else {
|
||||
ReportSections(summary, verdict, free)
|
||||
}
|
||||
onConfirm(sections)
|
||||
},
|
||||
enabled = !busy,
|
||||
) { Text("确认结束") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AbortSessionDialog(
|
||||
busy: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: (String) -> Unit,
|
||||
) {
|
||||
var phrase by remember { mutableStateOf("") }
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("误操作结束") },
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
"此操作会删除本次会话与学习预期,不产生碎片和报告,且不可恢复。",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Spacer(Modifier.height(10.dp))
|
||||
Text("请输入确认语:$MISOPERATION_PHRASE", style = MaterialTheme.typography.bodySmall)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = phrase,
|
||||
onValueChange = { phrase = it },
|
||||
label = { Text("确认语") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = { onConfirm(phrase) },
|
||||
enabled = !busy && phrase.trim() == MISOPERATION_PHRASE,
|
||||
) { Text("确认放弃") }
|
||||
},
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
|
||||
)
|
||||
}
|
||||
|
||||
private fun statusLabel(status: SessionController.Status): String = when (status) {
|
||||
SessionController.Status.ONGOING -> "进行中"
|
||||
SessionController.Status.PAUSED -> "已暂停"
|
||||
SessionController.Status.ENDED -> "已结束"
|
||||
SessionController.Status.NONE -> "无"
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Composable
|
||||
fun SettingsScreen(
|
||||
baseUrl: String,
|
||||
onSave: (String) -> Unit,
|
||||
onLogout: () -> Unit,
|
||||
onBack: () -> Unit,
|
||||
) {
|
||||
var draft by remember { mutableStateOf(baseUrl) }
|
||||
var saved by remember { mutableStateOf(false) }
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("设置", style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f))
|
||||
TextButton(onClick = onBack) { Text("返回") }
|
||||
}
|
||||
|
||||
OutlinedTextField(
|
||||
value = draft,
|
||||
onValueChange = {
|
||||
draft = it
|
||||
saved = false
|
||||
},
|
||||
label = { Text("API 地址") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Text(
|
||||
"例如 https://lpt-dev.cat-shark.xyz/api",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Button(
|
||||
onClick = {
|
||||
onSave(draft.trim())
|
||||
saved = true
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) { Text(if (saved) "已保存" else "保存") }
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = onLogout, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("退出登录", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.catshark.lpt.ui
|
||||
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.catshark.lpt.data.TaskItem
|
||||
|
||||
@Composable
|
||||
fun TaskListScreen(
|
||||
tasks: List<TaskItem>,
|
||||
loading: Boolean,
|
||||
error: String?,
|
||||
username: String?,
|
||||
onRefresh: () -> Unit,
|
||||
onStart: (TaskItem) -> Unit,
|
||||
onOpenSettings: () -> Unit,
|
||||
onOpenPermissions: () -> Unit,
|
||||
onLogout: () -> Unit,
|
||||
) {
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Text("学习任务", style = MaterialTheme.typography.titleLarge)
|
||||
Text(
|
||||
username?.let { "已登录:$it" } ?: "",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
TextButton(onClick = onOpenPermissions) { Text("权限") }
|
||||
TextButton(onClick = onOpenSettings) { Text("设置") }
|
||||
}
|
||||
|
||||
if (error != null) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 16.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
error,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
TextButton(onClick = onRefresh) { Text("重试") }
|
||||
}
|
||||
}
|
||||
|
||||
if (loading && tasks.isEmpty()) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CircularProgressIndicator()
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
if (tasks.isEmpty() && !loading) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Text("还没有学习任务", style = MaterialTheme.typography.bodyLarge)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
TextButton(onClick = onRefresh) { Text("刷新") }
|
||||
}
|
||||
}
|
||||
return@Column
|
||||
}
|
||||
|
||||
LazyColumn(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
items(tasks, key = { it.taskNum }) { task ->
|
||||
Card(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { onStart(task) },
|
||||
) {
|
||||
Column(modifier = Modifier.padding(14.dp)) {
|
||||
Text(
|
||||
task.taskName,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
if (!task.taskDescription.isNullOrBlank()) {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
task.taskDescription,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Text(
|
||||
"优先级 %.2f".format(task.taskPriority),
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
Spacer(Modifier.weight(1f))
|
||||
Text(
|
||||
"开始学习 ›",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
item {
|
||||
Spacer(Modifier.height(4.dp))
|
||||
TextButton(onClick = onLogout, modifier = Modifier.fillMaxWidth()) {
|
||||
Text("退出登录", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.catshark.lpt.ui.theme
|
||||
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
private val LightColors = lightColorScheme(
|
||||
primary = Color(0xFF1F6FEB),
|
||||
onPrimary = Color.White,
|
||||
secondary = Color(0xFF238636),
|
||||
error = Color(0xFFB62324),
|
||||
)
|
||||
|
||||
private val DarkColors = darkColorScheme(
|
||||
primary = Color(0xFF6EA8FE),
|
||||
onPrimary = Color(0xFF0B1220),
|
||||
secondary = Color(0xFF3FB950),
|
||||
error = Color(0xFFF85149),
|
||||
)
|
||||
|
||||
@Composable
|
||||
fun LptTheme(content: @Composable () -> Unit) {
|
||||
MaterialTheme(
|
||||
colorScheme = if (isSystemInDarkTheme()) DarkColors else LightColors,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.catshark.lpt.util
|
||||
|
||||
/** 把秒数格式化成 mm:ss 或 h:mm:ss */
|
||||
fun formatDuration(seconds: Double): String {
|
||||
val total = seconds.toLong().coerceAtLeast(0)
|
||||
val h = total / 3600
|
||||
val m = (total % 3600) / 60
|
||||
val s = total % 60
|
||||
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%02d:%02d".format(m, s)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
|
||||
<solid android:color="#1F6FEB" />
|
||||
</shape>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M38,32 L44,32 L44,66 L64,66 L64,72 L38,72 Z" />
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M66,32 L72,32 L72,50 L66,50 Z" />
|
||||
<path
|
||||
android:fillColor="#FFD166"
|
||||
android:pathData="M54,74 m-6,0 a6,6 0 1,0 12,0 a6,6 0 1,0 -12,0" />
|
||||
</vector>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24"
|
||||
android:tint="#FFFFFF">
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M12,2 A10,10 0 1,0 22,12 A10,10 0 0,0 12,2 Z M12,20 A8,8 0 1,1 20,12 A8,8 0 0,1 12,20 Z" />
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:pathData="M12.5,7 L11,7 L11,13 L16,13 L16,11.5 L12.5,11.5 Z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.LPT" parent="android:Theme.Material.NoActionBar" />
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">LPT 学习</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<style name="Theme.LPT" parent="android:Theme.Material.Light.NoActionBar" />
|
||||
|
||||
<!-- 悬浮窗拉起的碎片输入弹窗:悬浮小窗 + 键盘 -->
|
||||
<style name="Theme.LPT.InputDialog" parent="android:Theme.Material.Light.Dialog">
|
||||
<item name="android:windowBackground">@android:color/transparent</item>
|
||||
<item name="android:windowIsTranslucent">true</item>
|
||||
<item name="android:windowNoTitle">true</item>
|
||||
<item name="android:backgroundDimEnabled">true</item>
|
||||
<item name="android:windowSoftInputMode">stateVisible|adjustResize</item>
|
||||
</style>
|
||||
</resources>
|
||||
Reference in New Issue
Block a user