Files
PostPad/src/main/java/com/shitoucuo/postpad/ReaderActivity.kt

764 lines
34 KiB
Kotlin
Raw Normal View History

package com.shitoucuo.postpad
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Outline
import android.net.Uri
import android.os.Bundle
import android.app.Dialog
import android.text.method.LinkMovementMethod
import android.util.LruCache
import android.view.View
import android.view.ViewGroup
import android.view.ViewOutlineProvider
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import io.noties.markwon.Markwon
import io.noties.markwon.image.ImagesPlugin
import io.noties.markwon.image.network.OkHttpNetworkSchemeHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/** 统一阅读页:文章 / Memos / RSS 都在这里看 Markdown 正文 */
class ReaderActivity : AppCompatActivity() {
private lateinit var prefs: Prefs
private lateinit var tvTitle: TextView
private lateinit var tvMeta: TextView
private lateinit var bodyContainer: LinearLayout
private lateinit var progress: ProgressBar
private lateinit var btnOriginal: TextView
private lateinit var markwon: Markwon
private lateinit var imageClient: OkHttpClient
private var originalUrl: String = ""
/** 顶栏 meta 的三段信息:来源站点、作者、发布时间 */
private var metaSource: String = ""
private var metaAuthor: String = ""
private var metaDate: Long = 0L
companion object {
private const val EXTRA_KIND = "kind"
private const val EXTRA_ID = "id"
private const val EXTRA_TITLE = "title"
private const val EXTRA_SOURCE = "source"
private const val EXTRA_DATE = "date"
private const val EXTRA_CONTENT = "content"
private const val EXTRA_LINK = "link"
const val KIND_RSS = "rss"
const val KIND_ARTICLE = "article"
const val KIND_MEMO = "memo"
fun open(
context: Context,
kind: String,
id: String,
title: String,
source: String,
date: Long,
content: String,
link: String,
) {
val intent = Intent(context, ReaderActivity::class.java).apply {
putExtra(EXTRA_KIND, kind)
putExtra(EXTRA_ID, id)
putExtra(EXTRA_TITLE, title)
putExtra(EXTRA_SOURCE, source)
putExtra(EXTRA_DATE, date)
putExtra(EXTRA_CONTENT, content)
putExtra(EXTRA_LINK, link)
}
context.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
prefs = Prefs(this)
val target = prefs.nightMode()
if (AppCompatDelegate.getDefaultNightMode() != target) {
AppCompatDelegate.setDefaultNightMode(target)
}
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_reader)
tvTitle = findViewById(R.id.tvReaderTitle)
tvMeta = findViewById(R.id.tvReaderMeta)
bodyContainer = findViewById(R.id.bodyContainer)
progress = findViewById(R.id.readerProgress)
btnOriginal = findViewById(R.id.btnOpenOriginal)
imageClient = OkHttpClient.Builder()
.connectTimeout(20, java.util.concurrent.TimeUnit.SECONDS)
.readTimeout(60, java.util.concurrent.TimeUnit.SECONDS)
.build()
val imagePlugin = ImagesPlugin.create()
.addSchemeHandler(OkHttpNetworkSchemeHandler.create(imageClient))
markwon = Markwon.builder(this)
.usePlugin(imagePlugin)
.usePlugin(MdThemePlugin(this))
.build()
val kind = intent.getStringExtra(EXTRA_KIND).orEmpty()
val id = intent.getStringExtra(EXTRA_ID).orEmpty()
val title = intent.getStringExtra(EXTRA_TITLE).orEmpty()
val source = intent.getStringExtra(EXTRA_SOURCE).orEmpty()
val date = intent.getLongExtra(EXTRA_DATE, 0L)
val preloaded = intent.getStringExtra(EXTRA_CONTENT).orEmpty()
originalUrl = intent.getStringExtra(EXTRA_LINK).orEmpty()
tvTitle.text = title.ifBlank { getString(R.string.reader_untitled) }
metaSource = source
metaDate = date
renderMeta()
findViewById<ImageView>(R.id.btnReaderBack).setOnClickListener { finish() }
btnOriginal.setOnClickListener {
if (originalUrl.isBlank()) {
toast("这条内容没有原文链接")
return@setOnClickListener
}
runCatching {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(originalUrl)))
}.onFailure { toast("打不开浏览器") }
}
when (kind) {
KIND_ARTICLE -> loadArticle(id, preloaded)
KIND_RSS -> loadRss(preloaded)
else -> render(preloaded.ifBlank { "(empty)" })
}
}
private fun loadArticle(cid: String, preloaded: String) {
if (preloaded.isNotBlank()) {
render(preloaded)
return
}
progress.visibility = TextView.VISIBLE
lifecycleScope.launch {
try {
val detail = withContext(Dispatchers.IO) {
TypechoApi.postDetail(prefs, cid.toLongOrNull() ?: 0L)
}
originalUrl = detail.permalink.ifBlank { originalUrl }
tvTitle.text = detail.title
render(detail.markdown.ifBlank { detail.text })
} catch (e: Exception) {
render("读取文章失败:${e.message ?: "未知错误"}")
} finally {
progress.visibility = TextView.GONE
}
}
}
private fun loadRss(excerpt: String) {
if (originalUrl.isBlank()) {
render(excerpt.ifBlank { "(这条内容没有正文)" })
return
}
progress.visibility = TextView.VISIBLE
lifecycleScope.launch {
try {
val article = withContext(Dispatchers.IO) { RssApi.article(originalUrl) }
// 作者提到顶栏,正文里那条「作者:xxx」就不必再出现
if (article.author.isNotBlank()) {
metaAuthor = article.author
renderMeta()
}
val body = stripLeadingNoise(article.markdown.ifBlank { excerpt })
render(body.ifBlank { excerpt.ifBlank { "(原文里没有抓到正文)" } })
} catch (e: Exception) {
// 抓不到原文时用站端摘要兜底,至少能读个大概
render(excerpt.ifNotBlank() ?: "抓取原文失败:${e.message ?: "未知错误"}")
} finally {
progress.visibility = TextView.GONE
}
}
}
/**
* 顶栏信息行:来源 · 作者 · 发布时间。
*
* 「只留标题、作者、正文」——标题在页面最上方,作者与来源、时间收在这一行,
* 正文里就不再重复这些信息。
*/
private fun renderMeta() {
val text = buildString {
if (metaSource.isNotBlank()) append(metaSource)
if (metaAuthor.isNotBlank()) {
if (isNotEmpty()) append(" · ")
append(metaAuthor)
}
if (metaDate > 0) {
if (isNotEmpty()) append(" · ")
append(formatDate(metaDate))
}
}
tvMeta.text = text
tvMeta.visibility = if (text.isBlank()) View.GONE else View.VISIBLE
}
/**
* 正文开头的重复信息全部剥掉。
*
* 原文页面的 article 里常把「标题 + 日期 + 分类 + 作者」再写一遍,顶栏已经有了,
* 重复显示等于把同一段信息看两次。这里逐行往下剥,直到第一行是真正的正文:
* 重复标题(含 `# 标题`、`**标题**`、`标题 - 站点名`)、日期行、分类/标签/作者/阅读量
* 等 meta 行、头像小图、开头的分隔线都算噪音。
*/
private fun stripLeadingNoise(markdown: String): String {
val title = tvTitle.text.toString().trim()
var s = markdown.trim()
var guard = 0
while (guard++ < 16) {
val lines = s.lines()
val idx = lines.indexOfFirst { it.isNotBlank() }
if (idx < 0) return ""
if (!isHeaderNoise(lines[idx].trim(), title)) break
s = lines.drop(idx + 1).joinToString("\n").trim()
}
// 正文中部再出现一次同名一级标题,同样是重复
s = removeRedundantH1(s, title)
return stripTrailingNoise(s)
}
/** 这一行是不是「顶栏已经显示过」的信息 */
private fun isHeaderNoise(line: String, title: String): Boolean {
if (line.isEmpty()) return false
val plain = line
.replace(Regex("^#{1,6}\\s*"), "")
.replace(Regex("^\\*\\*(.*)\\*\\*$"), "$1")
.replace(Regex("^__(.*)__$"), "$1")
.replace(Regex("^\\[(.*)\\]\\([^)]*\\)$"), "$1")
.trim()
if (plain.isEmpty()) return true
if (Regex("^(?:-{3,}|\\*{3,}|_{3,})$").matches(plain)) return true
// 1) 重复标题
if (title.length >= 4) {
val t = title.lowercase()
val p = plain.lowercase()
if (p == t) return true
// 「主标题 - 站点名」「标题 | 分类」这类拼接也算重复
if (p.length <= t.length + 24 && (p.startsWith(t) || p.contains(t))) return true
}
// 2) 日期行:2026-06-08 / 2026年6月8日 / 2026/06/08 09:46
if (plain.length < 70 &&
Regex("^\\d{4}[-/年.]\\d{1,2}[-/月.]\\d{1,2}日?(?:[^\\n]{0,40})$").matches(plain)
) return true
// 3) 一行里既带日期又带「·」分隔的 meta(日期 · 分类 · 阅读数)
if (plain.length < 90 && plain.contains('·') &&
Regex("\\d{4}[-/年]\\d{1,2}").containsMatchIn(plain)
) return true
// 4) 分类 / 标签 / 作者 / 来源 / 字数 / 阅读
if (Regex("^(?:作者|撰文|文|分类|标签|来源|发布于|发表于|更新于|字数|阅读|浏览|编辑|责编|摄影)[::\\s].{0,40}$")
.containsMatchIn(plain)
) return true
// 5) 阅读时长 / 字数统计
if (Regex("^(?:约?\\s*\\d+\\s*分钟(?:阅读)?|\\d+\\s*字(?:数)?|阅读\\s*\\d+|\\d+\\s*阅读)$")
.matches(plain)
) return true
// 6) 头像 / 二维码小图
if (Regex("^!\\[[^\\]]*\\]\\([^)]*(?:avatar|gravatar|qrcode)[^)]*\\)$", RegexOption.IGNORE_CASE)
.matches(line)
) return true
return false
}
/** 正文里与标题同名的一级标题直接删除 */
private fun removeRedundantH1(markdown: String, title: String): String {
if (title.isBlank()) return markdown
val t = title.lowercase()
val h1 = Regex("^#\\s+(.+)$")
return markdown.lines().filterNot { line ->
val m = h1.find(line.trim())
m != null && m.groupValues[1].trim().lowercase() == t
}.joinToString("\n")
}
/** 结尾的分隔线与「一串标签」行没有阅读价值 */
private fun stripTrailingNoise(markdown: String): String {
val s = markdown
.replace(Regex("(?:\\n\\s*(?:-{3,}|\\*{3,}|_{3,})\\s*)+$"), "")
.trimEnd()
val lines = s.lines().toMutableList()
while (lines.isNotEmpty()) {
val last = lines.last().trim()
if (last.isEmpty()) {
lines.removeAt(lines.size - 1)
continue
}
if (Regex("^(?:#[^\\s#]+\\s*){2,}$").matches(last)) {
lines.removeAt(lines.size - 1)
continue
}
break
}
return lines.joinToString("\n").trimEnd()
}
private fun String.ifNotBlank(): String? = takeIf { isNotBlank() }
/**
* ATX 标题 # 后补空格:CommonMark 要求 `#` 与文字之间必须有空格才会识别为标题,
* 站里常写成 `#标题`。代码块 / 行内代码先占位保护再还原,代码里的 # 不受影响。
*/
private fun ensureHeadingSpaces(md: String): String {
if (!md.contains('#')) return md
val blocks = mutableListOf<String>()
var s = Regex("```[\\s\\S]*?```").replace(md) { m ->
blocks.add(m.value); "\u0000K${blocks.size - 1}\u0000"
}
val inlines = mutableListOf<String>()
s = Regex("`[^`\\n]+`").replace(s) { m ->
inlines.add(m.value); "\u0000k${inlines.size - 1}\u0000"
}
s = Regex("(?m)^(#{1,6})([^#\\s])").replace(s) { m ->
"${m.groupValues[1]} ${m.groupValues[2]}"
}
inlines.forEachIndexed { i, b -> s = s.replace("\u0000k$i\u0000", b) }
blocks.forEachIndexed { i, b -> s = s.replace("\u0000K$i\u0000", b) }
return s
}
/**
* 轻量 HTML → Markdown:正文里混写的 HTML 标签不再裸露。
* 代码块 / 行内代码先占位保护,转换完再还原,避免代码里的 HTML 被误改。
*/
private fun htmlToMarkdownLite(html: String): String {
if (!html.contains('<')) return html
val blocks = mutableListOf<String>()
var s = Regex("```[\\s\\S]*?```").replace(html) { m ->
blocks.add(m.value); "\u0000B${blocks.size - 1}\u0000"
}
val inlines = mutableListOf<String>()
s = Regex("`[^`\\n]+`").replace(s) { m ->
inlines.add(m.value); "\u0000I${inlines.size - 1}\u0000"
}
// 注释先清掉
s = s.replace(Regex("<!--[\\s\\S]*?-->"), "")
// 引用块整块处理:逐行补 ">",否则引用只剩第一句带样式
s = Regex("<blockquote\\b[^>]*>([\\s\\S]*?)</blockquote\\s*>", RegexOption.IGNORE_CASE)
.replace(s) { m ->
val inner = m.groupValues[1]
.replace(Regex("</p\\s*>|<br\\s*/?>", RegexOption.IGNORE_CASE), "\n")
.replace(Regex("<[^>]*>"), "")
val quoted = inner.lines()
.map { it.trim() }
.filter { it.isNotEmpty() }
.joinToString("\n") { "> $it" }
if (quoted.isEmpty()) "" else "\n\n$quoted\n\n"
}
// img(转成 markdown 图片,独立成行的后面会转成铺满整行的大图)
s = Regex("<img\\b[^>]*>", RegexOption.IGNORE_CASE).replace(s) { m ->
val src = Regex("\\b(?:data-src|src)\\s*=\\s*['\"]([^'\"]+)['\"]", RegexOption.IGNORE_CASE)
.find(m.value)?.groupValues?.get(1).orEmpty()
val alt = Regex("alt\\s*=\\s*['\"]([^'\"]*)['\"]", RegexOption.IGNORE_CASE)
.find(m.value)?.groupValues?.get(1).orEmpty()
if (src.isBlank()) "" else "\n\n![$alt]($src)\n\n"
}
// 标题
for (i in 1..6) {
s = Regex("<h$i\\b[^>]*>([\\s\\S]*?)</h$i\\s*>", RegexOption.IGNORE_CASE)
.replace(s) { m -> "\n\n${"#".repeat(i)} ${m.groupValues[1].trim()}\n\n" }
}
// 有序列表先整块编号
s = Regex("<ol\\b[^>]*>([\\s\\S]*?)</ol\\s*>", RegexOption.IGNORE_CASE).replace(s) { m ->
var n = 0
val body = Regex("<li\\b[^>]*>([\\s\\S]*?)</li\\s*>", RegexOption.IGNORE_CASE)
.replace(m.groupValues[1]) { li ->
n++
"\n$n. " + li.groupValues[1]
}
"\n\n" + body.trim() + "\n\n"
}
// 无序列表:相邻项之间只留一个换行,列表才是紧凑的
s = s.replace(Regex("</li\\s*>\\s*<li\\b[^>]*>", RegexOption.IGNORE_CASE), "\n- ")
s = s.replace(Regex("<li\\b[^>]*>", RegexOption.IGNORE_CASE), "- ")
s = s.replace(Regex("</li\\s*>", RegexOption.IGNORE_CASE), "")
s = s.replace(Regex("</?ul\\b[^>]*>", RegexOption.IGNORE_CASE), "\n\n")
// 块级容器开合都算段落边界。只在 </p> 断段,<div> 分段的正文会被压成一坨
s = s.replace(
Regex("</(?:p|div|section|article|figure|figcaption|table|tr)\\s*>", RegexOption.IGNORE_CASE),
"\n\n",
)
s = s.replace(
Regex("<(?:p|div|section|article|figure|figcaption|table|tr|center)\\b[^>]*>", RegexOption.IGNORE_CASE),
"\n\n",
)
// 单个 <br> 是行内换行,用 CommonMark 的行尾反斜杠(双空格会被后面的空白清理吃掉)
s = s.replace(Regex("(?:<br\\s*/?>\\s*){2,}", RegexOption.IGNORE_CASE), "\n\n")
s = s.replace(Regex("<br\\s*/?>", RegexOption.IGNORE_CASE), "\\\n")
// 行内样式
s = s.replace(Regex("<(strong|b)\\b[^>]*>", RegexOption.IGNORE_CASE), "**")
.replace(Regex("</(strong|b)\\s*>", RegexOption.IGNORE_CASE), "**")
.replace(Regex("<(em|i)\\b[^>]*>", RegexOption.IGNORE_CASE), "*")
.replace(Regex("</(em|i)\\s*>", RegexOption.IGNORE_CASE), "*")
.replace(Regex("<blockquote\\b[^>]*>", RegexOption.IGNORE_CASE), "\n> ")
// 链接
s = Regex(
"<a\\b[^>]*href\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>([\\s\\S]*?)</a\\s*>",
RegexOption.IGNORE_CASE,
).replace(s) { m -> "[${m.groupValues[2]}](${m.groupValues[1]})" }
// 剩余未知标签一律剥掉(含自闭合),正文不再露出 <span> 之类
s = s.replace(Regex("</?[a-zA-Z][^>]*>"), "")
s = s.replace(Regex("\\n{3,}"), "\n\n")
// 还原代码块 / 行内代码
blocks.forEachIndexed { i, b -> s = s.replace("\u0000B$i\u0000", b) }
inlines.forEachIndexed { i, b -> s = s.replace("\u0000I$i\u0000", b) }
return s
}
/** 渲染:文字段走 Markwon,FlexPhoto 图组横排,独立图片铺满整行 */
private fun render(markdown: String) {
var raw = if (markdown.contains("<!--markdown-->")) markdown.replace("<!--markdown-->", "")
else markdown
// MyTrack 足迹地图短代码 {map-数字}:APP 端无法渲染,直接隐藏
raw = raw.replace(Regex("\\{map-\\d+\\}", RegexOption.IGNORE_CASE), "")
// 正文混写 HTML 支持:<p>/<br>/<img>/<strong>/<h2> 等转成 Markdown,其余标签剥掉
raw = htmlToMarkdownLite(raw)
// 站里标题常写成 "#标题"(# 后无空格,CommonMark 不识别),补上空格;代码块内不动
raw = ensureHeadingSpaces(raw)
var body = normalizeFlexTokens(raw)
// 收集文末引用定义行(站里的定义行带前导空格),供引用式图片解析
val refs = Regex("(?m)^\\s*\\[([^\\]]+)\\]:\\s*(\\S+)")
.findAll(body)
.associate { it.groupValues[1].trim() to it.groupValues[2].trim() }
// 单独成行的引用式图片 ![alt][id] → 铺满整行的图片
body = Regex("(?m)^\\s*!\\[([^\\]]*)\\]\\[([^\\]]*)\\]\\s*$").replace(body) { m ->
val key = m.groupValues[2].trim().ifEmpty { m.groupValues[1].trim() }
refs[key]?.let { "\n%%IMG%%\n$it\n%%/IMG%%\n" } ?: m.value
}
// 单独成行的内联式图片 ![alt](url) → 铺满整行的图片
body = Regex("(?m)^\\s*!\\[[^\\]]*\\]\\(\\s*([^)\\s]+?)(?:\\s+\"[^\"]*\")?\\s*\\)\\s*$")
.replace(body) { m -> "\n%%IMG%%\n${m.groupValues[1].trim()}\n%%/IMG%%\n" }
// 删掉引用定义行(文末 [1]: url 之类),不在正文里显示图片地址
body = body.replace(Regex("(?m)^\\s*\\[[^\\]]+\\]:\\s*\\S+.*$"), "")
bodyContainer.removeAllViews()
val tokenRe = Regex("%%(FLEXP|IMG)%%\\s*([\\s\\S]*?)\\s*%%/\\1%%")
var last = 0
for (m in tokenRe.findAll(body)) {
addTextSegment(body.substring(last, m.range.first).trim())
val urls = m.groupValues[2].lines().map { it.trim() }.filter { it.isNotEmpty() }
when (m.groupValues[1]) {
"IMG" -> urls.forEach { addFullImage(it) }
else -> if (urls.isNotEmpty()) addFlexPhotoRow(urls)
}
last = m.range.last + 1
}
addTextSegment(body.substring(last).trim())
}
private fun addTextSegment(text: String) {
if (text.isBlank()) return
val tv = TextView(this).apply {
textSize = 15f
setTextColor(ContextCompat.getColor(context, R.color.text))
// 正文字距放宽一点:15sp 的中文正文按 1.0 行距排,段落一多就糊成一片
setLineSpacing(dp(7).toFloat(), 1.25f)
movementMethod = LinkMovementMethod.getInstance()
}
markwon.setMarkdown(tv, text)
bodyContainer.addView(
tv,
LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
).apply { topMargin = dp(10) },
)
}
/**
* FlexPhoto 图组:N 张图按各自宽高比分摊整行宽度,正好铺满一行——
* 2 张各占一半、3 张各占三分之一、单张自然占满整行;
* 图片全部加载完后统一排版,点击任意一张全屏放大。
*/
private fun addFlexPhotoRow(urls: List<String>) {
val resolved = urls.map { resolveUrl(it) }
val gap = dp(8)
val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
val views = resolved.map { _ ->
ImageView(this).apply {
scaleType = ImageView.ScaleType.FIT_CENTER
setBackgroundColor(ContextCompat.getColor(context, R.color.segment_track))
outlineProvider = RoundedOutline(dp(10))
clipToOutline = true
layoutParams = LinearLayout.LayoutParams(0, dp(120), 1f).apply {
marginEnd = gap
}
row.addView(this)
}
}
(views.last().layoutParams as LinearLayout.LayoutParams).marginEnd = 0
bodyContainer.addView(
row,
LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
).apply { topMargin = dp(10) },
)
// 拿到全部图片后按宽高比分摊:总宽 = rowW,共用高度 = (rowW - 间距) / 宽高比之和
val bitmaps = arrayOfNulls<Bitmap>(resolved.size)
var pending = resolved.size
fun relayout() {
val rowW = row.width.takeIf { it > 0 } ?: return
val aspects = bitmaps.map { b ->
if (b != null && b.height > 0) b.width.toFloat() / b.height else 1f
}
val h = ((rowW - gap * (resolved.size - 1)) / aspects.sum())
.toInt().coerceAtLeast(dp(80)).coerceAtMost(rowW * 2)
resolved.forEachIndexed { i, _ ->
views[i].layoutParams = LinearLayout.LayoutParams(
(aspects[i] * h).toInt().coerceAtLeast(dp(40)),
h,
).apply { if (i < resolved.size - 1) marginEnd = gap }
}
row.requestLayout()
}
resolved.forEachIndexed { index, url ->
val iv = views[index]
iv.tag = url
iv.setOnClickListener { showZoomDialog(resolved, index) }
loadThumb(url, iv, resources.displayMetrics.widthPixels) { bmp ->
bitmaps[index] = bmp
pending--
if (pending == 0) row.post { relayout() }
}
}
}
private fun dp(v: Int): Int = (v * resources.displayMetrics.density).toInt()
/** 独立图片:铺满整行、高度按图片比例,点击放大 */
private fun addFullImage(url: String) {
val resolved = resolveUrl(url)
val iv = ImageView(this).apply {
scaleType = ImageView.ScaleType.FIT_CENTER
setBackgroundColor(ContextCompat.getColor(context, R.color.segment_track))
setOnClickListener { showZoomDialog(listOf(resolved), 0) }
}
bodyContainer.addView(
iv,
LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
).apply { topMargin = dp(10) },
)
loadFullWidth(resolved, iv)
}
private fun loadFullWidth(url: String, view: ImageView) {
view.tag = url
// "w:" 前缀表示正文宽度规格,与缩略图、全屏图各自独立的键
val key = "w:$url"
synchronized(cacheLock) { thumbCache.get(key) }?.let { applyFullBitmap(view, it); return }
lifecycleScope.launch {
val screenW = resources.displayMetrics.widthPixels - dp(32)
val bmp = withContext(Dispatchers.IO) { fetchBitmap(url, screenW / 2) } ?: return@launch
synchronized(cacheLock) { thumbCache.put(key, bmp) }
if (view.tag == url) applyFullBitmap(view, bmp)
}
}
private fun applyFullBitmap(view: ImageView, bmp: Bitmap) {
view.setImageBitmap(bmp)
val w = resources.displayMetrics.widthPixels - dp(32)
val h = (w.toFloat() * bmp.height / bmp.width).toInt().coerceAtMost(dp(2400))
view.layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
h,
).apply { topMargin = dp(10) }
view.requestLayout()
}
private class RoundedOutline(private val radius: Int) : ViewOutlineProvider() {
override fun getOutline(view: View, outline: Outline) {
outline.setRoundRect(0, 0, view.width, view.height, radius.toFloat())
}
}
/** 相对地址补全成绝对地址(uploads 图片常以 / 开头) */
private fun resolveUrl(url: String): String = when {
url.startsWith("http://") || url.startsWith("https://") -> url
url.startsWith("//") -> "https:$url"
originalUrl.isNotBlank() -> runCatching {
java.net.URL(java.net.URL(originalUrl), url).toString()
}.getOrDefault(url)
else -> url
}
// ---- 图片加载:内存缓存 + 后台解码 ----
/**
* 按字节限额而不是按张数:旧实现 thumbCache 限 64 张、fullCache 限 8 张,
* 一张 4000px 的图解码后可达 48MB,64 张上限在低端机上必然 OOM。
* 这里取可用堆的 1/16 与 1/32(合计约 9%);上一版是 1/8 + 1/16(18.75%),
* 对 256MB 堆的机器仍留了太多余量,收窄后宁可多解一次也不要把堆吃满。
*/
private val thumbBudget = (Runtime.getRuntime().maxMemory() / 16).toInt()
private val fullBudget = (Runtime.getRuntime().maxMemory() / 32).toInt()
private val thumbCache = object : LruCache<String, Bitmap>(thumbBudget) {
override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount
}
private val fullCache = object : LruCache<String, Bitmap>(fullBudget) {
override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount
}
private val cacheLock = Any()
private fun loadThumb(url: String, view: ImageView, sizePx: Int, onLoaded: ((Bitmap?) -> Unit)? = null) {
view.tag = url
// 键里带尺寸:同一张图会按缩略图、正文宽度两种规格各解一次,
// 共用一个键会让正文图命中缩略图(放大后发虚),或缩略图命中大图(白占内存)。
val key = "t$sizePx:$url"
val cached = synchronized(cacheLock) { thumbCache.get(key) }
if (cached != null) {
view.setImageBitmap(cached)
onLoaded?.invoke(cached)
return
}
lifecycleScope.launch {
val bmp = withContext(Dispatchers.IO) { fetchBitmap(url, sizePx) }
if (bmp != null) synchronized(cacheLock) { thumbCache.put(key, bmp) }
if (view.tag == url && bmp != null) view.setImageBitmap(bmp)
onLoaded?.invoke(bmp)
}
}
/** targetSize > 0 时按长边降采样解码;0 表示不采样(仍受调用方尺寸约束) */
private fun fetchBitmap(url: String, targetSize: Int): Bitmap? = runCatching {
val request = Request.Builder()
.url(url)
.header("User-Agent", RssApi.UA_BROWSER)
.build()
imageClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) return@runCatching null
val bytes = response.body?.bytes() ?: return@runCatching null
val opts = BitmapFactory.Options().apply {
if (targetSize > 0) {
inJustDecodeBounds = true
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, this)
inJustDecodeBounds = false
var sample = 1
// 按长边判断:竖长图若同时要求宽高都达标,会采样不足直接爆内存
while (maxOf(outWidth, outHeight) / (sample * 2) >= targetSize) {
sample *= 2
}
inSampleSize = sample
}
}
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)
}
}.getOrNull()
private fun showZoomDialog(urls: List<String>, index: Int) {
val dialog = Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen)
val zoom = ZoomableImageView(this) { dialog.dismiss() }
zoom.setBackgroundColor(Color.BLACK)
dialog.setContentView(
zoom,
ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
),
)
dialog.show()
val url = urls[index]
// 全屏查看按屏幕长边采样即可;原实现 targetSize=0 解原图,
// 一张 4000×3000 的照片就是 48MB,连开两张低端机必崩。
val metrics = resources.displayMetrics
val zoomTarget = maxOf(metrics.widthPixels, metrics.heightPixels)
// 全屏图单独一个 "z:" 键:正文宽度图是降采样的,直接拿去放大一定发虚
val cacheKey = "z:$url"
lifecycleScope.launch {
val bmp = withContext(Dispatchers.IO) {
synchronized(cacheLock) { fullCache.get(cacheKey) }
?: fetchBitmap(url, zoomTarget)
?.also { synchronized(cacheLock) { fullCache.put(cacheKey, it) } }
}
if (isFinishing || isDestroyed) return@launch
if (bmp == null) {
dialog.dismiss()
toast("图片加载失败")
} else {
zoom.setBitmap(bmp)
}
}
}
/**
* FlexPhoto 多种形态统一转 token:
* 1) 原始 markdown:{flex ...} 组内可能是 Markdown 图片(含引用式 ![x][1])、HTML img
* 2) 服务端渲染:RssApi 已转 token,这里兜底漏网的 flexphoto div
*/
private fun normalizeFlexTokens(markdown: String): String {
val imgRe = Regex("<img\\b[^>]*>", RegexOption.IGNORE_CASE)
val srcRe = Regex("\\b(?:data-src|src)\\s*=\\s*['\"]([^'\"]+)['\"]", RegexOption.IGNORE_CASE)
// 内联式 markdown 图片:![alt](url) / ![alt](url "title")
val mdImgRe = Regex("!\\[[^\\]]*\\]\\(\\s*([^)\\s]+?)(?:\\s+\"[^\"]*\")?\\s*\\)")
// 引用式 markdown 图片:![alt][id],地址在文末 [id]: url 定义行(站里的定义行带前导空格)
val refImgRe = Regex("!\\[([^\\]]*)\\]\\[([^\\]]*)\\]")
val refDefRe = Regex("(?m)^\\s*\\[([^\\]]+)\\]:\\s*(\\S+)")
val refs = refDefRe.findAll(markdown)
.associate { it.groupValues[1].trim() to it.groupValues[2].trim() }
fun toToken(fragment: String): String {
val urls = mutableListOf<String>()
imgRe.findAll(fragment).forEach { img ->
srcRe.find(img.value)?.groupValues?.get(1)?.trim()
?.takeIf { it.isNotEmpty() }?.let { urls.add(it) }
}
mdImgRe.findAll(fragment).forEach { m ->
val u = m.groupValues[1].trim()
if (u.isNotEmpty()) urls.add(u)
}
refImgRe.findAll(fragment).forEach { m ->
val key = m.groupValues[2].trim().ifEmpty { m.groupValues[1].trim() }
refs[key]?.let { urls.add(it) }
}
if (urls.isNotEmpty()) {
return "\n%%FLEXP%%\n" + urls.joinToString("\n") + "\n%%/FLEXP%%\n"
}
// 兜底:任何形态都解析不到地址时不再整组删除,
// 去掉 flex 标记保留原文,图片至少能以竖排显示
val kept = fragment.trim()
return if (kept.isBlank()) "" else "\n$kept\n"
}
var s = markdown
s = Regex(
"<div[^>]*class=\"[^\"]*flexphoto[^\"]*\"[^>]*>[\\s\\S]*?</div>",
RegexOption.IGNORE_CASE,
).replace(s) { m -> toToken(m.value) }
s = Regex("\\{flex[^{}]*\\}([\\s\\S]*?)\\{/flex\\}", RegexOption.IGNORE_CASE)
.replace(s) { m -> toToken(m.groupValues[1]) }
s = Regex("\\{flex[^{}]*\\}([\\s\\S]*?)/flex\\}", RegexOption.IGNORE_CASE)
.replace(s) { m -> toToken(m.groupValues[1]) }
return s
}
private fun formatDate(ts: Long): String {
val seconds = if (ts > 1_000_000_000_000L) ts / 1000 else ts
return SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date(seconds * 1000))
}
private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}