同步插件源代码并补齐标准项目文件

This commit is contained in:
XIGE
2026-11-26 15:04:58 +08:00
commit d959ffed68
82 changed files with 12160 additions and 0 deletions

View File

@@ -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"
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -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 }
}
}
}

View File

@@ -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<String, Bitmap>(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 杂得多:
* 常见 `<https://…>` 包裹、`&amp;` 实体、协议相对 `//host/a.jpg`、Memos 的相对路径
* `/file/xxx.jpg`、以及地址里带空格。这些写法 OkHttp 直接拒绝(抛 IllegalArgumentException),
* 表现为「点了图进去提示加载失败」,而列表里 Markwon 用的是另一套解析,所以图又能显示。
* 统一在这里收敛成可直接请求的绝对地址。
*/
object ImageUrl {
fun normalize(context: Context, raw: String): String {
var s = raw.trim()
// CommonMark 允许 <url> 包一层,用于地址里带空格的情况
if (s.length > 2 && s.startsWith("<") && s.endsWith(">")) {
s = s.substring(1, s.length - 1).trim()
}
// Markdown 正文里 & 常被转义成实体
s = s.replace("&amp;", "&")
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")
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -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<String, Bitmap>(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
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,38 @@
package com.shitoucuo.postpad
import android.content.Context
import androidx.core.content.ContextCompat
import io.noties.markwon.AbstractMarkwonPlugin
import io.noties.markwon.core.MarkwonTheme
/**
* Markdown 排版样式:标题字号层次、代码底色、引用条、分割线、链接色。
* 颜色全部取自主题资源(带 values-night 变体),深浅色自动适配;
* 主题切换会重建 Activity,Markwon 随之重建,样式跟随。
*/
class MdThemePlugin(private val context: Context) : AbstractMarkwonPlugin() {
private val d = context.resources.displayMetrics.density
override fun configureTheme(builder: MarkwonTheme.Builder) {
builder
// # / ## / ### ... 字号逐级递减
.headingTextSizeMultipliers(floatArrayOf(1.5f, 1.32f, 1.2f, 1.1f, 1.05f, 1f))
.headingBreakHeight((1 * d).toInt())
.headingBreakColor(ContextCompat.getColor(context, R.color.divider))
// 行内代码与代码块
.codeBackgroundColor(ContextCompat.getColor(context, R.color.input_bg))
.codeTextColor(ContextCompat.getColor(context, R.color.text))
.codeTextSize((13 * d).toInt())
.codeBlockBackgroundColor(ContextCompat.getColor(context, R.color.input_bg))
.codeBlockTextColor(ContextCompat.getColor(context, R.color.text))
.codeBlockTextSize((13 * d).toInt())
.codeBlockMargin((8 * d).toInt())
// 引用条用品牌橙,分割线用主题分隔色,链接可点击
.blockQuoteColor(ContextCompat.getColor(context, R.color.brand))
.blockQuoteWidth((3 * d).toInt())
.thematicBreakColor(ContextCompat.getColor(context, R.color.divider))
.thematicBreakHeight((1 * d).toInt())
.linkColor(ContextCompat.getColor(context, R.color.brand))
}
}

View File

@@ -0,0 +1,265 @@
package com.shitoucuo.postpad
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.TimeUnit
/**
* Memos 官方 REST API 的最小封装(与 Obsidian 的 Memos 插件同一条链路)。
*
* 鉴权:Authorization: Bearer <token>
* 建博:POST /api/v1/memos(v0.22+),老版本是 /api/v1/memo,404/405 时自动换一个再试
* 传图:POST /api/v1/resource/blob(multipart,字段名 file),拿到资源 id 后
* 随 memo 的 resourceIdList 一起提交,与网页端上传完全一致
*/
object MemosApi {
private val JSON = "application/json; charset=utf-8".toMediaType()
private val client: OkHttpClient = Http.newWith(20, 180, 120, TimeUnit.SECONDS)
class ApiException(message: String, val code: Int = 0) : Exception(message)
data class UploadedResource(val id: Any, val link: String)
data class CreatedMemo(val id: String, val link: String)
/** Memos 列表项:正文就是 Markdown,图片在 resourceList 里 */
data class MemoItem(
val id: String,
val content: String,
val createdTs: Long,
val pinned: Boolean,
val images: List<String>,
)
data class MemoPage(val memos: List<MemoItem>, val nextPageToken: String)
suspend fun check(prefs: Prefs): String = withContext(Dispatchers.IO) {
val text = exec(baseBuilder(prefs).url(prefs.memosUrl + "/api/v1/status").get().build())
val json = try {
JSONObject(text)
} catch (e: Exception) {
// 地址填错时常常返回登录页或 404 页面,这里给出可操作的提示
throw ApiException("服务器返回的不是 JSON,检查地址是否为 Memos 根地址(不要带 /api/v1)")
}
val version = json.optJSONObject("profile")?.optString("version").orEmpty()
if (version.isNotEmpty()) "连接正常,Memos v$version" else "连接正常"
}
suspend fun upload(
prefs: Prefs,
bytes: ByteArray,
filename: String,
mime: String,
): UploadedResource = withContext(Dispatchers.IO) {
val body = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", filename, bytes.toRequestBody(mime.toMediaTypeOrNull()))
.build()
val request = baseBuilder(prefs)
.url(prefs.memosUrl + "/api/v1/resource/blob")
.post(body)
.build()
val json = JSONObject(exec(request))
val rawId = json.opt("id")
val id: Any = if (rawId == null || rawId == JSONObject.NULL) {
json.optString("name")
} else {
rawId
}
UploadedResource(id, json.optString("externalLink"))
}
suspend fun create(
prefs: Prefs,
content: String,
visibility: String,
resources: List<UploadedResource>,
): CreatedMemo = withContext(Dispatchers.IO) {
val payload = JSONObject().apply {
put("content", content)
put("visibility", visibility)
if (resources.isNotEmpty()) {
val array = JSONArray()
resources.forEach { array.put(it.id) }
put("resourceIdList", array)
}
}
val body = payload.toString().toRequestBody(JSON)
var failure: ApiException? = null
for (path in listOf("/api/v1/memos", "/api/v1/memo")) {
val request = baseBuilder(prefs)
.url(prefs.memosUrl + path)
.post(body)
.build()
try {
val json = JSONObject(exec(request))
return@withContext CreatedMemo(memoId(json), memoLink(prefs.memosUrl, json))
} catch (e: ApiException) {
failure = e
if (e.code != 404 && e.code != 405) throw e
}
}
throw failure ?: ApiException("Memos 接口不可用")
}
/**
* Memos 列表。
*
* v0.18.x(当前服务器)实际是:GET /api/v1/memo?limit=N&offset=N,
* 直接返回一个 JSON 数组;v0.22+ 才是 /api/v1/memos + pageToken + {memos:[...]}。
* 这里两条路径都试,并把两种响应结构统一成 MemoPage。
*
* pageToken 约定:普通数字表示 offset;"pt:xxx" 表示新版本的游标。
*/
suspend fun list(
prefs: Prefs,
pageSize: Int = 20,
pageToken: String = "",
): MemoPage = withContext(Dispatchers.IO) {
if (!prefs.memosReady) throw ApiException("先填 Memos 网站地址和 Access Token")
val isCursor = pageToken.startsWith("pt:")
val offset = if (isCursor) 0L else (pageToken.toLongOrNull() ?: 0L)
val paths = if (isCursor) {
listOf("/api/v1/memos", "/api/v1/memo")
} else {
listOf("/api/v1/memo", "/api/v1/memos")
}
var failure: ApiException? = null
for (path in paths) {
val query = StringBuilder("limit=$pageSize&offset=$offset&pageSize=$pageSize")
if (isCursor) {
query.append("&pageToken=")
.append(java.net.URLEncoder.encode(pageToken.removePrefix("pt:"), "UTF-8"))
}
try {
val text = exec(baseBuilder(prefs).url(prefs.memosUrl + path + "?" + query).get().build())
val parsed = parseMemoList(text, offset, pageSize)
val out = ArrayList<MemoItem>(parsed.first.length())
for (i in 0 until parsed.first.length()) {
val obj = parsed.first.optJSONObject(i) ?: continue
val id = memoId(obj)
if (id.isEmpty()) continue
out.add(
MemoItem(
id = id,
content = obj.optString("content"),
createdTs = obj.optLong("createdTs", obj.optLong("displayTs", 0L)),
pinned = obj.optBoolean("pinned", false),
images = resourceImages(obj.optJSONArray("resourceList")),
)
)
}
return@withContext MemoPage(out, parsed.second)
} catch (e: ApiException) {
failure = e
if (e.code != 404 && e.code != 405) throw e
}
}
throw failure ?: ApiException("Memos 列表接口不可用")
}
/** 返回值:Pair(memos 数组, 下一页游标) */
private fun parseMemoList(text: String, offset: Long, pageSize: Int): Pair<JSONArray, String> {
val trimmed = text.trim()
if (trimmed.startsWith("[")) {
val array = JSONArray(trimmed)
val next = if (array.length() >= pageSize) (offset + array.length()).toString() else ""
return array to next
}
val json = JSONObject(trimmed)
val array = json.optJSONArray("memos")
?: json.optJSONArray("data")
?: JSONArray()
val next = json.optString("nextPageToken").ifBlank {
if (array.length() >= pageSize) (offset + array.length()).toString() else ""
}
return array to next
}
private fun resourceImages(array: JSONArray?): List<String> {
if (array == null) return emptyList()
val out = ArrayList<String>()
for (i in 0 until array.length()) {
val item = array.optJSONObject(i) ?: continue
val type = item.optString("type")
val link = item.optString("externalLink")
.ifBlank { item.optString("publicUrl") }
.ifBlank { item.optString("uri") }
if (type.startsWith("image/", true) && link.isNotEmpty()) out.add(link)
}
return out
}
private fun baseBuilder(prefs: Prefs): Request.Builder =
Request.Builder()
.header("Authorization", "Bearer ${prefs.memosToken}")
.header("Accept", "application/json")
.header("User-Agent", RssApi.UA_BROWSER)
private fun exec(request: Request): String {
client.newCall(request).execute().use { response ->
val text = response.body?.string().orEmpty()
if (!response.isSuccessful) {
throw ApiException(friendlyMessage(response.code, text), response.code)
}
return text
}
}
private fun friendlyMessage(code: Int, text: String): String {
val detail = try {
val json = JSONObject(text)
json.optString("message").ifBlank {
json.optString("error").ifBlank { json.optString("detail") }
}
} catch (e: Exception) {
text.take(160)
}
val prefix = when (code) {
401 -> "Token 无效或已过期"
403 -> "没有权限,检查 Token 是否含 memos:write / resource:write"
404 -> "接口不存在,检查网站地址和 Memos 版本"
413 -> "内容或图片过大"
else -> "HTTP $code"
}
return if (detail.isBlank()) prefix else "$prefix:$detail"
}
private fun memoId(json: JSONObject): String {
val name = json.optString("name")
if (name.isNotEmpty()) return name
val raw = json.opt("id")
return if (raw == null || raw == JSONObject.NULL) "" else raw.toString()
}
/** 网页端链接形如 {base}/m/{id};新版 id 是 "memos/xxx",只取最后一段 */
private fun memoLink(base: String, json: JSONObject): String {
val name = json.optString("name")
val tail = when {
name.startsWith("memos/") -> name.removePrefix("memos/")
name.isNotEmpty() -> name
else -> {
val raw = json.opt("id")
if (raw == null || raw == JSONObject.NULL) "" else raw.toString()
}
}
return if (tail.isEmpty()) base else "$base/m/$tail"
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,132 @@
package com.shitoucuo.postpad
import android.content.Context
import android.content.res.Configuration
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.InsetDrawable
import android.text.TextPaint
import android.util.TypedValue
/** 通用 UI 小工具 */
object Ui {
/**
* 弹窗配色板:背景、文字、分隔线、高亮色一次性取齐,且**全部来自同一个 Resources 实例**。
*
* 这是「深色切浅色后下拉菜单黑底黑字」的根因修复。旧实现
* `popupBackground(context, night)` 会按 night 参数 `createConfigurationContext()`
* 另造一份资源去取 surface,而菜单项文字仍旧由页面按当前资源染色(`R.color.text`)。
* 一旦这两份资源对深浅色的判断不一致——切到浅色时恰好发生了——就成了
* 背景取深色 surface、文字取浅色 text,即黑底黑字。
*
* 现在统一走 `context.resources`,即弹出弹窗的那个页面自己的资源:
* 页面是什么色,弹窗就是什么色,背景与文字必然同一套,不可能再同色。
*/
class PopupPalette internal constructor(
val surface: Int,
val stroke: Int,
val text: Int,
val textSecondary: Int,
val divider: Int,
val brand: Int,
val night: Boolean,
private val density: Float,
) {
/** 圆角面板 + 1px 描边,6dp 内边距让文字不压到圆角与描边 */
fun background(cornerDp: Int = 12): Drawable {
val shape = GradientDrawable().apply {
shape = GradientDrawable.RECTANGLE
cornerRadius = cornerDp * density
setColor(surface)
setStroke((1 * density).toInt().coerceAtLeast(1), stroke)
}
return InsetDrawable(shape, (6 * density).toInt())
}
}
/**
* 取当前页面的弹窗配色板。
*
* 必须传 Activity(不能用 applicationContext):Activity 的资源才是页面真正
* 生效的那份,只有取自同一份资源,弹窗与页面才不会深浅错位。
*/
fun popupPalette(context: Context): PopupPalette {
val res = context.resources
val surface = res.getColor(R.color.surface, null)
var text = res.getColor(R.color.text, null)
var brand = res.getColor(R.color.brand, null)
// 兜底:同源取色时对比度必然充足,正常不会进这里。万一将来又有人在别处
// 混用两套资源(或厂商 ROM 的资源缓存出问题),这里至少保证文字与背景
// 分得开,绝不会再出现"背景黑、字也黑"这种完全看不见的情况。
if (contrastRatio(surface, text) < 3.0) {
text = if (luminance(surface) < 0.5) Color.WHITE else Color.BLACK
}
if (contrastRatio(surface, brand) < 2.0) brand = text
return PopupPalette(
surface = surface,
stroke = res.getColor(R.color.card_stroke, null),
text = text,
textSecondary = res.getColor(R.color.text_secondary, null),
divider = res.getColor(R.color.divider, null),
brand = brand,
night = (res.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) ==
Configuration.UI_MODE_NIGHT_YES,
density = res.displayMetrics.density,
)
}
/** 相对亮度(WCAG 2.0),用于判断前景与背景是否够区分 */
private fun luminance(color: Int): Double {
fun channel(value: Int): Double {
val s = value / 255.0
return if (s <= 0.03928) s / 12.92 else Math.pow((s + 0.055) / 1.055, 2.4)
}
return 0.2126 * channel(Color.red(color)) +
0.7152 * channel(Color.green(color)) +
0.0722 * channel(Color.blue(color))
}
/** 对比度(1~21),正文可读的经验下限约 3.0 */
private fun contrastRatio(a: Int, b: Int): Double {
val la = luminance(a)
val lb = luminance(b)
return (maxOf(la, lb) + 0.05) / (minOf(la, lb) + 0.05)
}
/** 只要背景时的便捷入口(与 popupPalette(context).background() 等价) */
fun popupBackground(context: Context, cornerDp: Int = 12): Drawable =
popupPalette(context).background(cornerDp)
/**
* 按最宽文本计算下拉菜单宽度:比文字稍宽即可,不再与锚点控件等宽。
*
* @param textSizeSp 菜单文字字号(与 item 布局保持一致)
* @param extraDp 额外预留:左右内边距 + 背景 + 滚动条
* @param minDp/maxDp 宽度上下限
*/
fun menuWidth(
context: Context,
texts: List<String>,
textSizeSp: Float = 15f,
extraDp: Int = 32,
minDp: Int = 96,
maxDp: Int = 240,
): Int {
val dm = context.resources.displayMetrics
val paint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
// 走 applyDimension 而不是直接乘已废弃的 scaledDensity:
// 系统字号放大后(尤其 Android 14 的非线性字体缩放),手乘得到的宽度
// 会小于实际渲染宽度,菜单项又带 ellipsize,四五个字就会被截成两三个。
textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, textSizeSp, dm)
}
var text = 0f
for (t in texts) text = maxOf(text, paint.measureText(t))
val d = dm.density
// +0.5f 是四舍五入:直接 toInt() 会向下取整,宽度总比算出来的少 1px
return (text + extraDp * d + 0.5f).toInt()
.coerceIn((minDp * d).toInt(), (maxDp * d).toInt())
}
}

View File

@@ -0,0 +1,158 @@
package com.shitoucuo.postpad
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.RectF
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
/**
* 图片缩放视图:双指缩放、拖动、双击放大/还原、单击关闭。
* 用于阅读页 FlexPhoto 图组点击放大查看。
*/
class ZoomableImageView(context: Context, private val onTapClose: () -> Unit) : View(context) {
private var bitmap: Bitmap? = null
private val drawMatrix = Matrix()
private val saved = Matrix()
private val displayRect = RectF()
private var minScale = 0.5f
private val maxScale = 6f
private val scaleDetector = ScaleGestureDetector(
context,
object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScaleBegin(detector: ScaleGestureDetector): Boolean {
saved.set(drawMatrix)
return true
}
override fun onScale(detector: ScaleGestureDetector): Boolean {
drawMatrix.set(saved)
drawMatrix.postScale(
detector.scaleFactor, detector.scaleFactor,
detector.focusX, detector.focusY,
)
clamp()
invalidate()
return true
}
},
)
private val gestureDetector = GestureDetector(
context,
object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean {
saved.set(drawMatrix)
return true
}
override fun onScroll(e1: MotionEvent?, e2: MotionEvent, dx: Float, dy: Float): Boolean {
drawMatrix.set(saved)
drawMatrix.postTranslate(-dx, -dy)
clamp()
invalidate()
return true
}
override fun onDoubleTap(e: MotionEvent): Boolean {
val current = scale()
if (current > minScale * 1.2f) {
resetFit()
} else {
drawMatrix.postScale(2.5f / current, 2.5f / current, e.x, e.y)
clamp()
}
invalidate()
return true
}
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
onTapClose()
return true
}
},
)
fun setBitmap(bmp: Bitmap) {
bitmap = bmp
resetFit()
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val bmp = bitmap ?: return
canvas.drawBitmap(bmp, drawMatrix, null)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
scaleDetector.onTouchEvent(event)
gestureDetector.onTouchEvent(event)
if (event.actionMasked == MotionEvent.ACTION_UP ||
event.actionMasked == MotionEvent.ACTION_CANCEL
) {
saved.set(drawMatrix)
}
return true
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
resetFit()
invalidate()
}
private fun scale(): Float {
val values = FloatArray(9)
drawMatrix.getValues(values)
return values[Matrix.MSCALE_X]
}
/** 初始按视图大小完整显示 */
private fun resetFit() {
val bmp = bitmap ?: return
val w = width.toFloat()
val h = height.toFloat()
if (w <= 0 || h <= 0) return
drawMatrix.reset()
val scale = minOf(w / bmp.width, h / bmp.height)
drawMatrix.postScale(scale, scale, w / 2, h / 2)
drawMatrix.postTranslate(w / 2 - bmp.width * scale / 2, h / 2 - bmp.height * scale / 2)
minScale = scale * 0.8f
clamp()
}
/** 缩放限制在 [minScale, maxScale],位移保证图片不会完全拖出屏幕 */
private fun clamp() {
val bmp = bitmap ?: return
val values = FloatArray(9)
drawMatrix.getValues(values)
val s = values[Matrix.MSCALE_X].coerceIn(minScale, maxScale)
if (values[Matrix.MSCALE_X] != s) {
drawMatrix.setScale(s, s, width / 2f, height / 2f)
}
displayRect.set(0f, 0f, bmp.width.toFloat(), bmp.height.toFloat())
drawMatrix.mapRect(displayRect)
var dx = 0f
var dy = 0f
if (displayRect.width() <= width) {
dx = width / 2f - displayRect.centerX()
} else {
if (displayRect.left > 0) dx = -displayRect.left
if (displayRect.right < width) dx = width - displayRect.right
}
if (displayRect.height() <= height) {
dy = height / 2f - displayRect.centerY()
} else {
if (displayRect.top > 0) dy = -displayRect.top
if (displayRect.bottom < height) dy = height - displayRect.bottom
}
if (dx != 0f || dy != 0f) drawMatrix.postTranslate(dx, dy)
}
}