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

1071 lines
46 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.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.ViewOutlineProvider
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.PopupWindow
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 btnMore: TextView
private lateinit var briefCard: LinearLayout
private lateinit var tvBriefTitle: TextView
private lateinit var tvBriefBody: TextView
private lateinit var briefTagScroll: View
private lateinit var briefTags: LinearLayout
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
/** 来源站点信息:作者主页按站点过滤,并用站点首页做「打开网站」 */
private var siteUrl: String = ""
private var urlId: Long = 0L
/** 条目自带的标签(服务端就有),AI 没给标签时用它兜底 */
private var itemTags: List<String> = emptyList()
/** 摘要缓存键:同类内容 id 可能撞号,所以带 kind 前缀 */
private var briefKey: String = ""
private var briefRequesting = false
private var briefBody: String = ""
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"
private const val EXTRA_TAGS = "tags"
private const val EXTRA_URL_ID = "url_id"
private const val EXTRA_SITE_URL = "site_url"
/** 正文短于这么多字就不必麻烦 AI 了 */
private const val BRIEF_MIN_CHARS = 200
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,
tags: List<String> = emptyList(),
urlId: Long = 0L,
siteUrl: 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)
putStringArrayListExtra(EXTRA_TAGS, ArrayList(tags))
putExtra(EXTRA_URL_ID, urlId)
putExtra(EXTRA_SITE_URL, siteUrl)
}
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)
btnMore = findViewById(R.id.btnReaderMore)
briefCard = findViewById(R.id.briefCard)
tvBriefTitle = findViewById(R.id.tvBriefTitle)
tvBriefBody = findViewById(R.id.tvBriefBody)
briefTagScroll = findViewById(R.id.briefTagScroll)
briefTags = findViewById(R.id.briefTags)
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()
itemTags = intent.getStringArrayListExtra(EXTRA_TAGS).orEmpty().filter { it.isNotBlank() }
urlId = intent.getLongExtra(EXTRA_URL_ID, 0L)
siteUrl = intent.getStringExtra(EXTRA_SITE_URL).orEmpty()
briefKey = if (id.isNotBlank()) "$kind:$id" else "$kind:${originalUrl.hashCode()}"
tvTitle.text = title.ifBlank { getString(R.string.reader_untitled) }
metaSource = source
metaDate = date
renderMeta()
findViewById<ImageView>(R.id.btnReaderBack).setOnClickListener { finish() }
btnMore.setOnClickListener { showMoreMenu(it) }
when (kind) {
KIND_ARTICLE -> loadArticle(id, preloaded)
KIND_RSS -> loadRss(preloaded)
else -> renderWithBrief(preloaded.ifBlank { "(empty)" })
}
}
private fun loadArticle(cid: String, preloaded: String) {
if (preloaded.isNotBlank()) {
renderWithBrief(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
renderWithBrief(detail.markdown.ifBlank { detail.text })
} catch (e: Exception) {
render("读取文章失败:${e.message ?: "未知错误"}")
} finally {
progress.visibility = TextView.GONE
}
}
}
private fun loadRss(excerpt: String) {
if (originalUrl.isBlank()) {
renderWithBrief(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 })
renderWithBrief(body.ifBlank { excerpt.ifBlank { "(原文里没有抓到正文)" } })
} catch (e: Exception) {
// 抓不到原文时用站端摘要兜底,至少能读个大概
renderWithBrief(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
}
// ==================== 顶栏「更多」菜单 ====================
/**
* 「更多」下拉:查看原文、作者主页。
*
* 原来顶栏只有一个「查看原文」按钮,加作者主页后排不下两个入口,
* 于是收进这个菜单;没有原文链接时该项直接不出现,不留一个点了会报错的项。
*/
private fun showMoreMenu(anchor: View) {
val entries = ArrayList<String>()
val actions = ArrayList<() -> Unit>()
if (originalUrl.isNotBlank()) {
entries.add(getString(R.string.open_original))
actions.add { openOriginal() }
}
entries.add(getString(R.string.author_page))
actions.add { openAuthorPage() }
if (entries.isEmpty()) return
val palette = Ui.popupPalette(this)
val listView = ListView(this).apply {
adapter = ArrayAdapter(this@ReaderActivity, R.layout.item_dropdown_center, entries)
dividerHeight = 0
setPadding(0, dp(6), 0, dp(6))
scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
}
val popupW = Ui.menuWidth(this, entries, textSizeSp = 13f, extraDp = 52, minDp = 120, maxDp = 240)
val popupH = entries.size * dp(46) + dp(12)
val popup = PopupWindow(listView, popupW, popupH, true).apply {
isOutsideTouchable = true
setBackgroundDrawable(palette.background())
elevation = dp(8).toFloat()
}
listView.setOnItemClickListener { _, _, position, _ ->
popup.dismiss()
actions.getOrNull(position)?.invoke()
}
// 按钮在右上角、下沿还有空间:贴着按钮下方展开,右边缘对齐
val loc = IntArray(2)
val rootLoc = IntArray(2)
anchor.getLocationOnScreen(loc)
anchor.rootView.getLocationOnScreen(rootLoc)
val x = (loc[0] - rootLoc[0] + anchor.width - popupW)
.coerceIn(dp(8), (anchor.rootView.width - popupW - dp(8)).coerceAtLeast(dp(8)))
popup.showAtLocation(
anchor.rootView,
Gravity.TOP or Gravity.START,
x,
loc[1] - rootLoc[1] + anchor.height + dp(4),
)
}
private fun openOriginal() {
if (originalUrl.isBlank()) {
toast("这条内容没有原文链接")
return
}
runCatching {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(originalUrl)))
}.onFailure { toast("打不开浏览器") }
}
/**
* 作者主页:按来源站点列出该作者(站点)的文章。
*
* 服务端条目没有 author 字段、接口也没有 author 参数,而这类"作者主页"基本都是
* 个人博客——一个站点就是一位作者,所以按站点 id 过滤,头部再标出网站名称与收录数量。
* 作者名取不到时退回网站名,仍能进到站点文章列表。
*/
private fun openAuthorPage() {
val site = siteName()
val author = metaAuthor.ifBlank { site }
if (author.isBlank()) {
toast("这条内容没有作者信息")
return
}
ArticleListActivity.openAuthor(this, author, site, siteUrl, urlId)
}
/** 站点名:优先 RSS 条目带的 siteTitle,其次从原文地址里取域名 */
private fun siteName(): String = metaSource.ifBlank { hostOf(originalUrl) }
private fun hostOf(url: String): String = runCatching {
java.net.URI(url).host.orEmpty().removePrefix("www.")
}.getOrDefault("")
// ==================== AI 摘要 + 标签 ====================
/** 先出正文,再补摘要:摘要是增强,不能挡住阅读 */
private fun renderWithBrief(markdown: String) {
render(markdown)
setupBrief(markdown)
}
private fun setupBrief(body: String) {
briefBody = body
// 没配 Key 就只显示条目自带标签,摘要位不占
if (!prefs.aiReady || plainLength(body) < BRIEF_MIN_CHARS) {
showTagsOnly()
return
}
prefs.getBrief(briefKey)?.let { cached ->
showBrief(cached.summary, mergeTags(cached.tags))
return
}
requestBrief()
}
/** 摘要看重的是文字量,图片(含 %%IMG%% token)与标签不计入 */
private fun plainLength(body: String): Int = body
.replace(Regex("%%(?:IMG|FLEXP)%%[\\s\\S]*?%%/(?:IMG|FLEXP)%%"), " ")
.replace(Regex("!\\[[^\\]]*\\]\\([^)]*\\)"), "")
.replace(Regex("<[^>]*>"), "")
.trim()
.length
/** AI 给的标签优先,再并上条目自带的,去重后最多 8 个 */
private fun mergeTags(aiTags: List<String>): List<String> {
val out = ArrayList<String>()
(aiTags + itemTags).forEach { raw ->
val tag = raw.trim().removePrefix("#").trim()
if (tag.isEmpty() || tag.length > 14) return@forEach
if (out.none { it.equals(tag, true) }) out.add(tag)
}
return out.take(8)
}
private fun requestBrief() {
if (briefRequesting) return
briefRequesting = true
briefCard.visibility = View.VISIBLE
tvBriefTitle.text = getString(R.string.ai_summary)
tvBriefBody.visibility = View.VISIBLE
tvBriefBody.setTextColor(ContextCompat.getColor(this, R.color.text_secondary))
tvBriefBody.text = getString(R.string.ai_summary_loading)
tvBriefBody.setOnClickListener(null)
briefTagScroll.visibility = View.GONE
lifecycleScope.launch {
try {
val brief = withContext(Dispatchers.IO) {
AiApi.brief(prefs, tvTitle.text.toString(), briefBody)
}
if (isFinishing || isDestroyed) return@launch
prefs.putBrief(briefKey, brief)
showBrief(brief.summary, mergeTags(brief.tags))
} catch (e: Exception) {
if (isFinishing || isDestroyed) return@launch
showBriefError(e.message.orEmpty())
} finally {
briefRequesting = false
}
}
}
private fun showBrief(summary: String, tags: List<String>) {
briefCard.visibility = View.VISIBLE
tvBriefTitle.text = getString(R.string.ai_summary)
tvBriefBody.visibility = View.VISIBLE
tvBriefBody.setTextColor(ContextCompat.getColor(this, R.color.text_secondary))
tvBriefBody.text = summary
tvBriefBody.setOnClickListener(null)
renderTags(tags)
}
/** 失败时不留空白卡:有标签就只显示标签,点文字可重试 */
private fun showBriefError(message: String) {
briefCard.visibility = View.VISIBLE
tvBriefTitle.text = getString(R.string.ai_summary)
tvBriefBody.visibility = View.VISIBLE
tvBriefBody.setTextColor(ContextCompat.getColor(this, R.color.brand))
tvBriefBody.text = if (message.isBlank()) getString(R.string.ai_summary_failed)
else getString(R.string.ai_summary_failed_reason, message)
tvBriefBody.setOnClickListener { requestBrief() }
renderTags(mergeTags(emptyList()))
}
private fun showTagsOnly() {
val tags = mergeTags(emptyList())
if (tags.isEmpty()) {
briefCard.visibility = View.GONE
return
}
briefCard.visibility = View.VISIBLE
tvBriefTitle.text = getString(R.string.article_tags)
tvBriefBody.visibility = View.GONE
tvBriefBody.setOnClickListener(null)
renderTags(tags)
}
/** 标签 chip 横排,点任意一个按该标签浏览 */
private fun renderTags(tags: List<String>) {
briefTags.removeAllViews()
if (tags.isEmpty()) {
briefTagScroll.visibility = View.GONE
return
}
briefTagScroll.visibility = View.VISIBLE
tags.forEach { tag ->
val chip = TextView(this).apply {
text = "#$tag"
textSize = 11.5f
setTextColor(ContextCompat.getColor(context, R.color.brand))
background = ContextCompat.getDrawable(context, R.drawable.bg_brand_soft)
setPadding(dp(10), dp(4), dp(10), dp(5))
isClickable = true
setOnClickListener {
ArticleListActivity.openTag(this@ReaderActivity, tag)
}
}
briefTags.addView(
chip,
LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
).apply { marginEnd = dp(8) },
)
}
}
/**
* 正文开头的重复信息全部剥掉。
*
* 原文页面的 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
}
/** 列表行(无序 / 有序),用于判断两行之间该不该留空行 */
private fun isListLine(line: String): Boolean =
line.startsWith("- ") || line.startsWith("* ") || line.startsWith("+ ") ||
Regex("^\\d+[.)]\\s").containsMatchIn(line)
/**
* 空行收尾。
*
* Markwon 把每个空行都当成块边界(并叠加 blockMargin),所以「空两行」在阅读页
* 会变成明显的空白段,读起来一句一断。多余空行有三个来源:
* 1. `</div><br><p>` 这类相邻写法会还原出一行只有反斜杠的硬换行标记;
* 2. 块闭合之间夹着源码空白,形成「带空格的空行」,`\n{3,}` 正则匹配不到;
* 3. 列表项之间留空行,Markwon 按松散列表把行距整体放大。
*
* 缩进 4 空格以上的行原样保留(Typecho 正文里的缩进代码块 / 子列表靠它),
* 围栏代码块内也原样保留。
*/
private fun tidyBlank(src: String): String {
val out = ArrayList<String>(src.length / 8 + 8)
var inFence = false
var pendingBlank = false
src.lines().forEach { rawLine ->
val line = rawLine.trimEnd()
val bare = line.trimStart()
if (bare.startsWith("```")) {
inFence = !inFence
if (pendingBlank && out.isNotEmpty()) out.add("")
pendingBlank = false
out.add(bare)
return@forEach
}
if (inFence) {
out.add(line)
return@forEach
}
val text = line.trim()
if (text.isEmpty() || text == "\\") {
if (out.isNotEmpty()) pendingBlank = true
return@forEach
}
if (pendingBlank) {
val prev = out.lastOrNull().orEmpty()
if (!(isListLine(prev) && isListLine(text))) out.add("")
pendingBlank = false
}
val indent = line.length - bare.length
// 缩进代码块/子列表保缩进;其余按源码缩进剥掉,避免被当成代码块
out.add(if (indent >= 4) line else text)
}
return out.joinToString("\n").trim()
}
/** 渲染:文字段走 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)
// 空行收尾:Markwon 把每个空行都当块边界,空行一多就成了「一句一断」
raw = tidyBlank(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 {
// 正文 16sp + 1.4 倍行高:中文长文按 15sp/1.25 排,段落一多就糊成一片
textSize = 16f
setTextColor(ContextCompat.getColor(context, R.color.text))
setLineSpacing(dp(4).toFloat(), 1.4f)
movementMethod = LinkMovementMethod.getInstance()
}
markwon.setMarkdown(tv, text)
bodyContainer.addView(
tv,
LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
).apply { topMargin = dp(8) },
)
}
/**
* 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(8) },
)
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()
}