From f4987e712115cec4bd92e3045470ba025ed65963 Mon Sep 17 00:00:00 2001 From: TongTongStudio Date: Tue, 1 Dec 2026 00:00:54 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20app=20=E6=A8=A1=E5=9D=97=E7=95=8C?= =?UTF-8?q?=E9=9D=A2=E8=BF=81=E7=A7=BB=E5=88=B0=20Jetpack=20Compose?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 首页、来源、历史、设置、目录浏览、本地视频库、播放页和来源编辑改为 Compose - 播放 Surface 通过 AndroidView 承载,保留画中画、全屏、手势和字幕 - 引入 Compose BOM/Material 3,删除原生 Views 工具类 - minSdk 保持 23 --- app/build.gradle.kts | 10 + .../com/ttstd/player/app/BrowserActivity.kt | 268 +++-- .../kotlin/com/ttstd/player/app/ComposeUi.kt | 275 ++++++ .../com/ttstd/player/app/HomeActivity.kt | 710 ++++++++++---- .../ttstd/player/app/LocalLibraryActivity.kt | 233 +++-- .../com/ttstd/player/app/PlayerActivity.kt | 921 ++++++++++++------ .../com/ttstd/player/app/PlayerModel.kt | 6 +- .../com/ttstd/player/app/SourceDialogs.kt | 211 ++-- .../main/kotlin/com/ttstd/player/app/Ui.kt | 73 -- build.gradle.kts | 1 + docs/app.md | 2 +- 11 files changed, 1880 insertions(+), 830 deletions(-) create mode 100644 app/src/main/kotlin/com/ttstd/player/app/ComposeUi.kt delete mode 100644 app/src/main/kotlin/com/ttstd/player/app/Ui.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 14236d7..9071326 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,6 +1,7 @@ plugins { id("com.android.application") kotlin("android") + id("org.jetbrains.kotlin.plugin.compose") } android { @@ -16,6 +17,8 @@ android { versionName = "1.0.0" } + buildFeatures { compose = true } + compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 @@ -25,6 +28,13 @@ android { kotlin { jvmToolchain(17) } dependencies { + implementation(platform("androidx.compose:compose-bom:2025.06.01")) + implementation("androidx.activity:activity-compose:1.10.1") + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.foundation:foundation") + implementation("androidx.compose.material3:material3") + implementation("androidx.lifecycle:lifecycle-runtime-compose:2.9.1") + implementation("androidx.appcompat:appcompat:1.7.1") implementation("androidx.activity:activity-ktx:1.10.1") implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.9.1") diff --git a/app/src/main/kotlin/com/ttstd/player/app/BrowserActivity.kt b/app/src/main/kotlin/com/ttstd/player/app/BrowserActivity.kt index 6d5b19a..347d66a 100644 --- a/app/src/main/kotlin/com/ttstd/player/app/BrowserActivity.kt +++ b/app/src/main/kotlin/com/ttstd/player/app/BrowserActivity.kt @@ -1,18 +1,33 @@ package com.ttstd.player.app -import android.app.AlertDialog import android.app.Application import android.content.Intent import android.os.Bundle -import android.text.Editable -import android.text.TextWatcher -import android.widget.* +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity -import androidx.lifecycle.* +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.background +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.viewModelScope import com.ttstd.player.library.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow -import com.ttstd.player.app.Ui.dp class BrowserModel(application: Application) : AndroidViewModel(application) { private val repo = AppRepository(application) @@ -21,36 +36,68 @@ class BrowserModel(application: Application) : AndroidViewModel(application) { val entries = MutableStateFlow>(emptyList()) val message = MutableStateFlow("") val busy = MutableStateFlow(false) - var more: Int? = null; private set + val title = MutableStateFlow("媒体浏览") + val more = MutableStateFlow(null) + val kind = MutableStateFlow(null) val folders = mutableListOf>() private var job: Job? = null + private var openJob: Job? = null + fun open(id: String) { if (account?.id == id) return - job = viewModelScope.launch { + openJob?.cancel() + openJob = viewModelScope.launch { try { val selected = withContext(Dispatchers.IO) { repo.accounts.all().firstOrNull { it.id == id } } ?: throw LibraryException("来源已删除") - account = selected; library = repo.library(selected); folders.clear(); folders += "" to selected.name + account = selected + library = repo.library(selected) + kind.value = selected.kind + folders.clear() + folders += "" to selected.name + title.value = selected.name load() - } catch (e: Exception) { message.value = SourceDialogs.safeError(e) } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (e: Exception) { + message.value = safeError(e) + } } } - fun enter(entry: LibraryEntry) { folders += entry.id to entry.name; load() } - fun up(): Boolean = if (folders.size > 1) { folders.removeAt(folders.lastIndex); load(); true } else false + + fun enter(entry: LibraryEntry) { + folders += entry.id to entry.name + title.value = entry.name + load() + } + + fun up(): Boolean = if (folders.size > 1) { + folders.removeAt(folders.lastIndex) + title.value = folders.last().second + load() + true + } else false + fun load(offset: Int = 0) { job?.cancel() val source = library ?: return val folder = folders.lastOrNull()?.first.orEmpty() job = viewModelScope.launch { - busy.value = true; message.value = "正在连接来源…" + busy.value = true + message.value = "正在连接来源…" try { val page = source.list(folder, offset) entries.value = (if (offset == 0) page.entries else entries.value + page.entries).distinctBy { it.id } - more = page.nextOffset + more.value = page.nextOffset message.value = "${entries.value.size} 个条目" - } catch (cancelled: CancellationException) { throw cancelled } - catch (e: Exception) { message.value = SourceDialogs.safeError(e) } - finally { busy.value = false } + title.value = folders.lastOrNull()?.second ?: "媒体浏览" + } catch (cancelled: CancellationException) { + throw cancelled + } catch (e: Exception) { + message.value = safeError(e) + } finally { + busy.value = false + } } } } @@ -59,91 +106,132 @@ class BrowserModel(application: Application) : AndroidViewModel(application) { class BrowserActivity : AppCompatActivity() { private lateinit var model: BrowserModel private val repo by lazy { AppRepository(applicationContext) } - private lateinit var title: TextView - private lateinit var status: TextView - private lateinit var list: ListView - private lateinit var more: TextView - private lateinit var search: EditText - private var visible = emptyList() + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - model = ViewModelProvider(this)[BrowserModel::class.java] - val root = Ui.column(this) - Ui.inset(this, root) - val toolbar = LinearLayout(this).apply { setPadding(dp(16), dp(12), dp(16), dp(8)); gravity = android.view.Gravity.CENTER_VERTICAL } - toolbar.addView(Ui.button(this, "‹") { goBack() }) - title = Ui.label(this, "媒体浏览", 22f, bold = true) - toolbar.addView(title, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(12) }) - toolbar.addView(Ui.button(this, "刷新") { model.load() }) - root.addView(toolbar) - search = EditText(this).apply { - hint = "筛选当前目录"; setTextColor(Ui.ink); setHintTextColor(Ui.muted); setSingleLine(true) - setPadding(dp(20), 0, dp(20), 0) - addTextChangedListener(object : TextWatcher { - override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit - override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { render() } - override fun afterTextChanged(s: Editable?) = Unit - }) - } - root.addView(search, LinearLayout.LayoutParams(-1, dp(52))) - status = Ui.label(this, "", 13f, Ui.muted).apply { setPadding(dp(20), dp(8), dp(20), dp(8)) } - root.addView(status) - list = ListView(this).apply { divider = null; clipToPadding = false; setPadding(dp(16), dp(4), dp(16), dp(12)) } - root.addView(list, LinearLayout.LayoutParams(-1, 0, 1f)) - more = Ui.button(this, "加载更多") { model.more?.let(model::load) } - root.addView(more, LinearLayout.LayoutParams(-1, -2).apply { setMargins(dp(16), dp(4), dp(16), dp(12)) }) - setContentView(root) - list.setOnItemClickListener { _, _, position, _ -> - val entry = visible[position] - if (entry.isFolder) { search.setText(""); model.enter(entry) } else play(entry) - } - list.setOnItemLongClickListener { _, _, position, _ -> - val entry = visible[position] - if (!entry.isFolder) AlertDialog.Builder(this).setTitle(entry.name).setItems(arrayOf("播放", "加入 / 取消收藏")) { _, choice -> - if (choice == 0) play(entry) else lifecycleScope.launch { - withContext(Dispatchers.IO) { - val ref = reference(entry); val old = repo.recent.find(ref.id) - if (old == null) repo.recent.save(ref, entry.resumeMs, null) - repo.recent.favorite(ref.id) - } - Toast.makeText(this@BrowserActivity, "收藏已更新", Toast.LENGTH_SHORT).show() - } - }.show() - true - } - lifecycleScope.launch { model.entries.collect { render() } } - lifecycleScope.launch { model.message.collect { status.text = it; title.text = model.folders.lastOrNull()?.second ?: "媒体浏览" } } - lifecycleScope.launch { model.busy.collect { more.isEnabled = !it && model.more != null; more.visibility = if (model.more == null) android.view.View.GONE else android.view.View.VISIBLE } } - onBackPressedDispatcher.addCallback(this, object : androidx.activity.OnBackPressedCallback(true) { override fun handleOnBackPressed() { goBack() } }) + model = androidx.lifecycle.ViewModelProvider(this)[BrowserModel::class.java] + setContent { TTVideoTheme { BrowserRoot() } } model.open(intent.getStringExtra("account").orEmpty()) } - private fun reference(entry: LibraryEntry) = MediaRef(entry.name, model.account?.id, entry) - private fun render() { - if (!::list.isInitialized) return - val jellyfin = model.account?.kind == LibraryKind.JELLYFIN - val query = search.text.toString() - visible = model.entries.value.filter { (it.isFolder || jellyfin || LibraryFiles.isVideo(it.name)) && it.name.contains(query, true) } - list.adapter = object : BaseAdapter() { - override fun getCount() = visible.size - override fun getItem(position: Int) = visible[position] - override fun getItemId(position: Int) = position.toLong() - override fun getView(position: Int, convertView: android.view.View?, parent: android.view.ViewGroup?): android.view.View { - val entry = visible[position] - return Ui.card(this@BrowserActivity, (if (entry.isFolder) "▤ " else "▷ ") + entry.name, - if (entry.isFolder) "打开目录" else listOfNotNull(entry.size?.let(Ui::bytes), entry.resumeMs.takeIf { it > 0 }?.let { "已看 ${Ui.time(it)}" }, "点击播放 · 长按收藏").joinToString(" · ")) - .apply { minimumHeight = dp(84); isFocusable = false } + + @Composable + private fun BrowserRoot() { + val entries by model.entries.collectAsStateWithLifecycle() + val message by model.message.collectAsStateWithLifecycle() + val busy by model.busy.collectAsStateWithLifecycle() + val more by model.more.collectAsStateWithLifecycle() + val title by model.title.collectAsStateWithLifecycle() + val kind by model.kind.collectAsStateWithLifecycle() + var query by rememberSaveable { mutableStateOf("") } + var menuEntry by remember { mutableStateOf(null) } + val visible = remember(entries, query, kind) { + entries.filter { (it.isFolder || kind == LibraryKind.JELLYFIN || LibraryFiles.isVideo(it.name)) && it.name.contains(query, true) } + } + val goBack = { if (model.up()) query = "" else finish() } + BackHandler { goBack() } + Column(Modifier.fillMaxSize().background(AppBg).windowInsetsPadding(WindowInsets.systemBars)) { + TopBar(title, onBack = goBack, actions = { + TextButton(onClick = { model.load() }) { Text("刷新", color = AppAccent) } + }) + AppTextField("筛选当前目录", query, { query = it }, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) + Text( + message, + style = MaterialTheme.typography.labelSmall, + color = AppMuted, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp), + ) + if (busy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth(), color = AppAccent, trackColor = AppPanel) + if (visible.isEmpty()) { + EmptyState( + if (busy) "正在加载…" else "当前目录为空", + if (busy) "请稍候" else "没有匹配的文件夹或视频。", + modifier = Modifier.weight(1f), + ) + } else { + LazyColumn( + Modifier.weight(1f), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + items(visible, key = { it.id }) { entry -> + BrowserCard( + entry = entry, + onClick = { + if (entry.isFolder) { + query = "" + model.enter(entry) + } else { + play(entry, visible) + } + }, + onLongClick = { menuEntry = entry }, + ) + } + } + } + more?.let { next -> + PrimaryButton( + "加载更多", + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), + enabled = !busy, + ) { model.load(next) } } } + val entry = menuEntry + if (entry != null) ChoiceDialog( + title = entry.name, + options = listOf("播放", "加入 / 取消收藏"), + onDismiss = { menuEntry = null }, + onSelect = { index -> + menuEntry = null + if (index == 0) play(entry, visible) else favorite(entry) + }, + ) } - private fun play(entry: LibraryEntry) { + + @OptIn(ExperimentalFoundationApi::class) + @Composable + private fun BrowserCard(entry: LibraryEntry, onClick: () -> Unit, onLongClick: () -> Unit) { + val subtitle = if (entry.isFolder) "打开目录" + else listOfNotNull( + entry.size?.let(::formatBytes), + entry.resumeMs.takeIf { it > 0 }?.let { "已看 ${formatTime(it)}" }, + "点击播放 · 长按收藏", + ).joinToString(" · ") + AppCard( + title = (if (entry.isFolder) "▤ " else "▷ ") + entry.name, + subtitle = subtitle, + modifier = Modifier.combinedClickable(onClick = onClick, onLongClick = onLongClick), + ) + } + + private fun reference(entry: LibraryEntry) = MediaRef(entry.name, model.account?.id, entry) + + private fun favorite(entry: LibraryEntry) { + lifecycleScope.launch { + withContext(Dispatchers.IO) { + val ref = reference(entry) + val old = repo.recent.find(ref.id) + if (old == null) repo.recent.save(ref, entry.resumeMs, null) + repo.recent.favorite(ref.id) + } + Toast.makeText(this@BrowserActivity, "收藏已更新", Toast.LENGTH_SHORT).show() + } + } + + private fun play(entry: LibraryEntry, visible: List) { val ref = reference(entry) PlaybackQueue.set(visible.filterNot { it.isFolder }.map(::reference)) lifecycleScope.launch { try { - withContext(Dispatchers.IO) { val old = repo.recent.find(ref.id); repo.recent.save(ref, old?.positionMs ?: entry.resumeMs, old?.durationMs) } + withContext(Dispatchers.IO) { + val old = repo.recent.find(ref.id) + repo.recent.save(ref, old?.positionMs ?: entry.resumeMs, old?.durationMs) + } startActivity(Intent(this@BrowserActivity, PlayerActivity::class.java).putExtra("media", ref.id)) - } catch (_: Exception) { status.text = "无法保存播放记录,请检查设备安全存储" } + } catch (_: Exception) { + Toast.makeText(this@BrowserActivity, "无法保存播放记录,请检查设备安全存储", Toast.LENGTH_LONG).show() + } } } - private fun goBack() { if (model.up()) search.setText("") else finish() } } diff --git a/app/src/main/kotlin/com/ttstd/player/app/ComposeUi.kt b/app/src/main/kotlin/com/ttstd/player/app/ComposeUi.kt new file mode 100644 index 0000000..5a7e289 --- /dev/null +++ b/app/src/main/kotlin/com/ttstd/player/app/ComposeUi.kt @@ -0,0 +1,275 @@ +package com.ttstd.player.app + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.* +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import java.util.Locale + +val AppBg = Color(0xFF0C121C) +val AppPanel = Color(0xFF16202E) +val AppRaised = Color(0xFF1F2C3D) +val AppInk = Color(0xFFECF3F9) +val AppMuted = Color(0xFF95A8BC) +val AppAccent = Color(0xFF64E3BE) +val AppError = Color(0xFFFF8A80) + +private val AppColors = darkColorScheme( + primary = AppAccent, + onPrimary = AppBg, + secondary = AppAccent, + onSecondary = AppBg, + background = AppBg, + onBackground = AppInk, + surface = AppPanel, + onSurface = AppInk, + surfaceVariant = AppRaised, + onSurfaceVariant = AppMuted, + error = AppError, + onError = AppBg, +) + +private val AppTypography = Typography( + headlineMedium = TextStyle(fontSize = 28.sp, fontWeight = FontWeight.Bold), + titleLarge = TextStyle(fontSize = 22.sp, fontWeight = FontWeight.Bold), + titleMedium = TextStyle(fontSize = 18.sp, fontWeight = FontWeight.Bold), + bodyLarge = TextStyle(fontSize = 16.sp), + bodyMedium = TextStyle(fontSize = 14.sp), + labelLarge = TextStyle(fontSize = 15.sp, fontWeight = FontWeight.Medium), + labelSmall = TextStyle(fontSize = 12.sp), +) + +@Composable +fun TTVideoTheme(content: @Composable () -> Unit) { + MaterialTheme(colorScheme = AppColors, typography = AppTypography, content = content) +} + +fun formatTime(ms: Long): String { + val seconds = ms.coerceAtLeast(0) / 1000 + return if (seconds >= 3600) "%d:%02d:%02d".format(Locale.US, seconds / 3600, seconds / 60 % 60, seconds % 60) + else "%d:%02d".format(Locale.US, seconds / 60, seconds % 60) +} + +fun formatBytes(value: Long): String = + if (value >= 1024L * 1024 * 1024) "%.1f GB".format(Locale.US, value / (1024.0 * 1024 * 1024)) + else "%.1f MB".format(Locale.US, value / (1024.0 * 1024)) + +@Composable +fun Heading(title: String, detail: String, modifier: Modifier = Modifier) { + Column(modifier.fillMaxWidth()) { + Text(title, style = MaterialTheme.typography.headlineMedium, color = AppInk) + if (detail.isNotBlank()) Text( + detail, + style = MaterialTheme.typography.bodyMedium, + color = AppMuted, + modifier = Modifier.padding(top = 8.dp), + ) + } +} + +@Composable +fun SectionTitle(title: String, modifier: Modifier = Modifier) { + Text( + title, + style = MaterialTheme.typography.titleMedium, + color = AppInk, + modifier = modifier.fillMaxWidth().padding(top = 20.dp, bottom = 12.dp), + ) +} + +@Composable +fun AppCard( + title: String, + subtitle: String = "", + modifier: Modifier = Modifier, + onClick: (() -> Unit)? = null, + content: @Composable ColumnScope.() -> Unit = {}, +) { + val shape = RoundedCornerShape(18.dp) + Column( + modifier + .fillMaxWidth() + .clip(shape) + .background(AppPanel) + .then(if (onClick != null) Modifier.clickable { onClick() } else Modifier) + .padding(18.dp), + ) { + Text( + title, + style = MaterialTheme.typography.titleMedium, + color = AppInk, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + if (subtitle.isNotBlank()) Text( + subtitle, + style = MaterialTheme.typography.bodyMedium, + color = AppMuted, + modifier = Modifier.padding(top = 8.dp), + ) + content() + } +} + +@Composable +fun EmptyState(title: String, description: String, modifier: Modifier = Modifier, action: (@Composable () -> Unit)? = null) { + Column( + modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 28.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Text("▷", fontSize = 52.sp, color = AppAccent) + Text(title, style = MaterialTheme.typography.titleLarge, color = AppInk, textAlign = TextAlign.Center) + Text( + description, + style = MaterialTheme.typography.bodyMedium, + color = AppMuted, + textAlign = TextAlign.Center, + modifier = Modifier.padding(top = 12.dp, bottom = if (action != null) 16.dp else 0.dp), + ) + action?.invoke() + } +} + +@Composable +fun TopBar( + title: String, + onBack: () -> Unit, + modifier: Modifier = Modifier, + actions: @Composable RowScope.() -> Unit = {}, +) { + Row( + modifier.fillMaxWidth().background(Color(0xD9111822)).padding(horizontal = 6.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + TextButton(onClick = onBack, contentPadding = PaddingValues(horizontal = 12.dp)) { + Text("‹", fontSize = 26.sp, color = AppInk) + } + Text( + title, + style = MaterialTheme.typography.titleMedium, + color = AppInk, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f).padding(horizontal = 4.dp), + ) + actions() + } +} + +@Composable +fun PrimaryButton(text: String, modifier: Modifier = Modifier, enabled: Boolean = true, onClick: () -> Unit) { + Button( + onClick = onClick, + enabled = enabled, + modifier = modifier.heightIn(min = 48.dp), + shape = RoundedCornerShape(14.dp), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.buttonColors(containerColor = AppAccent, contentColor = AppBg, disabledContainerColor = AppRaised, disabledContentColor = AppMuted), + ) { Text(text, maxLines = 2, textAlign = TextAlign.Center) } +} + +@Composable +fun SecondaryButton(text: String, modifier: Modifier = Modifier, enabled: Boolean = true, onClick: () -> Unit) { + Button( + onClick = onClick, + enabled = enabled, + modifier = modifier.heightIn(min = 48.dp), + shape = RoundedCornerShape(14.dp), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp), + colors = ButtonDefaults.buttonColors(containerColor = AppRaised, contentColor = AppInk, disabledContainerColor = AppPanel, disabledContentColor = AppMuted), + ) { Text(text, maxLines = 2, textAlign = TextAlign.Center) } +} + +@Composable +fun ChoiceDialog(title: String, options: List, onDismiss: () -> Unit, onSelect: (Int) -> Unit) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title, color = AppInk) }, + text = { + Column(Modifier.heightIn(max = 480.dp).verticalScroll(rememberScrollState())) { + options.forEachIndexed { index, option -> + TextButton( + onClick = { onSelect(index) }, + modifier = Modifier.fillMaxWidth(), + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 12.dp), + ) { + Text(option, color = AppInk, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Start) + } + } + } + }, + confirmButton = {}, + dismissButton = { TextButton(onClick = onDismiss) { Text("取消", color = AppMuted) } }, + containerColor = AppPanel, + ) +} + +@Composable +fun ConfirmDialog( + title: String, + message: String, + confirmText: String = "确定", + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(title, color = AppInk) }, + text = { Text(message, color = AppMuted) }, + confirmButton = { TextButton(onClick = onConfirm) { Text(confirmText, color = AppAccent) } }, + dismissButton = { TextButton(onClick = onDismiss) { Text("取消", color = AppMuted) } }, + containerColor = AppPanel, + ) +} + +@Composable +fun AppTextField( + label: String, + value: String, + onValueChange: (String) -> Unit, + modifier: Modifier = Modifier, + singleLine: Boolean = true, + minLines: Int = 1, + secret: Boolean = false, + placeholder: String? = null, + keyboardType: KeyboardType = KeyboardType.Text, +) { + OutlinedTextField( + value = value, + onValueChange = onValueChange, + modifier = modifier.fillMaxWidth(), + label = { Text(label) }, + placeholder = placeholder?.let { { Text(it) } }, + singleLine = singleLine, + minLines = minLines, + visualTransformation = if (secret) PasswordVisualTransformation() else VisualTransformation.None, + keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = keyboardType), + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = AppAccent, + unfocusedBorderColor = AppRaised, + focusedLabelColor = AppAccent, + unfocusedLabelColor = AppMuted, + focusedTextColor = AppInk, + unfocusedTextColor = AppInk, + cursorColor = AppAccent, + ), + ) +} diff --git a/app/src/main/kotlin/com/ttstd/player/app/HomeActivity.kt b/app/src/main/kotlin/com/ttstd/player/app/HomeActivity.kt index 91d2cc1..46a9f41 100644 --- a/app/src/main/kotlin/com/ttstd/player/app/HomeActivity.kt +++ b/app/src/main/kotlin/com/ttstd/player/app/HomeActivity.kt @@ -1,259 +1,573 @@ package com.ttstd.player.app -import android.app.AlertDialog import android.content.Intent +import android.net.Uri import android.os.Bundle import android.provider.OpenableColumns -import android.text.InputType -import android.view.Gravity -import android.widget.* +import android.widget.Toast +import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope import com.ttstd.player.api.* +import com.ttstd.player.cast.google.GoogleCastActivity +import com.ttstd.player.cast.google.GoogleCastResources import com.ttstd.player.core.HttpHeaders import com.ttstd.player.library.* import com.ttstd.player.media3.source.Media3FileCache -import com.ttstd.player.cast.google.GoogleCastActivity -import com.ttstd.player.cast.google.GoogleCastResources import kotlinx.coroutines.* import kotlinx.coroutines.flow.first -import com.ttstd.player.app.Ui.dp +import java.net.URI /** 正式应用入口:媒体、来源、历史、设置。宽屏使用侧边导航,手机使用底部导航。 */ class HomeActivity : AppCompatActivity() { private val repo by lazy { AppRepository(applicationContext) } - private lateinit var content: LinearLayout - private var tab = 0 - private var accounts: List = emptyList() - private var recent: List = emptyList() - private var favoritesOnly = false + private val accountsState = mutableStateOf>(emptyList()) + private val recentState = mutableStateOf>(emptyList()) + private val loadError = mutableStateOf(null) + private val cacheBytes = mutableLongStateOf(0L) + private val decoderState = mutableStateOf(DecodeMode.AUTO) + private val textureState = mutableStateOf(false) + private val autoSubtitleState = mutableStateOf(true) + private val castActive = mutableStateOf(false) + private val dialogState = mutableStateOf(null) private var loadJob: Job? = null + private val googleControl = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> val id = AppPlaybackRuntime.googleMediaId if (id != null && result.data != null) lifecycleScope.launch { - withContext(Dispatchers.IO) { repo.recent.find(id)?.let { repo.recent.save(it.ref, result.data!!.getLongExtra("position", it.positionMs) + AppPlaybackRuntime.googleOffsetMs, it.durationMs) } } + withContext(Dispatchers.IO) { + repo.recent.find(id)?.let { + repo.recent.save(it.ref, result.data!!.getLongExtra("position", it.positionMs) + AppPlaybackRuntime.googleOffsetMs, it.durationMs) + } + } startActivity(Intent(this@HomeActivity, PlayerActivity::class.java).putExtra("media", id)) } } private val pickVideo = registerForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris -> if (uris.isNotEmpty()) lifecycleScope.launch { - val refs = withContext(Dispatchers.IO) { uris.take(150).map { uri -> - runCatching { contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } - val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor -> - if (cursor.moveToFirst()) cursor.getString(0) else null - } ?: "本地视频" - MediaRef(name, uri = uri.toString()) - } } + val refs = withContext(Dispatchers.IO) { + uris.take(150).map { uri -> + runCatching { contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } + val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { cursor -> + if (cursor.moveToFirst()) cursor.getString(0) else null + } ?: "本地视频" + MediaRef(name, uri = uri.toString()) + } + } PlaybackQueue.set(refs) - open(refs.first()) + openMedia(refs.first()) } } + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - tab = savedInstanceState?.getInt("tab") ?: 0 - build() + decoderState.value = repo.preferences.decoder + textureState.value = repo.preferences.texture + autoSubtitleState.value = repo.preferences.autoSubtitle + setContent { TTVideoTheme { HomeRoot() } } if (intent.action == Intent.ACTION_VIEW && intent.data != null) { val uri = intent.data!! - if (uri.scheme?.lowercase() in setOf("content", "http", "https", "rtsp", "rtmp")) - lifecycleScope.launch { open(MediaRef(uri.lastPathSegment ?: "外部视频", uri = uri.toString())) } + if (uri.scheme?.lowercase() in setOf("content", "http", "https", "rtsp", "rtmp")) { + lifecycleScope.launch { openMedia(MediaRef(uri.lastPathSegment ?: "外部视频", uri = uri.toString())) } + } intent.action = null } } - override fun onResume() { super.onResume(); refresh() } - override fun onSaveInstanceState(outState: Bundle) { outState.putInt("tab", tab); super.onSaveInstanceState(outState) } - private fun build() { - val wide = resources.configuration.screenWidthDp >= 720 - val root = LinearLayout(this).apply { orientation = if (wide) LinearLayout.HORIZONTAL else LinearLayout.VERTICAL } - Ui.inset(this, root) - val nav = LinearLayout(this).apply { - orientation = if (wide) LinearLayout.VERTICAL else LinearLayout.HORIZONTAL - gravity = Gravity.CENTER; setPadding(dp(8), dp(8), dp(8), dp(8)) - } - val labels = arrayOf("首页", "来源", "历史", "设置") - for (index in labels.indices) { - nav.addView(Ui.button(this, labels[index], index == tab) { tab = index; build(); render() }, - if (wide) LinearLayout.LayoutParams(dp(100), dp(64)).apply { bottomMargin = dp(12) } - else LinearLayout.LayoutParams(0, dp(52), 1f).apply { marginStart = dp(3); marginEnd = dp(3) }) - } - val scroll = ScrollView(this).apply { isFillViewport = true } - content = Ui.column(this, if (wide) 32 else 20) - scroll.addView(content) - if (wide) { - root.addView(nav, LinearLayout.LayoutParams(dp(116), -1)) - root.addView(scroll, LinearLayout.LayoutParams(0, -1, 1f)) - } else { - root.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f)); root.addView(nav) - } - setContentView(root); render() + + override fun onResume() { + super.onResume() + refresh() } + private fun refresh() { loadJob?.cancel() loadJob = lifecycleScope.launch { try { - withContext(Dispatchers.IO) { accounts = repo.accounts.all(); recent = repo.recent.all() } - render() - } catch (cancelled: CancellationException) { throw cancelled } - catch (_: Exception) { content.removeAllViews(); content.addView(Ui.empty(this@HomeActivity, "本机数据暂不可读", "设备安全密钥可能发生变化,请在系统设置中检查应用数据。")) } - } - } - private fun heading(title: String, detail: String) { - content.addView(Ui.label(this, title, 28f, bold = true)) - content.addView(Ui.label(this, detail, 14f, Ui.muted).apply { setPadding(0, dp(8), 0, dp(24)) }) - } - private fun render() { - if (!::content.isInitialized) return - content.removeAllViews() - when (tab) { - 0 -> home() - 1 -> sources() - 2 -> history() - else -> settings() - } - } - private fun home() { - heading("同同影音", "你的媒体,随处播放") - if (DlnaSession.state.value.active) content.addView(Ui.card(this, "正在投屏 · ${DlnaSession.state.value.device}", DlnaSession.state.value.title) { - AlertDialog.Builder(this).setTitle("电视投屏").setItems(arrayOf("播放", "暂停", "结束投屏", "结束并在本机继续")) { _, choice -> - val lease = DlnaSession.lease - DlnaSession.command(this, listOf("play", "pause", "stop", "stop")[choice]) - if (choice == 3 && lease != null) lifecycleScope.launch { - withTimeoutOrNull(7000) { DlnaSession.state.first { !it.active } } - withContext(Dispatchers.IO) { repo.recent.find(lease.mediaId)?.let { repo.recent.save(it.ref, DlnaSession.state.value.playback.positionMs + lease.positionOffsetMs, it.durationMs) } } - startActivity(Intent(this@HomeActivity, PlayerActivity::class.java).putExtra("media", lease.mediaId)) + val accounts: List + val recent: List + val bytes: Long + withContext(Dispatchers.IO) { + accounts = repo.accounts.all() + recent = repo.recent.all() + bytes = runCatching { Media3FileCache.bytes() }.getOrDefault(0) } - }.show() - }) - if (GoogleCastResources.observer != null && AppPlaybackRuntime.googleMedia != null) content.addView(Ui.card(this, "Google Cast 正在播放", "打开设备控制或返回本机") { - AppPlaybackRuntime.googleMedia?.let { googleControl.launch(GoogleCastActivity.intent(this, it)) } - }) - content.addView(Ui.card(this, "连接你的媒体世界", "本地文件、网盘、局域网与家庭媒体库,在这里汇合。")) - val row = LinearLayout(this) - row.addView(Ui.button(this, "本地视频库", true) { startActivity(Intent(this, LocalLibraryActivity::class.java)) }, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) }) - row.addView(Ui.button(this, "打开本地视频") { pickVideo.launch(arrayOf("video/*")) }, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) }) - row.addView(Ui.button(this, "播放链接") { urlDialog() }, LinearLayout.LayoutParams(0, -2, 1f)) - content.addView(row) - content.addView(Ui.label(this, "继续观看", 19f, bold = true).apply { setPadding(0, dp(28), 0, dp(14)) }) - if (recent.isEmpty()) content.addView(Ui.empty(this, "从一部视频开始", "打开文件、粘贴链接,或添加你的媒体来源。")) - else for (item in recent.take(4)) mediaCard(item) - content.addView(Ui.label(this, "媒体来源", 19f, bold = true).apply { setPadding(0, dp(20), 0, dp(14)) }) - for (account in accounts.take(3)) sourceCard(account) - content.addView(Ui.button(this, if (accounts.isEmpty()) "+ 添加网盘或 NAS" else "管理全部来源") { - if (accounts.isEmpty()) SourceDialogs.edit(this) { refresh() } else { tab = 1; build() } - }) + accountsState.value = accounts + recentState.value = recent + cacheBytes.longValue = bytes + decoderState.value = repo.preferences.decoder + textureState.value = repo.preferences.texture + autoSubtitleState.value = repo.preferences.autoSubtitle + castActive.value = GoogleCastResources.observer != null && AppPlaybackRuntime.googleMedia != null + loadError.value = null + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + loadError.value = "本机数据暂不可读,请检查设备安全存储后重试。" + } + } } - private fun sources() { - heading("媒体来源", "WebDAV 网盘 · SMB 局域网 · Jellyfin") - content.addView(Ui.button(this, "+ 添加来源", true) { SourceDialogs.edit(this) { refresh() } }) - content.addView(Ui.label(this, "", 8f)) - if (accounts.isEmpty()) content.addView(Ui.empty(this, "连接你的网盘或 NAS", "WebDAV 可连接支持该协议的网盘或聚合服务;SMB 连接共享文件夹。")) - for (account in accounts) sourceCard(account) + + private suspend fun openMedia(ref: MediaRef) { + try { + withContext(Dispatchers.IO) { + val old = repo.recent.find(ref.id) + repo.recent.save(ref, old?.positionMs ?: 0, old?.durationMs) + } + startActivity(Intent(this, PlayerActivity::class.java).putExtra("media", ref.id)) + } catch (_: Exception) { + Toast.makeText(this, "无法保存播放记录,请检查设备安全存储", Toast.LENGTH_LONG).show() + } } - private fun sourceCard(account: LibraryAccount) { - val host = runCatching { java.net.URI(account.endpoint).host }.getOrNull().orEmpty() - val card = Ui.card(this, account.name, "${account.kind} · $host") { startActivity(Intent(this, BrowserActivity::class.java).putExtra("account", account.id)) } - card.addView(Ui.button(this, "管理来源") { - AlertDialog.Builder(this).setTitle(account.name).setItems(arrayOf("编辑连接", "删除来源")) { _, index -> - if (index == 0) SourceDialogs.edit(this, account) { refresh() } - else AlertDialog.Builder(this).setMessage("删除连接配置?服务器上的文件不会被修改。") - .setPositiveButton("删除") { _, _ -> lifecycleScope.launch { withContext(Dispatchers.IO) { repo.accounts.delete(account.id) }; refresh() } } - .setNegativeButton("取消", null).show() - }.show() - }.apply { layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(14) } }) - content.addView(card) + + private fun deleteAccount(account: LibraryAccount) { + lifecycleScope.launch { + withContext(Dispatchers.IO) { repo.accounts.delete(account.id) } + refresh() + } } - private fun history() { - heading("观看记录", "记录与播放链接加密保存在本机") - val filters = LinearLayout(this) - filters.addView(Ui.button(this, "全部", !favoritesOnly) { favoritesOnly = false; render() }, LinearLayout.LayoutParams(0, -2, 1f).apply { marginEnd = dp(8) }) - filters.addView(Ui.button(this, "收藏", favoritesOnly) { favoritesOnly = true; render() }, LinearLayout.LayoutParams(0, -2, 1f)) - content.addView(filters); content.addView(Ui.label(this, "", 8f)) - val visible = recent.filter { !favoritesOnly || it.favorite } - if (visible.isEmpty()) content.addView(Ui.empty(this, if (favoritesOnly) "还没有收藏" else "还没有观看记录", "视频卡片的更多菜单可收藏或移除记录。")) - for (item in visible) mediaCard(item) + + private fun updateFavorite(item: RecentMedia) { + lifecycleScope.launch { + withContext(Dispatchers.IO) { repo.recent.favorite(item.ref.id) } + refresh() + } } - private fun mediaCard(item: RecentMedia) { - val position = if (item.positionMs > 0) "已看 ${Ui.time(item.positionMs)}" else "从头播放" - val source = item.ref.accountId?.let { id -> accounts.firstOrNull { it.id == id }?.name } ?: if (item.ref.uri?.startsWith("content:") == true) "本地文件" else "在线视频" - val card = Ui.card(this, (if (item.favorite) "★ " else "") + item.ref.title, "$source · $position") { lifecycleScope.launch { open(item.ref) } } - if (item.durationMs != null && item.durationMs > 0) card.addView(ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply { - max = 1000; progress = (item.positionMs * 1000 / item.durationMs).coerceIn(0, 1000).toInt() - progressTintList = android.content.res.ColorStateList.valueOf(Ui.accent) - }) - card.addView(Ui.button(this, "更多") { - AlertDialog.Builder(this).setTitle(item.ref.title).setItems(arrayOf(if (item.favorite) "取消收藏" else "加入收藏", "从头播放", "移除记录")) { _, choice -> - lifecycleScope.launch { - withContext(Dispatchers.IO) { - when (choice) { 0 -> repo.recent.favorite(item.ref.id); 1 -> repo.recent.save(item.ref, 0, item.durationMs); else -> repo.recent.remove(item.ref.id) } + + private fun removeHistory(item: RecentMedia) { + lifecycleScope.launch { + withContext(Dispatchers.IO) { repo.recent.remove(item.ref.id) } + refresh() + } + } + + private fun restart(item: RecentMedia) { + lifecycleScope.launch { + withContext(Dispatchers.IO) { repo.recent.save(item.ref, 0, item.durationMs) } + openMedia(item.ref) + } + } + + private fun clearHistory() { + lifecycleScope.launch { + withContext(Dispatchers.IO) { repo.recent.clear() } + refresh() + } + } + + private fun clearCache() { + if (AppPlaybackRuntime.localActive || DlnaSession.resourcesOpen || GoogleCastResources.observer != null) { + Toast.makeText(this, "请先结束播放和投屏,再清理缓存", Toast.LENGTH_LONG).show() + return + } + lifecycleScope.launch { + val result = withContext(Dispatchers.IO) { runCatching { Media3FileCache.get(applicationContext); Media3FileCache.clear() } } + Toast.makeText(this@HomeActivity, if (result.isSuccess) "缓存已清理" else "缓存暂时无法清理,请结束播放后重试", Toast.LENGTH_SHORT).show() + refresh() + } + } + + private fun continueAfterDlna() { + val lease = DlnaSession.lease ?: return + DlnaSession.command(this, "stop") + lifecycleScope.launch { + withTimeoutOrNull(7000) { DlnaSession.state.first { !it.active } } + withContext(Dispatchers.IO) { + repo.recent.find(lease.mediaId)?.let { + repo.recent.save(it.ref, DlnaSession.state.value.playback.positionMs + lease.positionOffsetMs, it.durationMs) + } + } + startActivity(Intent(this@HomeActivity, PlayerActivity::class.java).putExtra("media", lease.mediaId)) + } + } + + @Composable + private fun HomeRoot() { + var tab by rememberSaveable { mutableIntStateOf(0) } + var favoritesOnly by rememberSaveable { mutableStateOf(false) } + val dlna by DlnaSession.state.collectAsStateWithLifecycle() + BoxWithConstraints( + Modifier.fillMaxSize().background(AppBg).windowInsetsPadding(WindowInsets.systemBars) + ) { + val wide = maxWidth >= 720.dp + if (wide) { + Row(Modifier.fillMaxSize()) { + HomeNav(tab, wide = true) { tab = it } + Box(Modifier.weight(1f)) { + HomeContent(tab, wide, favoritesOnly, dlna, onFavoritesOnly = { favoritesOnly = it }, onManageSources = { tab = 1 }) } - if (choice == 1) open(item.ref) else refresh() } - }.show() - }.apply { layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(12) } }) - content.addView(card) + } else { + Column(Modifier.fillMaxSize()) { + Box(Modifier.weight(1f)) { + HomeContent(tab, wide, favoritesOnly, dlna, onFavoritesOnly = { favoritesOnly = it }, onManageSources = { tab = 1 }) + } + HomeNav(tab, wide = false) { tab = it } + } + } + } + HomeDialogs() } - private fun settings() { - heading("播放与存储", "为不同设备选择合适的播放方式") + + @Composable + private fun HomeNav(tab: Int, wide: Boolean, onSelect: (Int) -> Unit) { + val labels = listOf("首页", "来源", "历史", "设置") + if (wide) { + Column( + Modifier.width(116.dp).fillMaxHeight().padding(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + labels.forEachIndexed { index, label -> + NavItem(label, tab == index, Modifier.fillMaxWidth()) { onSelect(index) } + } + } + } else { + Row( + Modifier.fillMaxWidth().padding(8.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + ) { + labels.forEachIndexed { index, label -> + NavItem(label, tab == index, Modifier.weight(1f)) { onSelect(index) } + } + } + } + } + + @Composable + private fun NavItem(label: String, selected: Boolean, modifier: Modifier, onClick: () -> Unit) { + Box( + modifier + .height(52.dp) + .clip(RoundedCornerShape(14.dp)) + .background(if (selected) AppAccent else AppRaised) + .clickable { onClick() }, + contentAlignment = Alignment.Center, + ) { + Text(label, color = if (selected) AppBg else AppInk, fontSize = 15.sp, textAlign = TextAlign.Center) + } + } + + @Composable + private fun HomeContent( + tab: Int, + wide: Boolean, + favoritesOnly: Boolean, + dlna: DlnaUiState, + onFavoritesOnly: (Boolean) -> Unit, + onManageSources: () -> Unit, + ) { + val horizontal = if (wide) 32.dp else 20.dp + if (loadError.value != null) { + Box(Modifier.fillMaxSize().padding(horizontal)) { + EmptyState("本机数据暂不可读", loadError.value ?: "") + } + return + } + LazyColumn( + Modifier.fillMaxSize(), + contentPadding = PaddingValues(horizontal = horizontal, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + when (tab) { + 0 -> homeTab(dlna, onManageSources) + 1 -> sourcesTab() + 2 -> historyTab(favoritesOnly, onFavoritesOnly) + else -> settingsTab() + } + } + } + + private fun androidx.compose.foundation.lazy.LazyListScope.homeTab( + dlna: DlnaUiState, + onManageSources: () -> Unit, + ) { + item { Heading("同同影音", "你的媒体,随处播放") } + if (dlna.active) item { + AppCard("正在投屏 · ${dlna.device}", dlna.title, onClick = { dialogState.value = HomeDialog.DlnaMenu }) { + Text("点击管理电视播放", style = MaterialTheme.typography.labelSmall, color = AppAccent, modifier = Modifier.padding(top = 10.dp)) + } + } + if (castActive.value) item { + AppCard("Google Cast 正在播放", "打开设备控制或返回本机", onClick = { + AppPlaybackRuntime.googleMedia?.let { googleControl.launch(GoogleCastActivity.intent(this@HomeActivity, it)) } + }) + } + item { AppCard("连接你的媒体世界", "本地文件、网盘、局域网与家庭媒体库,在这里汇合。") } + item { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + PrimaryButton("本地视频库", Modifier.weight(1f)) { startActivity(Intent(this@HomeActivity, LocalLibraryActivity::class.java)) } + SecondaryButton("打开视频", Modifier.weight(1f)) { pickVideo.launch(arrayOf("video/*")) } + SecondaryButton("播放链接", Modifier.weight(1f)) { dialogState.value = HomeDialog.Url } + } + } + item { SectionTitle("继续观看") } + val recent = recentState.value + if (recent.isEmpty()) item { + EmptyState("从一部视频开始", "打开文件、粘贴链接,或添加你的媒体来源。") + } else items(recent.take(4), key = { "recent-${it.ref.id}" }) { item -> MediaCard(item) } + item { SectionTitle("媒体来源") } + val accounts = accountsState.value + items(accounts.take(3), key = { "source-${it.id}" }) { account -> SourceCard(account) } + item { + PrimaryButton(if (accounts.isEmpty()) "+ 添加网盘或 NAS" else "管理全部来源") { + if (accounts.isEmpty()) dialogState.value = HomeDialog.SourceEditor(null) else onManageSources() + } + } + } + + private fun androidx.compose.foundation.lazy.LazyListScope.sourcesTab() { + item { Heading("媒体来源", "WebDAV 网盘 · SMB 局域网 · Jellyfin") } + item { PrimaryButton("+ 添加来源") { dialogState.value = HomeDialog.SourceEditor(null) } } + val accounts = accountsState.value + if (accounts.isEmpty()) item { + EmptyState("连接你的网盘或 NAS", "WebDAV 可连接支持该协议的网盘或聚合服务;SMB 连接共享文件夹。") + } else items(accounts, key = { "all-source-${it.id}" }) { account -> SourceCard(account) } + } + + private fun androidx.compose.foundation.lazy.LazyListScope.historyTab(favoritesOnly: Boolean, onFavoritesOnly: (Boolean) -> Unit) { + item { Heading("观看记录", "记录与播放链接加密保存在本机") } + item { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + PrimaryButton("全部", Modifier.weight(1f)) { onFavoritesOnly(false) } + SecondaryButton("收藏", Modifier.weight(1f)) { onFavoritesOnly(true) } + } + } + val visible = recentState.value.filter { !favoritesOnly || it.favorite } + if (visible.isEmpty()) item { + EmptyState(if (favoritesOnly) "还没有收藏" else "还没有观看记录", "视频卡片的更多菜单可收藏或移除记录。") + } else items(visible, key = { "history-${it.ref.id}" }) { item -> MediaCard(item) } + } + + private fun androidx.compose.foundation.lazy.LazyListScope.settingsTab() { + item { Heading("播放与存储", "为不同设备选择合适的播放方式") } val modes = DecodeMode.entries val names = arrayOf("自动选择", "优先硬件解码", "仅硬件解码", "仅系统软件解码") - content.addView(Ui.card(this, "默认解码方式", names[modes.indexOf(repo.preferences.decoder)]) { - AlertDialog.Builder(this).setTitle("默认解码方式").setSingleChoiceItems(names, modes.indexOf(repo.preferences.decoder)) { dialog, index -> repo.preferences.decoder = modes[index]; dialog.dismiss(); render() }.show() - }) - content.addView(Ui.card(this, "视频显示", if (repo.preferences.texture) "TextureView · 适合界面变换" else "SurfaceView · 默认省电路径") { - repo.preferences.texture = !repo.preferences.texture; render() - }) - content.addView(Ui.card(this, "自动加载同名字幕", if (repo.preferences.autoSubtitle) "已开启" else "已关闭") { repo.preferences.autoSubtitle = !repo.preferences.autoSubtitle; render() }) - content.addView(Ui.card(this, "媒体缓存", "已使用 ${Ui.bytes(cacheBytes())} · 目标上限 256 MB\n缓存可被系统回收,不是离线下载。")) - content.addView(Ui.button(this, "清理媒体缓存") { - if (AppPlaybackRuntime.localActive || DlnaSession.resourcesOpen || GoogleCastResources.observer != null) { - Toast.makeText(this, "请先结束播放和投屏,再清理缓存", Toast.LENGTH_LONG).show(); return@button + item { + AppCard("默认解码方式", names[modes.indexOf(decoderState.value)], onClick = { dialogState.value = HomeDialog.Decode }) { + Text("点击切换", style = MaterialTheme.typography.labelSmall, color = AppAccent, modifier = Modifier.padding(top = 10.dp)) } - AlertDialog.Builder(this).setMessage("确认清理已缓存的媒体片段?投屏或播放进行中时请先停止播放。") - .setPositiveButton("清理") { _, _ -> lifecycleScope.launch { - val result = withContext(Dispatchers.IO) { runCatching { Media3FileCache.get(applicationContext); Media3FileCache.clear() } } - Toast.makeText(this@HomeActivity, if (result.isSuccess) "缓存已清理" else "缓存暂时无法清理,请结束播放后重试", Toast.LENGTH_SHORT).show(); render() - } }.setNegativeButton("取消", null).show() - }) - content.addView(Ui.button(this, "清空历史与收藏") { - AlertDialog.Builder(this).setMessage("清空本机记录?媒体来源和远端文件会保留。") - .setPositiveButton("清空") { _, _ -> lifecycleScope.launch { withContext(Dispatchers.IO) { repo.recent.clear() }; refresh() } } - .setNegativeButton("取消", null).show() - }.apply { layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(12) } }) - content.addView(Ui.card(this, "关于同同影音", "1.0.0 · Android 6.0+\n本地 / 在线 / WebDAV / SMB / Jellyfin\n支持 DLNA 与 Google Cast;接收端需支持对应媒体格式。")) + } + item { + AppCard("视频显示", if (textureState.value) "TextureView · 适合界面变换" else "SurfaceView · 默认省电路径", onClick = { + repo.preferences.texture = !textureState.value + textureState.value = !textureState.value + }) + } + item { + AppCard("自动加载同名字幕", if (autoSubtitleState.value) "已开启" else "已关闭", onClick = { + repo.preferences.autoSubtitle = !autoSubtitleState.value + autoSubtitleState.value = !autoSubtitleState.value + }) + } + item { AppCard("媒体缓存", "已使用 ${formatBytes(cacheBytes.longValue)} · 目标上限 256 MB\n缓存可被系统回收,不是离线下载。") } + item { PrimaryButton("清理媒体缓存") { dialogState.value = HomeDialog.ClearCache } } + item { SecondaryButton("清空历史与收藏") { dialogState.value = HomeDialog.ClearHistory } } + item { AppCard("关于同同影音", "1.0.0 · Android 6.0+\n本地 / 在线 / WebDAV / SMB / Jellyfin\n支持 DLNA 与 Google Cast;接收端需支持对应媒体格式。") } } - private fun cacheBytes() = runCatching { Media3FileCache.bytes() }.getOrDefault(0) - private fun urlDialog() { - val form = Ui.column(this, 20) - val url = EditText(this).apply { hint = "视频地址或直播链接"; isSaveEnabled = false; inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI; setSingleLine(true) } - form.addView(url) + + @Composable + private fun MediaCard(item: RecentMedia) { + val position = if (item.positionMs > 0) "已看 ${formatTime(item.positionMs)}" else "从头播放" + val source = item.ref.accountId?.let { id -> accountsState.value.firstOrNull { it.id == id }?.name } + ?: if (item.ref.uri?.startsWith("content:") == true) "本地文件" else "在线视频" + AppCard( + title = (if (item.favorite) "★ " else "") + item.ref.title, + subtitle = "$source · $position", + onClick = { lifecycleScope.launch { openMedia(item.ref) } }, + ) { + if (item.durationMs != null && item.durationMs > 0) { + val fraction = (item.positionMs.toFloat() / item.durationMs).coerceIn(0f, 1f) + LinearProgressIndicator( + progress = { fraction }, + modifier = Modifier.fillMaxWidth().padding(top = 12.dp).height(4.dp), + color = AppAccent, + trackColor = AppRaised, + ) + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = { dialogState.value = HomeDialog.MediaMenu(item) }) { Text("更多", color = AppAccent) } + } + } + } + + @Composable + private fun SourceCard(account: LibraryAccount) { + val host = runCatching { URI(account.endpoint).host }.getOrNull().orEmpty() + AppCard( + title = account.name, + subtitle = "${account.kind} · $host", + onClick = { startActivity(Intent(this@HomeActivity, BrowserActivity::class.java).putExtra("account", account.id)) }, + ) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) { + TextButton(onClick = { dialogState.value = HomeDialog.SourceMenu(account) }) { Text("管理来源", color = AppAccent) } + } + } + } + + @Composable + private fun HomeDialogs() { + when (val dialog = dialogState.value) { + is HomeDialog.SourceEditor -> SourceEditorDialog( + repo = repo, + existing = dialog.account, + onDismiss = { dialogState.value = null }, + onSaved = { dialogState.value = null; refresh() }, + ) + is HomeDialog.SourceMenu -> ChoiceDialog( + title = dialog.account.name, + options = listOf("编辑连接", "删除来源"), + onDismiss = { dialogState.value = null }, + onSelect = { index -> + dialogState.value = if (index == 0) HomeDialog.SourceEditor(dialog.account) else HomeDialog.DeleteSource(dialog.account) + }, + ) + is HomeDialog.DeleteSource -> ConfirmDialog( + title = "删除来源", + message = "删除连接配置?服务器上的文件不会被修改。", + confirmText = "删除", + onConfirm = { dialogState.value = null; deleteAccount(dialog.account) }, + onDismiss = { dialogState.value = null }, + ) + is HomeDialog.MediaMenu -> ChoiceDialog( + title = dialog.item.ref.title, + options = listOf(if (dialog.item.favorite) "取消收藏" else "加入收藏", "从头播放", "移除记录"), + onDismiss = { dialogState.value = null }, + onSelect = { index -> + dialogState.value = null + when (index) { + 0 -> updateFavorite(dialog.item) + 1 -> restart(dialog.item) + else -> removeHistory(dialog.item) + } + }, + ) + HomeDialog.DlnaMenu -> ChoiceDialog( + title = "电视投屏", + options = listOf("播放", "暂停", "结束投屏", "结束并在本机继续"), + onDismiss = { dialogState.value = null }, + onSelect = { index -> + dialogState.value = null + if (index == 3) continueAfterDlna() else DlnaSession.command(this, listOf("play", "pause", "stop")[index]) + }, + ) + HomeDialog.ClearHistory -> ConfirmDialog( + title = "清空历史", + message = "清空本机记录?媒体来源和远端文件会保留。", + confirmText = "清空", + onConfirm = { dialogState.value = null; clearHistory() }, + onDismiss = { dialogState.value = null }, + ) + HomeDialog.ClearCache -> ConfirmDialog( + title = "清理媒体缓存", + message = "确认清理已缓存的媒体片段?投屏或播放进行中时请先停止播放。", + confirmText = "清理", + onConfirm = { dialogState.value = null; clearCache() }, + onDismiss = { dialogState.value = null }, + ) + HomeDialog.Decode -> ChoiceDialog( + title = "默认解码方式", + options = listOf("自动选择", "优先硬件解码", "仅硬件解码", "仅系统软件解码"), + onDismiss = { dialogState.value = null }, + onSelect = { index -> + dialogState.value = null + repo.preferences.decoder = DecodeMode.entries[index] + decoderState.value = DecodeMode.entries[index] + }, + ) + HomeDialog.Url -> UrlDialog() + null -> Unit + } + } + + @Composable + private fun UrlDialog() { + var url by rememberSaveable { mutableStateOf("") } + var headers by rememberSaveable { mutableStateOf("") } + var typeIndex by rememberSaveable { mutableIntStateOf(0) } + var tcp by rememberSaveable { mutableStateOf(false) } + var error by remember { mutableStateOf("") } + var typeMenu by remember { mutableStateOf(false) } val types = MediaSourceType.entries - val selector = Spinner(this).apply { adapter = ArrayAdapter(this@HomeActivity, android.R.layout.simple_spinner_dropdown_item, types.map { it.name }) } - form.addView(selector) - val headers = EditText(this).apply { hint = "请求头(选填,每行 Name: value)"; minLines = 2; isSaveEnabled = false; inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE } - form.addView(headers) - val tcp = CheckBox(this).apply { text = "RTSP 使用 TCP" }; form.addView(tcp) - val error = Ui.label(this, "", 13f, Ui.muted); form.addView(error) - val dialog = AlertDialog.Builder(this).setTitle("播放网络链接").setView(ScrollView(this).apply { addView(form) }).setPositiveButton("播放", null).setNegativeButton("取消", null).create() - dialog.setOnShowListener { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { - val parsed = runCatching { - val address = url.text.toString().trim() - require(java.net.URI(address).isAbsolute) { "请输入完整播放地址" } - MediaRef(android.net.Uri.parse(address).lastPathSegment?.takeIf(String::isNotBlank) ?: "在线视频", uri = address, - headers = HttpHeaders.parseLines(headers.text.toString()), sourceType = types[selector.selectedItemPosition], - network = NetworkOptions(rtspTransport = if (tcp.isChecked) RtspTransport.TCP else RtspTransport.AUTO)) - } - parsed.onSuccess { ref -> dialog.dismiss(); lifecycleScope.launch { open(ref) } }.onFailure { error.text = "地址或请求头格式不正确" } - } } - dialog.show() - } - private suspend fun open(ref: MediaRef) { - try { - withContext(Dispatchers.IO) { val old = repo.recent.find(ref.id); repo.recent.save(ref, old?.positionMs ?: 0, old?.durationMs) } - startActivity(Intent(this, PlayerActivity::class.java).putExtra("media", ref.id)) - } catch (_: Exception) { Toast.makeText(this, "无法保存播放记录,请检查设备安全存储", Toast.LENGTH_LONG).show() } + AlertDialog( + onDismissRequest = { dialogState.value = null }, + title = { Text("播放网络链接", color = AppInk) }, + text = { + Column( + Modifier.heightIn(max = 460.dp).verticalScroll(rememberScrollState()).imePadding(), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + AppTextField("视频地址或直播链接", url, { url = it }, placeholder = "https://… / rtsp://…", keyboardType = androidx.compose.ui.text.input.KeyboardType.Uri) + Box { + TextButton(onClick = { typeMenu = true }) { Text("协议:${types[typeIndex].name}", color = AppAccent) } + DropdownMenu(expanded = typeMenu, onDismissRequest = { typeMenu = false }) { + types.forEachIndexed { index, type -> + DropdownMenuItem(text = { Text(type.name, color = AppInk) }, onClick = { typeIndex = index; typeMenu = false }) + } + } + } + AppTextField("请求头(选填,每行 Name: value)", headers, { headers = it }, singleLine = false, minLines = 2) + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox(checked = tcp, onCheckedChange = { tcp = it }, colors = CheckboxDefaults.colors(checkedColor = AppAccent)) + Text("RTSP 使用 TCP", color = AppInk) + } + if (error.isNotBlank()) Text(error, color = AppError, style = MaterialTheme.typography.labelSmall) + } + }, + confirmButton = { + TextButton(onClick = { + val parsed = runCatching { + val address = url.trim() + require(URI(address).isAbsolute) { "请输入完整播放地址" } + MediaRef( + Uri.parse(address).lastPathSegment?.takeIf(String::isNotBlank) ?: "在线视频", + uri = address, + headers = HttpHeaders.parseLines(headers), + sourceType = types[typeIndex], + network = NetworkOptions(rtspTransport = if (tcp) RtspTransport.TCP else RtspTransport.AUTO), + ) + } + parsed.onSuccess { ref -> + dialogState.value = null + lifecycleScope.launch { openMedia(ref) } + }.onFailure { error = "地址或请求头格式不正确" } + }) { Text("播放", color = AppAccent) } + }, + dismissButton = { TextButton(onClick = { dialogState.value = null }) { Text("取消", color = AppMuted) } }, + containerColor = AppPanel, + ) } } +private sealed interface HomeDialog { + data class SourceEditor(val account: LibraryAccount?) : HomeDialog + data class SourceMenu(val account: LibraryAccount) : HomeDialog + data class DeleteSource(val account: LibraryAccount) : HomeDialog + data class MediaMenu(val item: RecentMedia) : HomeDialog + data object DlnaMenu : HomeDialog + data object ClearHistory : HomeDialog + data object ClearCache : HomeDialog + data object Decode : HomeDialog + data object Url : HomeDialog +} + /** 播放队列只存来源身份;进程重建后至少恢复当前历史条目。 */ object PlaybackQueue { var refs: List = emptyList(); private set diff --git a/app/src/main/kotlin/com/ttstd/player/app/LocalLibraryActivity.kt b/app/src/main/kotlin/com/ttstd/player/app/LocalLibraryActivity.kt index b1c3f31..e3d0bc9 100644 --- a/app/src/main/kotlin/com/ttstd/player/app/LocalLibraryActivity.kt +++ b/app/src/main/kotlin/com/ttstd/player/app/LocalLibraryActivity.kt @@ -1,111 +1,77 @@ package com.ttstd.player.app -import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.MediaStore -import android.view.Gravity -import android.view.View -import android.view.ViewGroup -import android.widget.* +import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp import androidx.lifecycle.lifecycleScope -import com.ttstd.player.app.Ui.dp import kotlinx.coroutines.* import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit class LocalLibraryActivity : AppCompatActivity() { - private lateinit var content: LinearLayout private lateinit var store: LocalMediaStore - private var videos: List = emptyList() + private val videos = mutableStateOf>(emptyList()) + private val loading = mutableStateOf(false) + private val permissionGranted = mutableStateOf(false) private var reloadJob: Job? = null - private var generation = 0 - private val thumbGate = Semaphore(4) private val permission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> - if (granted) reload() else render() + permissionGranted.value = granted + if (granted) reload() else loading.value = false } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) store = LocalMediaStore(applicationContext) - build() - // 缓存解析与 MediaStore 扫描都放到 IO,避免首帧在主线程读大 JSON。 - if (LocalMediaStore.hasPermission(this)) reload() - else permission.launch(LocalMediaStore.requiredPermission()) - } - - private fun build() { - val root = Ui.column(this) - Ui.inset(this, root) - val toolbar = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL; setPadding(dp(12), dp(8), dp(12), dp(8)); setBackgroundColor(0xd9111822.toInt()) } - toolbar.addView(Ui.button(this, "‹") { finish() }) - toolbar.addView(Ui.label(this, "本地视频", 16f, bold = true).apply { layoutParams = LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(12) } }) - toolbar.addView(Ui.button(this, "刷新") { reload() }) - root.addView(toolbar) - content = Ui.column(this) - root.addView(content, LinearLayout.LayoutParams(-1, 0, 1f)) - setContentView(root) + permissionGranted.value = LocalMediaStore.hasPermission(this) + setContent { TTVideoTheme { LocalLibraryRoot() } } + if (permissionGranted.value) reload() else permission.launch(LocalMediaStore.requiredPermission()) } private fun reload() { - if (!LocalMediaStore.hasPermission(this)) { render(); return } + permissionGranted.value = LocalMediaStore.hasPermission(this) + if (!permissionGranted.value) { + loading.value = false + return + } reloadJob?.cancel() - content.removeAllViews() - content.addView(Ui.label(this, "正在扫描设备与 U 盘…", 14f, Ui.muted).apply { setPadding(0, dp(16), 0, 0) }) + loading.value = true reloadJob = lifecycleScope.launch(Dispatchers.IO) { - // 先展示上次缓存,缩短首屏等待;扫描仍在后台继续。 val cached = store.cached() - if (cached.isNotEmpty()) withContext(Dispatchers.Main) { videos = cached; render() } + if (cached.isNotEmpty()) withContext(Dispatchers.Main) { + videos.value = cached + loading.value = false + } val list = store.refresh() - withContext(Dispatchers.Main) { videos = list; render() } - } - } - - private fun render() { - content.removeAllViews() - generation++ - if (!LocalMediaStore.hasPermission(this)) { - content.addView(Ui.empty(this, "需要存储权限", "允许访问视频后才能发现本机与 U 盘中的影片。"), LinearLayout.LayoutParams(-1, 0, 1f)) - content.addView(Ui.button(this, "授予权限", true) { permission.launch(LocalMediaStore.requiredPermission()) }) - return - } - if (videos.isEmpty()) { - content.addView(Ui.empty(this, "还没有视频", "把影片放入设备或 U 盘,然后点右上角刷新。"), LinearLayout.LayoutParams(-1, 0, 1f)) - return - } - content.addView(Ui.label(this, "共 ${videos.size} 部影片", 13f, Ui.muted).apply { setPadding(0, dp(4), 0, dp(12)) }) - // GridView 只创建可见行,避免一次性为几百个视频建卡;缩略图在 bind 时按需加载。 - val columns = if (resources.configuration.screenWidthDp >= 720) 5 else 3 - val grid = GridView(this).apply { - numColumns = columns - horizontalSpacing = dp(10) - verticalSpacing = dp(12) - stretchMode = GridView.STRETCH_COLUMN_WIDTH - clipToPadding = false - setPadding(0, 0, 0, dp(12)) - adapter = VideoAdapter() - } - content.addView(grid, LinearLayout.LayoutParams(-1, 0, 1f)) - } - - private fun bind(card: VideoCard, item: LocalVideo) { - card.tag = item.uri - card.title.text = item.title - card.duration.text = Ui.time(item.durationMs) - card.thumbJob?.cancel() - card.thumb.setImageDrawable(null) - card.setOnClickListener { open(item) } - val current = generation - card.thumbJob = lifecycleScope.launch(Dispatchers.IO) { - // 全程最多 4 张缩略图同时解码,低端机不会因为滚动或整库刷新而爆内存。 - val bitmap = thumbGate.withPermit { runCatching { loadThumbnail(item) }.getOrNull() } ?: return@launch withContext(Dispatchers.Main) { - if (current == generation && card.tag == item.uri) card.thumb.setImageBitmap(bitmap) + videos.value = list + loading.value = false } } } @@ -119,41 +85,92 @@ class LocalLibraryActivity : AppCompatActivity() { } } - private inner class VideoAdapter : BaseAdapter() { - override fun getCount() = videos.size - override fun getItem(position: Int): Any = videos[position] - override fun getItemId(position: Int) = position.toLong() - override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { - val card = (convertView as? VideoCard) ?: VideoCard(this@LocalLibraryActivity) - bind(card, videos[position]) - return card + @Composable + private fun LocalLibraryRoot() { + val list = videos.value + val granted = permissionGranted.value + val isLoading = loading.value + val gate = remember { Semaphore(4) } + Column(Modifier.fillMaxSize().background(AppBg).windowInsetsPadding(WindowInsets.systemBars)) { + TopBar("本地视频", onBack = { finish() }, actions = { + TextButton(onClick = { reload() }) { Text("刷新", color = AppAccent) } + }) + if (!granted) { + EmptyState("需要存储权限", "允许访问视频后才能发现本机与 U 盘中的影片。") { + PrimaryButton("授予权限") { permission.launch(LocalMediaStore.requiredPermission()) } + } + return@Column + } + if (list.isEmpty()) { + if (isLoading) { + Box(Modifier.fillMaxSize(), contentAlignment = androidx.compose.ui.Alignment.Center) { + Text("正在扫描设备与 U 盘…", color = AppMuted) + } + } else { + EmptyState("还没有视频", "把影片放入设备或 U 盘,然后点右上角刷新。") + } + return@Column + } + Text( + "共 ${list.size} 部影片", + style = MaterialTheme.typography.labelSmall, + color = AppMuted, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), + ) + if (isLoading) LinearProgressIndicator(modifier = Modifier.fillMaxWidth(), color = AppAccent, trackColor = AppPanel) + val columns = if (LocalConfiguration.current.screenWidthDp >= 720) 5 else 3 + LazyVerticalGrid( + columns = GridCells.Fixed(columns), + modifier = Modifier.weight(1f), + contentPadding = PaddingValues(start = 8.dp, end = 8.dp, top = 4.dp, bottom = 12.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + items(list, key = { it.uri }) { item -> LocalVideoCard(item, gate) } + } } } - private inner class VideoCard(context: Context) : LinearLayout(context) { - val thumb = ImageView(context).apply { - layoutParams = LinearLayout.LayoutParams(-1, dp(96)) - scaleType = ImageView.ScaleType.CENTER_CROP - setBackgroundColor(0xFF1E2935.toInt()) + @Composable + private fun LocalVideoCard(item: LocalVideo, gate: Semaphore) { + val thumb by produceState(initialValue = null, item.uri) { + value = withContext(Dispatchers.IO) { + gate.withPermit { runCatching { loadThumbnail(item) }.getOrNull() } + } } - val title = Ui.label(context, "", 13f).apply { - maxLines = 2 - ellipsize = android.text.TextUtils.TruncateAt.END - layoutParams = LinearLayout.LayoutParams(-1, -2).apply { topMargin = dp(4) } - } - val duration = Ui.label(context, "", 11f, Ui.muted) - var thumbJob: Job? = null - - init { - orientation = VERTICAL - gravity = Gravity.CENTER_HORIZONTAL - background = Ui.shape(Ui.panel, dp(12).toFloat()) - setPadding(dp(8), dp(8), dp(8), dp(6)) - addView(thumb) - addView(title) - addView(duration) - isFocusable = true - isClickable = true + Column( + Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background(AppPanel) + .clickable { open(item) } + .padding(8.dp), + ) { + Box( + Modifier + .fillMaxWidth() + .aspectRatio(16f / 10f) + .clip(RoundedCornerShape(8.dp)) + .background(androidx.compose.ui.graphics.Color(0xFF1E2935)), + ) { + thumb?.let { + Image( + bitmap = it.asImageBitmap(), + contentDescription = item.title, + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxSize(), + ) + } + } + Text( + item.title, + style = MaterialTheme.typography.bodyMedium, + color = AppInk, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(top = 6.dp), + ) + Text(formatTime(item.durationMs), fontSize = 11.sp, color = AppMuted) } } @@ -161,7 +178,7 @@ class LocalLibraryActivity : AppCompatActivity() { val uri = Uri.parse(item.uri) return runCatching { if (Build.VERSION.SDK_INT >= 29) { - contentResolver.loadThumbnail(uri, android.util.Size(dp(160), dp(96)), null) + contentResolver.loadThumbnail(uri, android.util.Size(320, 192), null) } else { val id = uri.lastPathSegment?.toLongOrNull() ?: return@runCatching null MediaStore.Video.Thumbnails.getThumbnail(contentResolver, id, MediaStore.Video.Thumbnails.MINI_KIND, null) diff --git a/app/src/main/kotlin/com/ttstd/player/app/PlayerActivity.kt b/app/src/main/kotlin/com/ttstd/player/app/PlayerActivity.kt index 6498a74..a0ecdf1 100644 --- a/app/src/main/kotlin/com/ttstd/player/app/PlayerActivity.kt +++ b/app/src/main/kotlin/com/ttstd/player/app/PlayerActivity.kt @@ -1,358 +1,691 @@ package com.ttstd.player.app -import android.app.AlertDialog +import android.app.PictureInPictureParams import android.content.Intent import android.content.pm.ActivityInfo import android.content.res.Configuration +import android.graphics.Rect import android.os.Build import android.os.Bundle import android.provider.OpenableColumns -import android.view.* -import android.widget.* +import android.util.Rational +import android.view.SurfaceView +import android.view.TextureView +import android.view.View +import android.view.WindowManager +import android.widget.Toast +import androidx.activity.compose.setContent import androidx.activity.result.contract.ActivityResultContracts +import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clipToBounds +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.boundsInWindow +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat import androidx.core.view.WindowInsetsControllerCompat -import androidx.lifecycle.* +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import com.ttstd.player.android.AndroidVideoOutput import com.ttstd.player.api.* +import com.ttstd.player.cast.dlna.DlnaDevice import com.ttstd.player.library.LibraryFiles -import com.ttstd.player.render.* +import com.ttstd.player.render.SurfaceViewBinding +import com.ttstd.player.render.TextureViewBinding import kotlinx.coroutines.launch -import com.ttstd.player.app.Ui.dp +import kotlin.math.roundToInt /** 播放界面只拥有 Surface 与控件;内核/观看会话由 PlayerModel 管理。 */ class PlayerActivity : AppCompatActivity() { private lateinit var model: PlayerModel private val repo by lazy { AppRepository(applicationContext) } - private var surfaceBinding: AutoCloseable? = null - private lateinit var video: FrameLayout - private lateinit var toolbar: LinearLayout - private lateinit var controls: LinearLayout - private var controlScroll: ScrollView? = null - private var pipMode = false - private var lastAutoEnter: Boolean? = null - private lateinit var subtitle: TextView - private lateinit var center: TextView - private lateinit var title: TextView - private lateinit var playButton: TextView - private lateinit var time: TextView - private lateinit var seek: SeekBar - private lateinit var information: TextView - private var dragging = false - private var crop = false - private var keepScreenOn = false - private val bufferingPhases = setOf(PlaybackPhase.PREPARING, PlaybackPhase.BUFFERING) + private val pipState = mutableStateOf(false) + private var lastVideoRect: Rect? = null private val google = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { - model.googleReturned(it.data?.getLongExtra("position", model.engine.state.value.positionMs) ?: model.engine.state.value.positionMs, - it.data?.getBooleanExtra("playing", true) ?: true) + model.googleReturned( + it.data?.getLongExtra("position", model.engine.state.value.positionMs) ?: model.engine.state.value.positionMs, + it.data?.getBooleanExtra("playing", true) ?: true, + ) } private val pickSubtitle = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> if (uri != null) { runCatching { contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } - val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use { if (it.moveToFirst()) it.getString(0) else "" }.orEmpty() + val name = contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null) + ?.use { if (it.moveToFirst()) it.getString(0) else "" }.orEmpty() val mime = LibraryFiles.subtitleMime(name) if (mime == null) Toast.makeText(this, "请选择 SRT、VTT、ASS 或 SSA 字幕", Toast.LENGTH_LONG).show() else model.attachSubtitle(ExternalSubtitle(uri.toString(), mime, isDefault = true)) } } + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) volumeControlStream = android.media.AudioManager.STREAM_MUSIC - model = ViewModelProvider(this)[PlayerModel::class.java] - build() - lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { - launch { model.engine.state.collect { render() } } - launch { model.current.collect { item -> - item?.let { intent.putExtra("media", it.ref.id) } - render() - } } - launch { model.loading.collect { render() } } - launch { model.error.collect { render() } } - launch { model.remote.collect { render() } } - launch { model.notices.collect { Toast.makeText(this@PlayerActivity, it, Toast.LENGTH_LONG).show() } } - launch { model.videoRatio.collect { fitVideo(); updatePipParams() } } - launch { DlnaSession.state.collect { render() } } - } } + WindowCompat.setDecorFitsSystemWindows(window, false) + model = androidx.lifecycle.ViewModelProvider(this)[PlayerModel::class.java] + setContent { TTVideoTheme { PlayerRoot() } } + lifecycleScope.launch { + model.notices.collect { Toast.makeText(this@PlayerActivity, it, Toast.LENGTH_LONG).show() } + } model.open(intent.getStringExtra("media").orEmpty()) } - private fun build() { - pipMode = false - surfaceBinding?.close() - val landscape = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE - val root = FrameLayout(this) - Ui.inset(this, root) - val stack = Ui.column(this) - root.addView(stack, FrameLayout.LayoutParams(-1, -1)) - val toolbar = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL; setPadding(dp(12), dp(8), dp(12), dp(8)); setBackgroundColor(0xd9111822.toInt()) } - toolbar.addView(Ui.button(this, "‹") { finish() }) - title = Ui.label(this, "正在准备视频", 16f, bold = true).apply { maxLines = 2; ellipsize = android.text.TextUtils.TruncateAt.END } - toolbar.addView(title, LinearLayout.LayoutParams(0, -2, 1f).apply { marginStart = dp(12); marginEnd = dp(12) }) - toolbar.addView(Ui.button(this, "投屏") { castDialog() }) - toolbar.addView(Ui.button(this, "⋮") { menu() }) - this.toolbar = toolbar - video = FrameLayout(this).apply { setBackgroundColor(android.graphics.Color.BLACK); clipChildren = true } - subtitle = Ui.label(this, "", 20f).apply { - gravity = Gravity.CENTER; setPadding(dp(20), dp(4), dp(20), dp(16)) - setShadowLayer(dp(2).toFloat(), 0f, 1f, android.graphics.Color.BLACK) - isClickable = false - } - center = Ui.label(this, "", 16f).apply { gravity = Gravity.CENTER; setBackgroundColor(0x77101822) } - val surface: View = if (repo.preferences.texture) TextureView(this) else SurfaceView(this) - video.addView(surface, FrameLayout.LayoutParams(-1, -1, Gravity.CENTER)) - video.addView(subtitle, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM)) - video.addView(center, FrameLayout.LayoutParams(-1, -1)) - val controls = Ui.column(this, 16).apply { setBackgroundColor(0xee101822.toInt()) } - this.controls = controls - time = Ui.label(this, "0:00 / --:--", 13f, Ui.muted) - controls.addView(time) - seek = SeekBar(this).apply { max = 1000 } - controls.addView(seek, LinearLayout.LayoutParams(-1, dp(44))) - seek.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { - override fun onStartTrackingTouch(seekBar: SeekBar) { dragging = true } - override fun onProgressChanged(seekBar: SeekBar, value: Int, fromUser: Boolean) = Unit - override fun onStopTrackingTouch(seekBar: SeekBar) { - dragging = false - val duration = currentDuration() ?: return - val target = duration * seekBar.progress / 1000 - if (model.remote.value == "dlna") startService(Intent(this@PlayerActivity, DlnaPlaybackService::class.java).setAction("seek").putExtra("position", target)) - else model.seek(target) - } - }) - val buttons = LinearLayout(this).apply { gravity = Gravity.CENTER } - fun control(label: String, primary: Boolean = false, action: () -> Unit): TextView = Ui.button(this, label, primary, action).also { - buttons.addView(it, LinearLayout.LayoutParams(0, dp(52), 1f).apply { marginStart = dp(3); marginEnd = dp(3) }) - } - control("上一部") { model.next(-1) } - control("−10s") { seekBy(-10000) } - playButton = control("播放", true) { - if (model.remote.value == "dlna") DlnaSession.command(this, if (DlnaSession.state.value.playback.playing) "pause" else "play") else model.toggle() - } - control("+10s") { seekBy(10000) } - control("下一部") { model.next(1) } - controls.addView(buttons) - information = Ui.label(this, "", 13f, Ui.muted).apply { setPadding(0, dp(14), 0, dp(8)) } - controls.addView(information) - controls.addView(Ui.button(this, if (landscape) "退出全屏" else "全屏播放") { - requestedOrientation = if (landscape) ActivityInfo.SCREEN_ORIENTATION_PORTRAIT else ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE - }) - if (landscape) { - root.removeView(stack) - root.addView(video, FrameLayout.LayoutParams(-1, -1)) - root.addView(toolbar, FrameLayout.LayoutParams(-1, -2, Gravity.TOP)) - root.addView(controls, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM)) - subtitle.setPadding(dp(24), dp(4), dp(24), dp(240)) - controlScroll = null - } else { - stack.addView(toolbar) - stack.addView(video, LinearLayout.LayoutParams(-1, (resources.displayMetrics.widthPixels * 9 / 16).coerceAtLeast(dp(180)))) - val scroll = ScrollView(this).apply { addView(controls) } - stack.addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f)) - controlScroll = scroll - } - val gesture = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() { - override fun onDown(e: android.view.MotionEvent) = true - override fun onDoubleTap(e: android.view.MotionEvent): Boolean { - if (model.remote.value == null) model.seek((model.absolutePosition() + if (e.x < video.width / 2) -10000 else 10000).coerceAtLeast(0)) - return true - } - override fun onSingleTapConfirmed(e: android.view.MotionEvent): Boolean { - if (landscape) { toolbar.visibility = if (toolbar.visibility == View.VISIBLE) View.GONE else View.VISIBLE; controls.visibility = toolbar.visibility } - return true - } - }) - video.setOnTouchListener { _, event -> gesture.onTouchEvent(event) } - center.setOnClickListener { if (model.error.value != null || model.engine.state.value.phase == PlaybackPhase.ERROR) model.retry() } - setContentView(root) - WindowInsetsControllerCompat(window, root).apply { if (landscape) hide(WindowInsetsCompat.Type.systemBars()) else show(WindowInsetsCompat.Type.systemBars()) } - video.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> fitVideo() } - surfaceBinding = if (surface is TextureView) TextureViewBinding(surface, model.engine) else SurfaceViewBinding(surface as SurfaceView, model.engine) - render() - } - private fun currentDuration(): Long? = if (model.remote.value == "dlna") DlnaSession.state.value.playback.durationMs else model.duration() - /** 播放中每秒都会 render;文本未变化时不触发 TextView 重排。 */ - private fun TextView.setTextIfChanged(value: String) { - if (text?.toString() != value) text = value - } - private fun render() { - if (!::center.isInitialized) return - val state = model.engine.state.value - val remote = model.remote.value - val error = model.error.value ?: state.error?.message - title.setTextIfChanged(model.current.value?.ref?.title ?: "正在准备视频") - val pos = if (remote == "dlna") DlnaSession.state.value.playback.positionMs else model.absolutePosition() - val duration = currentDuration() - time.setTextIfChanged("${Ui.time(pos)} / ${duration?.let(Ui::time) ?: "--:--"}") - if (!dragging && duration != null && duration > 0) seek.progress = (pos * 1000 / duration).coerceIn(0, 1000).toInt() - seek.isEnabled = duration != null && duration > 0 - val playing = if (remote == "dlna") DlnaSession.state.value.playback.playing else state.playWhenReady - playButton.setTextIfChanged(if (playing) "暂停" else "播放") - subtitle.setTextIfChanged(if (remote == null) state.subtitleLines.joinToString("\n") else "") + + @Composable + private fun PlayerRoot() { + val state by model.engine.state.collectAsStateWithLifecycle() + val current by model.current.collectAsStateWithLifecycle() + val loading by model.loading.collectAsStateWithLifecycle() + val modelError by model.error.collectAsStateWithLifecycle() + val error = modelError ?: state.error?.message + val remote by model.remote.collectAsStateWithLifecycle() + val ratio by model.videoRatio.collectAsStateWithLifecycle() + val dlna by DlnaSession.state.collectAsStateWithLifecycle() + val pip = pipState.value + val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE + var crop by rememberSaveable { mutableStateOf(false) } + var texture by remember { mutableStateOf(repo.preferences.texture) } + var controlsVisible by remember { mutableStateOf(true) } + var dialog by remember { mutableStateOf(null) } + var devices by remember { mutableStateOf?>(null) } + var castBusy by remember { mutableStateOf(false) } + var castError by remember { mutableStateOf(null) } + val scope = rememberCoroutineScope() + + val position = if (remote == "dlna") dlna.playback.positionMs else model.absolutePosition() + val duration = if (remote == "dlna") dlna.playback.durationMs else model.duration() + val playing = if (remote == "dlna") dlna.playback.playing else state.playWhenReady + val subtitleText = if (remote == null) state.subtitleLines.joinToString("\n") else "" val centerText = when { - remote == "dlna" -> "正在 ${DlnaSession.state.value.device} 播放\n${DlnaSession.state.value.error ?: "可关闭页面,投屏会继续"}" - model.loading.value || state.phase in bufferingPhases -> "正在缓冲…" + remote == "dlna" -> "正在 ${dlna.device} 播放\n${dlna.error ?: "可关闭页面,投屏会继续"}" + loading || state.phase == PlaybackPhase.PREPARING || state.phase == PlaybackPhase.BUFFERING -> "正在缓冲…" error != null -> "$error\n点击重试" state.phase == PlaybackPhase.ENDED -> "播放结束" - else -> "" + else -> null } - center.setTextIfChanged(centerText) - center.visibility = if (centerText.isEmpty()) View.GONE else View.VISIBLE - information.setTextIfChanged(if (remote != null) "投屏中 · 点击右上角投屏管理连接" else "${if (model.current.value?.ref?.accountId != null) "媒体来源播放" else "本机 / 在线播放"} · 双击画面快进 / 后退\n音轨、字幕、倍速与显示选项在更多菜单中") - val keepOn = state.isPlaying && remote == null - if (keepOn != keepScreenOn) { - keepScreenOn = keepOn - if (keepOn) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + val showControls = !pip && (!landscape || controlsVisible) + + LaunchedEffect(state.isPlaying, remote) { + if (state.isPlaying && remote == null) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + else window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } - val autoEnter = Build.VERSION.SDK_INT >= 31 && state.playWhenReady && remote == null - if (autoEnter != lastAutoEnter) { - lastAutoEnter = autoEnter - updatePipParams() + DisposableEffect(Unit) { + onDispose { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } } - } - private fun seekBy(delta: Long) { - if (model.remote.value == "dlna") startService(Intent(this, DlnaPlaybackService::class.java).setAction("seek") - .putExtra("position", (DlnaSession.state.value.playback.positionMs + delta).coerceAtLeast(0))) - else model.seek((model.absolutePosition() + delta).coerceAtLeast(0)) - } - private fun fitVideo() { - if (!::video.isInitialized) return - val child = video.getChildAt(0) ?: return - val ratio = model.videoRatio.value - if (video.width <= 0 || video.height <= 0 || ratio <= 0) return - val width = if (crop) maxOf(video.width, (video.height * ratio).toInt()) else minOf(video.width, (video.height * ratio).toInt()) - val height = if (crop) maxOf(video.height, (video.width / ratio).toInt()) else minOf(video.height, (video.width / ratio).toInt()) - if (child.layoutParams.width != width || child.layoutParams.height != height) child.layoutParams = FrameLayout.LayoutParams(width, height, Gravity.CENTER) - } - private fun menu() { - if (model.remote.value == "dlna") { castDialog(); return } - val labels = arrayOf("音轨", "字幕", "加载外挂字幕", "播放速度", "显示比例:${if (crop) "填充" else "适应"}", "收藏 / 取消收藏", "视频显示方式", "解码方式") - AlertDialog.Builder(this).setTitle("播放选项").setItems(labels) { _, index -> when (index) { - 0 -> tracks(TrackType.AUDIO) - 1 -> tracks(TrackType.TEXT) - 2 -> pickSubtitle.launch(arrayOf("*/*")) - 3 -> AlertDialog.Builder(this).setTitle("播放速度").setItems(arrayOf("0.5×", "0.75×", "1×", "1.25×", "1.5×", "2×")) { _, i -> model.setSpeed(listOf(.5f, .75f, 1f, 1.25f, 1.5f, 2f)[i]) }.show() - 4 -> { crop = !crop; fitVideo() } - 5 -> { model.favorite(); Toast.makeText(this, "收藏已更新", Toast.LENGTH_SHORT).show() } - 6 -> { repo.preferences.texture = !repo.preferences.texture; build() } - 7 -> AlertDialog.Builder(this).setTitle("解码方式").setItems(arrayOf("自动选择", "优先硬解", "仅硬解", "仅系统软解")) { _, i -> model.setDecoder(DecodeMode.entries[i]) }.show() - } }.show() - } - private fun tracks(type: TrackType) { - val list = model.engine.state.value.tracks.filter { it.type == type } - val options = if (type == TrackType.TEXT) listOf("关闭字幕") else listOf("自动选择") - AlertDialog.Builder(this).setTitle(if (type == TrackType.TEXT) "字幕" else "音轨") - .setItems((options + list.map { "${it.label ?: it.language ?: "轨道 ${it.id}"}${if (it.selected) " ✓" else ""}" }).toTypedArray()) { _, index -> - model.selectTrack(if (index == 0) TrackSelection(type, disabled = type == TrackType.TEXT) else TrackSelection(type, list[index - 1].id)) - }.show() - } - private fun castDialog() { - if (model.remote.value == "dlna") { - AlertDialog.Builder(this).setTitle(DlnaSession.state.value.device).setItems(arrayOf("播放", "暂停", "后退 30 秒", "前进 30 秒", "结束投屏并返回本机")) { _, index -> - DlnaSession.command(this, listOf("play", "pause", "back", "forward", "stop")[index]) - }.show(); return + LaunchedEffect(landscape, pip) { + val controller = WindowInsetsControllerCompat(window, window.decorView) + if (landscape || pip) controller.hide(WindowInsetsCompat.Type.systemBars()) + else controller.show(WindowInsetsCompat.Type.systemBars()) } - AlertDialog.Builder(this).setTitle("投屏到设备").setItems(arrayOf("DLNA · 电视 / 盒子", "Google Cast")) { _, index -> - lifecycleScope.launch { - if (index == 1) model.googleIntent()?.let(google::launch) else { - val progress = AlertDialog.Builder(this@PlayerActivity).setMessage("正在搜索同一局域网的电视…").create(); progress.show() - try { - val devices = model.devices(); progress.dismiss() - if (devices.isEmpty()) Toast.makeText(this@PlayerActivity, "未发现设备,请确认电视投屏已开启", Toast.LENGTH_LONG).show() - else AlertDialog.Builder(this@PlayerActivity).setTitle("选择电视").setItems(devices.map { it.name }.toTypedArray()) { _, i -> model.dlna(devices[i]) }.show() - } catch (cancelled: kotlinx.coroutines.CancellationException) { progress.dismiss(); throw cancelled } - catch (_: Exception) { progress.dismiss(); Toast.makeText(this@PlayerActivity, "设备搜索失败,请检查网络", Toast.LENGTH_LONG).show() } + LaunchedEffect(state.playWhenReady, ratio, remote) { updatePipParams() } + LaunchedEffect(pip) { if (pip) controlsVisible = false else controlsVisible = true } + + Box( + Modifier + .fillMaxSize() + .background(AppBg) + .then(if (!landscape && !pip) Modifier.windowInsetsPadding(WindowInsets.systemBars) else Modifier) + ) { + if (landscape || pip) { + VideoPane( + modifier = Modifier.fillMaxSize(), + engine = model.engine, + texture = texture, + crop = crop, + ratio = ratio, + subtitle = subtitleText, + centerText = centerText, + canRetry = error != null || state.phase == PlaybackPhase.ERROR, + onRetry = { model.retry() }, + pip = pip, + onTap = { if (!pip && landscape) controlsVisible = !controlsVisible }, + onDoubleTap = { left -> if (remote == null) model.seek((model.absolutePosition() + if (left) -10_000 else 10_000).coerceAtLeast(0)) }, + onBounds = { lastVideoRect = it }, + ) + if (showControls) { + TopBar( + title = current?.ref?.title ?: "正在准备视频", + onBack = { finish() }, + modifier = Modifier.align(Alignment.TopCenter), + actions = { + TextButton(onClick = { dialog = PlayerDialog.Cast; devices = null; castError = null }) { Text("投屏", color = AppAccent) } + TextButton(onClick = { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT }) { Text("退出全屏", color = AppAccent) } + TextButton(onClick = { dialog = PlayerDialog.Menu }) { Text("⋮", color = AppInk, fontSize = 20.sp) } + }, + ) + ControlsContent( + state = state, + position = position, + duration = duration, + playing = playing, + remote = remote, + dlna = dlna, + landscape = true, + fromServer = current?.ref?.accountId != null, + modifier = Modifier.align(Alignment.BottomCenter), + onSeek = ::seekTo, + onSeekBy = ::seekBy, + onToggle = { togglePlayback(remote, dlna) }, + onPrevious = { model.next(-1) }, + onNext = { model.next(1) }, + onFullscreen = { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT }, + ) + } + } else { + Column(Modifier.fillMaxSize()) { + TopBar( + title = current?.ref?.title ?: "正在准备视频", + onBack = { finish() }, + actions = { + TextButton(onClick = { dialog = PlayerDialog.Cast; devices = null; castError = null }) { Text("投屏", color = AppAccent) } + TextButton(onClick = { dialog = PlayerDialog.Menu }) { Text("⋮", color = AppInk, fontSize = 20.sp) } + }, + ) + VideoPane( + modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f), + engine = model.engine, + texture = texture, + crop = crop, + ratio = ratio, + subtitle = subtitleText, + centerText = centerText, + canRetry = error != null || state.phase == PlaybackPhase.ERROR, + onRetry = { model.retry() }, + pip = false, + onTap = {}, + onDoubleTap = { left -> if (remote == null) model.seek((model.absolutePosition() + if (left) -10_000 else 10_000).coerceAtLeast(0)) }, + onBounds = { lastVideoRect = it }, + ) + Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) { + ControlsContent( + state = state, + position = position, + duration = duration, + playing = playing, + remote = remote, + dlna = dlna, + landscape = false, + fromServer = current?.ref?.accountId != null, + onSeek = ::seekTo, + onSeekBy = ::seekBy, + onToggle = { togglePlayback(remote, dlna) }, + onPrevious = { model.next(-1) }, + onNext = { model.next(1) }, + onFullscreen = { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE }, + ) + } } } - }.show() + } + + PlayerDialogs( + dialog = dialog, + state = state, + crop = crop, + remote = remote, + dlna = dlna, + devices = devices, + castBusy = castBusy, + castError = castError, + onDismiss = { dialog = null }, + onCrop = { crop = !crop }, + onTexture = { + repo.preferences.texture = !texture + texture = !texture + }, + onOpenSubtitle = { pickSubtitle.launch(arrayOf("*/*")) }, + onDiscover = { + castBusy = true + castError = null + scope.launch { + try { + devices = model.devices() + } catch (_: Exception) { + castError = "设备搜索失败,请检查网络" + } finally { + castBusy = false + } + } + }, + onGoogle = { + scope.launch { + val intent = model.googleIntent() + if (intent != null) google.launch(intent) else castError = "该视频不能投屏" + } + }, + onDlna = { device -> model.dlna(device) }, + onCastCommand = { action -> DlnaSession.command(this, action) }, + onDialogChange = { dialog = it }, + ) } - override fun onConfigurationChanged(newConfig: Configuration) { - super.onConfigurationChanged(newConfig) - // 画中画里整页重建会重新创建 Surface,部分设备会短暂或持续黑屏;改为保持现有视频视图。 - if (pipMode || (Build.VERSION.SDK_INT >= 24 && isInPictureInPictureMode)) applyPipLayout(true) else build() + + @Composable + private fun VideoPane( + modifier: Modifier, + engine: AndroidVideoOutput, + texture: Boolean, + crop: Boolean, + ratio: Float, + subtitle: String, + centerText: String?, + canRetry: Boolean, + onRetry: () -> Unit, + pip: Boolean, + onTap: () -> Unit, + onDoubleTap: (Boolean) -> Unit, + onBounds: (Rect) -> Unit, + ) { + Box(modifier.background(Color.Black).clipToBounds()) { + VideoSurface(engine, texture, crop, ratio, Modifier.fillMaxSize(), onBounds) + if (subtitle.isNotEmpty()) { + Text( + subtitle, + color = Color.White, + fontSize = if (pip) 11.sp else 18.sp, + textAlign = TextAlign.Center, + modifier = Modifier + .align(Alignment.BottomCenter) + .fillMaxWidth() + .padding(horizontal = if (pip) 4.dp else 16.dp, vertical = if (pip) 2.dp else 12.dp) + .background(Color(0x66000000)) + .padding(horizontal = 8.dp, vertical = 4.dp), + ) + } + if (!pip) { + Box( + Modifier.matchParentSize().pointerInput(Unit) { + detectTapGestures( + onTap = { onTap() }, + onDoubleTap = { offset -> onDoubleTap(offset.x < size.width / 2f) }, + ) + }, + ) + } + if (centerText != null) { + Box( + Modifier + .matchParentSize() + .background(Color(0x77101822)) + .then(if (canRetry) Modifier.clickable { onRetry() } else Modifier), + contentAlignment = Alignment.Center, + ) { + Text(centerText, color = AppInk, textAlign = TextAlign.Center, fontSize = 16.sp) + } + } + } } - override fun onUserLeaveHint() { super.onUserLeaveHint(); enterPipIfPossible() } - /** 播放中按 Home/切走时进入画中画;暂停或非视频不进入。 */ - private fun enterPipIfPossible() { + + @Composable + private fun VideoSurface( + engine: AndroidVideoOutput, + texture: Boolean, + crop: Boolean, + ratio: Float, + modifier: Modifier, + onBounds: (Rect) -> Unit, + ) { + BoxWithConstraints(modifier) { + val safeRatio = if (ratio.isFinite() && ratio > 0.01f) ratio else 16f / 9f + val containerRatio = if (maxHeight > 0.dp) maxWidth / maxHeight else safeRatio + val width: Dp + val height: Dp + if (crop) { + if (containerRatio > safeRatio) { + width = maxWidth + height = maxWidth / safeRatio + } else { + height = maxHeight + width = maxHeight * safeRatio + } + } else { + if (containerRatio > safeRatio) { + height = maxHeight + width = maxHeight * safeRatio + } else { + width = maxWidth + height = maxWidth / safeRatio + } + } + val bindings = remember { mutableMapOf() } + DisposableEffect(Unit) { + onDispose { + bindings.values.forEach { runCatching { it.close() } } + bindings.clear() + } + } + key(texture) { + AndroidView( + factory = { context -> + val view: View = if (texture) TextureView(context) else SurfaceView(context) + val binding = if (view is TextureView) TextureViewBinding(view, engine) + else SurfaceViewBinding(view as SurfaceView, engine) + bindings[view] = binding + view + }, + modifier = Modifier + .size(width.coerceAtLeast(1.dp), height.coerceAtLeast(1.dp)) + .align(Alignment.Center) + .onGloballyPositioned { coordinates -> + val bounds = coordinates.boundsInWindow() + onBounds( + Rect( + bounds.left.roundToInt(), + bounds.top.roundToInt(), + bounds.right.roundToInt(), + bounds.bottom.roundToInt(), + ) + ) + }, + onRelease = { view -> bindings.remove(view)?.let { runCatching { it.close() } } }, + ) + } + } + } + + @Composable + private fun ControlsContent( + state: PlaybackState, + position: Long, + duration: Long?, + playing: Boolean, + remote: String?, + dlna: DlnaUiState, + landscape: Boolean, + fromServer: Boolean, + modifier: Modifier = Modifier, + onSeek: (Long) -> Unit, + onSeekBy: (Long) -> Unit, + onToggle: () -> Unit, + onPrevious: () -> Unit, + onNext: () -> Unit, + onFullscreen: () -> Unit, + ) { + var slider by remember { mutableFloatStateOf(0f) } + var dragging by remember { mutableStateOf(false) } + LaunchedEffect(position, duration, dragging) { + if (!dragging && duration != null && duration > 0) slider = (position.toFloat() / duration).coerceIn(0f, 1f) + } + Column( + modifier + .fillMaxWidth() + .background(if (landscape) Color(0xEE101822) else Color.Transparent) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + "${formatTime(position)} / ${duration?.let(::formatTime) ?: "--:--"}", + style = MaterialTheme.typography.labelSmall, + color = AppMuted, + ) + Slider( + value = slider, + onValueChange = { dragging = true; slider = it }, + onValueChangeFinished = { + dragging = false + duration?.let { onSeek((it * slider).toLong()) } + }, + enabled = duration != null && duration > 0, + colors = SliderDefaults.colors(thumbColor = AppAccent, activeTrackColor = AppAccent, inactiveTrackColor = AppRaised), + ) + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + ControlButton("上一部", Modifier.weight(1f), onPrevious) + ControlButton("−10s", Modifier.weight(1f)) { onSeekBy(-10_000) } + Button( + onClick = onToggle, + modifier = Modifier.weight(1f).height(52.dp), + shape = androidx.compose.foundation.shape.RoundedCornerShape(14.dp), + contentPadding = PaddingValues(horizontal = 4.dp, vertical = 0.dp), + colors = ButtonDefaults.buttonColors(containerColor = AppAccent, contentColor = AppBg), + ) { Text(if (state.phase == PlaybackPhase.ENDED) "重播" else if (playing) "暂停" else "播放", fontSize = 14.sp, maxLines = 1) } + ControlButton("+10s", Modifier.weight(1f)) { onSeekBy(10_000) } + ControlButton("下一部", Modifier.weight(1f), onNext) + } + if (!landscape) { + Text( + if (remote != null) "投屏中 · 点击右上角投屏管理连接" + else "${if (fromServer) "媒体来源播放" else "本机 / 在线播放"} · 双击画面快进 / 后退\n音轨、字幕、倍速与显示选项在更多菜单中", + style = MaterialTheme.typography.labelSmall, + color = AppMuted, + modifier = Modifier.padding(top = 4.dp), + ) + SecondaryButton("全屏播放", Modifier.fillMaxWidth(), onClick = onFullscreen) + } + } + } + + @Composable + private fun ControlButton(label: String, modifier: Modifier, onClick: () -> Unit) { + TextButton( + onClick = onClick, + modifier = modifier.height(52.dp), + contentPadding = PaddingValues(horizontal = 2.dp), + ) { Text(label, color = AppInk, fontSize = 13.sp, maxLines = 1, textAlign = TextAlign.Center) } + } + + @Composable + private fun PlayerDialogs( + dialog: PlayerDialog?, + state: PlaybackState, + crop: Boolean, + remote: String?, + dlna: DlnaUiState, + devices: List?, + castBusy: Boolean, + castError: String?, + onDismiss: () -> Unit, + onCrop: () -> Unit, + onTexture: () -> Unit, + onOpenSubtitle: () -> Unit, + onDiscover: () -> Unit, + onGoogle: () -> Unit, + onDlna: (DlnaDevice) -> Unit, + onCastCommand: (String) -> Unit, + onDialogChange: (PlayerDialog?) -> Unit, + ) { + when (dialog) { + PlayerDialog.Menu -> ChoiceDialog( + title = "播放选项", + options = listOf("音轨", "字幕", "加载外挂字幕", "播放速度", "显示比例:${if (crop) "填充" else "适应"}", "收藏 / 取消收藏", "视频显示方式", "解码方式"), + onDismiss = onDismiss, + onSelect = { index -> + when (index) { + 0 -> onDialogChange(PlayerDialog.Tracks(TrackType.AUDIO)) + 1 -> onDialogChange(PlayerDialog.Tracks(TrackType.TEXT)) + 2 -> { onDismiss(); onOpenSubtitle() } + 3 -> onDialogChange(PlayerDialog.Speed) + 4 -> { onCrop(); onDismiss() } + 5 -> { onDismiss(); model.favorite(); Toast.makeText(this, "收藏已更新", Toast.LENGTH_SHORT).show() } + 6 -> { onTexture(); onDismiss() } + 7 -> onDialogChange(PlayerDialog.Decode) + } + }, + ) + is PlayerDialog.Tracks -> { + val tracks = state.tracks.filter { it.type == dialog.type } + val prefix = if (dialog.type == TrackType.TEXT) "关闭字幕" else "自动选择" + val labels = listOf(prefix) + tracks.map { "${it.label ?: it.language ?: "轨道 ${it.id}"}${if (it.selected) " ✓" else ""}" } + ChoiceDialog( + title = if (dialog.type == TrackType.TEXT) "字幕" else "音轨", + options = labels, + onDismiss = onDismiss, + onSelect = { index -> + onDismiss() + val selection = if (index == 0) TrackSelection(dialog.type, disabled = dialog.type == TrackType.TEXT) + else TrackSelection(dialog.type, tracks[index - 1].id) + model.selectTrack(selection) + }, + ) + } + PlayerDialog.Speed -> ChoiceDialog( + title = "播放速度", + options = listOf("0.5×", "0.75×", "1×", "1.25×", "1.5×", "2×"), + onDismiss = onDismiss, + onSelect = { index -> + onDismiss() + model.setSpeed(listOf(0.5f, 0.75f, 1f, 1.25f, 1.5f, 2f)[index]) + }, + ) + PlayerDialog.Decode -> ChoiceDialog( + title = "解码方式", + options = listOf("自动选择", "优先硬解", "仅硬解", "仅系统软解"), + onDismiss = onDismiss, + onSelect = { index -> + onDismiss() + val mode = DecodeMode.entries[index] + repo.preferences.decoder = mode + model.setDecoder(mode) + }, + ) + PlayerDialog.Cast -> { + val found = devices + when { + remote == "dlna" || dlna.active -> ChoiceDialog( + title = dlna.device.ifBlank { "电视投屏" }, + options = listOf("播放", "暂停", "后退 30 秒", "前进 30 秒", "结束投屏并返回本机"), + onDismiss = onDismiss, + onSelect = { index -> + onDismiss() + when (index) { + 0 -> onCastCommand("play") + 1 -> onCastCommand("pause") + 2 -> onCastCommand("back") + 3 -> onCastCommand("forward") + else -> onCastCommand("stop") + } + }, + ) + castBusy -> AlertDialog( + onDismissRequest = onDismiss, + title = { Text("投屏", color = AppInk) }, + text = { Text("正在搜索同一局域网的电视…", color = AppMuted) }, + confirmButton = {}, + dismissButton = { TextButton(onClick = onDismiss) { Text("取消", color = AppMuted) } }, + containerColor = AppPanel, + ) + found != null -> ChoiceDialog( + title = if (found.isEmpty()) "未发现设备" else "选择电视", + options = if (found.isEmpty()) listOf("未发现设备,请确认电视投屏已开启") else found.map { it.name }, + onDismiss = onDismiss, + onSelect = { index -> onDismiss(); if (index < found.size) onDlna(found[index]) }, + ) + castError != null -> ConfirmDialog( + title = "投屏", + message = castError, + confirmText = "重试", + onConfirm = { onDiscover() }, + onDismiss = onDismiss, + ) + else -> ChoiceDialog( + title = "投屏到设备", + options = listOf("DLNA · 电视 / 盒子", "Google Cast"), + onDismiss = onDismiss, + onSelect = { index -> if (index == 0) onDiscover() else { onDismiss(); onGoogle() } }, + ) + } + } + null -> Unit + } + } + + private fun togglePlayback(remote: String?, dlna: DlnaUiState) { + when { + remote == "dlna" -> DlnaSession.command(this, if (dlna.playback.playing) "pause" else "play") + model.engine.state.value.phase == PlaybackPhase.ENDED -> model.restart() + else -> model.toggle() + } + } + + private fun seekTo(position: Long) { + if (model.remote.value == "dlna") { + startService(Intent(this, DlnaPlaybackService::class.java).setAction("seek").putExtra("position", position)) + } else model.seek(position) + } + + private fun seekBy(delta: Long) { + if (model.remote.value == "dlna") { + startService( + Intent(this, DlnaPlaybackService::class.java).setAction("seek") + .putExtra("position", (DlnaSession.state.value.playback.positionMs + delta).coerceAtLeast(0)) + ) + } else model.seek((model.absolutePosition() + delta).coerceAtLeast(0)) + } + + override fun onStart() { super.onStart(); model.onVisible() } + + override fun onResume() { + super.onResume() + if (pipState.value && (Build.VERSION.SDK_INT < 24 || !isInPictureInPictureMode)) pipState.value = false + } + + override fun onStop() { + val inPip = pipState.value || (Build.VERSION.SDK_INT >= 24 && isInPictureInPictureMode) + model.onHidden(isChangingConfigurations, inPip) + super.onStop() + } + + override fun onUserLeaveHint() { + super.onUserLeaveHint() if (Build.VERSION.SDK_INT < 26 || model.remote.value != null) return if (!model.engine.state.value.playWhenReady || isInPictureInPictureMode) return - // 先切成纯视频布局,避免 PiP 动画期间工具栏/控制区占据窗口。 - applyPipLayout(true) + pipState.value = true val entered = runCatching { enterPictureInPictureMode(pipParams()) }.getOrDefault(false) - if (!entered) applyPipLayout(false) + if (!entered) pipState.value = false } - /** 画中画只显示视频;宽高比跟随当前视频,系统据此选择尽量宽的窗口。 */ - private fun applyPipLayout(inPip: Boolean) { - if (!::toolbar.isInitialized || !::controls.isInitialized) return - pipMode = inPip - if (inPip) { - toolbar.visibility = View.GONE - controls.visibility = View.GONE - controlScroll?.visibility = View.GONE - val lp = video.layoutParams - if (lp is LinearLayout.LayoutParams) { - lp.height = 0 - lp.weight = 1f - video.layoutParams = lp - } - subtitle.setPadding(dp(8), dp(4), dp(8), dp(8)) - } else { - toolbar.visibility = View.VISIBLE - controls.visibility = View.VISIBLE - controlScroll?.visibility = View.VISIBLE - val lp = video.layoutParams - if (lp is LinearLayout.LayoutParams) { - lp.height = (resources.displayMetrics.widthPixels * 9 / 16).coerceAtLeast(dp(180)) - lp.weight = 0f - video.layoutParams = lp - } - val landscape = resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE - subtitle.setPadding(dp(if (landscape) 24 else 20), dp(4), dp(if (landscape) 24 else 20), dp(if (landscape) 240 else 16)) - } - video.post { fitVideo() } + + override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) { + super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) + pipState.value = isInPictureInPictureMode + if (isInPictureInPictureMode) model.onPipEntered() else model.onPipExited() } - @androidx.annotation.RequiresApi(26) - private fun pipParams(): android.app.PictureInPictureParams { + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + updatePipParams() + } + + @RequiresApi(26) + private fun pipParams(): PictureInPictureParams { val ratio = model.videoRatio.value.takeIf { it.isFinite() && it > 0f } ?: 16f / 9f val clamped = ratio.coerceIn(1f / 2.39f, 2.39f) - val rational = if (clamped >= 1f) android.util.Rational((clamped * 1000).toInt(), 1000) - else android.util.Rational(1000, (1000 / clamped).toInt()) - val builder = android.app.PictureInPictureParams.Builder().setAspectRatio(rational) + val rational = if (clamped >= 1f) Rational((clamped * 1000).toInt(), 1000) + else Rational(1000, (1000 / clamped).toInt()) + val builder = PictureInPictureParams.Builder().setAspectRatio(rational) if (Build.VERSION.SDK_INT >= 31) { builder.setAutoEnterEnabled(model.engine.state.value.playWhenReady && model.remote.value == null) - // SurfaceView 在 PiP 缩放时直接重设 buffer 容易闪黑,交给系统做淡入淡出。 builder.setSeamlessResizeEnabled(false) } - if (::video.isInitialized) { - val rect = android.graphics.Rect() - if (video.getGlobalVisibleRect(rect)) builder.setSourceRectHint(rect) - } + lastVideoRect?.takeIf { it.width() > 0 && it.height() > 0 }?.let { builder.setSourceRectHint(it) } return builder.build() } + private fun updatePipParams() { if (Build.VERSION.SDK_INT < 26 || isFinishing || isDestroyed) return runCatching { setPictureInPictureParams(pipParams()) } } - override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean, newConfig: Configuration) { - super.onPictureInPictureModeChanged(isInPictureInPictureMode, newConfig) - if (isInPictureInPictureMode) { - model.onPipEntered() - applyPipLayout(true) - } else { - model.onPipExited() - // 退出 PiP 时按当前方向重建一次,恢复工具栏和控制区。 - if (pipMode) build() else render() - } - } - override fun onStart() { super.onStart(); model.onVisible() } - override fun onResume() { - super.onResume() - // 系统未接受 PiP 或未回调时,避免页面停留在纯视频布局。 - if (pipMode && (Build.VERSION.SDK_INT < 24 || !isInPictureInPictureMode)) build() - } - override fun onStop() { - // onHidden 内决定:进入 PIP / 低版本后台续播时继续播放,否则暂停。 - val inPip = Build.VERSION.SDK_INT >= 24 && isInPictureInPictureMode - model.onHidden(isChangingConfigurations, inPip) - super.onStop() - } - override fun onDestroy() { surfaceBinding?.close(); surfaceBinding = null; super.onDestroy() } +} + +private sealed interface PlayerDialog { + data object Menu : PlayerDialog + data object Speed : PlayerDialog + data object Decode : PlayerDialog + data object Cast : PlayerDialog + data class Tracks(val type: TrackType) : PlayerDialog } diff --git a/app/src/main/kotlin/com/ttstd/player/app/PlayerModel.kt b/app/src/main/kotlin/com/ttstd/player/app/PlayerModel.kt index fc2b42c..7375ca0 100644 --- a/app/src/main/kotlin/com/ttstd/player/app/PlayerModel.kt +++ b/app/src/main/kotlin/com/ttstd/player/app/PlayerModel.kt @@ -96,7 +96,7 @@ class PlayerModel(application: Application) : AndroidViewModel(application) { current.value = item playResolved(repo.resolve(item.ref, item.positionMs), true) } catch (cancelled: CancellationException) { throw cancelled } - catch (e: Exception) { error.value = SourceDialogs.safeError(e) } + catch (e: Exception) { error.value = safeError(e) } finally { loading.value = false } } } @@ -110,6 +110,8 @@ class PlayerModel(application: Application) : AndroidViewModel(application) { } fun retry() { val id = current.value?.ref?.id ?: return; playback = null; open(id) } fun toggle() { viewModelScope.launch { if (engine.state.value.playWhenReady) engine.pause() else engine.play() } } + /** 播放结束后从起点重播;直播或不可 seek 时直接继续播放。 */ + fun restart() { viewModelScope.launch { if (engine.state.value.phase == PlaybackPhase.ENDED) engine.seekTo(0); engine.play() } } fun seek(position: Long) { viewModelScope.launch { val p = playback ?: return@launch if (p.positionOffsetMs > 0) resumeLocal((position - p.positionOffsetMs).coerceAtLeast(-p.positionOffsetMs), engine.state.value.playWhenReady) @@ -185,7 +187,7 @@ class PlayerModel(application: Application) : AndroidViewModel(application) { loading.value = true; error.value = null try { playResolved(repo.resolve(item.ref, (position + (playback?.positionOffsetMs ?: 0)).coerceAtLeast(0)), playing) } catch (cancelled: CancellationException) { throw cancelled } - catch (e: Exception) { error.value = SourceDialogs.safeError(e) } + catch (e: Exception) { error.value = safeError(e) } finally { loading.value = false } } private fun media(relay: CastRelay): CastMedia { diff --git a/app/src/main/kotlin/com/ttstd/player/app/SourceDialogs.kt b/app/src/main/kotlin/com/ttstd/player/app/SourceDialogs.kt index 9407d01..4a3f279 100644 --- a/app/src/main/kotlin/com/ttstd/player/app/SourceDialogs.kt +++ b/app/src/main/kotlin/com/ttstd/player/app/SourceDialogs.kt @@ -1,74 +1,157 @@ package com.ttstd.player.app -import android.app.AlertDialog -import android.text.InputType -import android.widget.* -import androidx.appcompat.app.AppCompatActivity -import androidx.lifecycle.lifecycleScope +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.imePadding +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.FilterChip +import androidx.compose.material3.FilterChipDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp import com.ttstd.player.library.* -import kotlinx.coroutines.* +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import java.net.URI import java.util.UUID -import com.ttstd.player.app.Ui.dp /** 来源编辑与连接测试共用同一个校验边界,保存前不向服务器发起请求。 */ -object SourceDialogs { - fun edit(activity: AppCompatActivity, existing: LibraryAccount? = null, saved: () -> Unit) { - val repo = AppRepository(activity.applicationContext) - val form = Ui.column(activity, 20) - val kinds = LibraryKind.entries - form.addView(Ui.label(activity, "选择连接方式", 13f, Ui.muted)) - val kind = Spinner(activity).apply { - adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_dropdown_item, listOf("WebDAV · 网盘 / NAS", "SMB · 局域网共享", "Jellyfin · 媒体服务器")) - setSelection(kinds.indexOf(existing?.kind ?: LibraryKind.WEBDAV)) +@Composable +fun SourceEditorDialog( + repo: AppRepository, + existing: LibraryAccount?, + onDismiss: () -> Unit, + onSaved: () -> Unit, +) { + val kinds = LibraryKind.entries + var kindIndex by rememberSaveable { mutableIntStateOf(kinds.indexOf(existing?.kind ?: LibraryKind.WEBDAV)) } + var name by rememberSaveable { mutableStateOf(existing?.name.orEmpty()) } + var endpoint by rememberSaveable { mutableStateOf(existing?.endpoint.orEmpty()) } + var user by rememberSaveable { mutableStateOf(existing?.username.orEmpty()) } + var password by rememberSaveable { mutableStateOf(existing?.password.orEmpty()) } + var domain by rememberSaveable { mutableStateOf(existing?.domain.orEmpty()) } + var status by remember { mutableStateOf("凭证加密保存在本机。WebDAV 支持匿名与 Basic 认证。") } + var testing by remember { mutableStateOf(false) } + var saving by remember { mutableStateOf(false) } + val scope = rememberCoroutineScope() + + fun account(): LibraryAccount { + val selected = kinds[kindIndex] + val uri = runCatching { URI(endpoint.trim()) }.getOrNull() + require(name.isNotBlank() && uri?.host != null && uri.userInfo == null && uri.query == null && uri.fragment == null) { + "请填写名称和正确的服务根地址" } - form.addView(kind) - fun input(label: String, value: String, secret: Boolean = false): EditText { - form.addView(Ui.label(activity, label, 13f, Ui.muted).apply { setPadding(0, activity.dp(12), 0, 0) }) - return EditText(activity).apply { - setSingleLine(true); isSaveEnabled = false - inputType = InputType.TYPE_CLASS_TEXT or if (secret) InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS - setText(value); form.addView(this) - } - } - val name = input("名称", existing?.name.orEmpty()) - val endpoint = input("服务地址(SMB 需包含共享名)", existing?.endpoint.orEmpty()).apply { hint = "https://nas.example/dav/" } - val user = input("用户名", existing?.username.orEmpty()) - val password = input("密码 / 应用专用密码", existing?.password.orEmpty(), true) - val domain = input("SMB 域(选填)", existing?.domain.orEmpty()) - val status = Ui.label(activity, "凭证加密保存在本机。WebDAV 支持匿名与 Basic 认证。", 12f, Ui.muted) - form.addView(status) - fun account(): LibraryAccount { - val selected = kinds[kind.selectedItemPosition] - val uri = runCatching { URI(endpoint.text.toString().trim()) }.getOrNull() - require(name.text.isNotBlank() && uri?.host != null && uri.userInfo == null && uri.query == null && uri.fragment == null) { "请填写名称和正确的服务根地址" } - require(if (selected == LibraryKind.SMB) uri.scheme == "smb" && uri.path.trim('/').isNotEmpty() else uri.scheme in setOf("http", "https")) { "地址与连接方式不匹配" } - return LibraryAccount(existing?.id ?: UUID.randomUUID().toString(), name.text.toString().trim(), selected, uri.toASCIIString(), - user.text.toString(), password.text.toString(), domain.text.toString()) - } - val test = Ui.button(activity, "测试连接") { - val value = runCatching { account() }.getOrElse { status.text = it.message; return@button } - status.text = "正在连接…" - activity.lifecycleScope.launch { - try { val page = withContext(Dispatchers.IO) { repo.library(value).list() }; status.text = "连接成功,当前目录 ${page.entries.size} 项" } - catch (cancelled: CancellationException) { throw cancelled } - catch (e: Exception) { status.text = safeError(e) } - } - } - form.addView(test) - val dialog = AlertDialog.Builder(activity).setTitle(if (existing == null) "添加媒体来源" else "编辑来源") - .setView(ScrollView(activity).apply { addView(form) }).setPositiveButton("保存", null).setNegativeButton("取消", null).create() - dialog.setOnShowListener { - dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { button -> - val value = runCatching { account() }.getOrElse { status.text = it.message; return@setOnClickListener } - button.isEnabled = false - activity.lifecycleScope.launch { - try { withContext(Dispatchers.IO) { repo.accounts.save(value) }; dialog.dismiss(); saved() } - catch (_: Exception) { status.text = "保存失败,请检查设备安全存储"; button.isEnabled = true } - } - } - } - dialog.show() + require( + if (selected == LibraryKind.SMB) uri!!.scheme == "smb" && uri.path.trim('/').isNotEmpty() + else uri!!.scheme in setOf("http", "https") + ) { "地址与连接方式不匹配" } + return LibraryAccount( + existing?.id ?: UUID.randomUUID().toString(), name.trim(), selected, uri.toASCIIString(), + user, password, domain, + ) } - fun safeError(error: Exception) = if (error is LibraryException) error.message ?: "来源请求失败" else "连接失败,请检查地址、账户和网络" + + AlertDialog( + onDismissRequest = { if (!saving) onDismiss() }, + title = { Text(if (existing == null) "添加媒体来源" else "编辑来源", color = AppInk) }, + text = { + Column( + Modifier + .heightIn(max = 460.dp) + .verticalScroll(rememberScrollState()) + .imePadding(), + verticalArrangement = Arrangement.spacedBy(10.dp), + ) { + Text("选择连接方式", style = MaterialTheme.typography.bodyMedium, color = AppMuted) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + LibraryKind.entries.forEachIndexed { index, kind -> + FilterChip( + selected = kindIndex == index, + onClick = { kindIndex = index }, + label = { Text(if (kind == LibraryKind.WEBDAV) "WebDAV" else kind.name) }, + colors = FilterChipDefaults.filterChipColors( + selectedContainerColor = AppAccent, + selectedLabelColor = AppBg, + labelColor = AppMuted, + ), + ) + } + } + AppTextField("名称", name, { name = it }) + AppTextField( + "服务地址(SMB 需包含共享名)", endpoint, { endpoint = it }, + placeholder = "https://nas.example/dav/", + keyboardType = KeyboardType.Uri, + ) + AppTextField("用户名", user, { user = it }) + AppTextField("密码 / 应用专用密码", password, { password = it }, secret = true) + AppTextField("SMB 域(选填)", domain, { domain = it }) + Text(status, style = MaterialTheme.typography.labelSmall, color = AppMuted) + TextButton( + onClick = { + val value = runCatching { account() }.getOrElse { status = it.message ?: "请检查输入"; return@TextButton } + testing = true + status = "正在连接…" + scope.launch { + try { + val page = withContext(Dispatchers.IO) { repo.library(value).list() } + status = "连接成功,当前目录 ${page.entries.size} 项" + } catch (cancelled: CancellationException) { + throw cancelled + } catch (e: Exception) { + status = safeError(e) + } finally { + testing = false + } + } + }, + enabled = !testing && !saving, + ) { Text(if (testing) "正在测试…" else "测试连接", color = AppAccent) } + } + }, + confirmButton = { + TextButton( + onClick = { + val value = runCatching { account() }.getOrElse { status = it.message ?: "请检查输入"; return@TextButton } + saving = true + scope.launch { + try { + withContext(Dispatchers.IO) { repo.accounts.save(value) } + onSaved() + onDismiss() + } catch (_: Exception) { + status = "保存失败,请检查设备安全存储" + saving = false + } + } + }, + enabled = !saving && !testing, + ) { Text(if (saving) "正在保存…" else "保存", color = AppAccent) } + }, + dismissButton = { TextButton(onClick = onDismiss, enabled = !saving) { Text("取消", color = AppMuted) } }, + containerColor = AppPanel, + ) } + +fun safeError(error: Exception) = + if (error is LibraryException) error.message ?: "来源请求失败" + else "连接失败,请检查地址、账户和网络" diff --git a/app/src/main/kotlin/com/ttstd/player/app/Ui.kt b/app/src/main/kotlin/com/ttstd/player/app/Ui.kt deleted file mode 100644 index d37f74b..0000000 --- a/app/src/main/kotlin/com/ttstd/player/app/Ui.kt +++ /dev/null @@ -1,73 +0,0 @@ -package com.ttstd.player.app - -import android.content.Context -import android.content.res.ColorStateList -import android.graphics.Color -import android.graphics.Typeface -import android.graphics.drawable.GradientDrawable -import android.graphics.drawable.RippleDrawable -import android.view.Gravity -import android.view.View -import android.widget.* -import androidx.appcompat.app.AppCompatActivity -import androidx.core.view.ViewCompat -import androidx.core.view.WindowInsetsCompat -import androidx.core.view.WindowInsetsControllerCompat -import androidx.core.view.doOnAttach - -/** 轻量原生界面组件,触摸目标至少 48dp,同时支持键盘焦点与大字体。 */ -object Ui { - val bg = Color.rgb(12, 18, 28) - val panel = Color.rgb(22, 32, 46) - val raised = Color.rgb(31, 44, 61) - val ink = Color.rgb(236, 243, 249) - val muted = Color.rgb(149, 168, 188) - val accent = Color.rgb(100, 227, 190) - fun Context.dp(value: Int) = (value * resources.displayMetrics.density).toInt() - fun shape(color: Int, radius: Float = 18f) = GradientDrawable().apply { setColor(color); cornerRadius = radius } - fun label(context: Context, value: String, size: Float = 15f, color: Int = ink, bold: Boolean = false) = TextView(context).apply { - text = value; textSize = size; setTextColor(color) - if (bold) setTypeface(typeface, Typeface.BOLD) - } - fun column(context: Context, padding: Int = 0) = LinearLayout(context).apply { - orientation = LinearLayout.VERTICAL - setPadding(context.dp(padding), context.dp(padding), context.dp(padding), context.dp(padding)) - } - fun button(context: Context, title: String, primary: Boolean = false, action: () -> Unit) = TextView(context).apply { - text = title; textSize = 15f; gravity = Gravity.CENTER; minHeight = context.dp(48); minimumWidth = context.dp(48) - setPadding(context.dp(16), context.dp(8), context.dp(16), context.dp(8)) - setTextColor(if (primary) bg else ink) - background = RippleDrawable(ColorStateList.valueOf(0x2264e3be), shape(if (primary) accent else raised, context.dp(14).toFloat()), null) - isFocusable = true; isClickable = true; contentDescription = title; setOnClickListener { action() } - } - fun card(context: Context, title: String, subtitle: String, action: (() -> Unit)? = null): LinearLayout = column(context, 18).apply { - background = shape(panel, context.dp(18).toFloat()) - addView(label(context, title, 18f, bold = true)) - addView(label(context, subtitle, 13f, muted).apply { setPadding(0, context.dp(8), 0, 0) }) - layoutParams = LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = context.dp(12) } - if (action != null) { isFocusable = true; isClickable = true; setOnClickListener { action() } } - } - fun inset(activity: AppCompatActivity, view: View) { - view.setBackgroundColor(bg) - // API 35 的窗口在 setContentView 前尚无 DecorView,等根视图附着后再访问控制器。 - view.doOnAttach { - WindowInsetsControllerCompat(activity.window, view).apply { isAppearanceLightStatusBars = false; isAppearanceLightNavigationBars = false } - ViewCompat.requestApplyInsets(view) - } - ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets -> - val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime()) - v.setPadding(bars.left, bars.top, bars.right, bars.bottom); insets - } - } - fun empty(context: Context, title: String, description: String) = column(context, 28).apply { - gravity = Gravity.CENTER; minimumHeight = context.dp(220) - addView(label(context, "▷", 52f, accent)) - addView(label(context, title, 20f, bold = true)) - addView(label(context, description, 14f, muted).apply { gravity = Gravity.CENTER; setPadding(0, context.dp(12), 0, 0) }) - } - fun time(ms: Long): String { - val s = ms.coerceAtLeast(0) / 1000 - return if (s >= 3600) "%d:%02d:%02d".format(s / 3600, s / 60 % 60, s % 60) else "%d:%02d".format(s / 60, s % 60) - } - fun bytes(value: Long): String = if (value >= 1024L * 1024 * 1024) "%.1f GB".format(value / (1024.0 * 1024 * 1024)) else "%.1f MB".format(value / (1024.0 * 1024)) -} diff --git a/build.gradle.kts b/build.gradle.kts index 5bee9c5..6acc393 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -3,4 +3,5 @@ plugins { id("com.android.application") version "8.13.2" apply false kotlin("android") version "2.4.21" apply false kotlin("jvm") version "2.4.21" apply false + id("org.jetbrains.kotlin.plugin.compose") version "2.4.21" apply false } diff --git a/docs/app.md b/docs/app.md index f0f8bb4..0ce8317 100644 --- a/docs/app.md +++ b/docs/app.md @@ -50,4 +50,4 @@ SRT/RIST、WebRTC、DRM、AirPlay、网盘专有认证和 Emby/Plex 等独立服 python tools/verify_apk_native.py app/build/outputs/apk/debug/app-debug.apk ``` -产物为 debug 签名测试包,发布商店前需配置自己的 release 签名和发行流程。界面使用原生 Views,手机为底部导航、宽屏为侧边导航,横屏播放全屏显示。来源契约、播放契约和 cast 契约允许继续添加服务与内核;当前 JVM 模块尚未迁移成 KMP。 +产物为 debug 签名测试包,发布商店前需配置自己的 release 签名和发行流程。app 界面已迁移到 Jetpack Compose(Material 3 深色主题),手机为底部导航、宽屏为侧边导航,横屏播放全屏显示;播放 Surface 仍由 `AndroidView` 承载,minSdk 保持 23。来源契约、播放契约和 cast 契约允许继续添加服务与内核;当前 JVM 模块尚未迁移成 KMP。