commit d959ffed68fa0a025ce1253575b62e85bc174321
Author: XIGE <710062962@qq.com>
Date: Thu Nov 26 15:04:58 2026 +0800
同步插件源代码并补齐标准项目文件
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..40fbae9
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,29 @@
+# Dependencies and build output
+node_modules/
+vendor/
+dist/
+build/
+out/
+main.js
+*.apk
+
+# Build tools and IDE
+.gradle/
+.idea/
+*.iml
+gradle/
+gradlew
+gradlew.bat
+
+# Environment and secrets
+.env
+.env.*
+keystore.properties
+*.jks
+credentials*.json
+
+# Runtime data and backups
+data/
+备份/
+*.log
+.DS_Store
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..a90ef58
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,7 @@
+# 变更记录
+
+## 2026-11-26 · 初始同步
+
+- 同步插件源代码到新 Gitea 仓库。
+- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。
+- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..6ed8c08
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,19 @@
+# 贡献指南
+
+欢迎对本插件提出改进建议或提交代码。
+
+## 提交前检查
+
+- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。
+- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。
+- 涉及对外服务或凭据的配置不要写入代码或文档。
+
+## 提交流程
+
+1. Fork 仓库并创建功能分支。
+2. 完成修改后提交 Pull Request,说明改动目的与影响范围。
+3. 重要功能变更请同步更新 `CHANGELOG.md`。
+
+## 问题反馈
+
+请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..68e8c20
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 石头厝 / XIGE
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..c8fc532
--- /dev/null
+++ b/README.md
@@ -0,0 +1,28 @@
+# PostPad(石头厝)
+
+> 仓库:`PostPad` · 类型:Android 应用 · 版本:`3.33` · 作者:石头厝 / XIGE
+
+自用安卓小工具:信息(RSS / 文章 / Memos)、发布(文章 / 微博)、邮件。
+
+本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。
+
+## 目录结构
+
+- `src/`
+
+## 安装与使用
+
+1. Android 源码位于 `app/src/`,按 Android 项目结构导入开发环境。
+2. 构建配置、签名密钥与依赖不在本仓库内,请按自有环境配置后构建安装。
+
+## 开发与贡献
+
+详见 [CONTRIBUTING.md](CONTRIBUTING.md)。
+
+## 授权
+
+授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。
+
+## 变更记录
+
+详见 [CHANGELOG.md](CHANGELOG.md)。
diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..5fe56ea
--- /dev/null
+++ b/src/main/AndroidManifest.xml
@@ -0,0 +1,61 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/java/com/shitoucuo/postpad/AiApi.kt b/src/main/java/com/shitoucuo/postpad/AiApi.kt
new file mode 100644
index 0000000..b01708b
--- /dev/null
+++ b/src/main/java/com/shitoucuo/postpad/AiApi.kt
@@ -0,0 +1,164 @@
+package com.shitoucuo.postpad
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import org.json.JSONArray
+import org.json.JSONObject
+import java.util.concurrent.TimeUnit
+
+/**
+ * 润色 / 完善用的 AI 调用。
+ *
+ * 走的是 AIAssist 插件同一家的对话接口(DeepSeek / 智谱),请求体就是标准的
+ * OpenAI 兼容格式:{model, messages[], stream:false}。
+ * 之所以在本地直接调、不复用插件的 /aiassist-analyze:
+ * 那个端点按 cid 取已发布文章的正文,草稿在提交前还没有 cid,拿不到。
+ * 这里填的 Key 与插件设置里的一致,模型也一样,效果等同插件的「润文」。
+ */
+object AiApi {
+
+ const val PROVIDER_DEEPSEEK = "deepseek"
+ const val PROVIDER_ZHIPU = "zhipu"
+
+ const val MODE_POLISH = "polish"
+ const val MODE_EXPAND = "expand"
+
+ /** 单次提交的字数上限:再长模型容易把结尾截掉,不如按住提示用户分段 */
+ const val MAX_INPUT = 12000
+
+ private val JSON = "application/json; charset=utf-8".toMediaType()
+
+ /** AI 生成慢,读超时给足;发布与上传用的是另外的 client */
+ private val client: OkHttpClient = Http.newWith(20, 60, 300, TimeUnit.SECONDS)
+
+ class ApiException(message: String, val code: Int = 0) : Exception(message)
+
+ /** 「润色」只改错:错别字、病句、标点,别的一律不动 */
+ private const val POLISH_PROMPT =
+ "你是中文文字编辑,只做校对。任务:修正错别字、错误用词、病句和标点,删掉重复的字词," +
+ "让句子读起来通顺。要求:不改变原意,不改写作者的表达风格,不增删内容,不加总结或点评," +
+ "不做文学加工。必须完整保留 Markdown 语法(标题 #、列表 -、引用 >、代码 ```、加粗 **、" +
+ "链接与图片 )以及图片地址,原样不动。保留原有段落划分与顺序。" +
+ "只输出修改后的全文,不要任何解释、前言或后缀。"
+
+ /** 「完善」在原意不变的前提下扩写补充 */
+ private const val EXPAND_PROMPT =
+ "你是中文写作助手。任务:在保持原意、观点、立场和段落顺序不变的前提下,把文章补充完整。" +
+ "具体做法:把过于简略的地方展开,补上必要的细节、背景、原因与过渡句;" +
+ "把口语化的碎片句子整理成通顺的复句;段落之间缺衔接的补上衔接。" +
+ "篇幅控制在原文的 1.3 到 1.6 倍,不要注水,不要重复啰嗦,不要编造事实、数字和人名。" +
+ "必须完整保留 Markdown 语法与图片  的写法、地址和位置,图片一行都不能丢。" +
+ "保留第一人称与作者语气。只输出完整正文,不要任何解释、前言或后缀。"
+
+ /**
+ * 执行一次改写。
+ *
+ * @param text 原文(调用方负责长度校验)
+ * @param mode [MODE_POLISH] 或 [MODE_EXPAND]
+ * @return 改写后的全文
+ */
+ suspend fun run(prefs: Prefs, text: String, mode: String): String =
+ withContext(Dispatchers.IO) {
+ val key = prefs.aiKey
+ if (key.isEmpty()) {
+ throw ApiException("还没填 AI Key,先到设置里填一下")
+ }
+
+ val provider = prefs.aiProvider
+ val endpoint: String
+ val defaultModel: String
+ when (provider) {
+ PROVIDER_ZHIPU -> {
+ endpoint = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
+ defaultModel = "glm-4-flash"
+ }
+ else -> {
+ endpoint = "https://api.deepseek.com/chat/completions"
+ defaultModel = "deepseek-chat"
+ }
+ }
+ val model = prefs.aiModel.ifEmpty { defaultModel }
+
+ val messages = JSONArray().apply {
+ put(JSONObject().apply {
+ put("role", "system")
+ put("content", if (mode == MODE_POLISH) POLISH_PROMPT else EXPAND_PROMPT)
+ })
+ put(JSONObject().apply {
+ put("role", "user")
+ put("content", text)
+ })
+ }
+
+ val payload = JSONObject().apply {
+ put("model", model)
+ put("messages", messages)
+ put("stream", false)
+ // 校对要稳定,扩写允许一点发挥
+ put("temperature", if (mode == MODE_POLISH) 0.2 else 0.7)
+ put("max_tokens", 8192)
+ }
+
+ val request = Request.Builder()
+ .url(endpoint)
+ .header("Authorization", "Bearer $key")
+ .header("Accept", "application/json")
+ .post(payload.toString().toRequestBody(JSON))
+ .build()
+
+ client.newCall(request).execute().use { response ->
+ val body = response.body?.string().orEmpty()
+ if (!response.isSuccessful) {
+ throw ApiException(friendlyMessage(response.code, body), response.code)
+ }
+
+ val json = try {
+ JSONObject(body)
+ } catch (e: Exception) {
+ throw ApiException("AI 返回的不是 JSON,稍后再试")
+ }
+
+ val content = json.optJSONArray("choices")
+ ?.optJSONObject(0)
+ ?.optJSONObject("message")
+ ?.optString("content")
+ .orEmpty()
+ .trim()
+
+ if (content.isEmpty()) {
+ val finish = json.optJSONArray("choices")
+ ?.optJSONObject(0)
+ ?.optString("finish_reason")
+ .orEmpty()
+ throw ApiException(
+ if (finish == "length") "内容太长,AI 输出被截断了,试着分段处理"
+ else "AI 没有返回内容,稍后再试"
+ )
+ }
+ content
+ }
+ }
+
+ private fun friendlyMessage(code: Int, body: String): String {
+ val detail = try {
+ val json = JSONObject(body)
+ json.optJSONObject("error")?.optString("message").orEmpty()
+ .ifBlank { json.optString("message") }
+ } catch (e: Exception) {
+ body.replace(Regex("<[^>]*>"), " ").replace(Regex("\\s+"), " ").trim().take(120)
+ }
+
+ val prefix = when (code) {
+ 401 -> "AI Key 无效或已过期"
+ 402 -> "AI 账户余额不足"
+ 429 -> "请求太频繁,稍等一会儿再点"
+ 400 -> "请求被拒绝(模型名可能不对)"
+ else -> "HTTP $code"
+ }
+ return if (detail.isBlank()) prefix else "$prefix:$detail"
+ }
+}
diff --git a/src/main/java/com/shitoucuo/postpad/FeedAdapter.kt b/src/main/java/com/shitoucuo/postpad/FeedAdapter.kt
new file mode 100644
index 0000000..07005df
--- /dev/null
+++ b/src/main/java/com/shitoucuo/postpad/FeedAdapter.kt
@@ -0,0 +1,831 @@
+package com.shitoucuo.postpad
+
+import android.content.Context
+import android.content.res.ColorStateList
+import android.content.res.Configuration
+import android.graphics.Rect
+import android.text.Spanned
+import android.text.method.LinkMovementMethod
+import android.text.style.ImageSpan
+import android.text.style.ReplacementSpan
+import android.view.LayoutInflater
+import android.view.MotionEvent
+import android.view.View
+import android.view.ViewConfiguration
+import android.view.ViewGroup
+import android.widget.ImageView
+import android.widget.TextView
+import androidx.core.content.ContextCompat
+import androidx.recyclerview.widget.RecyclerView
+import io.noties.markwon.AbstractMarkwonPlugin
+import io.noties.markwon.Markwon
+import io.noties.markwon.MarkwonConfiguration
+import io.noties.markwon.image.AsyncDrawable
+import io.noties.markwon.image.AsyncDrawableSpan
+import io.noties.markwon.image.ImageSizeResolver
+import io.noties.markwon.image.ImageSizeResolverDef
+import io.noties.markwon.image.ImagesPlugin
+import io.noties.markwon.image.network.OkHttpNetworkSchemeHandler
+import okhttp3.OkHttpClient
+import kotlin.math.abs
+import kotlin.math.roundToInt
+
+/** 信息页统一列表项(RSS / 文章 / Memos / 邮件) */
+data class FeedItem(
+ val kind: String,
+ val id: String,
+ val title: String,
+ val source: String,
+ val date: Long,
+ val summary: String,
+ val link: String,
+ val read: Boolean,
+ val content: String = "",
+ val hasAttachment: Boolean = false,
+ /**
+ * Memos 的图片资源(resourceList 中 type 以 image/ 开头的 externalLink)。
+ *
+ * Memos 上传的图片不写在正文里:无论网页端还是 App 上传,二进制都只挂在
+ * memo 的 resourceList 上,content 只有文字。网页端会在正文下方渲染这组图,
+ * App 早期版本忽略了该字段,于是"手写的 Markdown 图片能显示、上传的图片看不到"。
+ */
+ val images: List = emptyList(),
+ /**
+ * 邮件所属账户(邮箱地址)与显示名。
+ *
+ * 邮件页现在把**所有邮箱**合并成一条时间线,卡片必须让人看出这封属于哪个邮箱,
+ * 点开时也要按这个地址去找对应账户的配置(否则会拿错邮箱去连 IMAP,
+ * UID 对不上就提示"已删除",已读状态也会标到别的邮件上)。
+ */
+ val account: String = "",
+ val accountLabel: String = "",
+)
+
+class FeedAdapter(
+ private val context: Context,
+ private val onOpen: (FeedItem) -> Unit,
+ private val onToggleRead: (FeedItem) -> Unit,
+ private val onImageClick: (String) -> Unit,
+) : RecyclerView.Adapter() {
+
+ /** Memos 卡片渲染 Markdown(含图片),列表共享一个 Markwon 实例与全局连接池 */
+ private val markwon: Markwon by lazy {
+ Markwon.builder(themeCtx)
+ .usePlugin(
+ ImagesPlugin.create()
+ .addSchemeHandler(OkHttpNetworkSchemeHandler.create(imageClient)),
+ )
+ // 多图横排:默认解析器把每张图都缩到画布宽度,多图必然各占一行。
+ // 这里只改写「登记为网格图片」的宽度,正文手写的图片仍走默认逻辑。
+ .usePlugin(GridImagePlugin(imageGridColumns, themeCtx.resources.displayMetrics.density))
+ .usePlugin(MdThemePlugin(themeCtx))
+ .build()
+ }
+
+ /**
+ * 网格图片的目标列数:图片 URL → 该 memo 每行显示几张。
+ *
+ * Markwon 的 ImageSizeResolver 只拿得到 AsyncDrawable(含 destination 与画布宽度),
+ * 拿不到"这是第几张、总共几张",而列数必须由渲染方决定(1 张全宽、2 张并排、
+ * 3 张以上三列)。所以渲染前把 URL→列数 登记在这里,解析器按 URL 查表计算宽度。
+ * 只在主线程读写;`size` 上限兜底见 memoMarkdown()。
+ */
+ private val imageGridColumns = java.util.concurrent.ConcurrentHashMap()
+
+ /**
+ * 图片专用 OkHttp:由 [Http.imageClient] 提供单例(共享连接池 + 64MB 磁盘缓存)。
+ *
+ * 大图预览页用同一份实例,避免两个 Cache 指向同一目录;同一 URL 在列表里
+ * 已经下载过,点开大图直接命中缓存,不再重下一遍。
+ */
+ private val imageClient: OkHttpClient by lazy { Http.imageClient(context) }
+
+ private val items = mutableListOf()
+
+ // ==================== 批量选择 ====================
+
+ /**
+ * 是否处于「选择」模式。
+ *
+ * 打开后每张卡片左侧出现勾选圈,点卡片由「打开内容」改为「勾选」;
+ * 右上栏的 全选 / 设为已读 / 删除 只在这个模式下可用。
+ */
+ var selectionMode: Boolean = false
+ private set
+
+ /** 已选条目:key 为 `kind|id`(RSS 与邮件的 id 各自独立,必须带 kind 才不串) */
+ private val selected = LinkedHashSet()
+
+ /** 选中数量变化回调:首页据此刷新「已选 N 项」与按钮可用状态 */
+ var onSelectionChanged: ((Int) -> Unit)? = null
+
+ /**
+ * 当前页是否允许选择。
+ *
+ * 只有信息(RSS)与邮件页有批量操作栏;其它页(文章 / 动态)不显示操作栏,
+ * 若不拦住,长按卡片会进入「点了只勾选、却没有任何按钮」的死胡同。
+ */
+ var selectionEnabled: Boolean = false
+
+ private fun keyOf(item: FeedItem): String = item.kind + "|" + item.id
+
+ fun enterSelection() {
+ if (selectionMode || !selectionEnabled) return
+ selectionMode = true
+ selected.clear()
+ notifyDataSetChanged()
+ onSelectionChanged?.invoke(0)
+ }
+
+ fun exitSelection() {
+ if (!selectionMode) return
+ selectionMode = false
+ selected.clear()
+ notifyDataSetChanged()
+ onSelectionChanged?.invoke(0)
+ }
+
+ fun selectedKeys(): Set = HashSet(selected)
+
+ fun selectedCount(): Int = selected.size
+
+ /** 当前显示的条目是否已全部选中(决定「全选 / 取消全选」按钮文案) */
+ fun allSelected(): Boolean =
+ items.isNotEmpty() && items.all { selected.contains(keyOf(it)) }
+
+ /** 全选 / 取消全选:只作用于当前显示(含筛选)的条目,不会选中看不见的行 */
+ fun setSelectAll(all: Boolean) {
+ if (all) items.forEach { selected.add(keyOf(it)) } else selected.clear()
+ notifyDataSetChanged()
+ onSelectionChanged?.invoke(selected.size)
+ }
+
+ /** 勾选 / 取消勾选单条:只刷新那一行,列表不跳动 */
+ fun toggleSelection(item: FeedItem) {
+ val key = keyOf(item)
+ if (!selected.remove(key)) selected.add(key)
+ // 取消了最后一项=这次选择已经结束:收起选择栏、列表恢复「点开内容」,
+ // 不必再让用户去找「完成」按钮
+ if (selected.isEmpty()) {
+ exitSelection()
+ return
+ }
+ val index = items.indexOfFirst { keyOf(it) == key }
+ if (index >= 0) notifyItemChanged(index)
+ onSelectionChanged?.invoke(selected.size)
+ }
+
+ /** 数据整表替换后,把已不在列表里的选中项清掉,避免「删了还显示已选 3 项」 */
+ private fun pruneSelection() {
+ if (!selectionMode || selected.isEmpty()) return
+ val alive = items.mapTo(HashSet(items.size)) { keyOf(it) }
+ if (selected.retainAll(alive)) onSelectionChanged?.invoke(selected.size)
+ }
+
+ // ==================== 左滑激活选择 ====================
+
+ /**
+ * 左滑触发距离。
+ *
+ * 比系统 touchSlop(约 8dp)大不少:手指落在卡片上轻微抖动、或想拖动列表时
+ * 不会误进选择模式;真想选择时横向一划就过线。
+ */
+ private val swipeTrigger: Int = (40 * context.resources.displayMetrics.density).toInt()
+
+ /**
+ * 左滑激活批量选择。
+ *
+ * 语义与上一版的「左滑露出删除按钮」不同:左滑不再直接删东西(删除是破坏性操作,
+ * 一次滑动就删太容易误触,也和顶部的勾选/全选重复),而是把这张卡片当作
+ * 「想整理这一条」的意图——进入选择模式并勾上它,随后由上面的操作栏统一处理。
+ *
+ * 判定条件:横向位移超过 [swipeTrigger] **且** 横向明显大于纵向(1.5 倍),
+ * 否则把事件让给 RecyclerView 做纵向滚动,不影响上下滑列表。
+ * 一旦触发就 requestDisallowInterceptTouchEvent,并把本次手势剩下的 UP 一并消费掉,
+ * 避免卡片被当成「被点了一下」而打开内容(选择模式下点卡片又会把它取消勾选)。
+ */
+ private fun attachSwipeSelect(holder: ViewHolder) {
+ val view = holder.root
+ var downX = 0f
+ var downY = 0f
+ var consumed = false
+
+ view.setOnTouchListener { _, event ->
+ when (event.actionMasked) {
+ MotionEvent.ACTION_DOWN -> {
+ downX = event.rawX
+ downY = event.rawY
+ consumed = false
+ }
+
+ MotionEvent.ACTION_MOVE -> {
+ if (consumed) return@setOnTouchListener true
+ // 已经在选择模式里(点卡片即可勾选),或当前页不支持批量操作
+ // (动态 / 文章页),都不接管手势,交回默认处理
+ if (selectionMode || !selectionEnabled) return@setOnTouchListener false
+ val dx = event.rawX - downX
+ val dy = event.rawY - downY
+ if (dx < -swipeTrigger && abs(dx) > abs(dy) * 1.5f) {
+ val item = items.getOrNull(holder.bindingAdapterPosition)
+ ?: return@setOnTouchListener false
+ consumed = true
+ view.parent?.requestDisallowInterceptTouchEvent(true)
+ // 放到事件派发之后再做整表刷新:当前位置正在派发触摸事件,
+ // 立即 notifyDataSetChanged 会在派发中途改布局
+ view.post { swipeSelect(item) }
+ return@setOnTouchListener true
+ }
+ }
+
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
+ if (consumed) {
+ consumed = false
+ return@setOnTouchListener true
+ }
+ }
+ }
+ false
+ }
+ }
+
+ /**
+ * 左滑落到「进入选择并勾上这一条」。
+ *
+ * 选择栏平时不占位,只有这里(或长按)把它叫出来;已经在选择模式里时再左滑别的
+ * 卡片只会追加勾选,不会清掉之前选的——批量删除通常要选好几条。
+ */
+ fun swipeSelect(item: FeedItem) {
+ if (!selectionEnabled) return
+ if (!selectionMode) {
+ selectionMode = true
+ selected.clear()
+ }
+ selected.add(keyOf(item))
+ notifyDataSetChanged()
+ onSelectionChanged?.invoke(selected.size)
+ }
+
+ private val prefs = Prefs(context)
+
+ /**
+ * 卡片配色专用上下文:按偏好设置强制 uiMode 后再取资源。
+ *
+ * 列表页停在后台时,其资源层配置可能被其它页面(邮件 WebView / DayNight 应用机制)
+ * 刷新,返回首页后直接取色会拿到浅色值——表现为"背景深色、卡片浅色"。
+ * 这里以 prefs 里保存的深浅意图为唯一依据,深浅永远跟随设置,
+ * 不依赖运行期配置状态,从根上消除混色。
+ */
+ private fun themedContext(): Context {
+ val appCtx = context.applicationContext
+ val dark = when (prefs.darkMode) {
+ Prefs.MODE_DARK -> true
+ Prefs.MODE_LIGHT -> false
+ else -> (appCtx.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) ==
+ Configuration.UI_MODE_NIGHT_YES
+ }
+ val conf = Configuration(appCtx.resources.configuration)
+ conf.uiMode = (conf.uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()) or
+ if (dark) Configuration.UI_MODE_NIGHT_YES else Configuration.UI_MODE_NIGHT_NO
+ return appCtx.createConfigurationContext(conf)
+ }
+
+ private var themeCtx: Context = themedContext()
+
+ // ---- 主题配色:绑定时刻解析(而不是只在 inflate 时解析一次)----
+ // 复用的卡片可能是在另一主题下创建的,绑定时逐项重设颜色,
+ // 保证整张列表永远是当前主题的配色,不会深浅混排。
+ // 注意:这里只缓存颜色值(Int,无状态),Drawable 不能在这里缓存——见 themeVersion。
+ private var cSource = ContextCompat.getColor(themeCtx, R.color.brand)
+ private var cDate = ContextCompat.getColor(themeCtx, R.color.text_tertiary)
+ private var cTitle = ContextCompat.getColor(themeCtx, R.color.title)
+ private var cSummary = ContextCompat.getColor(themeCtx, R.color.text_secondary)
+
+ /**
+ * 主题版本号:卡片与「未读」徽标的背景,必须是**每个 View 各自一份**的 Drawable 实例。
+ *
+ * 3.24 及更早版本在 Adapter 上缓存了一个 `cardBg` / `unreadBg` 实例给全部卡片共用,
+ * 这是「卡片高度比内容短、未读与长正文露在边框外」的根因:
+ * Drawable 的 bounds 是实例自身状态,而 View.drawBackground() 只在
+ * mBackgroundSizeChanged 为 true(即 View 尺寸刚变过)时才重新 setBounds()。
+ * 共用实例时,一张矮卡片绘制会把这份共享 bounds 改成自己的尺寸;高卡片随后重绘,
+ * 因为自身尺寸没变(标志为 false)就直接拿被改小的 bounds 去画背景,
+ * 于是边框只画到一半,内容与徽标露在外面。下拉刷新时每张卡片都重新 bind、
+ * 重新 setBackground,标志全部置位,bounds 各归各位,所以一刷新就"好了"。
+ *
+ * 修复方式是每个 View 持有独立实例;深浅色切换需要换配色,
+ * 用版本号让每个 View 在版本变化后重取一份,回收到池里的 View 下次绑定也会更新。
+ */
+ private var themeVersion = 0
+
+ /** 深浅色状态变化后调用:重取配色并整表重绑 */
+ fun refreshTheme() {
+ themeCtx = themedContext()
+ themeVersion++
+ cSource = ContextCompat.getColor(themeCtx, R.color.brand)
+ cDate = ContextCompat.getColor(themeCtx, R.color.text_tertiary)
+ cTitle = ContextCompat.getColor(themeCtx, R.color.title)
+ cSummary = ContextCompat.getColor(themeCtx, R.color.text_secondary)
+ notifyDataSetChanged()
+ }
+
+ /**
+ * 邮件卡片是否显示所属邮箱名。
+ *
+ * 邮件页默认是「全部邮箱」的合并时间线,卡片必须标出这封属于哪个邮箱;
+ * 但用顶部筛选只看某一个邮箱时,每张卡片都重复同一个名字既啰嗦又占位,
+ * 所以由首页按当前筛选状态切换这个开关。
+ */
+ var showMailAccount: Boolean = true
+ set(value) {
+ if (field == value) return
+ field = value
+ // 内容没变但显示规则变了,只能整表重绑
+ if (items.isNotEmpty()) notifyDataSetChanged()
+ }
+
+ fun submit(list: List) {
+ items.clear()
+ items.addAll(list)
+ notifyDataSetChanged()
+ pruneSelection()
+ }
+
+ /**
+ * 用新数据刷新列表:能对齐就逐条差量更新,对不齐才整表重绑。
+ *
+ * 从邮件详情 / 阅读页返回时会重新读一遍缓存,直接 notifyDataSetChanged 会把
+ * 已经滚动到的位置弹回顶部;id 序列没变(只是已读状态、摘要变了)时逐条
+ * 刷新,滚动位置与正在播放的图片都能保住。
+ */
+ fun update(list: List) {
+ val sameShape = items.size == list.size && items.indices.all { i ->
+ items[i].id == list[i].id && items[i].kind == list[i].kind
+ }
+ if (!sameShape) {
+ submit(list)
+ return
+ }
+ list.forEachIndexed { index, item ->
+ if (items[index] != item) {
+ items[index] = item
+ notifyItemChanged(index)
+ }
+ }
+ pruneSelection()
+ }
+
+ /** 按 id 更新单条(点开即已读时用),找不到就忽略 */
+ fun updateItem(item: FeedItem) {
+ val index = items.indexOfFirst { it.kind == item.kind && it.id == item.id }
+ if (index < 0) return
+ items[index] = item
+ notifyItemChanged(index)
+ }
+
+ fun append(list: List) {
+ val from = items.size
+ items.addAll(list)
+ notifyItemRangeInserted(from, list.size)
+ }
+
+ inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
+ /** 卡片本体:整行都是它,左滑手势与点击都挂在上面 */
+ val root: View = view.findViewById(R.id.itemRoot)
+ /** 选择模式下的勾选圈 */
+ val check: ImageView = view.findViewById(R.id.itemCheck)
+ val source: TextView = view.findViewById(R.id.tvSource)
+ val date: TextView = view.findViewById(R.id.tvDate)
+ val title: TextView = view.findViewById(R.id.tvTitle)
+ val summary: TextView = view.findViewById(R.id.tvSummary)
+ val unread: TextView = view.findViewById(R.id.tvUnread)
+
+ /** 该 View 私有背景当前对应的主题版本,-1 表示尚未设置 */
+ var themeVersion: Int = -1
+ }
+
+ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
+ val view = LayoutInflater.from(parent.context).inflate(R.layout.item_feed, parent, false)
+ val holder = ViewHolder(view)
+ // 触摸监听只装一次:命中判断在抬手时读当前文本,回收复用不会串图
+ attachImageTaps(holder.summary)
+ attachSwipeSelect(holder)
+ return holder
+ }
+
+ override fun onBindViewHolder(holder: ViewHolder, position: Int) {
+ val item = items[position]
+ // 每个 View 一份独立 Drawable:共用实例会让 bounds 互相覆盖(见 themeVersion 注释)
+ if (holder.themeVersion != themeVersion) {
+ holder.root.background = ContextCompat.getDrawable(themeCtx, R.drawable.bg_card)
+ holder.unread.background = ContextCompat.getDrawable(themeCtx, R.drawable.bg_brand_soft)
+ holder.themeVersion = themeVersion
+ }
+ // 每次绑定都按当前主题重设颜色,跨主题复用的卡片不会残留旧配色
+ holder.source.setTextColor(cSource)
+ holder.date.setTextColor(cDate)
+ holder.title.setTextColor(cTitle)
+ holder.summary.setTextColor(cSummary)
+ holder.unread.setTextColor(cSource)
+ holder.date.text = formatDate(item.date)
+
+ // Memos 卡片直接显示全文:不显示标题行,正文不限行数;
+ // 左侧原本的来源位换成完整时间(右侧相对时间隐藏)
+ val isMemo = item.kind == "memo"
+ if (isMemo) {
+ holder.source.text = buildString {
+ if (item.source == "置顶") append("置顶 · ")
+ append(formatFullDate(item.date))
+ }
+ holder.date.text = ""
+ holder.title.visibility = View.GONE
+ holder.summary.maxLines = Int.MAX_VALUE
+ holder.summary.ellipsize = null
+ holder.summary.textSize = 14f
+ } else {
+ holder.source.text = buildString {
+ // 邮件卡片:邮箱名在前、发件人在后(合并时间线里「这是哪个邮箱」先要知道)。
+ // 只筛单个邮箱时不重复标注邮箱名,见 showMailAccount。
+ val showAccount = item.accountLabel.isNotBlank() && showMailAccount
+ if (showAccount) {
+ append(item.accountLabel)
+ if (item.source.isNotBlank()) append(" · ").append(item.source)
+ } else {
+ append(item.source)
+ }
+ if (item.hasAttachment) append(" · 有附件")
+ }
+ if (item.title.isBlank()) {
+ holder.title.visibility = View.GONE
+ } else {
+ holder.title.visibility = View.VISIBLE
+ holder.title.text = item.title
+ }
+ holder.summary.maxLines = 2
+ holder.summary.ellipsize = android.text.TextUtils.TruncateAt.END
+ holder.summary.textSize = 12.5f
+ }
+ // Memos 卡片正文:正文 + resourceList 里的图片,渲染前拼成一份 Markdown
+ val memoBody = if (isMemo) memoMarkdown(item) else null
+
+ val hasBody =
+ if (memoBody != null) memoBody.isNotBlank() else item.summary.isNotBlank()
+ if (!hasBody) {
+ holder.summary.visibility = View.GONE
+ } else {
+ holder.summary.visibility = View.VISIBLE
+ if (memoBody != null) {
+ // Memos 卡片支持 Markdown:粗体/斜体/列表/代码块/链接/图片
+ holder.summary.movementMethod = LinkMovementMethod.getInstance()
+ markwon.setMarkdown(holder.summary, memoBody)
+ } else {
+ holder.summary.text = item.summary
+ }
+ }
+ holder.unread.visibility = if (item.read) View.GONE else View.VISIBLE
+
+ // 选择模式:左侧出现勾选圈,勾中时填品牌色,未勾是灰色空心圆
+ val checked = selectionMode && selected.contains(keyOf(item))
+ holder.check.visibility = if (selectionMode) View.VISIBLE else View.GONE
+ if (selectionMode) {
+ holder.check.setImageResource(
+ if (checked) R.drawable.ic_check_circle_on else R.drawable.ic_check_circle_off
+ )
+ holder.check.imageTintList = ColorStateList.valueOf(if (checked) cSource else cDate)
+ }
+
+ holder.root.setOnClickListener {
+ if (selectionMode) toggleSelection(item) else onOpen(item)
+ }
+ // 长按与左滑等价:都直接进入选择模式并勾上这一条
+ holder.root.setOnLongClickListener {
+ if (selectionMode || !selectionEnabled) return@setOnLongClickListener false
+ enterSelection()
+ toggleSelection(item)
+ true
+ }
+ holder.check.setOnClickListener { if (selectionMode) toggleSelection(item) }
+ holder.unread.setOnClickListener { onToggleRead(item) }
+ }
+
+ /**
+ * Memos 卡片正文:把 resourceList 里的图片拼进 Markdown 一并渲染。
+ *
+ * Memos 的图片有两种来源,网页端都会显示:
+ * 1. 正文里手写的 ``(网页编辑器插入的图片);
+ * 2. 只挂在 resourceList 上、正文没写的图片(App 上传的就是这一类)。
+ * 这里按 resourceList 顺序把第 2 类追加到正文末尾,展示顺序与网页一致。
+ *
+ * 布局与网页端对齐:单图全宽,两张并排,三张以上每行三张。实现方式是先把
+ * 「一张图独占一段」的连续段落合并成**同一段落**(空格分隔),再让
+ * [GridImageSizeResolver] 把每张的宽度压到画布宽度的 1/n——宽度之和不足一行,
+ * TextView 自然把它们排在同一行。
+ *
+ * 正文图片与追加图片必须走同一套列数登记,否则会出现「一种横排、另一种竖排」,
+ * 点击行为也会跟着分叉(3.28 的 bug)。
+ */
+ private fun memoMarkdown(item: FeedItem): String {
+ // MyTrack 足迹地图短代码 {map-数字} APP 端无法渲染,直接隐藏
+ val cleaned = item.summary.replace(
+ Regex("\\{map-\\d+\\}", RegexOption.IGNORE_CASE), "",
+ )
+ // 正文里「每张图一段」的写法(网页编辑器、Obsidian 都这么写)合并成一段
+ val text = mergeImageParagraphs(cleaned)
+ // 登记正文图片的列数,让它们和追加图片一样横排、一样能点
+ registerGridColumns(text)
+
+ if (item.images.isEmpty()) return text
+
+ // 正文里已经手写引用过的图片不重复追加
+ val extra = item.images.filter { it.isNotBlank() && !text.contains(it) }
+ if (extra.isEmpty()) return text
+
+ // 少数部署版本只返回相对路径(/file/xxx),补成绝对地址,图片加载器才取得到
+ val base = prefs.memosUrl.trimEnd('/')
+ val columns = columnsFor(extra.size)
+ // 登记表只为渲染服务,长期滚动会堆积已不再显示的历史 URL,超过阈值整体清一次;
+ // 清掉后下次绑定会重新登记,最差退化成一次全宽图片
+ if (imageGridColumns.size > 256) imageGridColumns.clear()
+
+ return buildString {
+ append(text.trimEnd())
+ if (isNotEmpty()) append("\n\n")
+ extra.forEachIndexed { index, raw ->
+ val url = if (raw.startsWith("/")) base + raw else raw
+ imageGridColumns[url] = columns
+ append(".append(url).append(")")
+ // 同一段落内以空格分隔,图片才会横向排列;强制换行就会退回竖排
+ if (index != extra.lastIndex) append(' ')
+ }
+ }.trimEnd()
+ }
+
+ /**
+ * 把「一张图独占一段」的连续段落合并成一段(空格分隔)。
+ *
+ * 网页端的图片网格不看段落:连续几张图并排显示。Markdown 里每张图各占一段时,
+ * 无论尺寸解析器怎么算宽度,TextView 也会按段落换行,结果只能是竖排。
+ * 只有整段都是图片的段落参与合并,混着文字的段落原样保留。
+ */
+ private fun mergeImageParagraphs(text: String): String {
+ if (!text.contains("![")) return text
+ val blocks = text.split(PARAGRAPH_BREAK)
+ val out = ArrayList(blocks.size)
+ val run = ArrayList()
+ fun flush() {
+ if (run.isEmpty()) return
+ out.add(if (run.size == 1) run[0] else run.joinToString(" "))
+ run.clear()
+ }
+ for (block in blocks) {
+ if (IMAGE_ONLY_BLOCK.matches(block.trim())) {
+ // 整段都是图片时,段内换行统一收成空格:Obsidian / 网页编辑器常用单个换行
+ // 分隔图片,不收成空格的话仍会被渲染成换行,又退回竖排
+ run.add(block.trim().replace(INLINE_BREAK, " "))
+ } else {
+ flush()
+ out.add(block)
+ }
+ }
+ flush()
+ return out.joinToString("\n\n")
+ }
+
+ /** 按段落登记图片的列数:只有「整段都是图片」的段落才按网格排 */
+ private fun registerGridColumns(text: String) {
+ if (!text.contains("![")) return
+ if (imageGridColumns.size > 256) imageGridColumns.clear()
+ text.split(PARAGRAPH_BREAK).forEach { block ->
+ val trimmed = block.trim()
+ if (!IMAGE_ONLY_BLOCK.matches(trimmed)) return@forEach
+ val urls = IMAGE_URL.findAll(trimmed).map { it.groupValues[1] }.toList()
+ if (urls.size < 2) return@forEach
+ val columns = columnsFor(urls.size)
+ urls.forEach { imageGridColumns[it] = columns }
+ }
+ }
+
+ /** 与网页端网格一致:单图全宽、两张并排、三张以上三列 */
+ private fun columnsFor(count: Int): Int = when {
+ count <= 1 -> 1
+ count == 2 -> 2
+ else -> 3
+ }
+
+ override fun getItemCount(): Int = items.size
+
+ /** 系统认定的滑动阈值:位移超过它就算滚动,不当作点击 */
+ private val touchSlop: Int = ViewConfiguration.get(context).scaledTouchSlop
+
+ /**
+ * 图片点击:按「图片实际占用的矩形」命中,不依赖 ClickableSpan。
+ *
+ * 3.28 的做法是给每个图片 span 同区间叠一个透明 ClickableSpan,靠 LinkMovementMethod
+ * 转发点击。实测只有「由 resourceList 追加的图片」能点,正文里手写的 ``
+ * 点了没反应——两者 span 类型相同,差异在 span 的标记与 offset 落点,靠猜不可靠。
+ *
+ * 这里换成直接命中判断:抬手时把坐标换算成 Layout 里的行与横向位置,再拿所有
+ * AsyncDrawableSpan 的实际绘制区间比对。不关心 span 标记、不关心 offset 落在图片
+ * 左端还是右端,也不需要 ClickableSpan,正文图片与追加图片走同一条路。
+ *
+ * 返回 false 让 TextView 照常处理:文字链接仍由 LinkMovementMethod 打开,
+ * 普通区域仍交给卡片与 RecyclerView(滑动不受影响,滑动时父容器会拦走事件,
+ * 子 View 收到的是 CANCEL,不会误触发)。
+ */
+ private fun attachImageTaps(tv: TextView) {
+ var downX = 0f
+ var downY = 0f
+ tv.setOnTouchListener { _, event ->
+ // 选择模式下点卡片是勾选,不要再弹大图(否则勾选时容易误触)
+ if (selectionMode) return@setOnTouchListener false
+ when (event.actionMasked) {
+ MotionEvent.ACTION_DOWN -> {
+ downX = event.x
+ downY = event.y
+ }
+
+ MotionEvent.ACTION_UP -> {
+ val dx = event.x - downX
+ val dy = event.y - downY
+ if (dx * dx + dy * dy <= (touchSlop * touchSlop).toFloat()) {
+ val hit = imageAt(tv, event.x, event.y)
+ if (hit != null) {
+ // 地址先归一化:正文里的图常带 <…>、&、相对路径、空格,
+ // 这些都是 OkHttp 直接拒绝的写法,预览页会误报"加载失败"
+ val target = ImageUrl.normalize(context, hit.url)
+ // 顺手把卡片里已经解码好的位图交给预览页做兜底
+ ImageMemoryCache.put(target, hit.bitmap)
+ if (target != hit.url) ImageMemoryCache.put(hit.url, hit.bitmap)
+ onImageClick(target)
+ return@setOnTouchListener true
+ }
+ }
+ }
+ }
+ false
+ }
+ }
+
+ /** 命中结果:图片地址 + 卡片里已经解码好的位图(可能为 null) */
+ private class ImageHit(val url: String, val bitmap: android.graphics.Bitmap?)
+
+ /** 返回 (x, y) 处的图片;没命中图片返回 null */
+ private fun imageAt(tv: TextView, x: Float, y: Float): ImageHit? {
+ val layout = tv.layout ?: return null
+ val text = tv.text as? Spanned ?: return null
+ if (text.isEmpty()) return null
+
+ // 与 LinkMovementMethod 相同的坐标换算:先减内边距,再加滚动量
+ val px = x - tv.totalPaddingLeft + tv.scrollX
+ val py = y - tv.totalPaddingTop + tv.scrollY
+ if (px < 0f || py < 0f) return null
+
+ val line = layout.getLineForVertical(py.toInt())
+ if (py < layout.getLineTop(line) || py > layout.getLineBottom(line)) return null
+
+ // 用 ReplacementSpan 取:Markwon 的图片是 AsyncDrawableSpan 子类,
+ // 但别的渲染路径(HTML/图组)可能给的是普通 ImageSpan,一并覆盖
+ val spans = text.getSpans(0, text.length, ReplacementSpan::class.java)
+ if (spans.isEmpty()) return null
+ // 允许 4dp 误差:图片外框与行边界常有 1~2px 的取整偏差
+ val tolerance = 4 * tv.resources.displayMetrics.density
+
+ for (span in spans) {
+ val start = text.getSpanStart(span)
+ val end = text.getSpanEnd(span)
+ if (start < 0 || end <= start) continue
+ val first = layout.getLineForOffset(start)
+ // 用 end - 1 判断末行:图片正好结束在换行处时,end 会落到下一行
+ val last = layout.getLineForOffset(end - 1)
+ if (line < first || line > last) continue
+
+ val left = if (line == first) layout.getPrimaryHorizontal(start) else layout.getLineLeft(line)
+ val layoutRight =
+ if (line == last) layout.getPrimaryHorizontal(end) else layout.getLineRight(line)
+ // 图片刚下载完、TextView 还没来得及重新排版时,Layout 里记的还是占位符宽度
+ // (很小),而图片已经按真实宽度画出来了。用绘制宽度把命中区补上,
+ // 避免这几十毫秒的空窗期点了没反应。
+ val drawnWidth = runCatching {
+ (span as? AsyncDrawableSpan)?.drawable?.bounds?.width() ?: 0
+ }.getOrDefault(0)
+ val right = if (drawnWidth > 0) maxOf(layoutRight, left + drawnWidth) else layoutRight
+ if (px < minOf(left, right) - tolerance) continue
+ if (px > maxOf(left, right) + tolerance) continue
+
+ val url = when (span) {
+ is AsyncDrawableSpan -> runCatching { span.drawable.destination }.getOrNull()
+ is ImageSpan -> span.source
+ else -> null
+ }
+ if (!url.isNullOrBlank()) {
+ // Markwon 的 AsyncDrawable 持有已解码的 Drawable(getResult),取出来给预览页做兜底
+ val bitmap = runCatching {
+ val d = (span as? AsyncDrawableSpan)?.drawable?.result
+ (d as? android.graphics.drawable.BitmapDrawable)?.bitmap
+ }.getOrNull()
+ return ImageHit(url, bitmap)
+ }
+ }
+ return null
+ }
+
+ /** 格式化对象只建一次(绑定在主线程串行执行),滚动更省 CPU */
+ private val shortFormat = java.text.SimpleDateFormat("MM-dd", java.util.Locale.getDefault())
+ private val fullFormat =
+ java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault())
+
+ private fun formatDate(ts: Long): String {
+ if (ts <= 0) return ""
+ val seconds = if (ts > 1_000_000_000_000L) ts / 1000 else ts
+ val diff = System.currentTimeMillis() / 1000 - seconds
+ return when {
+ diff < 60 -> "刚刚"
+ diff < 3600 -> "${diff / 60}分钟前"
+ diff < 86_400 -> "${diff / 3600}小时前"
+ diff < 7 * 86_400 -> "${diff / 86_400}天前"
+ else -> shortFormat.format(java.util.Date(seconds * 1000))
+ }
+ }
+
+ /** Memos 左侧使用的完整时间:yyyy-MM-dd HH:mm:ss */
+ private fun formatFullDate(ts: Long): String {
+ if (ts <= 0) return ""
+ val seconds = if (ts > 1_000_000_000_000L) ts / 1000 else ts
+ return fullFormat.format(java.util.Date(seconds * 1000))
+ }
+}
+
+/** 段落分隔:一个空行(兼容 CRLF 与行尾空白) */
+private val PARAGRAPH_BREAK = Regex("\\r?\\n[ \\t]*\\r?\\n")
+
+/** 整段都是图片(一张或多张,图片之间以空白分隔),没有其他文字 */
+private val IMAGE_ONLY_BLOCK = Regex("^(?:!\\[[^\\]]*\\]\\([^)\\s]+\\)\\s*)+$")
+
+/** 从段落文本中取图片地址(第 1 组) */
+private val IMAGE_URL = Regex("!\\[[^\\]]*\\]\\(([^)\\s]+)\\)")
+
+/** 段内换行(不含空行),图片段落里统一收成空格 */
+private val INLINE_BREAK = Regex("[ \\t]*\\r?\\n[ \\t]*")
+
+/** 把网格尺寸解析器装进 Markwon 配置 */
+private class GridImagePlugin(
+ private val columns: Map,
+ private val density: Float,
+) : AbstractMarkwonPlugin() {
+
+ private val resolver = GridImageSizeResolver(columns, density)
+
+ override fun configureConfiguration(builder: MarkwonConfiguration.Builder) {
+ builder.imageSizeResolver(resolver)
+ }
+}
+
+/**
+ * 多图横排的尺寸解析器。
+ *
+ * Markwon 4.6.2 的 [ImageSizeResolverDef] 会把每张图都缩到画布宽度,因此同一段落里的
+ * 多张图片必然各占一行。这里对「已登记列数」的图片改成按列均分:目标宽度 =
+ * (画布宽 − 图片间距) / 列数,高度按原始宽高比推算。
+ *
+ * 尺寸在这里返回后会成为 AsyncDrawable 的 bounds,`AsyncDrawableSpan.getSize()` 与绘制
+ * 都直接采用它(已核实 4.6.2 的实现),所以宽度就是最终显示宽度。
+ *
+ * 未登记列数的图片(正文手写的 `![]()`)、单图、以及画布宽度未知的情况一律交回默认解析器,
+ * 行为与改动前完全一致。
+ */
+private class GridImageSizeResolver(
+ private val columns: Map,
+ private val density: Float,
+) : ImageSizeResolver() {
+
+ private val fallback = ImageSizeResolverDef()
+
+ override fun resolveImageSize(drawable: AsyncDrawable): Rect {
+ val count = columns[drawable.destination] ?: return fallback.resolveImageSize(drawable)
+ if (count < 2) return fallback.resolveImageSize(drawable)
+
+ // 图片尚未下载完时先按默认逻辑排版,加载完成会再次回调(setResult → initBounds)
+ val result = drawable.result ?: return fallback.resolveImageSize(drawable)
+ val imageW = result.intrinsicWidth
+ val imageH = result.intrinsicHeight
+ val canvas = drawable.lastKnownCanvasWidth
+ if (imageW <= 0 || imageH <= 0 || canvas <= 0) {
+ return fallback.resolveImageSize(drawable)
+ }
+
+ // 间距 6dp:网页端网格的视觉间隔约 4~8dp。图片之间还会夹一个空格字符,
+ // 所以这里只按目标间隔预留,另一半由空格提供
+ val gap = (6 * density).toInt().coerceAtLeast(1)
+ // 每格再收 2dp:像素取整、系统字体放大后空格变宽,都可能让总宽度刚好超过
+ // 画布,最后一张被挤到下一行(又退回竖排)
+ val cell = (canvas - gap * (count - 1)).toFloat() / count - 2 * density
+ if (cell < 1f) return fallback.resolveImageSize(drawable)
+
+ val height = cell * imageH / imageW
+ return Rect(
+ 0,
+ 0,
+ cell.roundToInt().coerceAtLeast(1),
+ height.roundToInt().coerceAtLeast(1),
+ )
+ }
+}
diff --git a/src/main/java/com/shitoucuo/postpad/HomeActivity.kt b/src/main/java/com/shitoucuo/postpad/HomeActivity.kt
new file mode 100644
index 0000000..edcd37f
--- /dev/null
+++ b/src/main/java/com/shitoucuo/postpad/HomeActivity.kt
@@ -0,0 +1,1311 @@
+package com.shitoucuo.postpad
+
+import android.content.Intent
+import android.content.res.Configuration
+import android.graphics.Rect
+import android.os.Bundle
+import android.text.Editable
+import android.text.TextWatcher
+import android.view.Gravity
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ArrayAdapter
+import android.widget.EditText
+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.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+import androidx.appcompat.app.AppCompatDelegate
+import androidx.core.content.ContextCompat
+import androidx.lifecycle.lifecycleScope
+import androidx.recyclerview.widget.LinearLayoutManager
+import androidx.recyclerview.widget.RecyclerView
+import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/**
+ * 首页:底部三菜单(信息 / 发布 / 邮件)。
+ * 信息页顶部切换 RSS(默认)/ 文章 / Memos,筛选放在顶部;
+ * 文章可按站点筛选,邮件可按邮箱切换;
+ * 发布按钮向上展开「发布文章 / 发布微博」二级菜单,复用原有 MainActivity。
+ */
+class HomeActivity : AppCompatActivity() {
+
+ private lateinit var prefs: Prefs
+ private lateinit var adapter: FeedAdapter
+ private lateinit var recyclerView: RecyclerView
+ private lateinit var swipeRefresh: SwipeRefreshLayout
+ private lateinit var tvEmpty: TextView
+ private lateinit var progress: ProgressBar
+ private lateinit var etFilter: EditText
+ private lateinit var btnFilter: TextView
+ private lateinit var btnSourcePick: TextView
+
+ private lateinit var feedTabs: LinearLayout
+ private lateinit var filterRow: LinearLayout
+ private lateinit var selectionBar: LinearLayout
+ private lateinit var btnSelectDone: TextView
+ private lateinit var btnSelectAll: TextView
+ private lateinit var btnMarkRead: TextView
+ private lateinit var btnDeleteSelected: TextView
+ private lateinit var tvSelectedCount: TextView
+ private lateinit var tabRss: TextView
+ private lateinit var tabArticle: TextView
+ private lateinit var tabMemo: TextView
+ private lateinit var navInfo: TextView
+ private lateinit var navMail: TextView
+ private lateinit var badgeInfo: TextView
+ private lateinit var badgeMail: TextView
+
+ /** rss / article / memo / mail */
+ private var current = TAB_RSS
+ private var filterMode = FILTER_ALL
+ private var keyword = ""
+
+ /**
+ * 邮件页按邮箱筛选:空串表示「全部邮箱」。
+ *
+ * 邮件页默认把**所有账户**的邮件合成一条时间线(卡片上标出邮箱名),
+ * 顶部这个筛选只在需要专注某个邮箱时用;它是纯本地过滤,切换不重新联网。
+ */
+ private var mailFilter = ""
+ private var searchJob: Job? = null
+ private var loadJob: Job? = null
+
+ private var rssPage = 1
+ private var rssPages = 1
+ private var articlePage = 1
+ private var articlePages = 1
+ private var memoToken = ""
+ private var memoHasMore = false
+
+ private val allItems = mutableListOf()
+
+ companion object {
+ const val TAB_RSS = "rss"
+ const val TAB_ARTICLE = "article"
+ const val TAB_MEMO = "memo"
+ const val TAB_MAIL = "mail"
+
+ private const val FILTER_ALL = 0
+ private const val FILTER_UNREAD = 1
+ private const val FILTER_READ = 2
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ prefs = Prefs(this)
+ // 站点 / 邮箱都只存在 sites、mail_accounts 两个 JSON 数组里,没有更早的单条格式,
+ // 因此不需要「老配置物化」这一步。原写法 siteCount()==0 && typechoReady 恒为假
+ // (siteUrl 本身就取自数组,数组为空必然空串),属于死代码,已删除。
+ val target = prefs.nightMode()
+ if (AppCompatDelegate.getDefaultNightMode() != target) {
+ AppCompatDelegate.setDefaultNightMode(target)
+ }
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_home)
+
+ bindViews()
+ setupList()
+ setupTabs()
+ setupFilter()
+ setupSelection()
+ setupNav()
+ setupTheme()
+
+ load(refresh = true)
+ // 角标独立于列表加载:这里先在后台统计,结果到了再显示
+ refreshBadges()
+ }
+
+ // ==================== 初始化 ====================
+
+ private fun bindViews() {
+ recyclerView = findViewById(R.id.recyclerView)
+ swipeRefresh = findViewById(R.id.swipeRefresh)
+ tvEmpty = findViewById(R.id.tvEmpty)
+ progress = findViewById(R.id.progressBar)
+ etFilter = findViewById(R.id.etFilter)
+ btnFilter = findViewById(R.id.btnFilter)
+ btnSourcePick = findViewById(R.id.btnSourcePick)
+ feedTabs = findViewById(R.id.feedTabs)
+ filterRow = findViewById(R.id.filterRow)
+ selectionBar = findViewById(R.id.selectionBar)
+ btnSelectDone = findViewById(R.id.btnSelectDone)
+ btnSelectAll = findViewById(R.id.btnSelectAll)
+ btnMarkRead = findViewById(R.id.btnMarkRead)
+ btnDeleteSelected = findViewById(R.id.btnDeleteSelected)
+ tvSelectedCount = findViewById(R.id.tvSelectedCount)
+ tabRss = findViewById(R.id.tabRss)
+ tabArticle = findViewById(R.id.tabArticle)
+ tabMemo = findViewById(R.id.tabMemo)
+ navInfo = findViewById(R.id.navInfo)
+ navMail = findViewById(R.id.navMail)
+ badgeInfo = findViewById(R.id.badgeInfo)
+ badgeMail = findViewById(R.id.badgeMail)
+ }
+
+ private fun setupList() {
+ adapter = FeedAdapter(
+ context = this,
+ onOpen = { openItem(it) },
+ onToggleRead = { toggleRead(it) },
+ onImageClick = { url -> startActivity(ImagePreviewActivity.intent(this, url)) },
+ )
+ adapter.onSelectionChanged = { count -> renderSelection(count) }
+ recyclerView.layoutManager = LinearLayoutManager(this)
+ recyclerView.adapter = adapter
+ // 列表尺寸不随内容变化,跳过多余的整表测量
+ recyclerView.setHasFixedSize(true)
+ recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
+ override fun onScrolled(rv: RecyclerView, dx: Int, dy: Int) {
+ if (dy <= 0) return
+ val manager = rv.layoutManager as? LinearLayoutManager ?: return
+ val last = manager.findLastVisibleItemPosition()
+ if (last >= adapter.itemCount - 3 && adapter.itemCount > 0) loadMore()
+ }
+ })
+
+ // 下拉刷新是用户明确要求「来最新的」:邮件页重算邮件角标,其它页强制重扫 RSS 未读
+ swipeRefresh.setOnRefreshListener {
+ load(refresh = true)
+ if (current == TAB_MAIL) refreshMailBadge() else refreshBadges(rssForce = true)
+ }
+ }
+
+ private fun setupTabs() {
+ tabRss.setOnClickListener { switchTab(TAB_RSS) }
+ tabArticle.setOnClickListener { switchTab(TAB_ARTICLE) }
+ tabMemo.setOnClickListener { switchTab(TAB_MEMO) }
+ updateTabStyle()
+ }
+
+ private fun setupFilter() {
+ btnSourcePick.setOnClickListener { showSourcePickPopup() }
+ btnFilter.setOnClickListener {
+ filterMode = (filterMode + 1) % 3
+ btnFilter.text = when (filterMode) {
+ FILTER_UNREAD -> getString(R.string.filter_unread)
+ FILTER_READ -> getString(R.string.filter_read)
+ else -> getString(R.string.filter_all)
+ }
+ applyFilter()
+ }
+ etFilter.addTextChangedListener(object : TextWatcher {
+ override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
+ override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
+ override fun afterTextChanged(s: Editable?) {
+ keyword = s?.toString().orEmpty().trim()
+ searchJob?.cancel()
+ searchJob = lifecycleScope.launch {
+ delay(350)
+ load(refresh = true)
+ }
+ }
+ })
+ }
+
+ // ==================== 批量选择 / 删除 ====================
+
+ private fun keyOf(item: FeedItem): String = item.kind + "|" + item.id
+
+ private fun setupSelection() {
+ // 操作栏没有「选择」入口:左滑卡片即进入选择,这里只提供退出
+ btnSelectDone.setOnClickListener { adapter.exitSelection() }
+ btnSelectAll.setOnClickListener {
+ if (!adapter.selectionMode) return@setOnClickListener
+ adapter.setSelectAll(!adapter.allSelected())
+ }
+ btnMarkRead.setOnClickListener { markSelectedRead() }
+ btnDeleteSelected.setOnClickListener { confirmDeleteSelected() }
+ renderSelection(0)
+ }
+
+ /** 只有「信息」与「邮件」支持批量选择与删除(文章/动态没有对应的服务端语义) */
+ private fun selectionAvailable(): Boolean = current == TAB_RSS || current == TAB_MAIL
+
+ /**
+ * 刷新批量操作栏。
+ *
+ * 这根操作栏平时不占位:左滑(或长按)激活选择后 [FeedAdapter.selectionMode] 为 true,
+ * 它才出现在筛选行下面;退出选择(点「完成」、取消掉最后一项、切页、批量操作完成)
+ * 之后再次隐藏,界面回到平常的样子。
+ */
+ private fun renderSelection(count: Int) {
+ val on = adapter.selectionMode && selectionAvailable()
+ selectionBar.visibility = if (on) View.VISIBLE else View.GONE
+ if (!on) return
+ btnSelectAll.isEnabled = adapter.itemCount > 0
+ btnSelectAll.alpha = if (btnSelectAll.isEnabled) 1f else 0.45f
+ btnSelectAll.text = getString(
+ if (adapter.allSelected()) R.string.select_none else R.string.select_all
+ )
+ tvSelectedCount.text = if (count > 0) getString(R.string.selected_count, count) else ""
+ listOf(btnMarkRead, btnDeleteSelected).forEach { btn ->
+ btn.isEnabled = count > 0
+ btn.alpha = if (btn.isEnabled) 1f else 0.45f
+ }
+ }
+
+ /** 当前选中的条目(按 key 回 allItems 里取,拿到的都是完整字段) */
+ private fun selectedItems(): List {
+ val keys = adapter.selectedKeys()
+ if (keys.isEmpty()) return emptyList()
+ return allItems.filter { keys.contains(keyOf(it)) }
+ }
+
+ /** 批量设为已读:邮件走 IMAP 补标,RSS 只写本地已读集(站点接口只读) */
+ private fun markSelectedRead() {
+ if (!adapter.selectionMode) return
+ val targets = selectedItems().filter { !it.read }
+ if (targets.isEmpty()) {
+ toast(getString(R.string.mark_read_none))
+ return
+ }
+
+ if (current == TAB_MAIL) {
+ val mails = targets.mapNotNull { item ->
+ val uid = item.id.substringAfterLast('|').toLongOrNull() ?: return@mapNotNull null
+ val account = prefs.mailAccount(item.account) ?: return@mapNotNull null
+ account to uid
+ }
+ targets.forEach { item ->
+ val index = allItems.indexOfFirst { it.kind == item.kind && it.id == item.id }
+ if (index >= 0) allItems[index] = allItems[index].copy(read = true)
+ }
+ mailUnread = (mailUnread - targets.size).coerceAtLeast(0)
+ renderBadges()
+ adapter.exitSelection()
+ applyFilter()
+ toast(getString(R.string.mark_read_done))
+ lifecycleScope.launch {
+ var failed = 0
+ withContext(Dispatchers.IO) {
+ // 本地缓存先落盘,保证下次进入仍是已读
+ targets.forEach { item ->
+ val uid = item.id.substringAfterLast('|').toLongOrNull() ?: return@forEach
+ val account = prefs.mailAccount(item.account) ?: return@forEach
+ MailApi.markSeenLocal(prefs, account, uid, true)
+ }
+ }
+ for ((account, uid) in mails) {
+ val ok = runCatching {
+ withContext(Dispatchers.IO) {
+ MailApi.setSeen(prefs, account, uid, "INBOX", true)
+ }
+ }.isSuccess
+ if (!ok) failed++
+ }
+ refreshMailBadge()
+ if (failed > 0) toast("有 $failed 封邮件没同步到服务器,下次同步会校正")
+ }
+ return
+ }
+
+ targets.forEach { prefs.setRssRead(it.id, true) }
+ targets.forEach { item ->
+ val index = allItems.indexOfFirst { it.kind == item.kind && it.id == item.id }
+ if (index >= 0) allItems[index] = allItems[index].copy(read = true)
+ }
+ rssUnread = (rssUnread - targets.size).coerceAtLeast(0)
+ RssApi.adjustUnread(-targets.size)
+ renderBadges()
+ adapter.exitSelection()
+ applyFilter()
+ toast(getString(R.string.mark_read_done))
+ }
+
+ private fun confirmDeleteSelected() {
+ if (!adapter.selectionMode) return
+ val targets = selectedItems()
+ if (targets.isEmpty()) return
+ val isMail = current == TAB_MAIL
+ AlertDialog.Builder(this)
+ .setTitle(getString(R.string.delete_selected_title, targets.size))
+ .setMessage(
+ getString(
+ if (isMail) R.string.delete_selected_msg else R.string.delete_selected_msg_local
+ )
+ )
+ .setNegativeButton(R.string.cancel, null)
+ .setPositiveButton(R.string.delete) { _, _ -> performDelete(targets) }
+ .show()
+ }
+
+ /** 批量删除:邮件的服务端删除与其它类型的本地隐藏分开跑,互不影响 */
+ private fun performDelete(targets: List) {
+ adapter.exitSelection()
+ val mails = targets.filter { it.kind == TAB_MAIL }
+ val locals = targets.filter { it.kind != TAB_MAIL }
+ if (locals.isNotEmpty()) hideLocally(locals)
+ if (mails.isNotEmpty()) deleteMails(mails)
+ }
+
+ /**
+ * RSS / 文章删除=本地隐藏。
+ *
+ * 站点只提供查询接口(obsidianItems 等),没有删除条目的入口,
+ * 所以记下 id 后在列表与未读统计里都跳过,观感与删除一致。
+ * key 带类型前缀,避免 RSS 的 id 与文章 cid 数值相同而互相误伤。
+ */
+ private fun hideLocally(targets: List) {
+ prefs.hideRssIds(targets.map { "${it.kind}:${it.id}" })
+ val keys = targets.map { keyOf(it) }.toSet()
+ val removedUnread = targets.count { !it.read }
+ allItems.removeAll { keys.contains(keyOf(it)) }
+ if (removedUnread > 0) {
+ rssUnread = (rssUnread - removedUnread).coerceAtLeast(0)
+ RssApi.adjustUnread(-removedUnread)
+ renderBadges()
+ }
+ applyFilter()
+ toast(getString(R.string.deleted_count, targets.size))
+ }
+
+ /** 邮件删除:先乐观移除,再逐封 IMAP 删除;失败的整表读回缓存 */
+ private fun deleteMails(targets: List) {
+ val keys = targets.map { keyOf(it) }.toSet()
+ val removedUnread = targets.count { !it.read }
+ allItems.removeAll { keys.contains(keyOf(it)) }
+ if (removedUnread > 0) {
+ mailUnread = (mailUnread - removedUnread).coerceAtLeast(0)
+ renderBadges()
+ }
+ applyFilter()
+ lifecycleScope.launch {
+ var failed = 0
+ var lastError: String? = null
+ for (item in targets) {
+ val uid = item.id.substringAfterLast('|').toLongOrNull() ?: continue
+ val account = prefs.mailAccount(item.account) ?: continue
+ val error = runCatching {
+ withContext(Dispatchers.IO) { MailApi.delete(prefs, account, uid, "INBOX") }
+ }.exceptionOrNull()
+ // GoneException 表示服务器上本来就没有,等同删除成功
+ if (error != null && error !is MailApi.GoneException) {
+ failed++
+ if (lastError == null) lastError = error.message
+ }
+ }
+ refreshMailBadge()
+ if (failed > 0) {
+ toast(getString(R.string.delete_failed, failed, lastError ?: "未知错误"))
+ refreshMailList()
+ } else {
+ toast(getString(R.string.deleted_count, targets.size))
+ }
+ }
+ }
+
+ private fun setupNav() {
+ // 点击区域是整格(文字 + 角标),所以监听挂在包住它们的容器上
+ findViewById(R.id.navInfoHost).setOnClickListener { switchTab(TAB_RSS) }
+ findViewById(R.id.navMailHost).setOnClickListener { switchTab(TAB_MAIL) }
+ findViewById(R.id.navPublish).setOnClickListener { showPublishSheet() }
+ findViewById(R.id.btnSettingsHome).setOnClickListener {
+ startActivity(Intent(this, SettingsActivity::class.java))
+ }
+ }
+
+ // ==================== 未读角标 ====================
+
+ /** 未读 RSS 条数(全部条目,不只是当前列表里已加载的这些) */
+ private var rssUnread = 0
+
+ /** 全部邮箱的未读邮件数 */
+ private var mailUnread = 0
+
+ private var rssBadgeJob: Job? = null
+ private var mailBadgeJob: Job? = null
+
+ /** 统计任务序号:后发起的任务才能写结果,避免慢的旧任务把新结果覆盖掉 */
+ private var rssBadgeSeq = 0
+ private var mailBadgeSeq = 0
+
+ /**
+ * 统计并刷新两个角标。
+ *
+ * 信息角标 = 未读 RSS 条数:本地只存「已读集合」,条目集合必须向服务端要,
+ * 所以这里按 100 条/页把条目扫一遍再相减——只数已加载的前 20 条会明显偏小。
+ * 邮件角标 = 所有账户缓存里的未读邮件数,数据本来就在本地,直接数即可。
+ */
+ private fun refreshBadges(rssForce: Boolean = false) {
+ refreshRssBadge(rssForce)
+ refreshMailBadge()
+ }
+
+ private fun refreshRssBadge(force: Boolean) {
+ if (!prefs.rssReady) {
+ rssBadgeJob?.cancel()
+ rssBadgeSeq++
+ rssUnread = 0
+ renderBadges()
+ return
+ }
+ val seq = ++rssBadgeSeq
+ rssBadgeJob?.cancel()
+ rssBadgeJob = lifecycleScope.launch {
+ val count = try {
+ withContext(Dispatchers.IO) { RssApi.unreadCount(prefs, force) }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ // 统计失败就保留上次的数字,不要让角标忽有忽无
+ return@launch
+ }
+ if (seq != rssBadgeSeq) return@launch
+ rssUnread = count
+ renderBadges()
+ }
+ }
+
+ private fun refreshMailBadge() {
+ if (prefs.mailAccounts().none { it.email.isNotBlank() }) {
+ mailBadgeJob?.cancel()
+ mailBadgeSeq++
+ mailUnread = 0
+ renderBadges()
+ return
+ }
+ val seq = ++mailBadgeSeq
+ mailBadgeJob?.cancel()
+ mailBadgeJob = lifecycleScope.launch {
+ // 缓存是磁盘 JSON,解析放 IO 线程;这里每次都重算,避免本地增减与服务端修正后的真实值脱节
+ val count = try {
+ withContext(Dispatchers.IO) {
+ MailApi.cachedAll(prefs).count { !it.item.seen }
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ return@launch
+ }
+ if (seq != mailBadgeSeq) return@launch
+ mailUnread = count
+ renderBadges()
+ }
+ }
+
+ private fun renderBadges() {
+ bindBadge(badgeInfo, rssUnread)
+ bindBadge(badgeMail, mailUnread)
+ }
+
+ /** 0 隐藏;三位数收成 99+,避免把菜单文字挤走 */
+ private fun bindBadge(view: TextView, count: Int) {
+ if (count <= 0) {
+ view.visibility = View.GONE
+ return
+ }
+ view.text = if (count > 99) "99+" else count.toString()
+ view.visibility = View.VISIBLE
+ }
+
+ private fun setupTheme() {
+ val btn = findViewById(R.id.btnThemeHome)
+ btn.setImageResource(if (isNight())
+ R.drawable.ic_sun else R.drawable.ic_moon)
+ btn.setOnClickListener {
+ // 防抖:连续快速点击会让 recreate 排队,产生新旧窗口叠加、卡片深浅混乱
+ val now = System.currentTimeMillis()
+ if (now - lastThemeClick < 1000) return@setOnClickListener
+ lastThemeClick = now
+ val night = isNight()
+ prefs.darkMode = if (night) Prefs.MODE_LIGHT else Prefs.MODE_DARK
+ AppCompatDelegate.setDefaultNightMode(
+ if (night) AppCompatDelegate.MODE_NIGHT_NO else AppCompatDelegate.MODE_NIGHT_YES
+ )
+ }
+ }
+
+ /**
+ * 当前是否为深色:以 Activity 实际生效的 configuration 为准。
+ * 不能用 prefs.nightMode() == MODE_NIGHT_YES —— 用户没手动切过时它是
+ * FOLLOW_SYSTEM,系统深色下会误判成浅色,弹窗就会与页面不一致。
+ */
+ private fun isNight(): Boolean =
+ (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) ==
+ Configuration.UI_MODE_NIGHT_YES
+
+ private var lastThemeClick = 0L
+
+ /**
+ * 发布二级菜单:底部「发布」按钮上方展开的圆角面板,
+ * 两行纯文字(发布文章 / 发布微博),不用系统弹窗。
+ */
+ private fun showPublishSheet() {
+ // 背景统一交给 PopupWindow,与站点/筛选弹窗走同一套深浅色逻辑;
+ // panel 只保留 6dp 内边距,与背景的 6dp inset 对齐,文字不会压到圆角上。
+ // 配色一次性取齐:背景与文字必须来自同一份资源,否则深浅色切换后
+ // 会出现「深色背景 + 浅色模式黑字」的黑底黑字。
+ val palette = Ui.popupPalette(this)
+ val panel = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(dp(6), dp(6), dp(6), dp(6))
+ }
+
+ val options = listOf(
+ getString(R.string.publish_article),
+ getString(R.string.publish_memo),
+ )
+
+ options.forEachIndexed { index, title ->
+ val row = TextView(this).apply {
+ text = title
+ textSize = 15f
+ setTextColor(palette.text)
+ // 文字水平居中,左右留对称内边距,菜单不再偏宽
+ gravity = Gravity.CENTER
+ setPadding(dp(12), 0, dp(12), 0)
+ minimumHeight = dp(46)
+ isClickable = true
+ isFocusable = true
+ val attrs = obtainStyledAttributes(intArrayOf(android.R.attr.selectableItemBackground))
+ background = attrs.getDrawable(0)
+ attrs.recycle()
+
+ setOnClickListener {
+ sheetPopup?.dismiss()
+ val intent = Intent(this@HomeActivity, MainActivity::class.java).apply {
+ putExtra(MainActivity.EXTRA_TAB, if (index == 0) "publish" else "memo")
+ }
+ startActivity(intent)
+ }
+ }
+ panel.addView(row)
+
+ if (index < options.lastIndex) {
+ panel.addView(View(this).apply {
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT, dp(1),
+ ).apply { setMargins(dp(12), dp(4), dp(12), dp(4)) }
+ setBackgroundColor(palette.divider)
+ })
+ }
+ }
+
+ // 宽度只比最宽的菜单文字稍宽一点,不再固定偏宽。
+ // extraDp 必须覆盖:背景 inset 6dp×2 + panel padding 6dp×2 + 行内边距 12dp×2 = 48,
+ // 再留 16dp 余量。之前正好取 48,文字可用宽度等于文字宽度,一点裕度都没有,
+ // 四字标题在部分字体/字号缩放下会贴边甚至换行。
+ val popupW = Ui.menuWidth(
+ this, options, textSizeSp = 15f, extraDp = 64, minDp = 120, maxDp = 240,
+ )
+ panel.measure(
+ View.MeasureSpec.makeMeasureSpec(popupW - dp(12), View.MeasureSpec.EXACTLY),
+ View.MeasureSpec.UNSPECIFIED,
+ )
+ val popupH = panel.measuredHeight
+ val popup = PopupWindow(panel, popupW, popupH, true).apply {
+ isOutsideTouchable = true
+ setBackgroundDrawable(palette.background())
+ elevation = dp(10).toFloat()
+ }
+ sheetPopup = popup
+
+ // 贴着底部「发布」按钮的正上方居中展开,留 5dp 呼吸间距
+ val anchor = findViewById(R.id.navPublish)
+ val loc = IntArray(2)
+ val rootLoc = IntArray(2)
+ anchor.getLocationOnScreen(loc)
+ anchor.rootView.getLocationOnScreen(rootLoc)
+ val rootW = anchor.rootView.width
+ val x = (loc[0] - rootLoc[0] + (anchor.width - popupW) / 2)
+ .coerceIn(dp(12), (rootW - popupW - dp(12)).coerceAtLeast(dp(12)))
+ val y = loc[1] - rootLoc[1] - popupH - dp(5)
+ popup.showAtLocation(anchor.rootView, Gravity.TOP or Gravity.START, x, y)
+ }
+
+ private var sheetPopup: PopupWindow? = null
+
+ // ==================== 切换与加载 ====================
+
+ private fun switchTab(tab: String) {
+ if (current == tab) return
+ current = tab
+ filterMode = FILTER_ALL
+ btnFilter.text = getString(R.string.filter_all)
+ etFilter.setText("")
+ keyword = ""
+ // 换页时退出选择模式,避免带着上一页的选中状态
+ if (adapter.selectionMode) adapter.exitSelection()
+ updateTabStyle()
+ load(refresh = true)
+ }
+
+ private fun updateTabStyle() {
+ val isMail = current == TAB_MAIL
+ feedTabs.visibility = if (isMail) View.GONE else View.VISIBLE
+ // 批量操作栏平时不占位,只在选择模式下出现;切走后必须退出选择模式,
+ // 否则回来时列表是「点一下只勾选」的状态,点卡片打不开内容
+ val canSelect = selectionAvailable()
+ adapter.selectionEnabled = canSelect
+ if (!canSelect && adapter.selectionMode) adapter.exitSelection()
+ renderSelection(adapter.selectedCount())
+ // 文章页按站点筛选、邮件页按邮箱切换;其它页隐藏
+ when (current) {
+ TAB_ARTICLE -> {
+ btnSourcePick.visibility = View.VISIBLE
+ btnSourcePick.text = prefs.siteLabel(prefs.typechoCurrent)
+ }
+ TAB_MAIL -> {
+ // 被筛选的邮箱可能已在设置里删除,这里自动退回「全部邮箱」
+ if (mailFilter.isNotBlank() && prefs.mailAccount(mailFilter) == null) {
+ mailFilter = ""
+ }
+ btnSourcePick.visibility = View.VISIBLE
+ btnSourcePick.text = mailFilterLabel()
+ }
+ else -> btnSourcePick.visibility = View.GONE
+ }
+ navInfo.setTextColor(if (isMail) colorSecondary() else colorBrand())
+ navMail.setTextColor(if (isMail) colorBrand() else colorSecondary())
+
+ val activeTab = when (current) {
+ TAB_ARTICLE -> tabArticle
+ TAB_MEMO -> tabMemo
+ else -> tabRss
+ }
+ listOf(tabRss, tabArticle, tabMemo).forEach { tab ->
+ val on = tab === activeTab
+ tab.setBackgroundResource(if (on) R.drawable.bg_segment_on else 0)
+ tab.setTextColor(if (on) colorText() else colorSecondary())
+ }
+ }
+
+ /** 邮件页顶部按钮文案:未筛选时显示「全部邮箱」 */
+ private fun mailFilterLabel(): String {
+ if (mailFilter.isBlank()) return getString(R.string.mail_all_accounts)
+ return prefs.mailAccount(mailFilter)?.label ?: getString(R.string.mail_all_accounts)
+ }
+
+ /**
+ * 站点 / 邮箱切换弹窗:与分类下拉同款样式,向上展开,文字居中、左右对称。
+ * 文章页切站点会重新加载;邮件页只是本地筛选(数据本来就是全账户合并的)。
+ */
+ private fun showSourcePickPopup() {
+ if (current == TAB_MAIL) {
+ val accounts = prefs.mailAccounts().filter { it.email.isNotBlank() }
+ if (accounts.isEmpty()) return
+ val labels = ArrayList(accounts.size + 1)
+ labels.add(getString(R.string.mail_all_accounts))
+ accounts.forEach { labels.add(it.label) }
+ val checked = if (mailFilter.isBlank()) 0 else {
+ val index = accounts.indexOfFirst { it.email.equals(mailFilter, true) }
+ if (index < 0) 0 else index + 1
+ }
+ showPickList(labels, checked) { position ->
+ mailFilter = if (position <= 0) "" else accounts[position - 1].email
+ updateTabStyle()
+ applyFilter()
+ }
+ return
+ }
+
+ val count = prefs.siteCount()
+ if (count == 0) return
+ val labels = (0 until count).map { prefs.siteLabel(it) }
+ showPickList(labels, prefs.typechoCurrent) { position ->
+ prefs.typechoCurrent = position
+ updateTabStyle()
+ load(refresh = true)
+ }
+ }
+
+ /** 通用「单选下拉」:labels + 当前选中项 + 选中回调 */
+ private fun showPickList(labels: List, checked: Int, onPick: (Int) -> Unit) {
+ val palette = Ui.popupPalette(this)
+ val currentIdx = checked.coerceIn(0, (labels.size - 1).coerceAtLeast(0))
+
+ val listView = ListView(this).apply {
+ adapter = object : ArrayAdapter(
+ this@HomeActivity, R.layout.item_dropdown_center, labels,
+ ) {
+ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
+ val view = super.getView(position, convertView, parent) as TextView
+ // 与背景同一套色板:先前这里取的是页面资源、背景取自另一份资源,
+ // 深色切浅色后就成了「深底 + 黑字」,未选中项完全看不见。
+ view.setTextColor(if (position == currentIdx) palette.brand else palette.text)
+ return view
+ }
+ }
+ dividerHeight = 0
+ setPadding(0, dp6(), 0, dp6())
+ scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
+ }
+ val listH = (labels.size * dp(46) + dp(12)).coerceAtMost(dp(320))
+ val popupH = listH + dp(12)
+ // 宽度只比最宽的站点 / 邮箱名稍宽,不再与筛选按钮等宽
+ val popupW = Ui.menuWidth(
+ this, labels, textSizeSp = 15f, extraDp = 52, minDp = 110, maxDp = 320,
+ )
+ val popup = PopupWindow(listView, popupW, popupH, true).apply {
+ isOutsideTouchable = true
+ setBackgroundDrawable(palette.background())
+ elevation = dp(8).toFloat()
+ }
+ listView.setOnItemClickListener { _, _, position, _ ->
+ popup.dismiss()
+ onPick(position)
+ }
+ val loc = IntArray(2)
+ val rootLoc = IntArray(2)
+ btnSourcePick.getLocationOnScreen(loc)
+ btnSourcePick.rootView.getLocationOnScreen(rootLoc)
+ // 以筛选按钮为中心展开,弹出框别顶出屏幕两边
+ val x = (loc[0] - rootLoc[0] + (btnSourcePick.width - popupW) / 2)
+ .coerceIn(dp(8), (btnSourcePick.rootView.width - popupW - dp(8)).coerceAtLeast(dp(8)))
+ popup.showAtLocation(
+ btnSourcePick.rootView,
+ Gravity.TOP or Gravity.START,
+ x,
+ loc[1] - rootLoc[1] - popupH - dp(6),
+ )
+ }
+
+ private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt()
+ private fun dp6(): Int = dp(6)
+
+ private fun colorBrand(): Int = getColor(R.color.brand)
+ private fun colorSecondary(): Int = getColor(R.color.text_secondary)
+ private fun colorText(): Int = getColor(R.color.text)
+
+ private fun emptyText(): String = when (current) {
+ // 邮件要分两种:真的没配置,还是配置好了但最近没邮件。
+ // 原先不论哪种都说"先到设置里填邮箱",配置正确的人会被误导成配置丢了。
+ TAB_MAIL -> {
+ val accounts = prefs.mailAccounts().filter { it.ready }
+ if (accounts.isEmpty()) {
+ getString(R.string.feed_empty_mail)
+ } else {
+ getString(R.string.feed_empty_mail_none, accounts.maxOf { it.days })
+ }
+ }
+ TAB_ARTICLE -> if (prefs.typechoReady) getString(R.string.feed_empty) else getString(R.string.feed_empty_article)
+ TAB_MEMO -> if (prefs.memosReady) getString(R.string.feed_empty) else getString(R.string.feed_empty_memo)
+ else -> if (prefs.rssReady) getString(R.string.feed_empty) else getString(R.string.feed_empty_rss)
+ }
+
+ private fun load(refresh: Boolean) {
+ loadJob?.cancel()
+ rssPage = 1
+ articlePage = 1
+ memoToken = ""
+ allItems.clear()
+ adapter.submit(emptyList())
+ tvEmpty.visibility = View.GONE
+
+ if (refresh) swipeRefresh.isRefreshing = true else progress.visibility = View.VISIBLE
+
+ loadJob = lifecycleScope.launch {
+ try {
+ val result = withContext(Dispatchers.IO) {
+ when (current) {
+ TAB_ARTICLE -> loadArticles()
+ TAB_MEMO -> loadMemos()
+ TAB_MAIL -> loadMails()
+ else -> loadRss()
+ }
+ }
+ allItems.clear()
+ allItems.addAll(result.first)
+ applyFilter()
+ // 邮件:缓存先渲染,这里再补一次增量同步
+ if (current == TAB_MAIL) syncMailInBackground()
+ } catch (e: CancellationException) {
+ // 切页 / 刷新会取消旧任务,取消不是错误:静默退出,
+ // 否则「StandaloneCoroutine was cancelled」会挂满屏幕
+ throw e
+ } catch (e: Exception) {
+ tvEmpty.text = "加载失败:${e.message ?: "未知错误"}"
+ tvEmpty.visibility = View.VISIBLE
+ } finally {
+ swipeRefresh.isRefreshing = false
+ progress.visibility = View.GONE
+ }
+ }
+ }
+
+ /** 邮件后台增量同步:逐个账户只拉比缓存里最新 UID 更新的邮件,全部跑完再刷新列表 */
+ private var mailSyncJob: Job? = null
+
+ private fun syncMailInBackground() {
+ if (mailSyncJob?.isActive == true) return
+ // 快照一次账户列表:同步过程可能持续几十秒,中途用户改设置也不影响本轮
+ val accounts = prefs.mailAccounts().filter { it.ready }
+ if (accounts.isEmpty()) return
+ val hadCache = allItems.isNotEmpty()
+ mailSyncJob = lifecycleScope.launch {
+ var added = 0
+ var firstError: String? = null
+ for (account in accounts) {
+ try {
+ added += withContext(Dispatchers.IO) { MailApi.sync(prefs, account) }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ // 单个邮箱失败不影响其它邮箱:记下第一条错误,全部跑完再决定是否提示
+ if (firstError == null) firstError = "${account.label}:${e.message ?: "同步失败"}"
+ }
+ }
+ // 同步会用服务端的已读标记校正缓存,角标必须跟着重算(不论当前在哪个页)
+ refreshMailBadge()
+ if (current != TAB_MAIL) return@launch
+ // 300 封邮件的 JSON 解析放 IO 线程,避免主线程卡顿
+ val items = withContext(Dispatchers.IO) {
+ mailsToFeedItems(MailApi.cachedAll(prefs))
+ }
+ allItems.clear()
+ allItems.addAll(items)
+ applyFilter()
+ if (added > 0) {
+ toast("收到 $added 封新邮件")
+ } else if (firstError != null && !hadCache && allItems.isEmpty()) {
+ tvEmpty.text = "邮件同步失败:$firstError"
+ tvEmpty.visibility = View.VISIBLE
+ }
+ }
+ }
+
+ private suspend fun loadRss(): Pair, Boolean> {
+ if (!prefs.rssReady) return emptyList() to false
+ val result = RssApi.items(prefs, 1, keyword)
+ rssPage = result.page
+ rssPages = result.pages
+ memoHasMore = result.page < result.pages
+ return result.items.filterNot { prefs.isRssHidden("$TAB_RSS:${it.id}") }.map { item ->
+ FeedItem(
+ kind = TAB_RSS,
+ id = item.id.toString(),
+ title = item.title,
+ source = item.siteTitle.ifBlank { item.categoryName },
+ date = parseDate(item.pubDate),
+ summary = item.excerpt,
+ link = item.link,
+ read = prefs.isRssRead(item.id.toString()),
+ content = item.excerpt,
+ )
+ } to memoHasMore
+ }
+
+ /**
+ * 文章搜索是客户端过滤(Typecho 插件接口没有 search 参数),
+ * 首页与「加载更多」必须走同一套规则,否则搜索后翻页会混进不匹配的文章。
+ */
+ private fun List.matchKeyword(): List =
+ if (keyword.isBlank()) this
+ else filter { it.title.contains(keyword, true) || it.digest.contains(keyword, true) }
+
+ private suspend fun loadArticles(): Pair, Boolean> {
+ if (!prefs.typechoReady) return emptyList() to false
+ val result = TypechoApi.posts(prefs, 1)
+ articlePage = result.page
+ articlePages = result.pages
+ return result.posts.matchKeyword().filterNot { prefs.isRssHidden("$TAB_ARTICLE:${it.cid}") }
+ .map { post ->
+ FeedItem(
+ kind = TAB_ARTICLE,
+ id = post.cid.toString(),
+ title = post.title,
+ source = "${prefs.siteLabel(prefs.typechoCurrent)} · ${post.comments} 条评论",
+ date = post.created,
+ summary = post.digest,
+ link = post.permalink,
+ read = true,
+ )
+ } to (result.page < result.pages)
+ }
+
+ private suspend fun loadMemos(): Pair, Boolean> {
+ if (!prefs.memosReady) return emptyList() to false
+ val result = MemosApi.list(prefs, 30)
+ memoToken = result.nextPageToken
+ memoHasMore = result.nextPageToken.isNotEmpty()
+ val list = if (keyword.isBlank()) result.memos else
+ result.memos.filter { it.content.contains(keyword, true) }
+ return list.map { memo ->
+ FeedItem(
+ kind = TAB_MEMO,
+ id = memo.id,
+ title = "",
+ source = if (memo.pinned) "置顶" else "",
+ date = memo.createdTs,
+ summary = memo.content,
+ link = "",
+ read = true,
+ content = memo.content,
+ images = memo.images,
+ )
+ } to memoHasMore
+ }
+
+ /** 缓存的邮件 → 列表项(带关键词过滤);全部账户合并,卡片带上所属邮箱 */
+ private fun mailsToFeedItems(mails: List): List {
+ val list = mails.filter { entry ->
+ val mail = entry.item
+ keyword.isBlank() || mail.subject.contains(keyword, true) ||
+ mail.from.contains(keyword, true) || mail.fromName.contains(keyword, true)
+ }
+ return list.map { entry ->
+ val mail = entry.item
+ FeedItem(
+ kind = TAB_MAIL,
+ // UID 只在单个账户内唯一,卡片标识必须带上邮箱,否则两个账户的同一 UID 会互相顶掉
+ id = "${entry.account.email}|${mail.uid}",
+ title = mail.subject,
+ source = mail.fromName.ifBlank { mail.from },
+ date = mail.date,
+ summary = mail.snippet,
+ link = "",
+ read = mail.seen,
+ hasAttachment = mail.hasAttachment,
+ account = entry.account.email,
+ accountLabel = entry.account.label,
+ )
+ }
+ }
+
+ private suspend fun loadMails(): Pair, Boolean> {
+ if (prefs.mailAccounts().none { it.ready }) return emptyList() to false
+ // 打开即渲染本地缓存(全部账户合并),增量同步放到 syncMailInBackground 里后台做。
+ // 缓存是磁盘 JSON,解析必须在 IO 线程,否则首帧会明显掉帧。
+ val items = withContext(Dispatchers.IO) { mailsToFeedItems(MailApi.cachedAll(prefs)) }
+ return items to false
+ }
+
+ /**
+ * 从缓存重读邮件列表并差量刷新。
+ *
+ * 从详情页返回时用它代替 load():后者会清空列表重新加载、列表弹回顶部,
+ * 而这里只是把缓存的最新状态(已读、摘要、被删的邮件)同步到界面。
+ */
+ private fun refreshMailList() {
+ lifecycleScope.launch {
+ val items = withContext(Dispatchers.IO) { mailsToFeedItems(MailApi.cachedAll(prefs)) }
+ allItems.clear()
+ allItems.addAll(items)
+ applyFilter()
+ }
+ }
+
+ /** 正在加载更多:防止滚动时重复触发,同一时刻只允许一个请求 */
+ private var loadingMore = false
+
+ private fun loadMore() {
+ if (loadingMore) return
+ val job = loadJob
+ if (job?.isActive == true) return
+ if (current == TAB_MAIL) return
+ if (current == TAB_RSS && rssPage >= rssPages) return
+ if (current == TAB_ARTICLE && articlePage >= articlePages) return
+ if (current == TAB_MEMO && memoToken.isEmpty()) return
+
+ loadingMore = true
+ lifecycleScope.launch {
+ var lastError: Exception? = null
+ // 站点偶发拦截(WAF / 限频)时静默重试一次,不给用户报错;
+ // 成功时静默追加,不再弹提示——否则退出 APP 后 Toast 还会留在桌面上
+ try {
+ for (attempt in 1..2) {
+ try {
+ val more = withContext(Dispatchers.IO) { fetchMore() }
+ allItems.addAll(more)
+ if (filterMode == FILTER_ALL) adapter.append(more) else applyFilter()
+ return@launch
+ } catch (e: Exception) {
+ if (e is CancellationException) throw e
+ lastError = e
+ if (attempt == 1) delay(1200)
+ }
+ }
+ toast("加载更多失败:${friendlyError(lastError)}")
+ } finally {
+ loadingMore = false
+ }
+ }
+ }
+
+ /** 拉下一页(loadMore 专用,失败可整体重试) */
+ private suspend fun fetchMore(): List = withContext(Dispatchers.IO) {
+ when (current) {
+ TAB_RSS -> {
+ val result = RssApi.items(prefs, rssPage + 1, keyword)
+ rssPage = result.page
+ rssPages = result.pages
+ result.items.filterNot { prefs.isRssHidden("$TAB_RSS:${it.id}") }.map { item ->
+ FeedItem(TAB_RSS, item.id.toString(), item.title,
+ item.siteTitle.ifBlank { item.categoryName },
+ parseDate(item.pubDate), item.excerpt, item.link,
+ prefs.isRssRead(item.id.toString()), item.excerpt)
+ }
+ }
+ TAB_ARTICLE -> {
+ val result = TypechoApi.posts(prefs, articlePage + 1)
+ articlePage = result.page
+ articlePages = result.pages
+ result.posts.matchKeyword().filterNot { prefs.isRssHidden("$TAB_ARTICLE:${it.cid}") }
+ .map { post ->
+ FeedItem(TAB_ARTICLE, post.cid.toString(), post.title,
+ prefs.siteLabel(prefs.typechoCurrent), post.created,
+ post.digest, post.permalink, true)
+ }
+ }
+ else -> {
+ val result = MemosApi.list(prefs, 30, memoToken)
+ memoToken = result.nextPageToken
+ result.memos.map { memo ->
+ FeedItem(TAB_MEMO, memo.id, "", "", memo.createdTs,
+ memo.content, "", true, memo.content, images = memo.images)
+ }
+ }
+ }
+ }
+
+ /** WAF 拦截页 / HTML 响应转成人话,不再把整页文字甩给用户 */
+ private fun friendlyError(e: Exception?): String {
+ val raw = e?.message ?: "未知错误"
+ return if (raw.contains("拦截") || raw.contains("<") || raw.contains("html", true) ||
+ raw.contains("waf", true) || raw.contains("安全")
+ ) "站点防护拦截了请求,稍后再试" else raw
+ }
+
+ private fun applyFilter() {
+ // 邮件页只在「全部邮箱」时给卡片标注邮箱名:筛了某个邮箱后每张都重复同一个名字
+ adapter.showMailAccount = current != TAB_MAIL || mailFilter.isBlank()
+
+ var list = when (filterMode) {
+ FILTER_UNREAD -> allItems.filter { !it.read }
+ FILTER_READ -> allItems.filter { it.read }
+ else -> allItems
+ }
+ // 邮件页还可按邮箱再筛一层(纯本地过滤,不动网络)
+ if (current == TAB_MAIL && mailFilter.isNotBlank()) {
+ list = list.filter { it.account.equals(mailFilter, true) }
+ }
+ // 差量刷新:只有已读状态变化时不会把列表弹回顶部
+ adapter.update(list)
+ if (adapter.selectionMode) renderSelection(adapter.selectedCount())
+ if (list.isEmpty()) {
+ tvEmpty.text = if (allItems.isEmpty()) emptyText() else "没有符合筛选条件的内容"
+ tvEmpty.visibility = View.VISIBLE
+ } else {
+ tvEmpty.visibility = View.GONE
+ }
+ }
+
+ // ==================== 交互 ====================
+
+ private fun openItem(item: FeedItem) {
+ when (item.kind) {
+ // 卡片 id 形如 "邮箱|UID":必须带上账户,否则会拿当前账户去连服务端
+ TAB_MAIL -> {
+ val uid = item.id.substringAfterLast('|').toLongOrNull() ?: 0L
+ // 点开即已读:列表与缓存先本地生效,服务端标记在后台补
+ if (markLocalRead(item)) {
+ markMailSeenLocally(item, uid)
+ markMailSeenOnServer(item, uid)
+ }
+ MailDetailActivity.open(this, item.account, uid, "INBOX", item.title)
+ }
+ TAB_ARTICLE -> ReaderActivity.open(
+ this, ReaderActivity.KIND_ARTICLE, item.id, item.title,
+ item.source, item.date, "", item.link
+ )
+ TAB_MEMO -> {
+ // 卡片已直接显示全文,不再进阅读内页
+ }
+ else -> {
+ // 点开即已读:先写本地已读集,再原地刷新这一条(不重建列表,滚动位置不动)
+ prefs.setRssRead(item.id, true)
+ if (markLocalRead(item)) RssApi.adjustUnread(-1)
+ ReaderActivity.open(
+ this, ReaderActivity.KIND_RSS, item.id, item.title,
+ item.source, item.date, item.content, item.link
+ )
+ }
+ }
+ }
+
+ /**
+ * 把列表里的一条标为已读(纯内存 + 原地刷新),返回是否真的从「未读」变成了「已读」。
+ *
+ * 不用 applyFilter():那会按筛选条件重建整张表,未读筛选下点开的条目会立刻消失、
+ * 其它条目位置全变,返回首页时找不到刚才读的那条。这里只刷新那一行。
+ */
+ private fun markLocalRead(item: FeedItem): Boolean {
+ if (item.read) return false
+ val index = allItems.indexOfFirst { it.kind == item.kind && it.id == item.id }
+ if (index < 0) return false
+ val updated = allItems[index].copy(read = true)
+ allItems[index] = updated
+ adapter.updateItem(updated)
+ when (item.kind) {
+ TAB_RSS -> if (rssUnread > 0) {
+ rssUnread--
+ renderBadges()
+ }
+ TAB_MAIL -> if (mailUnread > 0) {
+ mailUnread--
+ renderBadges()
+ }
+ }
+ return true
+ }
+
+ /** 本地缓存先记成已读:列表、角标、下次进入都一致,不必等服务端往返 */
+ private fun markMailSeenLocally(item: FeedItem, uid: Long) {
+ if (uid <= 0) return
+ val account = prefs.mailAccount(item.account) ?: return
+ lifecycleScope.launch(Dispatchers.IO) {
+ MailApi.markSeenLocal(prefs, account, uid, true)
+ }
+ }
+
+ /**
+ * 服务端补标已读。
+ *
+ * 刻意不因为失败而把界面改回未读:用户确实点开看过了,
+ * 回滚只会让列表和实际阅读行为对不上;缓存已按已读记录,
+ * 服务端状态会在下一次同步时以服务端为准校正(届时才可能回到未读)。
+ */
+ private fun markMailSeenOnServer(item: FeedItem, uid: Long) {
+ if (uid <= 0) return
+ val account = prefs.mailAccount(item.account) ?: return
+ lifecycleScope.launch {
+ val result = runCatching {
+ withContext(Dispatchers.IO) {
+ MailApi.setSeen(prefs, account, uid, "INBOX", true)
+ }
+ }
+ val error = result.exceptionOrNull() ?: return@launch
+ if (error is MailApi.GoneException) {
+ toast(error.message ?: "邮件已不存在")
+ load(refresh = true)
+ return@launch
+ }
+ toast("已标为已读,但同步到邮箱失败:${error.message ?: "未知错误"}")
+ }
+ }
+
+ private fun toggleRead(item: FeedItem) {
+ // 列表持有的是不可变 FeedItem,改完必须替换 allItems 里那一条,
+ // 否则 applyFilter() 仍按旧状态过滤("标为未读"后不会消失)
+ val index = allItems.indexOfFirst { it.kind == item.kind && it.id == item.id }
+ if (index < 0) return
+ val target = !item.read
+
+ when (item.kind) {
+ TAB_RSS -> {
+ prefs.setRssRead(item.id, target)
+ allItems[index] = allItems[index].copy(read = target)
+ applyFilter()
+ // 角标同步挪一格,并与统计缓存对齐,切页回来不会跳
+ val delta = if (target) -1 else 1
+ rssUnread = (rssUnread + delta).coerceAtLeast(0)
+ RssApi.adjustUnread(delta)
+ renderBadges()
+ }
+
+ TAB_MAIL -> {
+ val uid = item.id.substringAfterLast('|').toLongOrNull() ?: return
+ // 必须按卡片记录的邮箱去连:列表是所有账户合并的,
+ // 拿「当前账户」会把已读标到另一个邮箱里同 UID 的邮件上
+ val account = prefs.mailAccount(item.account)
+ if (account == null) {
+ toast("这个邮箱的配置已被删除")
+ return
+ }
+ // 先本地生效,再后台同步到 IMAP,失败时回滚并提示
+ allItems[index] = allItems[index].copy(read = target)
+ applyFilter()
+ mailUnread = (mailUnread + if (target) -1 else 1).coerceAtLeast(0)
+ renderBadges()
+ lifecycleScope.launch {
+ val result = runCatching {
+ withContext(Dispatchers.IO) {
+ MailApi.setSeen(prefs, account, uid, "INBOX", target)
+ }
+ }
+ val error = result.exceptionOrNull()
+ if (error == null) {
+ // 服务端已同步:以缓存里的真实状态重算角标
+ refreshMailBadge()
+ return@launch
+ }
+ if (error is MailApi.GoneException) {
+ // 服务端已没有这封邮件:缓存已被清理,整表重读让它从列表消失
+ toast(error.message ?: "邮件已不存在")
+ load(refresh = true)
+ refreshMailBadge()
+ return@launch
+ }
+ val current = allItems.indexOfFirst {
+ it.kind == TAB_MAIL && it.id == item.id
+ }
+ if (current >= 0) {
+ allItems[current] = allItems[current].copy(read = item.read)
+ applyFilter()
+ }
+ refreshMailBadge()
+ toast("同步到邮箱失败,已还原状态:${error.message ?: "未知错误"}")
+ }
+ }
+
+ else -> toast("仅 RSS 与邮件支持切换已读状态")
+ }
+ }
+
+ /** 日期解析格式按线程缓存,避免每条 RSS 都新建 SimpleDateFormat */
+ private val dateFormats = object : ThreadLocal>() {
+ override fun initialValue(): List = listOf(
+ java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.US),
+ java.text.SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.US),
+ java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", java.util.Locale.US),
+ java.text.SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", java.util.Locale.US),
+ java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US),
+ )
+ }
+
+ private fun parseDate(raw: String): Long {
+ if (raw.isBlank()) return 0L
+ for (format in dateFormats.get() ?: emptyList()) {
+ runCatching {
+ return format.parse(raw)?.time ?: 0L
+ }
+ }
+ return 0L
+ }
+
+ /** 页面已退出时不再弹提示,避免 Toast 残留在桌面上 */
+ private fun toast(text: String) {
+ if (isFinishing || isDestroyed) return
+ Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
+ }
+
+ override fun onResume() {
+ super.onResume()
+ val btn = findViewById(R.id.btnThemeHome)
+ btn.setImageResource(if (prefs.nightMode() == AppCompatDelegate.MODE_NIGHT_YES)
+ R.drawable.ic_sun else R.drawable.ic_moon)
+ // 从阅读页 / 邮件详情 / 设置页回来时整表按当前主题重刷:
+ // 绑定时逐项重设配色(FeedAdapter 内部完成),任何来源的卡片都不会深浅混排
+ recyclerView.recycledViewPool.clear()
+ adapter.refreshTheme()
+ // 设置页可能改过站点 / 邮箱名称,刷新一次顶部来源标签
+ updateTabStyle()
+ // 邮件详情里删了信、回填了摘要或已读过,回来按缓存差量刷新(不重建,滚动位置不动)
+ if (MailDetailActivity.consumeDataChanged() && current == TAB_MAIL) {
+ refreshMailList()
+ refreshMailBadge()
+ }
+ }
+}
diff --git a/src/main/java/com/shitoucuo/postpad/Http.kt b/src/main/java/com/shitoucuo/postpad/Http.kt
new file mode 100644
index 0000000..b28635d
--- /dev/null
+++ b/src/main/java/com/shitoucuo/postpad/Http.kt
@@ -0,0 +1,48 @@
+package com.shitoucuo.postpad
+
+import android.content.Context
+import okhttp3.Cache
+import okhttp3.OkHttpClient
+import java.io.File
+import java.util.concurrent.TimeUnit
+
+/**
+ * 全局共享的 OkHttpClient:连接池、线程池只保留一份。
+ * 各 API 用 newWith() 微调超时,底层仍复用同一连接池,减少并发开销。
+ */
+object Http {
+
+ val client: OkHttpClient = OkHttpClient.Builder()
+ .connectTimeout(20, TimeUnit.SECONDS)
+ .writeTimeout(180, TimeUnit.SECONDS)
+ .readTimeout(120, TimeUnit.SECONDS)
+ .build()
+
+ /** 在共享实例基础上调整超时;连接池与调度线程池与全局共用 */
+ fun newWith(connect: Long, write: Long, read: Long, unit: TimeUnit): OkHttpClient =
+ client.newBuilder()
+ .connectTimeout(connect, unit)
+ .writeTimeout(write, unit)
+ .readTimeout(read, unit)
+ .build()
+
+ @Volatile
+ private var cachedImageClient: OkHttpClient? = null
+
+ /**
+ * 图片专用客户端:在共享连接池上加 64MB 磁盘缓存。
+ *
+ * 图床/资源响应带 `Cache-Control: public, max-age=31536000`(一年)。没有磁盘缓存时,
+ * 列表每次复用卡片都会把几 MB 的原图重新下载一遍——滚动一趟就是几十 MB 流量。
+ *
+ * 必须是**单例**:OkHttp 的 Cache 不允许两个实例指向同一目录(日志文件会互相踩),
+ * 而列表缩略图与大图预览用的是同一批 URL,共用一份缓存命中率也最高。
+ */
+ fun imageClient(context: Context): OkHttpClient =
+ cachedImageClient ?: synchronized(this) {
+ cachedImageClient ?: run {
+ val cache = Cache(File(context.cacheDir, "image-cache"), 64L * 1024 * 1024)
+ client.newBuilder().cache(cache).build().also { cachedImageClient = it }
+ }
+ }
+}
diff --git a/src/main/java/com/shitoucuo/postpad/ImageCache.kt b/src/main/java/com/shitoucuo/postpad/ImageCache.kt
new file mode 100644
index 0000000..9284e0c
--- /dev/null
+++ b/src/main/java/com/shitoucuo/postpad/ImageCache.kt
@@ -0,0 +1,71 @@
+package com.shitoucuo.postpad
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.util.LruCache
+
+/**
+ * 列表与预览页共享的位图缓存。
+ *
+ * 点开大图时,卡片里的那张图其实**已经解码在内存里**(Markwon 的 AsyncDrawable 持有它)。
+ * 预览页先拿这张立即显示,再去请求原图;网络被拦、地址被改写、图床限流时,
+ * 至少不会只剩一行「加载失败」,用户点开的图一定能看到。
+ * 上限 8MB,只存最近看过的几张,不会长期占内存。
+ */
+object ImageMemoryCache {
+
+ private val cache = object : LruCache(8 * 1024 * 1024) {
+ override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount
+ }
+
+ fun put(url: String, bitmap: Bitmap?) {
+ if (url.isBlank() || bitmap == null || bitmap.isRecycled) return
+ cache.put(url, bitmap)
+ }
+
+ fun get(url: String): Bitmap? {
+ if (url.isBlank()) return null
+ val bitmap = cache.get(url) ?: return null
+ return if (bitmap.isRecycled) null else bitmap
+ }
+}
+
+/**
+ * 图片地址归一化。
+ *
+ * Markdown 正文里的图片地址由用户手写,形态比 resourceList 里的 externalLink 杂得多:
+ * 常见 `` 包裹、`&` 实体、协议相对 `//host/a.jpg`、Memos 的相对路径
+ * `/file/xxx.jpg`、以及地址里带空格。这些写法 OkHttp 直接拒绝(抛 IllegalArgumentException),
+ * 表现为「点了图进去提示加载失败」,而列表里 Markwon 用的是另一套解析,所以图又能显示。
+ * 统一在这里收敛成可直接请求的绝对地址。
+ */
+object ImageUrl {
+
+ fun normalize(context: Context, raw: String): String {
+ var s = raw.trim()
+ // CommonMark 允许 包一层,用于地址里带空格的情况
+ if (s.length > 2 && s.startsWith("<") && s.endsWith(">")) {
+ s = s.substring(1, s.length - 1).trim()
+ }
+ // Markdown 正文里 & 常被转义成实体
+ s = s.replace("&", "&")
+
+ if (s.startsWith("data:", true)) return s
+ if (s.startsWith("//")) s = "https:$s"
+
+ // Memos 自带资源的相对路径,按配置的站点补全
+ if (s.startsWith("/")) {
+ val base = runCatching { Prefs(context).memosUrl }.getOrNull().orEmpty().trimEnd('/')
+ if (base.isNotEmpty()) s = base + s
+ }
+ if (s.startsWith("file://") || s.startsWith("content://")) return s
+
+ if (!s.contains("://")) {
+ // 只可能是漏了协议;不像域名就原样返回,让上层给出明确错误
+ if (!s.contains('.')) return s
+ s = "https://$s"
+ }
+ // OkHttp 会拒绝含空格的 URL;图片地址里的空格按 RFC 3986 编码即可
+ return s.replace(" ", "%20")
+ }
+}
diff --git a/src/main/java/com/shitoucuo/postpad/ImagePreviewActivity.kt b/src/main/java/com/shitoucuo/postpad/ImagePreviewActivity.kt
new file mode 100644
index 0000000..dc97391
--- /dev/null
+++ b/src/main/java/com/shitoucuo/postpad/ImagePreviewActivity.kt
@@ -0,0 +1,425 @@
+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.Matrix
+import android.graphics.RectF
+import android.net.Uri
+import android.os.Bundle
+import android.util.TypedValue
+import android.view.GestureDetector
+import android.view.Gravity
+import android.view.MotionEvent
+import android.view.ScaleGestureDetector
+import android.view.View
+import android.view.ViewGroup
+import android.widget.FrameLayout
+import android.widget.ProgressBar
+import android.widget.TextView
+import androidx.appcompat.app.AppCompatActivity
+import androidx.lifecycle.lifecycleScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import okhttp3.Request
+
+/**
+ * 大图预览:黑底、双指缩放、放大后单指拖动、双击在「适应屏幕 / 2.5 倍」之间切换,
+ * 单击图片或点右上角 × 退出。
+ *
+ * 界面用代码搭建:整页只有一张图和两个状态提示,写成布局文件反而多几个文件要维护。
+ *
+ * 取图分三层,任何一层成功就显示,避免"点开只剩一行加载失败":
+ * 1. [ImageMemoryCache]:卡片上那张图已经解码在内存里,点开立即显示;
+ * 2. 原图下载:[Http.imageClient] 与列表共用 64MB 磁盘缓存,列表里下过的图直接命中;
+ * 3. 地址归一化 + 退一步的请求头(浏览器 UA + Referer):正文里手写的图片地址
+ * 常带 `<…>`、`&`、相对路径、空格,或图床按 Referer 防盗链,直接请求会失败。
+ */
+class ImagePreviewActivity : AppCompatActivity() {
+
+ companion object {
+ private const val EXTRA_URL = "url"
+
+ fun intent(context: Context, url: String): Intent =
+ Intent(context, ImagePreviewActivity::class.java).putExtra(EXTRA_URL, url)
+ }
+
+ private lateinit var imageView: ZoomableImageView
+ private lateinit var progress: ProgressBar
+ private lateinit var errorView: TextView
+
+ /** 原始地址(点卡片传过来的)与归一化后用于请求的地址 */
+ private var rawUrl: String = ""
+ private var url: String = ""
+
+ /** 当前正在显示的位图:用来判断原图是否比兜底图更清晰 */
+ private var shown: Bitmap? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ rawUrl = intent.getStringExtra(EXTRA_URL).orEmpty().trim()
+ if (rawUrl.isBlank()) {
+ finish()
+ return
+ }
+ url = ImageUrl.normalize(this, rawUrl)
+
+ // 看图页固定黑底,状态栏与导航栏一并压黑,避免白边割裂画面
+ window.statusBarColor = Color.BLACK
+ window.navigationBarColor = Color.BLACK
+
+ val root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
+
+ imageView = ZoomableImageView(this).apply {
+ layoutParams = FrameLayout.LayoutParams(
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ ViewGroup.LayoutParams.MATCH_PARENT,
+ )
+ onSingleTap = { finish() }
+ visibility = View.INVISIBLE
+ }
+
+ progress = ProgressBar(this).apply {
+ layoutParams = FrameLayout.LayoutParams(dp(36), dp(36), Gravity.CENTER)
+ indeterminateDrawable?.setTint(Color.WHITE)
+ }
+
+ errorView = TextView(this).apply {
+ setTextColor(Color.WHITE)
+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
+ gravity = Gravity.CENTER
+ setPadding(dp(24), dp(16), dp(24), dp(16))
+ layoutParams = FrameLayout.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ Gravity.CENTER,
+ )
+ visibility = View.GONE
+ setOnClickListener { load() }
+ }
+
+ val close = TextView(this).apply {
+ text = getString(R.string.image_preview_close_glyph)
+ contentDescription = getString(R.string.image_preview_close)
+ setTextColor(Color.WHITE)
+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)
+ gravity = Gravity.CENTER
+ setPadding(dp(16), dp(10), dp(16), dp(10))
+ layoutParams = FrameLayout.LayoutParams(
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ ViewGroup.LayoutParams.WRAP_CONTENT,
+ Gravity.TOP or Gravity.END,
+ ).apply {
+ topMargin = dp(28)
+ rightMargin = dp(10)
+ }
+ setOnClickListener { finish() }
+ }
+
+ root.addView(imageView)
+ root.addView(progress)
+ root.addView(errorView)
+ root.addView(close)
+ setContentView(root)
+
+ load()
+ }
+
+ private fun load() {
+ // 第一层:卡片里已经解码好的那张,先摆上去,用户点开立刻有画面
+ val fallback = ImageMemoryCache.get(url) ?: ImageMemoryCache.get(rawUrl)
+ if (fallback != null) {
+ show(fallback)
+ progress.visibility = View.GONE
+ } else {
+ progress.visibility = View.VISIBLE
+ errorView.visibility = View.GONE
+ imageView.visibility = View.INVISIBLE
+ }
+
+ lifecycleScope.launch {
+ val result = withContext(Dispatchers.IO) { runCatching { fetch(url) } }
+ if (isFinishing || isDestroyed) return@launch
+ progress.visibility = View.GONE
+ val bitmap = result.getOrNull()
+ if (bitmap != null) {
+ val current = shown
+ // 兜底图已经显示时,只在原图更清晰、且用户还没开始缩放的情况下替换,
+ // 否则会把正在看的位置与缩放比例重置掉
+ val sharper = current == null || bitmap.byteCount > current.byteCount
+ if (current == null || (sharper && !imageView.transformed)) {
+ show(bitmap)
+ }
+ ImageMemoryCache.put(url, bitmap)
+ errorView.visibility = View.GONE
+ } else if (shown == null) {
+ val reason = result.exceptionOrNull()?.message.orEmpty()
+ errorView.text = if (reason.isBlank()) {
+ getString(R.string.image_preview_failed)
+ } else {
+ getString(R.string.image_preview_failed) + "\n" + reason
+ }
+ errorView.visibility = View.VISIBLE
+ }
+ }
+ }
+
+ private fun show(bitmap: Bitmap) {
+ shown = bitmap
+ imageView.visibility = View.VISIBLE
+ imageView.setBitmap(bitmap)
+ }
+
+ /** 下载并按目标尺寸采样解码,避免几千万像素的原图直接 OOM */
+ private fun fetch(address: String): Bitmap {
+ val bytes = fetchBytes(address)
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
+ if (bounds.outWidth <= 0 || bounds.outHeight <= 0) {
+ throw IllegalStateException("图片内容无法解析(可能被拦截或已失效)")
+ }
+
+ val metrics = resources.displayMetrics
+ // 采样目标是屏幕长边:保证放大时仍有细节,同时把内存压在十几 MB 以内
+ val target = maxOf(metrics.widthPixels, metrics.heightPixels)
+ val options = BitmapFactory.Options().apply {
+ inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, target)
+ inPreferredConfig = Bitmap.Config.ARGB_8888
+ }
+ return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
+ ?: throw IllegalStateException("图片解码失败")
+ }
+
+ /**
+ * 取原始字节。失败时抛出带原因的消息(直接显示给用户,便于对症下药):
+ * - `data:` / `content:` / `file:` 走本地解析;
+ * - http(s) 先按普通请求,失败再换浏览器 UA + Referer 重试一次(防盗链最常见的拦法)。
+ */
+ private fun fetchBytes(address: String): ByteArray {
+ if (address.startsWith("data:", true)) return dataUriBytes(address)
+ if (address.startsWith("content://") || address.startsWith("file://")) {
+ return contentResolver.openInputStream(Uri.parse(address))?.use { it.readBytes() }
+ ?: throw IllegalStateException("读不到本地图片")
+ }
+
+ var reason = "图片地址无效:$address"
+ for (attempt in 0 until 2) {
+ val request = Request.Builder()
+ .url(address)
+ .header("Accept", "image/*,*/*;q=0.8")
+ .apply {
+ if (attempt == 0) {
+ header("User-Agent", "PostPad")
+ } else {
+ header("User-Agent", RssApi.UA_BROWSER)
+ refererOf(address)?.let { header("Referer", it) }
+ }
+ }
+ .build()
+ try {
+ Http.imageClient(this).newCall(request).execute().use { response ->
+ if (!response.isSuccessful) {
+ reason = "HTTP ${response.code}"
+ return@use
+ }
+ val type = response.header("Content-Type").orEmpty().lowercase()
+ if (type.startsWith("text/") || type.contains("html")) {
+ reason = "服务器返回的是网页($type)"
+ return@use
+ }
+ val body = response.body ?: run {
+ reason = "响应为空"
+ return@use
+ }
+ // inline use:这里是直接返回整个函数的字节
+ return body.bytes()
+ }
+ } catch (e: Exception) {
+ reason = e.message ?: e.javaClass.simpleName
+ }
+ }
+ throw IllegalStateException(reason)
+ }
+
+ /** data:image/png;base64,… 这类内联图片 */
+ private fun dataUriBytes(uri: String): ByteArray {
+ val comma = uri.indexOf(',')
+ if (comma < 0) throw IllegalStateException("内联图片地址无效")
+ val meta = uri.substring(5, comma)
+ val payload = uri.substring(comma + 1)
+ return if (meta.contains("base64", true)) {
+ android.util.Base64.decode(payload, android.util.Base64.DEFAULT)
+ } else {
+ java.net.URLDecoder.decode(payload, "UTF-8").toByteArray()
+ }
+ }
+
+ /** 防盗链常校验 Referer:取图片所在站点的根地址 */
+ private fun refererOf(address: String): String? = runCatching {
+ val parsed = java.net.URL(address)
+ val host = parsed.host ?: return@runCatching null
+ "${parsed.protocol}://$host/"
+ }.getOrNull()
+
+ private fun sampleSize(width: Int, height: Int, target: Int): Int {
+ var sample = 1
+ while (width / (sample * 2) >= target && height / (sample * 2) >= target) {
+ sample *= 2
+ }
+ return sample
+ }
+
+ private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt()
+
+ /**
+ * 简易可缩放图片:只依赖 Matrix 与系统手势检测器,不引第三方手势库。
+ * 缩放范围从「适应屏幕」到其 4 倍;放大后单指拖动,松手时把图拉回可视区域。
+ */
+ private class ZoomableImageView(context: Context) :
+ androidx.appcompat.widget.AppCompatImageView(context) {
+
+ var onSingleTap: (() -> Unit)? = null
+
+ private val transform = Matrix()
+ private var baseScale = 1f
+ private var currentScale = 1f
+ private var lastX = 0f
+ private var lastY = 0f
+ private var multiTouch = false
+
+ /** 用户是否缩放/拖动过:用于决定原图到达时要不要替换画面 */
+ var transformed = false
+ private set
+
+ private val scaleDetector = ScaleGestureDetector(
+ context,
+ object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
+ override fun onScale(detector: ScaleGestureDetector): Boolean {
+ applyScale(currentScale * detector.scaleFactor, detector.focusX, detector.focusY)
+ return true
+ }
+ },
+ )
+
+ private val tapDetector = GestureDetector(
+ context,
+ object : GestureDetector.SimpleOnGestureListener() {
+ override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
+ // 双指缩放结束后系统仍可能补一个单击,这里挡掉,避免缩放完直接被关掉
+ if (!multiTouch) onSingleTap?.invoke()
+ return true
+ }
+
+ override fun onDoubleTap(e: MotionEvent): Boolean {
+ val target = if (currentScale > baseScale * 1.5f) baseScale else baseScale * 2.5f
+ applyScale(target, e.x, e.y)
+ return true
+ }
+ },
+ )
+
+ init {
+ scaleType = ScaleType.MATRIX
+ }
+
+ fun setBitmap(bitmap: Bitmap) {
+ transformed = false
+ setImageBitmap(bitmap)
+ // 等一帧再算:此刻 width/height 可能还是 0
+ post { fitToView() }
+ }
+
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
+ super.onSizeChanged(w, h, oldw, oldh)
+ if (drawable != null) fitToView()
+ }
+
+ /** 按控件尺寸等比缩放并居中,作为缩放下限 */
+ private fun fitToView() {
+ val d = drawable ?: return
+ val viewW = width.toFloat()
+ val viewH = height.toFloat()
+ val imageW = d.intrinsicWidth.toFloat()
+ val imageH = d.intrinsicHeight.toFloat()
+ if (viewW <= 0f || viewH <= 0f || imageW <= 0f || imageH <= 0f) return
+
+ val scale = minOf(viewW / imageW, viewH / imageH)
+ baseScale = scale
+ currentScale = scale
+ transform.reset()
+ transform.postScale(scale, scale)
+ transform.postTranslate((viewW - imageW * scale) / 2f, (viewH - imageH * scale) / 2f)
+ imageMatrix = transform
+ }
+
+ private fun applyScale(target: Float, focusX: Float, focusY: Float) {
+ if (currentScale <= 0f) return
+ val clamped = target.coerceIn(baseScale, baseScale * 4f)
+ val factor = clamped / currentScale
+ if (factor == 1f) {
+ // 已经到边界:回弹到初始状态,避免反复缩放积累误差
+ if (clamped <= baseScale) fitToView()
+ return
+ }
+ if (clamped != baseScale) transformed = true
+ currentScale = clamped
+ transform.postScale(factor, factor, focusX, focusY)
+ imageMatrix = transform
+ if (clamped <= baseScale) fitToView()
+ }
+
+ override fun onTouchEvent(event: MotionEvent): Boolean {
+ scaleDetector.onTouchEvent(event)
+ tapDetector.onTouchEvent(event)
+ when (event.actionMasked) {
+ MotionEvent.ACTION_DOWN -> {
+ multiTouch = false
+ lastX = event.x
+ lastY = event.y
+ }
+
+ MotionEvent.ACTION_POINTER_DOWN -> {
+ multiTouch = true
+ transformed = true
+ }
+
+ MotionEvent.ACTION_MOVE -> {
+ if (!scaleDetector.isInProgress && currentScale > baseScale) {
+ transform.postTranslate(event.x - lastX, event.y - lastY)
+ imageMatrix = transform
+ lastX = event.x
+ lastY = event.y
+ transformed = true
+ }
+ }
+
+ MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> settle()
+ }
+ return true
+ }
+
+ /** 松手后把图片拉回可视范围,避免拖出屏幕后找不回来 */
+ private fun settle() {
+ val d = drawable ?: return
+ val rect = RectF(0f, 0f, d.intrinsicWidth.toFloat(), d.intrinsicHeight.toFloat())
+ transform.mapRect(rect)
+ val viewW = width.toFloat()
+ val viewH = height.toFloat()
+ var dx = 0f
+ var dy = 0f
+ if (rect.width() <= viewW) dx = (viewW - rect.width()) / 2f - rect.left
+ else if (rect.left > 0f) dx = -rect.left
+ else if (rect.right < viewW) dx = viewW - rect.right
+ if (rect.height() <= viewH) dy = (viewH - rect.height()) / 2f - rect.top
+ else if (rect.top > 0f) dy = -rect.top
+ else if (rect.bottom < viewH) dy = viewH - rect.bottom
+ if (dx != 0f || dy != 0f) {
+ transform.postTranslate(dx, dy)
+ imageMatrix = transform
+ }
+ }
+ }
+}
diff --git a/src/main/java/com/shitoucuo/postpad/ImageUtils.kt b/src/main/java/com/shitoucuo/postpad/ImageUtils.kt
new file mode 100644
index 0000000..278acf4
--- /dev/null
+++ b/src/main/java/com/shitoucuo/postpad/ImageUtils.kt
@@ -0,0 +1,97 @@
+package com.shitoucuo.postpad
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.net.Uri
+import android.provider.OpenableColumns
+import android.util.LruCache
+
+/**
+ * 相册取图的读取、缩略图与文件名处理。
+ * 不引第三方图片库,自己按 inSampleSize 采样,避免大图 OOM。
+ */
+object ImageUtils {
+
+ data class PickedImage(val uri: Uri, val name: String, val mime: String)
+
+ /**
+ * 缩略图按字节限额缓存(8MB)。
+ * 原来每渲染一次配图条就要重新解码全部缩略图,删图时会重解 N-1 张;
+ * 有了缓存,同一张图在多次重建里只解一次。
+ */
+ private val thumbCache = object : LruCache(8 * 1024 * 1024) {
+ override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount
+ }
+
+ fun picked(context: Context, uri: Uri): PickedImage =
+ PickedImage(uri, displayName(context, uri), mimeOf(context, uri))
+
+ fun displayName(context: Context, uri: Uri): String {
+ var name = ""
+ try {
+ context.contentResolver
+ .query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)
+ ?.use { cursor ->
+ if (cursor.moveToFirst()) {
+ val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
+ if (index >= 0) name = cursor.getString(index) ?: ""
+ }
+ }
+ } catch (e: Exception) {
+ // 少数 provider 不给名字,下面用时间戳兜底
+ }
+ if (name.isBlank()) {
+ name = "image-${System.currentTimeMillis()}.jpg"
+ }
+ return name.replace(Regex("[\"\\r\\n]"), "_")
+ }
+
+ fun mimeOf(context: Context, uri: Uri): String =
+ context.contentResolver.getType(uri) ?: "image/jpeg"
+
+ fun readBytes(context: Context, uri: Uri): ByteArray {
+ context.contentResolver.openInputStream(uri)?.use { stream ->
+ return stream.readBytes()
+ }
+ throw IllegalStateException("读取图片失败,可能已失去访问权限")
+ }
+
+ fun loadThumbnail(context: Context, uri: Uri, maxSize: Int): Bitmap? {
+ val key = "$uri@$maxSize"
+ thumbCache.get(key)?.let { return it }
+
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ try {
+ context.contentResolver.openInputStream(uri)?.use {
+ BitmapFactory.decodeStream(it, null, bounds)
+ }
+ } catch (e: Exception) {
+ return null
+ }
+
+ val options = BitmapFactory.Options().apply {
+ inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, maxSize)
+ }
+ val bitmap = try {
+ context.contentResolver.openInputStream(uri)?.use {
+ BitmapFactory.decodeStream(it, null, options)
+ }
+ } catch (e: Exception) {
+ null
+ }
+ if (bitmap != null) thumbCache.put(key, bitmap)
+ return bitmap
+ }
+
+ private fun sampleSize(width: Int, height: Int, maxSize: Int): Int {
+ if (width <= 0 || height <= 0 || maxSize <= 0) return 1
+ var longest = maxOf(width, height)
+ var sample = 1
+ while (longest / 2 >= maxSize) {
+ longest /= 2
+ sample *= 2
+ }
+ return sample
+ }
+}
diff --git a/src/main/java/com/shitoucuo/postpad/MailApi.kt b/src/main/java/com/shitoucuo/postpad/MailApi.kt
new file mode 100644
index 0000000..a0f8f55
--- /dev/null
+++ b/src/main/java/com/shitoucuo/postpad/MailApi.kt
@@ -0,0 +1,733 @@
+package com.shitoucuo.postpad
+
+import com.sun.mail.iap.Argument
+import com.sun.mail.imap.IMAPFolder
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import org.json.JSONArray
+import org.json.JSONObject
+import java.util.Properties
+import javax.mail.FetchProfile
+import javax.mail.Flags
+import javax.mail.Folder
+import javax.mail.Message
+import javax.mail.Session
+import javax.mail.Store
+import javax.mail.UIDFolder
+import javax.mail.internet.InternetAddress
+import javax.mail.internet.MimeMessage
+import javax.mail.internet.MimeMultipart
+import javax.mail.internet.MimeUtility
+
+/**
+ * 邮件直连 IMAP(与 obsidian-mail-desk 同一条链路,无服务端代理)。
+ *
+ * **所有函数都接收账户快照 [Prefs.MailEntry],不在流程中途读 prefs 的当前账户。**
+ * 早期版本全程依赖 prefs.mailEmail / mailImapHost,用户切邮箱时正在跑的同步
+ * 会在写缓存那一步读到新账户,把 A 的邮件写进 B 的缓存文件——表现为
+ * 「列表里混进其它邮箱的邮件」「点开提示已删除」「已读状态错位」。快照消除这类竞态。
+ *
+ * 列表走本地缓存(每个邮箱一份缓存文件):
+ * - 首次拉最近 N 天(最多 200 封);
+ * - 之后按 UID 增量,只向服务端要「比上次最大的 UID 更新」的邮件;
+ * - 每次同步顺带核对服务端的存留 UID 与已读标记,幽灵邮件会被清掉、
+ * 已在其它端读过的邮件也会同步成已读;
+ * - 缓存记 UIDVALIDITY,邮箱被服务端重建时旧 UID 全部失效,整份缓存作废重拉。
+ *
+ * 正文与附件在点开时才解析。
+ *
+ * QQ / 163 邮箱要求客户端先发 IMAP ID 命令,否则登录成功但报 Unsafe Login,
+ * 这里在 connect 之后通过 IMAPFolder.doCommand 补发一次。
+ */
+object MailApi {
+
+ class ApiException(message: String) : Exception(message)
+
+ /** 邮件在服务端已不存在(被其它端删除或已清理),缓存已同步移除 */
+ class GoneException(message: String) : Exception(message)
+
+ /** 列表项;snippet 在列表阶段可能为空,点开详情时回填 */
+ data class MailItem(
+ val uid: Long,
+ val folder: String,
+ val subject: String,
+ val from: String,
+ val fromName: String,
+ val date: Long,
+ val snippet: String,
+ val seen: Boolean,
+ val hasAttachment: Boolean,
+ /** 所属邮箱地址,聚合列表里用于卡片标识与详情页路由 */
+ val account: String = "",
+ )
+
+ data class Attachment(val name: String, val type: String, val size: Long)
+
+ data class MailDetail(
+ val item: MailItem,
+ val body: String,
+ val html: String,
+ val attachments: List,
+ )
+
+ /** 聚合列表项:邮件 + 它所属的账户(卡片要显示邮箱名,详情要按账户连) */
+ data class AccountMail(val account: Prefs.MailEntry, val item: MailItem)
+
+ // ==================== 连接 ====================
+
+ private fun session(account: Prefs.MailEntry): Session {
+ val protocol = if (account.secure) "imaps" else "imap"
+ val props = Properties().apply {
+ put("mail.store.protocol", protocol)
+ put("mail.$protocol.host", account.host)
+ put("mail.$protocol.port", account.port.toString())
+ put("mail.$protocol.ssl.enable", account.secure.toString())
+ put("mail.$protocol.connectiontimeout", "20000")
+ put("mail.$protocol.timeout", "20000")
+ // 不把授权码写进日志
+ put("mail.debug", "false")
+ }
+ return Session.getInstance(props)
+ }
+
+ private fun connect(account: Prefs.MailEntry, version: String = ""): Store {
+ if (!account.ready) throw ApiException(
+ // 说清缺哪一项:笼统的"先填邮箱、授权码和 IMAP 主机"会让人以为整段配置都丢了
+ when {
+ account.email.isBlank() -> "邮箱 ${account.label} 没填邮箱地址"
+ account.auth.isBlank() -> "邮箱 ${account.label} 没填 IMAP 授权码"
+ else -> "邮箱 ${account.label} 没填 IMAP 服务器"
+ }
+ )
+ val protocol = if (account.secure) "imaps" else "imap"
+ val store = session(account).getStore(protocol)
+ try {
+ store.connect(account.host, account.port, account.email, account.auth)
+ } catch (e: Exception) {
+ val message = e.message.orEmpty()
+ if (message.contains("Unsafe Login", true) ||
+ message.contains(" ID ", true) ||
+ account.host.contains("qq.com", true)
+ ) {
+ // QQ 系邮箱:连接成功后需要补发 ID,这里先关闭再按带 ID 的流程重连
+ runCatching { store.close() }
+ try {
+ val retry = session(account).getStore(protocol)
+ retry.connect(account.host, account.port, account.email, account.auth)
+ sendId(retry, version)
+ return retry
+ } catch (retryError: Exception) {
+ // 重连失败也要走 friendly(),否则会漏出 IMAP 原始英文报错
+ throw ApiException(friendly(retryError))
+ }
+ }
+ throw ApiException(friendly(e))
+ }
+ sendId(store, version)
+ return store
+ }
+
+ /**
+ * 补发 IMAP ID。126 / QQ 要求登录后、打开邮箱前发送,否则一直返回 Unsafe Login。
+ *
+ * 用 IMAPFolder 公开的 doCommand 拿到底层协议,并用 writeAtom 原样发送
+ * 括号参数(writeString 会被拆成裸字符串,服务端报 BAD Parse)。
+ */
+ private fun sendId(store: Store, version: String) {
+ runCatching {
+ val folder = store.getFolder("INBOX") as? IMAPFolder ?: return
+ val ver = version.ifBlank { "unknown" }
+ val fields = "(\"name\" \"PostPad\" \"version\" \"$ver\" \"vendor\" \"shitoucuo\")"
+ val arg = Argument().writeAtom(fields)
+ folder.doCommand { protocol ->
+ protocol.simpleCommand("ID", arg)
+ null
+ }
+ }
+ }
+
+ private fun friendly(e: Exception): String = when {
+ e.message?.contains("Authentication failed", true) == true ||
+ e.message?.contains("LOGIN failed", true) == true ->
+ "授权码错误,或邮箱未开启 IMAP 服务"
+ e.message?.contains("Connection refused", true) == true ||
+ e.message?.contains("timed out", true) == true ->
+ "连不上 IMAP 服务器,检查主机、端口和网络"
+ e.message?.contains("Unsafe Login", true) == true ->
+ "邮箱要求客户端标识,仍被拒绝,尝试换 993 端口或关闭 SSL"
+ else -> e.message?.take(160).orEmpty().ifBlank { "邮箱连接失败" }
+ }
+
+ // ==================== 连通检查 ====================
+
+ suspend fun check(prefs: Prefs, account: Prefs.MailEntry): String =
+ withContext(Dispatchers.IO) {
+ val store = connect(account, prefs.appVersion)
+ try {
+ val inbox = store.getFolder("INBOX")
+ if (!inbox.exists()) throw ApiException("邮箱里没有 INBOX 文件夹")
+ inbox.open(Folder.READ_ONLY)
+ val count = inbox.messageCount
+ "${account.label}:连接正常,收件箱 $count 封邮件"
+ } catch (e: ApiException) {
+ throw e
+ } catch (e: Exception) {
+ throw ApiException(friendly(e))
+ } finally {
+ runCatching { store.close() }
+ }
+ }
+
+ // ==================== 缓存 ====================
+
+ /**
+ * 账户的缓存文件,按邮箱地址散列命名。
+ *
+ * 旧版的单文件缓存 `postpad_mail_cache.json` 不再"改名继承":那个文件属于
+ * 升级前的单一账户,无法确定现在对应哪个邮箱,继承过去就会把别的邮箱的邮件
+ * 显示在当前账户下(UID 又对不上,点开就是"已删除")。这里直接删除,
+ * 各账户首次打开时按 mailFetchDays 重新拉一遍。
+ */
+ private fun cacheFile(prefs: Prefs, account: Prefs.MailEntry): java.io.File {
+ val target = prefs.mailCacheFile(account.email)
+ val legacy = prefs.legacyMailCacheFile
+ if (legacy.exists()) runCatching { legacy.delete() }
+ return target
+ }
+
+ private class CacheSnapshot(
+ val mails: List,
+ val lastUid: Long,
+ val uidValidity: Long,
+ )
+
+ /** 缓存读写的互斥锁:detail 与 markRead 都会「读-改-写」,并发会互相覆盖 */
+ private val cacheLock = Any()
+
+ private fun readCache(prefs: Prefs, account: Prefs.MailEntry): CacheSnapshot {
+ val file = cacheFile(prefs, account)
+ if (!file.exists()) return CacheSnapshot(emptyList(), 0L, 0L)
+ val root = runCatching { JSONObject(file.readText()) }.getOrNull()
+ ?: return CacheSnapshot(emptyList(), 0L, 0L)
+ val array = root.optJSONArray("mails") ?: JSONArray()
+ val out = ArrayList(array.length())
+ for (i in 0 until array.length()) {
+ val obj = array.optJSONObject(i) ?: continue
+ out.add(
+ MailItem(
+ uid = obj.optLong("uid"),
+ folder = obj.optString("folder").ifBlank { "INBOX" },
+ // 旧缓存里可能存着未解码的编码串与「名字 <地址>」格式,读的时候顺手纠正,
+ // 不必为了编码问题强制全量重同步一遍。
+ subject = decodeHeader(obj.optString("subject")).ifBlank { "(无主题)" },
+ from = plainAddress(obj.optString("from")),
+ fromName = decodeHeader(obj.optString("fromName")),
+ date = obj.optLong("date"),
+ snippet = obj.optString("snippet"),
+ seen = obj.optBoolean("seen"),
+ hasAttachment = obj.optBoolean("hasAttachment"),
+ account = account.email,
+ )
+ )
+ }
+ return CacheSnapshot(
+ out.sortedByDescending { it.date },
+ root.optLong("lastUid"),
+ root.optLong("uidValidity"),
+ )
+ }
+
+ private fun writeCache(
+ prefs: Prefs,
+ account: Prefs.MailEntry,
+ items: List,
+ lastUid: Long,
+ uidValidity: Long,
+ ) {
+ val file = cacheFile(prefs, account)
+ val array = JSONArray()
+ items.forEach { item ->
+ array.put(
+ JSONObject().apply {
+ put("uid", item.uid)
+ put("folder", item.folder)
+ put("subject", item.subject)
+ put("from", item.from)
+ put("fromName", item.fromName)
+ put("date", item.date)
+ put("snippet", item.snippet)
+ put("seen", item.seen)
+ put("hasAttachment", item.hasAttachment)
+ }
+ )
+ }
+ file.writeText(
+ JSONObject()
+ .put("mails", array)
+ .put("lastUid", lastUid)
+ .put("uidValidity", uidValidity)
+ .toString()
+ )
+ }
+
+ /** 「读-改-写」一次性完成,避免 detail / setSeen / delete 并发时互相覆盖 */
+ private fun updateCache(
+ prefs: Prefs,
+ account: Prefs.MailEntry,
+ block: (LinkedHashMap, CacheSnapshot) -> Unit,
+ ) {
+ synchronized(cacheLock) {
+ val snapshot = readCache(prefs, account)
+ val merged = LinkedHashMap()
+ snapshot.mails.forEach { merged[it.uid] = it }
+ block(merged, snapshot)
+ writeCache(
+ prefs,
+ account,
+ merged.values.sortedByDescending { it.date }.take(300),
+ merged.keys.maxOrNull() ?: 0L,
+ snapshot.uidValidity,
+ )
+ }
+ }
+
+ /** 从本地缓存读取单个账户的列表(按时间倒序),断网可用 */
+ fun cached(prefs: Prefs, account: Prefs.MailEntry): List =
+ readCache(prefs, account).mails
+
+ /**
+ * 全部账户的缓存合并成一个列表(按时间倒序)。
+ *
+ * 首页邮件页展示的是「所有邮箱」:不需要用户在顶部切来切去,
+ * 想知道某封属于哪个邮箱看卡片上的徽标即可。
+ */
+ fun cachedAll(prefs: Prefs): List {
+ val out = ArrayList()
+ prefs.mailAccounts().forEach { account ->
+ if (account.email.isBlank()) return@forEach
+ readCache(prefs, account).mails.forEach { out.add(AccountMail(account, it)) }
+ }
+ return out.sortedByDescending { it.item.date }
+ }
+
+ /**
+ * 清掉指定账户的缓存,下次同步按新设置全量重拉。
+ *
+ * 增量同步只取「比缓存里最新 UID 更新」的邮件,所以用户在设置里调大同步天数后,
+ * 不清缓存的话更早的邮件永远进不来,设置项等于无效。
+ */
+ fun resetCache(prefs: Prefs, account: Prefs.MailEntry) {
+ if (account.email.isBlank()) return
+ runCatching { cacheFile(prefs, account).delete() }
+ }
+
+ /** 从缓存移除指定 UID(服务端已不存在时调用,保证列表不再出现幽灵邮件) */
+ private fun removeFromCache(prefs: Prefs, account: Prefs.MailEntry, uid: Long) {
+ updateCache(prefs, account) { merged, _ -> merged.remove(uid) }
+ }
+
+ // ==================== 列表与同步 ====================
+
+ /** 正在同步的账户(小写邮箱),防止同一账户被两个流程同时写缓存 */
+ private val syncing = java.util.concurrent.ConcurrentHashMap.newKeySet()
+
+ /**
+ * 增量同步一个账户的收件箱:
+ * - 缓存里有 lastUid 时只拉 UID 更大的新邮件,几封就几封,不再全量重取;
+ * - 首次同步取最近 200 封,并受该账户的 days 限制;
+ * - 顺带按服务端的 UID 存留与 FLAGS 校正缓存(清幽灵、同步已读)。
+ * 返回本次新增的邮件数,方便界面提示。
+ */
+ suspend fun sync(prefs: Prefs, account: Prefs.MailEntry): Int = withContext(Dispatchers.IO) {
+ val key = account.email.trim().lowercase()
+ if (!account.ready) return@withContext 0
+ // 同一账户已在同步:直接返回 0,避免两条连接对着同一份缓存互相覆盖
+ if (!syncing.add(key)) return@withContext 0
+ val store = try {
+ connect(account, prefs.appVersion)
+ } catch (e: Exception) {
+ syncing.remove(key)
+ throw e
+ }
+ try {
+ val folder = store.getFolder("INBOX")
+ folder.open(Folder.READ_ONLY)
+ val uidFolder = folder as UIDFolder
+ val uidValidity = runCatching { uidFolder.uidValidity }.getOrDefault(0L)
+
+ var snapshot = readCache(prefs, account)
+ // UIDVALIDITY 变了说明服务端重建过邮箱:旧 UID 指向的已是别的邮件,
+ // 继续用缓存就会出现"打开是另一封""提示已删除",整份作废按首次同步重来
+ if (uidValidity > 0 && snapshot.uidValidity > 0 && snapshot.uidValidity != uidValidity) {
+ snapshot = CacheSnapshot(emptyList(), 0L, uidValidity)
+ writeCache(prefs, account, emptyList(), 0L, uidValidity)
+ }
+
+ // 与服务端核对存留 + 已读状态:其它端删除的邮件要清掉,其它端读过的要同步。
+ // 只拉 UID 与 FLAGS,不拉内容,一次 FETCH 就能覆盖全部邮件。
+ val serverFlags: Map? = runCatching {
+ val all = uidFolder.getMessagesByUID(1, UIDFolder.LASTUID)
+ if (all.isEmpty()) {
+ if (folder.messageCount == 0) emptyMap() else null
+ } else {
+ folder.fetch(all, FetchProfile().apply {
+ add(UIDFolder.FetchProfileItem.UID)
+ add(FetchProfile.Item.FLAGS)
+ })
+ val out = HashMap(all.size)
+ for (m in all) {
+ val u = runCatching { uidFolder.getUID(m) }.getOrDefault(0L)
+ if (u > 0) {
+ out[u] = runCatching {
+ m.flags?.contains(Flags.Flag.SEEN) == true
+ }.getOrDefault(false)
+ }
+ }
+ out
+ }
+ }.getOrNull()
+ val kept = if (serverFlags != null) {
+ snapshot.mails.filter { it.uid in serverFlags }
+ .map { it.copy(seen = serverFlags[it.uid] ?: it.seen, account = account.email) }
+ } else {
+ snapshot.mails // 核对失败时不动缓存,宁可多显示也不误删
+ }
+
+ val messages = if (snapshot.lastUid > 0) {
+ // 增量:只取比已知最大 UID 新的邮件(LASTUID 是服务端最新一封)
+ uidFolder.getMessagesByUID(snapshot.lastUid + 1, UIDFolder.LASTUID)
+ } else {
+ val total = folder.messageCount
+ val limit = minOf(total, 200)
+ val start = total - limit + 1
+ if (start > 1) folder.getMessages(start, total) else folder.getMessages()
+ }
+
+ val profile = FetchProfile().apply {
+ add(FetchProfile.Item.ENVELOPE)
+ add(FetchProfile.Item.FLAGS)
+ add(UIDFolder.FetchProfileItem.UID)
+ add(FetchProfile.Item.CONTENT_INFO)
+ }
+ folder.fetch(messages, profile)
+
+ val cutoff = System.currentTimeMillis() - account.days * 86_400_000L
+ val existingUids = snapshot.mails.map { it.uid }.toHashSet()
+ val fetched = ArrayList(messages.size)
+ var maxUid = snapshot.lastUid
+ var added = 0
+ for (msg in messages) {
+ val uid = runCatching { uidFolder.getUID(msg) }.getOrDefault(0L)
+ if (uid <= 0) continue
+ if (uid <= snapshot.lastUid) continue // LASTUID 兜底返回旧邮件时跳过
+ if (uid > maxUid) maxUid = uid
+ val sent = runCatching { msg.sentDate?.time ?: msg.receivedDate?.time ?: 0L }
+ .getOrDefault(0L)
+ // 首次同步只保留 days 内的;增量阶段全部收下
+ if (snapshot.lastUid == 0L && sent > 0 && sent < cutoff) continue
+ val existed = uid in existingUids
+ if (!existed) added++
+ fetched.add(toItem(msg, uid, "INBOX").copy(account = account.email))
+ }
+
+ val merged = LinkedHashMap()
+ kept.forEach { merged[it.uid] = it }
+ fetched.forEach { merged[it.uid] = it }
+ val all = merged.values.sortedByDescending { it.date }
+ synchronized(cacheLock) {
+ writeCache(
+ prefs, account, all.take(300), maxUid,
+ if (uidValidity > 0) uidValidity else snapshot.uidValidity,
+ )
+ }
+ added
+ } catch (e: ApiException) {
+ throw e
+ } catch (e: Exception) {
+ throw ApiException(friendly(e))
+ } finally {
+ syncing.remove(key)
+ runCatching { store.close() }
+ }
+ }
+
+ /** 打开邮件:解析正文与附件,并把 120 字摘要写回缓存 */
+ suspend fun detail(prefs: Prefs, account: Prefs.MailEntry, uid: Long, folderName: String): MailDetail =
+ withContext(Dispatchers.IO) {
+ val store = connect(account, prefs.appVersion)
+ try {
+ val folder = store.getFolder(folderName)
+ folder.open(Folder.READ_ONLY)
+ val uidFolder = folder as UIDFolder
+ val message = uidFolder.getMessageByUID(uid)
+ if (message == null) {
+ // 服务端已没有这封邮件(其它端删过 / 已清理):清掉缓存幽灵项并明确告知
+ removeFromCache(prefs, account, uid)
+ throw GoneException("这封邮件可能已被删除,已从列表移除")
+ }
+ folder.fetch(arrayOf(message), FetchProfile().apply {
+ add(FetchProfile.Item.ENVELOPE)
+ add(FetchProfile.Item.CONTENT_INFO)
+ })
+
+ val parsed = parseContent(message)
+ val base = toItem(message, uid, folderName).copy(account = account.email)
+ val item = base.copy(
+ snippet = parsed.first.take(120).ifBlank { base.snippet },
+ )
+ // 回填摘要(不覆盖已读标记:是否已读由 markRead / setSeen 负责)
+ updateCache(prefs, account) { merged, _ ->
+ val seen = merged[uid]?.seen ?: item.seen
+ merged[uid] = item.copy(seen = seen)
+ }
+
+ MailDetail(item, parsed.first, parsed.second, parsed.third)
+ } catch (e: ApiException) {
+ throw e
+ } catch (e: GoneException) {
+ // 已从缓存移除:调用方要按"已删除"处理(刷新列表),不能当普通错误
+ throw e
+ } catch (e: Exception) {
+ throw ApiException(friendly(e))
+ } finally {
+ runCatching { store.close() }
+ }
+ }
+
+ /** 标记已读(IMAP \Seen) */
+ suspend fun markRead(prefs: Prefs, account: Prefs.MailEntry, uid: Long, folderName: String) =
+ setSeen(prefs, account, uid, folderName, true)
+
+ /**
+ * 只写本地缓存的已读状态,不连服务端。
+ *
+ * 「点开即已读」要求列表、底部角标、下次进入看到的状态立刻一致,不能等一次
+ * IMAP 往返(网络差时要好几秒,中途退出就白读了)。服务端的 \Seen 由
+ * [setSeen] 随后补;万一补失败,本地仍按已读算,下一次同步再用服务端 FLAGS 校正。
+ */
+ fun markSeenLocal(prefs: Prefs, account: Prefs.MailEntry, uid: Long, seen: Boolean) {
+ if (account.email.isBlank() || uid <= 0) return
+ runCatching {
+ updateCache(prefs, account) { merged, _ ->
+ merged[uid]?.let { merged[uid] = it.copy(seen = seen) }
+ }
+ }
+ }
+
+ /** 设置已读 / 未读,并同步本地缓存;列表的「标为未读」走这里 */
+ suspend fun setSeen(
+ prefs: Prefs,
+ account: Prefs.MailEntry,
+ uid: Long,
+ folderName: String,
+ seen: Boolean,
+ ) = withContext(Dispatchers.IO) {
+ val store = connect(account, prefs.appVersion)
+ try {
+ val folder = store.getFolder(folderName)
+ folder.open(Folder.READ_WRITE)
+ val message = (folder as UIDFolder).getMessageByUID(uid)
+ if (message == null) {
+ removeFromCache(prefs, account, uid)
+ throw GoneException("这封邮件可能已被删除,已从列表移除")
+ }
+ message.setFlag(Flags.Flag.SEEN, seen)
+ updateCache(prefs, account) { merged, _ ->
+ merged[uid]?.let { merged[uid] = it.copy(seen = seen) }
+ }
+ } catch (e: ApiException) {
+ throw e
+ } catch (e: GoneException) {
+ throw e
+ } catch (e: Exception) {
+ throw ApiException(friendly(e))
+ } finally {
+ runCatching { store.close() }
+ }
+ }
+
+ /** 删除邮件:服务端标记删除并 expunge,同时从本地缓存移除 */
+ suspend fun delete(prefs: Prefs, account: Prefs.MailEntry, uid: Long, folderName: String) =
+ withContext(Dispatchers.IO) {
+ val store = connect(account, prefs.appVersion)
+ try {
+ val folder = store.getFolder(folderName)
+ folder.open(Folder.READ_WRITE)
+ val message = (folder as UIDFolder).getMessageByUID(uid)
+ if (message == null) {
+ // 服务端已没有这封邮件:视为删除完成,清缓存让列表同步消失
+ removeFromCache(prefs, account, uid)
+ throw GoneException("邮件在服务器上已不存在,已从列表移除")
+ }
+ message.setFlag(Flags.Flag.DELETED, true)
+ (folder as? IMAPFolder)?.expunge()
+ folder.close(false)
+ updateCache(prefs, account) { merged, _ -> merged.remove(uid) }
+ } catch (e: ApiException) {
+ throw e
+ } catch (e: GoneException) {
+ throw e
+ } catch (e: Exception) {
+ throw ApiException(friendly(e))
+ } finally {
+ runCatching { store.close() }
+ }
+ }
+
+ /**
+ * 用该账户的 SMTP 发信(回复用)。SMTP 主机由 IMAP 主机推导:
+ * imap.qq.com → smtp.qq.com,126 同理;465 端口 SSL。
+ */
+ suspend fun send(account: Prefs.MailEntry, to: String, subject: String, text: String) =
+ withContext(Dispatchers.IO) {
+ val smtpHost = account.host.replaceFirst("imap.", "smtp.", true)
+ val props = Properties().apply {
+ put("mail.smtp.host", smtpHost)
+ put("mail.smtp.port", "465")
+ put("mail.smtp.ssl.enable", "true")
+ put("mail.smtp.auth", "true")
+ put("mail.smtp.connectiontimeout", "20000")
+ put("mail.smtp.timeout", "30000")
+ }
+ try {
+ val session = Session.getInstance(props)
+ val message = MimeMessage(session).apply {
+ setFrom(javax.mail.internet.InternetAddress(account.email))
+ setRecipients(Message.RecipientType.TO, to)
+ setSubject(subject, "UTF-8")
+ setText(text, "UTF-8")
+ }
+ val transport = session.getTransport("smtp")
+ try {
+ transport.connect(smtpHost, 465, account.email, account.auth)
+ transport.sendMessage(message, message.allRecipients)
+ } finally {
+ runCatching { transport.close() }
+ }
+ } catch (e: ApiException) {
+ throw e
+ } catch (e: Exception) {
+ throw ApiException("发送失败:" + friendly(e))
+ }
+ }
+
+ // ==================== 解析 ====================
+
+ private fun toItem(msg: Message, uid: Long, folder: String): MailItem {
+ val from = msg.from?.firstOrNull()
+ val addr = from as? InternetAddress
+ // from 只存纯地址:InternetAddress.toString() 会把显示名一起拼进来("张三" ),
+ // 详情页再套一层尖括号就成了「张三 <"张三" >」。
+ val address = addr?.address?.trim().orEmpty()
+ .ifBlank { plainAddress(from?.toString().orEmpty()) }
+ // 显示名走 IMAP ENVELOPE 过来时是 RFC 2047 原文(=?utf-8?B?...?=),JavaMail 不会自动解,
+ // 不处理就直接把编码串显示在名字后面,即用户看到的"乱码"。
+ val personal = decodeHeader(addr?.personal.orEmpty())
+ val subject = decodeHeader(runCatching { msg.subject }.getOrNull().orEmpty())
+ .ifBlank { "(无主题)" }
+ val date = runCatching { msg.sentDate?.time ?: msg.receivedDate?.time ?: 0L }.getOrDefault(0L)
+ val flags = runCatching { msg.flags }.getOrNull()
+ return MailItem(
+ uid = uid,
+ folder = folder,
+ subject = subject,
+ from = address,
+ fromName = personal.ifBlank { address.substringBefore('@') },
+ date = date,
+ snippet = "",
+ seen = flags?.contains(Flags.Flag.SEEN) == true,
+ hasAttachment = hasAttachmentHeader(msg),
+ )
+ }
+
+ /**
+ * 解 RFC 2047 编码头:`=?UTF-8?B?5byg5LiJ?=`、`=?GBK?Q?...?=` 这类。
+ *
+ * JavaMail 只在 MimeMessage.getSubject() 里自动解码,地址里的显示名
+ * (InternetAddress.personal)保持原样,所以必须自己解一次。
+ * 已经是正常文字的输入会原样返回,可以反复调用。
+ */
+ private fun decodeHeader(raw: String): String {
+ if (raw.isBlank()) return ""
+ // 先把折行(CRLF + 空格/Tab)展开,折在编码字中间时直接解码会失败
+ val unfolded = raw.replace(Regex("[\\r\\n]+[ \\t]"), " ").trim()
+ return runCatching { MimeUtility.decodeText(unfolded) }.getOrDefault(unfolded)
+ }
+
+ /** 从 "名字 " 里提出纯地址;缓存里存过旧格式,读的时候顺手归一 */
+ private fun plainAddress(raw: String): String {
+ val s = raw.trim()
+ val lt = s.lastIndexOf('<')
+ if (lt >= 0) {
+ val end = s.indexOf('>', lt)
+ val inside = if (end > lt) s.substring(lt + 1, end) else s.substring(lt + 1)
+ if (inside.contains('@')) return inside.trim()
+ }
+ return s
+ }
+
+ /**
+ * 只凭 BODYSTRUCTURE 判断有没有附件。
+ *
+ * 旧实现访问 msg.content,JavaMail 为了拿到 MimeMultipart 会补拉 BODY[](整封正文),
+ * 首屏几百封邮件就等于把整个邮箱下载一遍——这是"第一次打开邮件页特别慢"的主因。
+ *
+ * 也不能改用 msg.getHeader("Content-Type"):BODYSTRUCTURE 不含原始头部,
+ * 读 header 会让 JavaMail 逐封补拉 BODY.PEEK[HEADER],只是把整封换成了头部。
+ * 这里只用 msg.contentType —— 它直接来自 BODYSTRUCTURE,不产生任何额外请求。
+ * 代价是 multipart/mixed 的纯正文邮件会多显示一个附件图标,判断只会偏多不会漏。
+ */
+ private fun hasAttachmentHeader(msg: Message): Boolean = runCatching {
+ val topType = msg.contentType.orEmpty().lowercase()
+ if (!topType.startsWith("multipart/")) return@runCatching false
+ topType.startsWith("multipart/mixed") || topType.contains("name=")
+ }.getOrDefault(false)
+
+ /** 返回 Triple(纯文本摘要, HTML 正文, 附件列表) */
+ private fun parseContent(msg: Message): Triple> {
+ var plain = ""
+ var html = ""
+ val attachments = ArrayList()
+ fun walk(part: javax.mail.Part) {
+ if (part.isMimeType("text/plain")) {
+ if (plain.isEmpty()) plain = runCatching { part.content as? String }.getOrNull().orEmpty()
+ } else if (part.isMimeType("text/html")) {
+ if (html.isEmpty()) html = runCatching { part.content as? String }.getOrNull().orEmpty()
+ } else if (part.isMimeType("multipart/*")) {
+ val multipart = part.content as? MimeMultipart ?: return
+ for (i in 0 until multipart.count) walk(multipart.getBodyPart(i))
+ } else if (part.isMimeType("message/rfc822")) {
+ walk(part.content as? javax.mail.Part ?: return)
+ } else {
+ val disposition = runCatching { part.disposition }.getOrNull().orEmpty()
+ val name = runCatching { part.fileName }.getOrNull()
+ ?: disposition.substringAfter("filename=", "").trim('"')
+ if (name.isNotEmpty() || disposition.contains("attachment", true)) {
+ attachments.add(
+ Attachment(
+ name = name.ifBlank { "附件 ${attachments.size + 1}" },
+ type = runCatching { part.contentType }.getOrDefault("application/octet-stream"),
+ size = runCatching { part.size.toLong() }.getOrDefault(0L),
+ )
+ )
+ }
+ }
+ }
+ walk(msg)
+ if (plain.isBlank() && html.isNotBlank()) {
+ plain = htmlToText(html)
+ }
+ return Triple(plain.trim(), html, attachments)
+ }
+
+ private fun htmlToText(html: String): String = html
+ .replace(Regex("", RegexOption.IGNORE_CASE), "")
+ .replace(Regex("", RegexOption.IGNORE_CASE), " ")
+ .replace(Regex("", RegexOption.IGNORE_CASE), "")
+ s = s.replace(Regex("