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]*>([\\s\\S]*?)
", RegexOption.IGNORE_CASE)
.replace(s) { m ->
val inner = m.groupValues[1]
.replace(Regex("
]*>", RegexOption.IGNORE_CASE), "\n> ") // 链接 s = Regex( "]*href\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>([\\s\\S]*?)", RegexOption.IGNORE_CASE, ).replace(s) { m -> "[${m.groupValues[2]}](${m.groupValues[1]})" } // 剩余未知标签一律剥掉(含自闭合),正文不再露出 之类 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.replace("", "") else markdown // MyTrack 足迹地图短代码 {map-数字}:APP 端无法渲染,直接隐藏 raw = raw.replace(Regex("\\{map-\\d+\\}", RegexOption.IGNORE_CASE), "") // 正文混写 HTML 支持:/
///
等转成 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 } // 单独成行的内联式图片  → 铺满整行的图片 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
) { 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 (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 (thumbBudget) { override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount } private val fullCache = object : LruCache (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 , 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(" ]*>", RegexOption.IGNORE_CASE) val srcRe = Regex("\\b(?:data-src|src)\\s*=\\s*['\"]([^'\"]+)['\"]", RegexOption.IGNORE_CASE) // 内联式 markdown 图片: /  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
() 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( " ]*class=\"[^\"]*flexphoto[^\"]*\"[^>]*>[\\s\\S]*?", 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() }